From 979a5046006683136e777ab6d77527ffaf48f14b Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jaroslav=20Bene=C5=A1?= Date: Wed, 18 Nov 2026 00:38:23 +0000 Subject: [PATCH] A folder picker for a linked computer, the folder's usual model, Chat and Agentic schedules, @ in the composer Contract and strings pinned at the server's dev (a6288a2); the release re-pins at its tag. - DirectoryPicker: GET /devices/{id}/directories walked down and up, a refused directory not choosable, the model last used beside a folder, the typed path kept where the device lists nothing (PickerState, took, up). Used by a new agent chat and by the schedule form. - A new agent chat shows `start.model` for its device and folder, read again when either changes; a picked model wins; `model` is sent only when picked. - The schedule form asks the type first: Chat, or Agentic with computer, folder, mode, approval wait and model (empty: the folder's usual model). A save says `runs_on` only for what the form knows (whereToSend). The task page shows type and model; a run its `ran_on` and `model.reason`. - `@word` at the end of the composer's text: the server's mentions attach, an agent chat's device files complete as `@path`. - Models: `interactive_only`, a device's `scheduled`, `max_mode`, `directory_model`. Co-Authored-By: Claude Fable 5.2 --- CHANGELOG.md | 28 ++ .../java/eu/llembas/android/api/ApiClient.kt | 56 ++- .../eu/llembas/android/api/Directories.kt | 62 +++ .../java/eu/llembas/android/api/Models.kt | 28 +- .../java/eu/llembas/android/api/Schedules.kt | 30 +- .../eu/llembas/android/ui/DirectoryPicker.kt | 288 ++++++++++++++ .../llembas/android/ui/chat/ChatViewModel.kt | 117 +++++- .../eu/llembas/android/ui/chat/Composer.kt | 90 ++++- .../eu/llembas/android/ui/chat/Mentions.kt | 31 ++ .../android/ui/scheduled/ScheduledScreens.kt | 352 +++++++++++++++++- app/src/main/res/values-cs/strings.xml | 33 ++ app/src/main/res/values-de/strings.xml | 33 ++ app/src/main/res/values-es/strings.xml | 33 ++ app/src/main/res/values-fr/strings.xml | 33 ++ app/src/main/res/values-hu/strings.xml | 33 ++ app/src/main/res/values-it/strings.xml | 33 ++ app/src/main/res/values-pl/strings.xml | 33 ++ app/src/main/res/values-sk/strings.xml | 33 ++ app/src/main/res/values/strings.xml | 33 ++ .../eu/llembas/android/DirectoriesTest.kt | 174 +++++++++ .../java/eu/llembas/android/MentionsTest.kt | 72 ++++ .../llembas/android/ScheduleContractTest.kt | 2 +- .../eu/llembas/android/ScheduleTypesTest.kt | 171 +++++++++ .../java/eu/llembas/android/shots/Fakes.kt | 36 ++ .../eu/llembas/android/shots/ScreenShots.kt | 22 ++ contract/device_directories.json | 44 +++ contract/device_directories_cli_too_old.json | 16 + contract/device_directories_not_linked.json | 14 + contract/device_directories_places.json | 34 ++ contract/devices.json | 6 +- contract/event_schedules.json | 3 +- contract/lock.json | 6 +- contract/models_agent_directory.json | 88 +++++ contract/schedule.json | 1 + contract/schedule_on_device.json | 1 + contract/schedule_run.json | 1 + contract/schedule_run_agentic.json | 44 +++ contract/schedule_runs.json | 2 + contract/schedule_watching.json | 1 + contract/schedules.json | 1 + scripts/strings.py | 36 ++ scripts/strings_own.json | 40 ++ 42 files changed, 2150 insertions(+), 44 deletions(-) create mode 100644 app/src/main/java/eu/llembas/android/api/Directories.kt create mode 100644 app/src/main/java/eu/llembas/android/ui/DirectoryPicker.kt create mode 100644 app/src/main/java/eu/llembas/android/ui/chat/Mentions.kt create mode 100644 app/src/test/java/eu/llembas/android/DirectoriesTest.kt create mode 100644 app/src/test/java/eu/llembas/android/MentionsTest.kt create mode 100644 app/src/test/java/eu/llembas/android/ScheduleTypesTest.kt create mode 100644 contract/device_directories.json create mode 100644 contract/device_directories_cli_too_old.json create mode 100644 contract/device_directories_not_linked.json create mode 100644 contract/device_directories_places.json create mode 100644 contract/models_agent_directory.json create mode 100644 contract/schedule_run_agentic.json diff --git a/CHANGELOG.md b/CHANGELOG.md index 3c258f0..91437b1 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -5,6 +5,34 @@ is in alpha and releases come off `main`. ## [Unreleased] +Needs LLeMbas 2.0.0-beta.14 for what is new here; with an older instance the app works as before. + +### Added + +- **Choose a folder on your computer instead of typing its path.** A new agent chat's *Folder + on the device* opens a picker: the computer's places, then down through its folders and back + up -- the back gesture goes up a level and closes at the top. A folder the computer will not + open a session in says why and cannot be chosen; a folder you worked in before names the + model you last used there. The path can still be typed, and that is what remains when the + computer is not linked, does not answer, or runs a LLeMbas CLI too old to list its folders -- + the picker says which. +- **A new agent chat starts on the model you last used in that folder.** Once the computer and + the folder are chosen, the model shown is the folder's usual one (the computer remembers it; + the app keeps nothing), and it changes when you choose another computer or folder. A model + you pick yourself stays picked. +- **Scheduled tasks have two types: Chat and Agentic.** The form asks the type first. *Chat* + runs on your instance, as tasks always have. *Agentic* runs on one of your computers, in one + folder there, as an agent: you choose the computer, the folder (with the picker, or typed), + the mode, how long an approval waits, and the model -- *The folder's usual model* unless you + choose one of your scheduling models. Agentic can be chosen only while one of your computers + accepts scheduled work, and says so otherwise. A task's page shows its type, computer, folder + and model; each run says where it ran and when its model was the folder's usual one, your + default or the conversation's own. +- **`@` in the composer.** Type `@` and a few letters at the end of a message: in a chat the + list offers your files, what was attached earlier in the chat and a web address, and a tap + attaches it; in an agent chat it offers the files in the chat's folder on the computer, and + a tap completes the path for the agent to read. + ### Changed - **The badge on Reports is live.** The count of unread reports in the drawer follows the 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 c539987..1951b28 100644 --- a/app/src/main/java/eu/llembas/android/api/ApiClient.kt +++ b/app/src/main/java/eu/llembas/android/api/ApiClient.kt @@ -5,6 +5,7 @@ import kotlinx.coroutines.suspendCancellableCoroutine import kotlinx.coroutines.withContext import kotlinx.serialization.KSerializer import kotlinx.serialization.json.JsonArray +import kotlinx.serialization.json.JsonNull import kotlinx.serialization.json.JsonObject import kotlinx.serialization.json.JsonPrimitive import kotlinx.serialization.json.buildJsonObject @@ -150,8 +151,11 @@ class ApiClient(val base: String, private val token: String, val http: OkHttpCli suspend fun modelList(chatId: String? = null): ModelList = get(if (chatId != null) "/models?chat=$chatId" else "/models") /** The models for a new agent chat on [deviceId], with whether it may have subagents (`agent_subagents`). */ - suspend fun agentModelList(deviceId: String?): ModelList = - get("/models?kind=agent" + deviceId?.let { "&device=" + java.net.URLEncoder.encode(it, "UTF-8") }.orEmpty()) + suspend fun agentModelList(deviceId: String?, directory: String? = null): ModelList = get( + "/models?kind=agent" + deviceId?.let { "&device=" + segment(it) }.orEmpty() + + // With a directory (spec 3.9.0) the answer carries `start`: the model a chat there starts on. + directory?.takeIf { deviceId != null && it.isNotBlank() }?.let { "&directory=" + segment(it.trim()) }.orEmpty(), + ) suspend fun folders(): List = get("/folders").folders @@ -174,6 +178,16 @@ class ApiClient(val base: String, private val token: String, val http: OkHttpCli /** The app releases this server recommends; 404 from a server older than the route. */ suspend fun apps(): AppsInfo = get("/apps") + /** + * What `@` offers in an agent chat: the device's files matching [q], from the chat's + * directory ([chatId]) or, before the chat exists, from the folder chosen for it ([cwd]). + */ + suspend fun deviceFiles(deviceId: String, q: String, chatId: String? = null, cwd: String? = null): DeviceFiles = get( + "/devices/${segment(deviceId)}/files?q=${segment(q)}" + + chatId?.let { "&chat=${segment(it)}" }.orEmpty() + + cwd?.takeIf { chatId == null && it.isNotBlank() }?.let { "&cwd=${segment(it.trim())}" }.orEmpty(), + ) + /** What `@` offers from the server for [q]: the chat's earlier attachments, files of the tree, a web address. */ suspend fun mentions(q: String, chatId: String? = null): Mentions = get("/mentions?q=${segment(q)}" + (chatId?.let { "&chat=${segment(it)}" } ?: "")) @@ -219,6 +233,14 @@ class ApiClient(val base: String, private val token: String, val http: OkHttpCli suspend fun devices(): List = get("/devices").devices + /** + * A directory on a linked device, for choosing where an agent chat or an Agentic schedule + * works; without a [path], the device's places. No listing is still an answer: its `code` + * and `error` say why. + */ + suspend fun deviceDirectories(deviceId: String, path: String? = null): DeviceDirectory = + get("/devices/${segment(deviceId)}/directories" + path?.takeIf { it.isNotEmpty() }?.let { "?path=" + segment(it) }.orEmpty()) + /** The token revokes itself (`lembas logout`'s route). */ suspend fun signOut() = empty(authed("$base/api/v1/token").delete().build()) @@ -379,8 +401,36 @@ class ApiClient(val base: String, private val token: String, val http: OkHttpCli * Save what the compile made of [words]: a new schedule (201), or with [id] the one being * edited. The words go along as the schedule's `request`, so editing starts from them. */ - suspend fun saveSchedule(compiled: ScheduleCompiled, words: String, id: String? = null, notify: String? = null, notifyWhen: String = ""): Schedule { + suspend fun saveSchedule( + compiled: ScheduleCompiled, + words: String, + id: String? = null, + notify: String? = null, + notifyWhen: String = "", + where: WhereToRun = WhereToRun.Leave, + ): Schedule { val body = buildJsonObject { + // The type (spec 3.9.0): Agentic is a schedule with a computer, Chat one without. Left + // out where the form did not say, so a schedule is never moved by a form that did not read it. + when (where) { + WhereToRun.Leave -> Unit + + WhereToRun.Server -> put("runs_on", JsonNull) + + is WhereToRun.Computer -> { + put( + "runs_on", + buildJsonObject { + put("device", where.device) + put("cwd", where.cwd) + put("mode", where.mode) + where.approvalWaitMinutes?.let { put("approval_wait_minutes", it) } + }, + ) + // Empty: the folder's usual model, asked of the computer as each run starts. + put("model", where.model) + } + } put("title", compiled.title) put("instruction", compiled.instruction) put("rule", compiled.rule) diff --git a/app/src/main/java/eu/llembas/android/api/Directories.kt b/app/src/main/java/eu/llembas/android/api/Directories.kt new file mode 100644 index 0000000..c04d3eb --- /dev/null +++ b/app/src/main/java/eu/llembas/android/api/Directories.kt @@ -0,0 +1,62 @@ +package eu.llembas.android.api + +import kotlinx.serialization.Serializable + +// --- A linked device's directories (`GET /api/v2/devices/{id}/directories`) ------------------- +// +// The JSON twin of the page's directory dialog (harness spec 3.9.0), as the contract pins it +// (`contract/device_directories*.json`). Every field has a default, so a server that says less +// still parses. + +/** The model last used in a directory on the device, as one the person still has. */ +@Serializable +data class DirectoryModel(val id: String = "", val name: String = "") { + /** What to call it: its name, else its id. */ + val label: String get() = name.ifBlank { id } +} + +/** A subdirectory: whether a session may be opened in it ([reason]: the device's words when not), and its [model]. */ +@Serializable +data class DirectoryEntry( + val path: String = "", + val name: String = "", + val accepted: Boolean = true, + val reason: String = "", + val model: DirectoryModel? = null, +) + +/** + * One directory on a device, or -- with an empty [path] -- the device's places. Where there is + * no listing, [code] says why (`device_not_linked`, `cli_too_old`, `no_answer`, `refused`) and + * [error] is the sentence for the person; a typed path still works then. + */ +@Serializable +data class DeviceDirectory( + val device: String = "", + val path: String = "", + val name: String = "", + val accepted: Boolean = true, + val reason: String = "", + val model: DirectoryModel? = null, + val parent: String = "", + val roots: List = emptyList(), + val entries: List = emptyList(), + /** Whether the device says a directory's model at all. */ + val remembers: Boolean = false, + val code: String = "", + val error: String = "", +) { + /** The device's places, not a directory. */ + val places: Boolean get() = path.isEmpty() + + /** Whether this answer is a listing; one with a [code] is the reason there is none. */ + val listed: Boolean get() = code.isEmpty() +} + +/** + * The model a new agent chat on a device and directory starts on when the app names none + * (`GET /models?kind=agent&device=&directory=`): [from] `directory` (the model last used + * there) or `default`. The device remembers it; nothing here is kept by the app. + */ +@Serializable +data class StartModel(val model: String = "", val from: String = "") 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 c578743..0cf5afd 100644 --- a/app/src/main/java/eu/llembas/android/api/Models.kt +++ b/app/src/main/java/eu/llembas/android/api/Models.kt @@ -117,6 +117,8 @@ data class ModelInfo( val default: Boolean = false, /** Whether a new chat on this model is offered subagents (server 2.0.0-beta.7); null from an older one. */ val subagents: SubagentsOffer? = null, + /** On a connection whose terms allow interactive use only: never a schedule's model. */ + @SerialName("interactive_only") val interactiveOnly: Boolean = false, ) { /** * The levels, for a server that says them; an older one said only `efforts`, offered after @@ -159,6 +161,8 @@ data class ModelList( @SerialName("subagents_cap") val subagentsCap: Int? = null, /** With `kind=agent` (spec 3.4.0 §14): whether a new agent chat may have subagents. */ @SerialName("agent_subagents") val agentSubagents: AgentSubagents? = null, + /** With `kind=agent`, a device and a directory (spec 3.9.0): the model a new agent chat there starts on. */ + val start: StartModel? = null, ) /** @@ -243,6 +247,14 @@ data class Mention(val kind: String = "", val id: String = "", val path: String @Serializable data class Mentions(val items: List = emptyList()) +/** A file or directory on a linked device, by its [path] from the chat's directory ([kind] `file` or `dir`). */ +@Serializable +data class DeviceFile(val path: String = "", val kind: String = "", val name: String = "") + +/** What `@` offers in an agent chat (`GET /devices/{id}/files`): the device's files; one that cannot answer offers none and may say why. */ +@Serializable +data class DeviceFiles(val files: List = emptyList(), val error: String = "", val device: String = "") + @Serializable data class ServerChannel(val version: String = "", val channel: String = "") @@ -288,7 +300,21 @@ data class FolderList(val folders: List = emptyList()) data class Device(@SerialName("token_id") val tokenId: String? = null, val directory: String = "") @Serializable -data class LinkedDevice(val id: String, val name: String = "", val host: String = "", val platform: String = "") +data class LinkedDevice( + val id: String, + val name: String = "", + val host: String = "", + val platform: String = "", + /** Whether the device accepts scheduled work: only then may an Agentic schedule belong to it. */ + val scheduled: Boolean = false, + /** The widest mode the device lets a scheduled run have; empty where it accepts none. */ + @SerialName("max_mode") val maxMode: String = "", + /** Whether the device remembers the model last used in a directory (spec 3.9.0). */ + @SerialName("directory_model") val directoryModel: Boolean = false, +) { + /** What to call it: its name, else its host. */ + val label: String get() = name.ifBlank { host.ifBlank { id } } +} @Serializable data class DeviceList(val devices: List = emptyList()) diff --git a/app/src/main/java/eu/llembas/android/api/Schedules.kt b/app/src/main/java/eu/llembas/android/api/Schedules.kt index af76a43..16cb521 100644 --- a/app/src/main/java/eu/llembas/android/api/Schedules.kt +++ b/app/src/main/java/eu/llembas/android/api/Schedules.kt @@ -11,7 +11,12 @@ import kotlinx.serialization.json.JsonObject // `event_schedules.json`; `ContractTest` reads every one). Every field has a default, so a // server that says less still parses. -/** The model a run used: [reason] `switched` when it stood in for [switchedFrom], which was busy. */ +/** + * The model a run used, and how it came to it ([reason]): `pinned` (the schedule's own), + * `switched` (it stood in for [switchedFrom], which was busy), `directory` (the folder's usual + * model, asked of the computer), `default` (the person's default, where the folder had none) or + * `session` (a continued conversation kept its own). + */ @Serializable data class RunModel( val id: String? = null, @@ -72,6 +77,8 @@ data class ScheduleRun( val note: String = "", /** The report this run filed, when it filed one: its id (or an object carrying it). */ val report: JsonElement? = null, + /** Where an Agentic schedule's run ran (spec 3.9.0); null for a Chat schedule's, or from an older server. */ + @SerialName("ran_on") val ranOn: RanOn? = null, ) { val reportId: String? get() = idOf(report) } @@ -235,5 +242,26 @@ data class RunsOn( @SerialName("approval_wait_minutes") val approvalWaitMinutes: Int? = null, ) +/** Where one run ran: the computer ([deviceName]), the folder there and the mode it had. */ +@Serializable +data class RanOn(val device: String = "", @SerialName("device_name") val deviceName: String = "", val cwd: String = "", val mode: String = "") + +/** The two types of schedule (spec 3.9.0). There is no field for it: Agentic is one with a computer. */ +val Schedule.agentic: Boolean get() = runsOn != null + /** A run that waits because its computer is not linked (`error.class` `device_away`). */ val ScheduleRun.computerAway: Boolean get() = error?.kind == "device_away" + +/** + * What a save says about where a schedule runs, which is its type: nothing ([Leave]), on the + * server ([Server]: Chat), or on a computer ([Computer]: Agentic) -- in a folder there, in a + * mode, with an approval's wait in minutes (null: the server's default) and a model, where the + * empty one is the folder's usual model. + */ +sealed interface WhereToRun { + data object Leave : WhereToRun + + data object Server : WhereToRun + + data class Computer(val device: String, val cwd: String, val mode: String, val approvalWaitMinutes: Int?, val model: String) : WhereToRun +} diff --git a/app/src/main/java/eu/llembas/android/ui/DirectoryPicker.kt b/app/src/main/java/eu/llembas/android/ui/DirectoryPicker.kt new file mode 100644 index 0000000..26d82fd --- /dev/null +++ b/app/src/main/java/eu/llembas/android/ui/DirectoryPicker.kt @@ -0,0 +1,288 @@ +package eu.llembas.android.ui + +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.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.layout.size +import androidx.compose.foundation.layout.width +import androidx.compose.foundation.layout.widthIn +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.automirrored.filled.ArrowBack +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.FolderOff +import androidx.compose.material3.Button +import androidx.compose.material3.CircularProgressIndicator +import androidx.compose.material3.HorizontalDivider +import androidx.compose.material3.Icon +import androidx.compose.material3.IconButton +import androidx.compose.material3.MaterialTheme +import androidx.compose.material3.OutlinedTextField +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.getValue +import androidx.compose.runtime.mutableStateOf +import androidx.compose.runtime.remember +import androidx.compose.runtime.rememberCoroutineScope +import androidx.compose.runtime.setValue +import androidx.compose.ui.Alignment +import androidx.compose.ui.Modifier +import androidx.compose.ui.platform.LocalContext +import androidx.compose.ui.res.stringResource +import androidx.compose.ui.text.font.FontFamily +import androidx.compose.ui.text.style.TextOverflow +import androidx.compose.ui.unit.dp +import androidx.compose.ui.window.Dialog +import androidx.compose.ui.window.DialogProperties +import eu.llembas.android.R +import eu.llembas.android.api.DeviceDirectory +import eu.llembas.android.api.DirectoryEntry +import eu.llembas.android.ui.theme.LocalPalette +import kotlinx.coroutines.CancellationException +import kotlinx.coroutines.Job +import kotlinx.coroutines.launch + +/** + * Choosing a folder on a linked computer: the last listing the device gave ([listing]; null + * before the first, or where there never was one), the path in the field ([typed]: where the + * walk is, or what the person wrote -- the way in that always works), and the sentence for a + * listing that could not be had ([error]). + */ +data class PickerState(val listing: DeviceDirectory? = null, val loading: Boolean = false, val typed: String = "", val error: String? = null) + +/** + * The device's answer. A listing is shown and the field follows it (the places have no path, + * so the field keeps what it had). No listing -- the device is away, too old, silent or said + * no -- leaves the last listing and the typed path where they were, with the server's sentence + * ([fallback] where it sent none). + */ +fun PickerState.took(answer: DeviceDirectory, fallback: String = ""): PickerState = when { + answer.listed -> copy(listing = answer, loading = false, error = null, typed = answer.path.ifEmpty { typed }) + else -> copy(loading = false, error = answer.error.ifBlank { fallback }) +} + +/** + * Where "up" leads from the listing shown: the parent, the places (`""`) from a directory that + * has none, or null at the places themselves and where nothing is listed -- there the picker + * closes instead. + */ +val PickerState.up: String? + get() = listing?.takeIf { !it.places }?.parent + +/** + * Whether the path in the field may be chosen: something is written, and it is not the listed + * directory the device said it would open no session in. A path the device was never asked + * about may be chosen: the instance checks it when it is used. + */ +val PickerState.canChoose: Boolean + get() = typed.isNotBlank() && !refusedHere + +/** The field holds the listed directory, and the device will not open a session there. */ +val PickerState.refusedHere: Boolean + get() = listing?.let { !it.places && !it.accepted && it.path == typed.trim() } == true + +interface PickerActions { + fun open(path: String) {} + fun typed(text: String) {} + fun choose() {} + fun back() {} + fun close() {} +} + +/** + * The directory picker over whatever asked for it: [load] asks the device for a path (`""`: + * its places), [onPick] is given the chosen path. It opens at [initial], or at the places. + * Back goes up a level, and closes at the top. + */ +@Composable +fun DirectoryPicker(title: String, initial: String, load: suspend (String) -> DeviceDirectory, onPick: (String) -> Unit, onDismiss: () -> Unit) { + val context = LocalContext.current + val scope = rememberCoroutineScope() + var state by remember { mutableStateOf(PickerState(typed = initial.trim(), loading = true)) } + var reading by remember { mutableStateOf(null) } + val fallback = stringResource(R.string.directory_no_listing) + val read: (String) -> Unit = { path -> + reading?.cancel() + state = state.copy(loading = true, error = null) + reading = scope.launch { + try { + val answer = load(path) + // Applied to the state as it is now: what was typed while the device answered stays. + state = state.took(answer, fallback) + } catch (e: CancellationException) { + throw e + } catch (e: Exception) { + state = state.copy(loading = false, error = context.explain(e)) + } + } + } + LaunchedEffect(Unit) { read(initial.trim()) } + val actions = object : PickerActions { + override fun open(path: String) = read(path) + + override fun typed(text: String) { + state = state.copy(typed = text) + } + + override fun choose() { + if (state.canChoose) onPick(state.typed.trim()) + } + + override fun back() { + val up = state.up + if (up == null) onDismiss() else read(up) + } + + override fun close() = onDismiss() + } + Dialog(onDismissRequest = actions::back, properties = DialogProperties(usePlatformDefaultWidth = false, dismissOnClickOutside = false)) { + DirectoryPickerContent(title, state, actions) + } +} + +/** + * The picker, drawn from its state: where the walk is, the model last used there, the + * subdirectories (a row is 56 dp; its name gives, the model beside it keeps to a third), and at + * the foot the path as text with Choose -- which is all there is when the device lists nothing. + */ +@Composable +fun DirectoryPickerContent(title: String, state: PickerState, actions: PickerActions, modifier: Modifier = Modifier) { + val palette = LocalPalette.current + val listing = state.listing + Surface(color = palette.bg, contentColor = palette.ink, modifier = modifier.fillMaxSize()) { + Column(Modifier.fillMaxSize()) { + Row(Modifier.fillMaxWidth().heightIn(min = 56.dp).padding(horizontal = 4.dp), verticalAlignment = Alignment.CenterVertically) { + IconButton(onClick = actions::back) { Icon(Icons.AutoMirrored.Filled.ArrowBack, contentDescription = stringResource(R.string.back)) } + Text(title, style = MaterialTheme.typography.titleLarge, maxLines = 1, overflow = TextOverflow.Ellipsis, modifier = Modifier.weight(1f)) + if (state.loading) CircularProgressIndicator(strokeWidth = 2.dp, modifier = Modifier.padding(horizontal = 12.dp).size(20.dp)) + IconButton(onClick = actions::close) { Icon(Icons.Filled.Close, contentDescription = stringResource(R.string.close)) } + } + Column(Modifier.padding(horizontal = 16.dp), verticalArrangement = Arrangement.spacedBy(4.dp)) { + Text( + listing?.path?.ifEmpty { null } ?: stringResource(R.string.directory_places), + style = MaterialTheme.typography.bodyMedium, + fontFamily = if (listing?.places == false) FontFamily.Monospace else null, + color = palette.inkMuted, + maxLines = 2, + overflow = TextOverflow.Ellipsis, + ) + listing?.model?.let { + Text(stringResource(R.string.directory_last_used, it.label), style = MaterialTheme.typography.bodySmall, color = palette.inkMuted) + } + if (listing != null && !listing.places && !listing.accepted) { + Text( + listing.reason.ifBlank { stringResource(R.string.directory_refused) }, + style = MaterialTheme.typography.bodySmall, + color = palette.warning, + ) + } + state.error?.let { Text(it, style = MaterialTheme.typography.bodyMedium, color = palette.danger) } + } + LazyColumn(Modifier.fillMaxWidth().weight(1f).padding(top = 8.dp)) { + // The way out of a directory, and -- where nothing is listed -- the way to the places. + if (listing?.places != true) { + item(key = "up") { + val places = listing == null || listing.parent.isEmpty() + EntryRow( + name = stringResource(if (places) R.string.directory_all_places else R.string.directory_up), + icon = { Icon(Icons.Filled.ArrowUpward, contentDescription = null, tint = palette.inkMuted) }, + onClick = { actions.open(listing?.parent.orEmpty()) }, + ) + } + } + if (listing != null && listing.entries.isEmpty() && !state.loading) { + item(key = "empty") { + Text( + stringResource(if (listing.places) R.string.directory_no_places else R.string.directory_empty), + style = MaterialTheme.typography.bodyMedium, + color = palette.inkMuted, + modifier = Modifier.padding(horizontal = 16.dp, vertical = 12.dp), + ) + } + } + items(listing?.entries.orEmpty(), key = { "d:" + it.path }) { entry -> Entry(entry, onOpen = { actions.open(entry.path) }) } + } + HorizontalDivider(color = palette.border) + Column(Modifier.padding(16.dp), verticalArrangement = Arrangement.spacedBy(12.dp)) { + OutlinedTextField( + value = state.typed, + onValueChange = actions::typed, + singleLine = true, + label = { Text(stringResource(R.string.directory_path)) }, + shape = RoundedCornerShape(16.dp), + modifier = Modifier.fillMaxWidth(), + ) + Row( + Modifier.fillMaxWidth(), + horizontalArrangement = Arrangement.spacedBy(12.dp, Alignment.End), + verticalAlignment = Alignment.CenterVertically, + ) { + TextButton(onClick = actions::close, modifier = Modifier.heightIn(min = 48.dp)) { Text(stringResource(R.string.cancel)) } + Button(onClick = actions::choose, enabled = state.canChoose, modifier = Modifier.heightIn(min = 48.dp)) { + Text(stringResource(R.string.directory_choose)) + } + } + } + } + } +} + +/** A subdirectory: its name, why no session opens in it where none does, and the model last used in it. */ +@Composable +private fun Entry(entry: DirectoryEntry, onOpen: () -> Unit) { + val palette = LocalPalette.current + EntryRow( + name = entry.name.ifBlank { entry.path }, + note = if (entry.accepted) null else entry.reason.ifBlank { stringResource(R.string.directory_not_trusted) }, + model = entry.model?.label, + icon = { + Icon( + if (entry.accepted) Icons.Filled.Folder else Icons.Filled.FolderOff, + contentDescription = null, + tint = if (entry.accepted) palette.accent else palette.inkFaint, + ) + }, + onClick = onOpen, + ) +} + +@Composable +private fun EntryRow(name: String, icon: @Composable () -> Unit, onClick: () -> Unit, note: String? = null, model: String? = null) { + val palette = LocalPalette.current + Row( + Modifier.fillMaxWidth().clickable(onClick = onClick).heightIn(min = 56.dp).padding(horizontal = 16.dp, vertical = 8.dp), + verticalAlignment = Alignment.CenterVertically, + ) { + Box(Modifier.size(24.dp), contentAlignment = Alignment.Center) { icon() } + Spacer(Modifier.width(16.dp)) + Column(Modifier.weight(1f)) { + Text(name, style = MaterialTheme.typography.bodyLarge, maxLines = 1, overflow = TextOverflow.Ellipsis) + note?.let { Text(it, style = MaterialTheme.typography.bodySmall, color = palette.inkMuted, maxLines = 2, overflow = TextOverflow.Ellipsis) } + } + model?.let { + Spacer(Modifier.width(12.dp)) + Text( + it, + style = MaterialTheme.typography.labelMedium, + color = palette.inkMuted, + maxLines = 1, + overflow = TextOverflow.Ellipsis, + modifier = Modifier.widthIn(max = 120.dp), + ) + } + } +} 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 100f172..9f95172 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 @@ -21,12 +21,15 @@ import eu.llembas.android.api.Card import eu.llembas.android.api.CardAnswer import eu.llembas.android.api.Chat import eu.llembas.android.api.ChatDetail +import eu.llembas.android.api.DeviceDirectory import eu.llembas.android.api.LembasJson import eu.llembas.android.api.LinkedDevice import eu.llembas.android.api.LiveReply +import eu.llembas.android.api.Mention import eu.llembas.android.api.Message import eu.llembas.android.api.MessagePage import eu.llembas.android.api.ModelInfo +import eu.llembas.android.api.StartModel import eu.llembas.android.api.StreamClient import eu.llembas.android.api.SubagentTree import eu.llembas.android.api.Turn @@ -35,6 +38,7 @@ import eu.llembas.android.ui.explain import kotlinx.coroutines.CancellationException import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.Job +import kotlinx.coroutines.delay import kotlinx.coroutines.flow.MutableStateFlow import kotlinx.coroutines.flow.asStateFlow import kotlinx.coroutines.flow.update @@ -83,6 +87,14 @@ data class ChatState( val tree: SubagentTree? = null, /** For a new agent chat: whether it may have subagents, and whether its device runs them. */ val agentSubagents: AgentSubagents? = null, + /** + * For a new agent chat: the model it starts on in the chosen device and folder when the + * person picks none (spec 3.9.0) -- the folder's usual model, as the instance asked the + * device. Shown, never sent and never kept: the instance does the same on its own. + */ + val start: StartModel? = null, + /** What `@` offers for the word being typed: the server's files, earlier attachments and pages, or an agent chat's device's files. */ + val mentions: List = emptyList(), ) /** @@ -104,9 +116,17 @@ data class Draft( /** The one tool a message may force (the server's `FORCEABLE_TOOLS`): make a picture. */ const val IMAGE_TOOL = "image_generate" -/** The model in force: the chat's, else the one chosen for the new chat, else the default. */ +/** + * The model in force: the chat's, else the one chosen for the new chat, else the folder's usual + * one (a new agent chat's, where the person still has it), else the default. A model the + * person picked is never set aside by the folder's. + */ val ChatState.modelId: String? - get() = chat?.model?.ifBlank { null } ?: draft.model ?: models.firstOrNull { it.default }?.id ?: models.firstOrNull()?.id + get() = chat?.model?.ifBlank { null } ?: draft.model ?: folderModel ?: models.firstOrNull { it.default }?.id ?: models.firstOrNull()?.id + +/** The folder's usual model for a chat not made yet, when it is one of the models offered here. */ +val ChatState.folderModel: String? + get() = start?.model?.takeIf { id -> chat == null && id.isNotBlank() && models.any { it.id == id } } val ChatState.modelInfo: ModelInfo? get() = models.firstOrNull { it.id == modelId } @@ -193,9 +213,18 @@ interface ChatActions { /** A new agent chat with no computer linked: read the linked devices again. */ fun recheckDevices() {} + + /** A new agent chat's device, asked for a directory (`""`: its places), for the folder picker. */ + suspend fun directories(path: String): DeviceDirectory = DeviceDirectory() fun setAgents(agents: AgentsSetting) {} fun updateDraft(change: (Draft) -> Draft) {} fun attach(uris: List) {} + + /** The `@` word being typed ([query]; null: none) -- what it offers comes to the state's `mentions`. */ + fun suggest(query: String?) {} + + /** Attach what an `@` entry names: an earlier attachment, a file of the tree, or a page. */ + fun mention(item: Mention) {} fun unattach(attachment: Attachment) {} fun photoTarget(): Uri? = null fun rename(title: String) {} @@ -233,20 +262,43 @@ class ChatViewModel(app: Application) : override fun clearUnsent() = _state.update { it.copy(unsent = null) } override fun updateDraft(change: (Draft) -> Draft) { - val before = _state.value.device?.id + val before = _state.value.let { it.device?.id to it.draft.directory } _state.update { it.copy(draft = change(it.draft)) } - if (agentChat && _state.value.chat == null && _state.value.device?.id != before) readAgentFacts() + val after = _state.value.let { it.device?.id to it.draft.directory } + // Another computer or another folder: its Subagents fact and its usual model are read again. + if (agentChat && _state.value.chat == null && after != before) readAgentFacts() } - /** A new agent chat's Subagents fact, for the device chosen now; an older server says nothing. */ + /** + * A new agent chat's facts for the device and folder chosen now: whether it may have + * subagents, and the model it starts on there. An older server says neither; an answer for + * a choice that has changed meanwhile is dropped. + */ private fun readAgentFacts() { val device = _state.value.device?.id + val directory = _state.value.draft.directory + // What was read for another device or folder is not this one's. + _state.update { it.copy(start = null) } viewModelScope.launch { - val facts = runCatching { api().agentModelList(device) }.getOrNull()?.agentSubagents - _state.update { if (it.device?.id == device) it.copy(agentSubagents = facts) else it } + val list = runCatching { api().agentModelList(device, directory) }.getOrNull() + _state.update { + if (it.device?.id == device && + it.draft.directory == directory + ) { + it.copy(agentSubagents = list?.agentSubagents, start = list?.start) + } else { + it + } + } } } + override suspend fun directories(path: String): DeviceDirectory { + // No computer linked: there is nothing to list, and the typed path is what remains. + val device = _state.value.device ?: return DeviceDirectory(code = "device_not_linked") + return api().deviceDirectories(device.id, path) + } + 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. */ @@ -623,6 +675,53 @@ class ChatViewModel(app: Application) : } } + private var suggesting: Job? = null + + override fun suggest(query: String?) { + suggesting?.cancel() + if (query == null) { + if (_state.value.mentions.isNotEmpty()) _state.update { it.copy(mentions = emptyList()) } + return + } + suggesting = viewModelScope.launch { + // Asked once the typing pauses, not at every letter. + delay(MENTION_PAUSE_MS) + val found = try { + offered(query) + } catch (e: CancellationException) { + throw e + } catch (_: Exception) { + // An older server, or a device that cannot answer: nothing is offered. + emptyList() + } + _state.update { it.copy(mentions = found) } + } + } + + /** An agent chat's `@` is its device's files (the device reads them); a chat's is the server's. */ + private suspend fun offered(query: String): List { + val now = _state.value + val chat = now.chat + if (chat?.kind == "agent" || (chat == null && agentChat)) { + val device = chat?.device?.tokenId ?: now.device?.id ?: return emptyList() + return api().deviceFiles(device, query, chatId = chat?.id, cwd = now.draft.directory).files.map { it.asMention() } + } + return api().mentions(query, chat?.id).items + } + + override fun mention(item: Mention) { + _state.update { it.copy(mentions = emptyList(), uploading = true) } + viewModelScope.launch { + try { + val stored = api().attachFrom(item, _state.value.chat?.id) + _state.update { it.copy(pending = it.pending + stored) } + } catch (e: Exception) { + fail(e) + } + _state.update { it.copy(uploading = false) } + } + } + private val photoAuthority get() = "${getApplication().packageName}.files" /** @@ -650,4 +749,8 @@ class ChatViewModel(app: Application) : } } } + + private companion object { + const val MENTION_PAUSE_MS = 250L + } } 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 index 668be64..aeab0d9 100644 --- a/app/src/main/java/eu/llembas/android/ui/chat/Composer.kt +++ b/app/src/main/java/eu/llembas/android/ui/chat/Composer.kt @@ -28,12 +28,16 @@ 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.foundation.verticalScroll 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.AttachFile import androidx.compose.material.icons.filled.Brush import androidx.compose.material.icons.filled.Close +import androidx.compose.material.icons.filled.Description import androidx.compose.material.icons.filled.Folder +import androidx.compose.material.icons.filled.Link import androidx.compose.material.icons.filled.Mic import androidx.compose.material.icons.filled.PhotoCamera import androidx.compose.material.icons.filled.PhotoLibrary @@ -51,7 +55,6 @@ import androidx.compose.material3.IconButtonDefaults import androidx.compose.material3.InputChip import androidx.compose.material3.LinearProgressIndicator import androidx.compose.material3.MaterialTheme -import androidx.compose.material3.OutlinedTextField import androidx.compose.material3.RangeSlider import androidx.compose.material3.SliderDefaults import androidx.compose.material3.Surface @@ -83,11 +86,13 @@ 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.api.Mention import eu.llembas.android.assist.PhoneRecognizer import eu.llembas.android.assist.Recorder import eu.llembas.android.assist.usePhoneRecognizer import eu.llembas.android.auth.Prefs import eu.llembas.android.lembas +import eu.llembas.android.ui.DirectoryPicker import eu.llembas.android.ui.theme.LocalPalette import kotlinx.coroutines.flow.first import kotlinx.coroutines.launch @@ -209,6 +214,7 @@ fun Composer(state: ChatState, actions: ChatActions, agent: Boolean, onTune: () } // A suggestion from the empty chat lands here (a new value each tap). LaunchedEffect(initial) { if (initial.isNotBlank()) text = initial } + LaunchedEffect(text) { actions.suggest(mentionQuery(text)) } val newAgent = agent && state.chat == null val canSend = (text.isNotBlank() || state.pending.isNotEmpty()) && !state.uploading && (!newAgent || state.device != null) val summary = tuneSummary(state, agent) @@ -262,6 +268,19 @@ fun Composer(state: ChatState, actions: ChatActions, agent: Boolean, onTune: () } } } + // What `@` offers for the word being typed, above the words: a tap attaches it (the + // server's files, earlier attachments, pages) or completes it (a device's file). + if (state.mentions.isNotEmpty() && mentionQuery(text) != null) { + MentionList(state.mentions) { item -> + if (item.kind == MENTION_DEVICE) { + text = withMention(text, item.path) + } else { + text = withoutMention(text) + actions.mention(item) + } + actions.suggest(null) + } + } TextField( value = text, onValueChange = { text = it }, @@ -419,6 +438,48 @@ fun Composer(state: ChatState, actions: ChatActions, agent: Boolean, onTune: () } } +/** + * The `@` list: at most a few rows in view, the rest scrolled to. A row is 48 dp; its name + * gives, and where it is (a path, a kind) is one quiet line under it. + */ +@Composable +private fun MentionList(items: List, onPick: (Mention) -> Unit) { + val palette = LocalPalette.current + Column(Modifier.fillMaxWidth().heightIn(max = 216.dp).verticalScroll(rememberScrollState()).padding(top = 8.dp)) { + items.forEach { item -> + Row( + Modifier.fillMaxWidth().clickable { onPick(item) }.heightIn(min = 48.dp).padding(horizontal = 16.dp, vertical = 6.dp), + verticalAlignment = Alignment.CenterVertically, + ) { + Icon( + when (item.kind) { + "url" -> Icons.Filled.Link + "attachment" -> Icons.Filled.AttachFile + else -> if (item.detail.endsWith("/")) Icons.Filled.Folder else Icons.Filled.Description + }, + contentDescription = null, + tint = palette.inkMuted, + modifier = Modifier.size(20.dp), + ) + Spacer(Modifier.width(12.dp)) + Column(Modifier.weight(1f)) { + Text( + item.name.ifBlank { + item.path.ifBlank { item.url } + }, + style = MaterialTheme.typography.bodyMedium, + maxLines = 1, + overflow = TextOverflow.Ellipsis, + ) + if (item.detail.isNotBlank() && item.detail != item.name) { + Text(item.detail, style = MaterialTheme.typography.bodySmall, color = palette.inkFaint, maxLines = 1, overflow = TextOverflow.Ellipsis) + } + } + } + } + } +} + // --- The tune sheet -------------------------------------------------------------------------- /** @@ -549,26 +610,15 @@ fun TuneContent(state: ChatState, actions: ChatActions, agent: Boolean, modifier } 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(), - ) + DirectoryPicker( + title = stringResource(R.string.agent_directory), + initial = state.draft.directory, + load = actions::directories, + onPick = { path -> + actions.updateDraft { it.copy(directory = path) } + askDirectory = false }, - 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)) } }, + onDismiss = { askDirectory = false }, ) } } diff --git a/app/src/main/java/eu/llembas/android/ui/chat/Mentions.kt b/app/src/main/java/eu/llembas/android/ui/chat/Mentions.kt new file mode 100644 index 0000000..bab70f7 --- /dev/null +++ b/app/src/main/java/eu/llembas/android/ui/chat/Mentions.kt @@ -0,0 +1,31 @@ +package eu.llembas.android.ui.chat + +import eu.llembas.android.api.DeviceFile +import eu.llembas.android.api.Mention + +// The composer's `@`: what is being asked for is the `@word` the text ends with. The field's +// cursor is not followed -- a mention is offered for what is typed last, which is where typing +// on a phone is. + +/** A file on a linked device, as the `@` list holds it beside the server's kinds: put into the text as `@path`, never attached. */ +const val MENTION_DEVICE = "device" + +/** + * The `@` word [text] ends with, without the `@` (empty right after it), or null when it ends + * with none: the `@` must open a word (so an e-mail address is not one), and the word holds no + * space yet. + */ +fun mentionQuery(text: String): String? { + val at = text.lastIndexOf('@') + if (at < 0 || (at > 0 && !text[at - 1].isWhitespace())) return null + return text.substring(at + 1).takeIf { word -> word.none { it.isWhitespace() } } +} + +/** [text] without the `@word` it ends with: what stays when the mention became an attachment. */ +fun withoutMention(text: String): String = if (mentionQuery(text) == null) text else text.substring(0, text.lastIndexOf('@')) + +/** [text] with the `@word` it ends with made `@path` and a space: a device's file, which the device reads. */ +fun withMention(text: String, path: String): String = if (mentionQuery(text) == null) text else text.substring(0, text.lastIndexOf('@')) + "@" + path + " " + +/** A device's file as an entry of the `@` list: its name, and its path as the detail. */ +fun DeviceFile.asMention(): Mention = Mention(kind = MENTION_DEVICE, path = path, name = name.ifBlank { path }, detail = if (kind == "dir") "$path/" else path) 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 index c177c96..9dc0baa 100644 --- a/app/src/main/java/eu/llembas/android/ui/scheduled/ScheduledScreens.kt +++ b/app/src/main/java/eu/llembas/android/ui/scheduled/ScheduledScreens.kt @@ -8,6 +8,8 @@ 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.ExperimentalLayoutApi +import androidx.compose.foundation.layout.FlowRow import androidx.compose.foundation.layout.PaddingValues import androidx.compose.foundation.layout.Row import androidx.compose.foundation.layout.Spacer @@ -24,6 +26,7 @@ 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.text.KeyboardOptions import androidx.compose.foundation.verticalScroll import androidx.compose.material.icons.Icons import androidx.compose.material.icons.automirrored.filled.ArrowBack @@ -31,6 +34,7 @@ import androidx.compose.material.icons.filled.Add import androidx.compose.material.icons.filled.Computer import androidx.compose.material.icons.filled.Delete import androidx.compose.material.icons.filled.Edit +import androidx.compose.material.icons.filled.Folder import androidx.compose.material.icons.filled.Pause import androidx.compose.material.icons.filled.PlayArrow import androidx.compose.material.icons.filled.Schedule @@ -41,6 +45,7 @@ import androidx.compose.material3.Button import androidx.compose.material3.CircularProgressIndicator import androidx.compose.material3.ExtendedFloatingActionButton import androidx.compose.material3.FilledTonalButton +import androidx.compose.material3.FilterChip import androidx.compose.material3.Icon import androidx.compose.material3.IconButton import androidx.compose.material3.MaterialTheme @@ -68,6 +73,7 @@ import androidx.compose.ui.Modifier import androidx.compose.ui.draw.clip import androidx.compose.ui.graphics.Color import androidx.compose.ui.res.stringResource +import androidx.compose.ui.text.input.KeyboardType import androidx.compose.ui.text.style.TextAlign import androidx.compose.ui.text.style.TextOverflow import androidx.compose.ui.unit.dp @@ -79,16 +85,23 @@ 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.DeviceDirectory import eu.llembas.android.api.LembasJson +import eu.llembas.android.api.LinkedDevice +import eu.llembas.android.api.RanOn import eu.llembas.android.api.RunsOn import eu.llembas.android.api.Schedule import eu.llembas.android.api.ScheduleCompiled import eu.llembas.android.api.ScheduleRun import eu.llembas.android.api.SchedulesFrame +import eu.llembas.android.api.SchedulingModel import eu.llembas.android.api.StreamClient +import eu.llembas.android.api.WhereToRun +import eu.llembas.android.api.agentic import eu.llembas.android.api.computerAway import eu.llembas.android.api.notifyChoice import eu.llembas.android.lembas +import eu.llembas.android.ui.DirectoryPicker import eu.llembas.android.ui.explain import eu.llembas.android.ui.progressLineOf import eu.llembas.android.ui.theme.LocalPalette @@ -541,7 +554,14 @@ private fun ScheduleBody( } Text(schedule.instruction, style = MaterialTheme.typography.bodyMedium) val facts = listOfNotNull( - schedule.model?.takeIf { it.isNotBlank() }?.let { stringResource(R.string.schedule_model, it) }, + stringResource(R.string.schedule_type) + ": " + + stringResource(if (schedule.agentic) R.string.schedule_agentic else R.string.schedule_chat), + // An Agentic schedule with no model of its own runs on the folder's usual one. + stringResource( + R.string.schedule_model, + schedule.model?.takeIf { it.isNotBlank() } + ?: stringResource(if (schedule.agentic) R.string.schedule_folder_model else R.string.schedule_first_free_model), + ), modeWords(schedule.mode), notifyWords(schedule), ) @@ -663,6 +683,23 @@ private fun ComputerLine(on: RunsOn, away: Boolean) { } } +/** A run's own line for where it ran: the computer and the folder there. The folder gives first. */ +@Composable +private fun RanOnLine(on: RanOn) { + val palette = LocalPalette.current + Row(verticalAlignment = Alignment.CenterVertically) { + Icon(Icons.Filled.Computer, contentDescription = stringResource(R.string.schedule_computer), tint = palette.inkFaint, modifier = Modifier.size(14.dp)) + Spacer(Modifier.width(4.dp)) + Text( + listOf(on.deviceName.ifBlank { stringResource(R.string.schedule_computer_gone) }, on.cwd).filter { it.isNotBlank() }.joinToString(" · "), + style = MaterialTheme.typography.bodySmall, + color = palette.inkMuted, + maxLines = 2, + overflow = TextOverflow.Ellipsis, + ) + } +} + /** A run row's line: the computer's name, and "not linked now" when the run found it away. */ @Composable private fun ComputerName(on: RunsOn, away: Boolean) { @@ -729,8 +766,13 @@ private fun RunRow(run: ScheduleRun, runsOn: RunsOn?, onOpen: () -> Unit, onOpen Box(Modifier.width(112.dp)) { StatusChip(run.status, run.missed, run.waitingFor) } Column(Modifier.weight(1f), verticalArrangement = Arrangement.spacedBy(2.dp)) { Text(ScheduleLogic.moment(run.startedAt ?: run.dueAt) ?: "—", style = MaterialTheme.typography.bodyMedium) - // Which computer the run was for, and whether it was away. - runsOn?.let { on -> ComputerName(on, away = run.computerAway) } + // Where the run ran (its own word, spec 3.9.0), else which computer it was for -- + // and whether that was away. + val ran = run.ranOn?.takeIf { it.device.isNotBlank() } + when { + ran != null -> RanOnLine(ran) + runsOn != null -> ComputerName(runsOn, away = run.computerAway) + } RunFacts(run, maxLines = 2) run.reportId?.let { report -> ReportLink(onClick = { onOpenReport(report) }) } } @@ -758,9 +800,11 @@ internal fun RunFacts(run: ScheduleRun, maxLines: Int = Int.MAX_VALUE, withPrevi val palette = LocalPalette.current val name = run.model.label val from = run.model.switchedFrom + val why = runModelWhy(run.model.reason) val model = when { name == null -> null run.model.reason == "switched" && from != null -> stringResource(R.string.run_model_instead, name, from) + why != null -> name + " · " + stringResource(why) else -> name } model?.let { Text(it, style = MaterialTheme.typography.bodySmall, color = palette.inkMuted, maxLines = 1, overflow = TextOverflow.Ellipsis) } @@ -788,6 +832,18 @@ internal fun RunFacts(run: ScheduleRun, maxLines: Int = Int.MAX_VALUE, withPrevi } } +/** + * How a run's model was chosen, where that is worth a word (spec 3.9.0): the folder's usual + * one, the person's default where the folder had none, or a continued conversation's own. A + * pinned model needs none, and a switched one has its own sentence. + */ +fun runModelWhy(reason: String?): Int? = when (reason) { + "directory" -> R.string.run_model_directory + "default" -> R.string.run_model_default + "session" -> R.string.run_model_session + else -> null +} + // --- Create and edit ------------------------------------------------------------------------ data class EditState( @@ -809,8 +865,77 @@ data class EditState( val loadFailed: Boolean = false, /** The person chose a "notify when" themselves. */ val notifyTouched: Boolean = false, + /** The type (spec 3.9.0): Agentic runs on [device], in [cwd]; Chat on the server. */ + val agentic: Boolean = false, + /** The linked computers, and -- for a schedule being edited -- its own, linked now or not. */ + val devices: List = emptyList(), + val device: String = "", + val cwd: String = "", + /** The agent's mode on the computer: `manual`, `edit` or `auto`. */ + val agentMode: String = "edit", + /** How long an approval waits, in minutes, as typed; empty: the instance's own. */ + val wait: String = "", + /** An Agentic schedule's model; empty: the folder's usual model. */ + val model: String = "", + /** The models scheduled work may run on (`GET /schedules/models`): never an interactive-only one. */ + val models: List = emptyList(), + /** The person changed the type or one of its fields themselves. */ + val whereTouched: Boolean = false, + /** What the schedule being edited was when it was read: Agentic or Chat. */ + val wasAgentic: Boolean = false, ) +/** Agentic is offered only while one of the person's computers accepts scheduled work. */ +val EditState.agenticOffered: Boolean get() = devices.any { it.scheduled } + +/** The computer chosen, when it is one of those listed. */ +val EditState.chosenDevice: LinkedDevice? get() = devices.firstOrNull { it.id == device } + +/** An approval's wait as a number of minutes, or null for the instance's own (empty, or not a number). */ +val EditState.waitMinutes: Int? get() = wait.trim().toIntOrNull()?.takeIf { it > 0 } + +/** What an Agentic schedule still lacks before it can be saved: a computer and a full path. */ +val EditState.whereComplete: Boolean get() = !agentic || (device.isNotBlank() && cwd.isNotBlank()) + +/** + * Where a save says the schedule runs -- its type. A new schedule says a computer when it is + * Agentic and nothing otherwise (the server's own default is Chat). An edit says something only + * for what the form knows: nothing where the schedule could not be read, or was read and left + * alone as a Chat schedule; the computer for an Agentic one; and "the server" only when an + * Agentic schedule was made a Chat one. + */ +fun whereToSend(state: EditState, editing: Boolean): WhereToRun = when { + editing && !state.loaded -> WhereToRun.Leave + state.agentic -> WhereToRun.Computer(state.device, state.cwd.trim(), state.agentMode, state.waitMinutes, state.model) + editing && state.wasAgentic -> WhereToRun.Server + else -> WhereToRun.Leave +} + +/** A schedule as the form holds where it runs; what the person changed meanwhile stays changed. */ +fun EditState.read(s: Schedule): EditState { + val on = s.runsOn + val known = devices.any { it.id == on?.device } + return copy( + wasAgentic = on != null, + // Its own computer is in the list also when it is not linked now, so it can stay chosen. + devices = if (on == null || known) devices else devices + LinkedDevice(id = on.device, name = on.deviceName), + agentic = if (whereTouched) agentic else on != null, + device = if (whereTouched || on == null) device else on.device, + cwd = if (whereTouched || on == null) cwd else on.cwd, + agentMode = if (whereTouched || on == null) agentMode else on.mode.ifBlank { agentMode }, + wait = if (whereTouched || on == null) wait else on.approvalWaitMinutes?.toString().orEmpty(), + model = if (whereTouched || on == null) model else s.model.orEmpty(), + ) +} + +/** The linked computers as the form lists them, keeping a schedule's own that is not among them. */ +fun EditState.listed(linked: List): EditState { + val own = devices.filter { mine -> linked.none { it.id == mine.id } && mine.id == device } + val all = linked + own + // A new Agentic schedule starts on the first computer that accepts scheduled work. + return copy(devices = all, device = device.ifBlank { all.firstOrNull { it.scheduled }?.id.orEmpty() }) +} + /** * The `notify` a save sends, or null for none: only to an instance with Reports, and when * [editing] only what the form really knows -- the schedule's own value once it was read, or the @@ -841,11 +966,19 @@ class ScheduleEditViewModel(app: Application) : AndroidViewModel(app) { val has = runCatching { getApplication().api().reports(unread = true) }.isSuccess _state.update { it.copy(reports = has) } } + // The type's choices: the computers (Agentic is offered while one accepts scheduled + // work) and the models a schedule may run on. Either may be missing on an older server. + viewModelScope.launch { + runCatching { getApplication().api().devices() }.onSuccess { linked -> _state.update { it.listed(linked) } } + } + viewModelScope.launch { + runCatching { getApplication().api().schedulingModels() }.onSuccess { m -> _state.update { it.copy(models = m.models) } } + } if (id == null) return viewModelScope.launch { runCatching { getApplication().api().schedule(id) }.onSuccess { s -> _state.update { - it.copy( + it.read(s).copy( words = s.request.ifBlank { s.instruction }, // What the person chose while it was read stays chosen. notify = if (it.notifyTouched) it.notify else notifyChoice(s.notify), @@ -867,6 +1000,15 @@ class ScheduleEditViewModel(app: Application) : AndroidViewModel(app) { fun notifyWhen(text: String) = _state.update { it.copy(notifyWhen = text, notifyTouched = true) } + /** A change to the type or one of its fields: the person's, so a schedule read later does not undo it. */ + fun where(change: (EditState) -> EditState) = _state.update { change(it).copy(whereTouched = true, error = null) } + + /** The chosen computer, asked for a directory (`""`: its places), for the folder picker. */ + suspend fun directories(path: String): DeviceDirectory { + val device = _state.value.device.ifBlank { return DeviceDirectory(code = "device_not_linked") } + return getApplication().api().deviceDirectories(device, path) + } + /** The server reads the words: the title, the instruction, the rule and the next runs. */ fun preview() { val words = _state.value.words.trim() @@ -896,6 +1038,7 @@ class ScheduleEditViewModel(app: Application) : AndroidViewModel(app) { editing, notify = notifyToSend(now, editing = editing != null), notifyWhen = now.notifyWhen, + where = whereToSend(now, editing = editing != null), ) then(saved.id) } catch (e: Exception) { @@ -923,6 +1066,8 @@ fun ScheduleEditScreen( onSave = { model.save(onSaved) }, onNotify = model::notify, onNotifyWhen = model::notifyWhen, + onWhere = model::where, + directories = model::directories, ) } @@ -942,6 +1087,8 @@ fun ScheduleEditContent( onSave: () -> Unit = {}, onNotify: (String) -> Unit = {}, onNotifyWhen: (String) -> Unit = {}, + onWhere: ((EditState) -> EditState) -> Unit = {}, + directories: suspend (String) -> DeviceDirectory = { DeviceDirectory() }, ) { val palette = LocalPalette.current Scaffold( @@ -951,7 +1098,7 @@ fun ScheduleEditContent( Box(Modifier.background(palette.bg).navigationBarsPadding().imePadding().padding(16.dp)) { Button( onClick = onSave, - enabled = state.compiled?.savable == true && !state.saving && !state.loadFailed, + enabled = state.compiled?.savable == true && !state.saving && !state.loadFailed && state.whereComplete, modifier = Modifier.fillMaxWidth().heightIn(min = 52.dp), ) { Text(stringResource(R.string.save)) } } @@ -961,6 +1108,9 @@ fun ScheduleEditContent( Modifier.fillMaxSize().padding(padding).verticalScroll(rememberScrollState()).padding(horizontal = 16.dp), verticalArrangement = Arrangement.spacedBy(12.dp), ) { + // The type comes first: it decides where the task runs and what else the form asks. + TypeChoice(state, onWhere) + if (state.agentic) OnComputer(state, onWhere, directories) Text(stringResource(R.string.schedule_words_hint), style = MaterialTheme.typography.bodyMedium, color = palette.inkMuted) OutlinedTextField( value = state.words, @@ -990,6 +1140,198 @@ fun ScheduleEditContent( } } +/** + * The type (spec 3.9.0): Chat runs on the server, Agentic on one of the person's computers, each + * with one line saying what that means. Agentic cannot be chosen while no computer accepts + * scheduled work, and says so; one that is Agentic already stays shown as it is. + */ +@Composable +private fun TypeChoice(state: EditState, onWhere: ((EditState) -> EditState) -> Unit) { + val palette = LocalPalette.current + val offered = state.agenticOffered || state.agentic + Surface(shape = RoundedCornerShape(20.dp), color = palette.surfaceRaised, contentColor = palette.ink, modifier = Modifier.fillMaxWidth()) { + Column(Modifier.padding(vertical = 12.dp)) { + Text( + stringResource(R.string.schedule_type), + style = MaterialTheme.typography.labelLarge, + color = palette.accent, + modifier = Modifier.padding(horizontal = 16.dp), + ) + ChoiceRow( + selected = !state.agentic, + title = stringResource(R.string.schedule_chat), + line = stringResource(R.string.schedule_chat_line), + onClick = { onWhere { it.copy(agentic = false) } }, + ) + ChoiceRow( + selected = state.agentic, + enabled = offered, + title = stringResource(R.string.schedule_agentic), + line = stringResource(if (offered) R.string.schedule_agentic_line else R.string.schedule_agentic_unavailable), + onClick = { onWhere { it.copy(agentic = true) } }, + ) + } + } +} + +/** One choice of a few: the radio button keeps its size, the words give. The whole row is the target. */ +@Composable +private fun ChoiceRow(selected: Boolean, title: String, line: String?, onClick: () -> Unit, enabled: Boolean = true) { + val palette = LocalPalette.current + Row( + Modifier.fillMaxWidth().clickable( + enabled = enabled, + onClick = onClick, + ).heightIn(min = 56.dp).padding(start = 4.dp, end = 16.dp, top = 4.dp, bottom = 4.dp), + verticalAlignment = Alignment.CenterVertically, + ) { + RadioButton(selected = selected, onClick = onClick, enabled = enabled) + Column(Modifier.weight(1f)) { + Text(title, style = MaterialTheme.typography.bodyLarge, color = if (enabled) palette.ink else palette.inkFaint) + line?.let { Text(it, style = MaterialTheme.typography.bodySmall, color = palette.inkMuted) } + } + } +} + +/** + * An Agentic schedule's own fields: the computer, the folder there (the picker, or a typed + * path), the mode, how long an approval waits, and the model -- the folder's usual one unless + * another is chosen. + */ +@OptIn(ExperimentalLayoutApi::class) +@Composable +private fun OnComputer(state: EditState, onWhere: ((EditState) -> EditState) -> Unit, directories: suspend (String) -> DeviceDirectory) { + val palette = LocalPalette.current + var browsing by remember { mutableStateOf(false) } + var choosingModel by remember { mutableStateOf(false) } + Surface(shape = RoundedCornerShape(20.dp), color = palette.surfaceRaised, contentColor = palette.ink, modifier = Modifier.fillMaxWidth()) { + Column(Modifier.padding(vertical = 12.dp)) { + FieldLabel(stringResource(R.string.schedule_computer)) + state.devices.forEach { d -> + // A computer that does not accept scheduled work cannot be chosen; the one the + // schedule already has stays shown, whatever it says now. + val mine = d.id == state.device + ChoiceRow( + selected = mine, + enabled = d.scheduled || mine, + title = d.label, + line = if (d.scheduled) null else stringResource(R.string.schedule_computer_refuses), + onClick = { onWhere { it.copy(device = d.id) } }, + ) + } + Text( + stringResource(R.string.schedule_computer_hint), + style = MaterialTheme.typography.bodySmall, + color = palette.inkMuted, + modifier = Modifier.padding(horizontal = 16.dp), + ) + + FieldLabel(stringResource(R.string.schedule_folder)) + Row(Modifier.fillMaxWidth().padding(horizontal = 16.dp), verticalAlignment = Alignment.CenterVertically) { + OutlinedTextField( + value = state.cwd, + onValueChange = { text -> onWhere { it.copy(cwd = text) } }, + singleLine = true, + placeholder = { Text(stringResource(R.string.directory_path)) }, + shape = RoundedCornerShape(16.dp), + modifier = Modifier.weight(1f), + ) + Spacer(Modifier.width(8.dp)) + IconButton(onClick = { browsing = true }, enabled = state.device.isNotBlank()) { + Icon(Icons.Filled.Folder, contentDescription = stringResource(R.string.directory_browse), tint = palette.accent) + } + } + + FieldLabel(stringResource(R.string.schedule_agent_mode)) + FlowRow(Modifier.padding(horizontal = 16.dp), horizontalArrangement = Arrangement.spacedBy(8.dp)) { + listOf("manual" to R.string.mode_manual, "edit" to R.string.mode_edit, "auto" to R.string.mode_auto).forEach { (value, name) -> + FilterChip(selected = state.agentMode == value, onClick = { + onWhere { it.copy(agentMode = value) } + }, label = { Text(stringResource(name)) }) + } + } + Text( + stringResource(R.string.schedule_agent_mode_hint), + style = MaterialTheme.typography.bodySmall, + color = palette.inkMuted, + modifier = Modifier.padding(horizontal = 16.dp), + ) + + FieldLabel(stringResource(R.string.schedule_approval_wait)) + OutlinedTextField( + value = state.wait, + onValueChange = { text -> onWhere { it.copy(wait = text.filter(Char::isDigit).take(4)) } }, + singleLine = true, + keyboardOptions = KeyboardOptions(keyboardType = KeyboardType.Number), + supportingText = { Text(stringResource(R.string.schedule_approval_wait_hint)) }, + shape = RoundedCornerShape(16.dp), + modifier = Modifier.fillMaxWidth().padding(horizontal = 16.dp), + ) + + FieldLabel(stringResource(R.string.model)) + Row( + Modifier.fillMaxWidth().clickable { choosingModel = true }.heightIn(min = 56.dp).padding(horizontal = 16.dp, vertical = 8.dp), + verticalAlignment = Alignment.CenterVertically, + ) { + Column(Modifier.weight(1f)) { + Text( + state.models.firstOrNull { it.id == state.model }?.let { it.name.ifBlank { it.id } } + ?: state.model.ifBlank { stringResource(R.string.schedule_folder_model) }, + style = MaterialTheme.typography.bodyLarge, + ) + Text(stringResource(R.string.schedule_folder_model_hint), style = MaterialTheme.typography.bodySmall, color = palette.inkMuted) + } + Spacer(Modifier.width(12.dp)) + Icon(Icons.Filled.Tune, contentDescription = null, tint = palette.inkMuted) + } + } + } + if (browsing) { + DirectoryPicker( + title = state.chosenDevice?.label ?: stringResource(R.string.schedule_folder), + initial = state.cwd, + load = directories, + onPick = { path -> + onWhere { it.copy(cwd = path) } + browsing = false + }, + onDismiss = { browsing = false }, + ) + } + if (choosingModel) { + AlertDialog( + onDismissRequest = { choosingModel = false }, + title = { Text(stringResource(R.string.model)) }, + text = { + Column(Modifier.verticalScroll(rememberScrollState())) { + val pick: (String) -> Unit = { id -> + onWhere { it.copy(model = id) } + choosingModel = false + } + ChoiceRow(selected = state.model.isBlank(), title = stringResource(R.string.schedule_folder_model), line = null, onClick = { pick("") }) + // The schedule's own model stays offered where the instance no longer lists it: the server says why on Save. + val own = state.model.takeIf { m -> m.isNotBlank() && state.models.none { it.id == m } } + own?.let { ChoiceRow(selected = true, title = it, line = null, onClick = { pick(it) }) } + state.models.forEach { m -> + ChoiceRow(selected = state.model == m.id, title = m.name.ifBlank { m.id }, line = null, onClick = { pick(m.id) }) + } + } + }, + confirmButton = { TextButton(onClick = { choosingModel = false }) { Text(stringResource(R.string.cancel)) } }, + ) + } +} + +@Composable +private fun FieldLabel(text: String) { + Text( + text, + style = MaterialTheme.typography.labelLarge, + color = LocalPalette.current.accent, + modifier = Modifier.padding(start = 16.dp, end = 16.dp, top = 16.dp, bottom = 4.dp), + ) +} + /** * Notify when: every run, when the person's own words hold, or never -- each with one line * saying what it does. A report is what tells the person; a run without one is a line in the diff --git a/app/src/main/res/values-cs/strings.xml b/app/src/main/res/values-cs/strings.xml index 312be28..2c432b3 100644 --- a/app/src/main/res/values-cs/strings.xml +++ b/app/src/main/res/values-cs/strings.xml @@ -565,6 +565,39 @@ Podívejte se na tohle. Co s tím má LLeMbas udělat? (nepovinné) Zeptejte se na cokoli + Místa na tomto zařízení + Naposledy zde použitý: %1$s. Nový chat v této složce začne na něm, pokud nevyberete jiný. + Zařízení tu relaci neotevře. + O úroveň výš + Všechna místa + Na zařízení není důvěryhodné + Nejsou tu žádné složky. + Toto zařízení nenabízí žádné složky: jeho vzdálené kořeny jsou prázdné nebo chybějí. + Procházet + Úplná cesta + Vybrat + Adresáře tohoto zařízení teď nelze vypsat. Napište cestu níže. + Model + Typ + Konverzace + Běží na tomto serveru jako chat: s nástroji serveru (vyhledávání, vaše soubory zde, paměť) a na modelu určeném pro plánování. + Agentní + Běží na jednom z vašich počítačů, v jedné složce na něm, jako agent: s nástroji agenta na tom počítači — jeho soubory a jeho shellem — v rámci vlastních omezení počítače. Patří k tomu počítači a složce. + Žádný z vašich počítačů teď nepřijímá naplánovanou práci. Propojte některý a zapněte „Accept scheduled work“ v jeho LLeMbas CLI (lembas service scheduled on). + nepřijímá plánovanou práci + Počítač to musí povolit: „Accept scheduled work“ v jeho LLeMbas CLI (lembas service scheduled on). Když v čase spuštění není propojen, spuštění na něj počká; pokud se nevrátí, než čas spuštění uplyne, spuštění se zaznamená jako zmeškané a dozvíte se o tom. + počítač, který už není přihlášen + Složka na počítači + Režim + Edit, pokud nezvolíte jinak; Auto spouští příkazy bez ptaní. Počítač ho může snížit. + Schválení čeká (minuty) + Příkaz, který spuštění potřebuje schválit, přijde do telefonu jako karta. Pokud do té doby nebude zodpovězen, počítá se jako zamítnutý. + Obvyklý model složky + Obvyklý model složky je ten, který jste v té složce na tom počítači použili naposledy — počítač si ho pamatuje a každé spuštění se ho na něj zeptá — nebo váš výchozí model, pokud žádný není. Model vybraný zde je modelem spuštění, ať je model složky jakýkoli. Spuštění nikdy nemění model složky. + První volný z vašich modelů pro plánování + obvyklý model složky + váš výchozí model + vlastní model konverzace Mluvit Ptejte se hlasem nebo textem, nebo pokračujte v poslední konverzaci s asistentem. Neukazuje nic z vašeho účtu. Poslední chat diff --git a/app/src/main/res/values-de/strings.xml b/app/src/main/res/values-de/strings.xml index 13809b0..b4846d1 100644 --- a/app/src/main/res/values-de/strings.xml +++ b/app/src/main/res/values-de/strings.xml @@ -565,6 +565,39 @@ Schauen Sie sich das an. Was soll LLeMbas damit tun? (optional) Frag mich alles + Orte auf diesem Gerät + Hier zuletzt verwendet: %1$s. Ein neuer Chat in diesem Verzeichnis beginnt damit, sofern Sie kein anderes wählen. + Das Gerät öffnet hier keine Sitzung. + Eine Ebene höher + Alle Orte + Auf dem Gerät nicht vertrauenswürdig + Hier gibt es keine Ordner. + Dieses Gerät bietet keine Ordner an: Seine Remote-Wurzeln sind leer oder fehlen. + Durchsuchen + Ein vollständiger Pfad + Auswählen + Die Verzeichnisse dieses Geräts können gerade nicht aufgelistet werden. Geben Sie den Pfad unten ein. + Modell + Typ + Chat + Läuft auf diesem Server wie ein Chat: mit den Werkzeugen des Servers (Suche, Ihre Dateien hier, Gedächtnis) und auf einem Planungsmodell. + Agentisch + Läuft auf einem Ihrer Computer, in einem Ordner dort, als Agent: mit den Werkzeugen des Agenten auf diesem Computer — seinen Dateien und seiner Shell — innerhalb der eigenen Grenzen des Computers. Er gehört zu diesem Computer und Ordner. + Keiner Ihrer Computer nimmt jetzt geplante Arbeit an. Verbinden Sie einen und schalten Sie „Accept scheduled work“ in seinem LLeMbas CLI ein (lembas service scheduled on). + nimmt keine geplante Arbeit an + Der Computer muss es erlauben: „Accept scheduled work“ in seinem LLeMbas CLI (lembas service scheduled on). Ist er zur Zeit eines Laufs nicht verbunden, wartet der Lauf auf ihn; ist er nicht zurück, bevor die Zeit des Laufs vorbei ist, wird der Lauf als verpasst vermerkt und Sie erfahren es. + ein Computer, der nicht mehr angemeldet ist + Ordner auf dem Computer + Modus + Edit, sofern Sie nichts anderes wählen; Auto führt Befehle ohne Nachfrage aus. Der Computer kann ihn herabsetzen. + Eine Genehmigung wartet (Minuten) + Ein Befehl, den der Lauf genehmigt braucht, kommt als Karte auf Ihr Telefon. Bis dahin unbeantwortet, gilt er als abgelehnt. + Das übliche Modell des Ordners + Das übliche Modell des Ordners ist das, das Sie in diesem Ordner auf diesem Computer zuletzt verwendet haben — der Computer merkt es sich, und jeder Lauf fragt ihn danach — oder Ihr Standardmodell, wo es keines gibt. Ein hier gewähltes Modell ist das des Laufs, was auch immer das des Ordners ist. Ein Lauf ändert das Modell des Ordners nie. + Das erste freie Ihrer Modelle für geplante Aufgaben + das übliche Modell des Ordners + Ihr Standardmodell + das eigene Modell der Unterhaltung Sprechen Per Sprache oder Text fragen oder den letzten Assistenten-Chat fortsetzen. Zeigt nichts aus Ihrem Konto. Letzter Chat diff --git a/app/src/main/res/values-es/strings.xml b/app/src/main/res/values-es/strings.xml index 7b56060..fdba544 100644 --- a/app/src/main/res/values-es/strings.xml +++ b/app/src/main/res/values-es/strings.xml @@ -565,6 +565,39 @@ Échele un vistazo a esto. ¿Qué debe hacer LLeMbas con esto? (opcional) Pregunta lo que quieras + Lugares de este dispositivo + Último usado aquí: %1$s. Un chat nuevo en este directorio empieza con él salvo que elija otro. + El dispositivo no abrirá una sesión aquí. + Subir un nivel + Todos los lugares + No es de confianza en el dispositivo + Aquí no hay carpetas. + Este dispositivo no ofrece carpetas: sus raíces remotas están vacías o no existen. + Examinar + Una ruta completa + Elegir + Ahora no se pueden listar las carpetas de este dispositivo. Escriba la ruta abajo. + Modelo + Tipo + Chat + Se ejecuta en este servidor, como un chat: con las herramientas del servidor (búsqueda, sus archivos aquí, memoria) y en un modelo de programación. + Agéntico + Se ejecuta en uno de sus ordenadores, en una carpeta de él, como agente: con las herramientas del agente en ese ordenador — sus archivos y su shell — dentro de los límites propios del ordenador. Pertenece a ese ordenador y a esa carpeta. + Ninguno de sus ordenadores acepta trabajo programado ahora. Vincule uno y active «Accept scheduled work» en su LLeMbas CLI (lembas service scheduled on). + no acepta trabajo programado + El ordenador debe permitirlo: «Accept scheduled work» en su LLeMbas CLI (lembas service scheduled on). Si no está vinculado en el momento de una ejecución, la ejecución lo espera; si no ha vuelto antes de que pase su hora, la ejecución se registra como perdida y se le avisa. + un ordenador que ya no tiene sesión iniciada + Carpeta en el ordenador + Modo + Edit salvo que elijas otro; Auto ejecuta comandos sin preguntar. El ordenador puede rebajarlo. + Una aprobación espera (minutos) + Un comando que la ejecución necesita aprobar llega a tu teléfono como tarjeta. Sin respuesta para entonces, cuenta como denegado. + El modelo habitual de la carpeta + El modelo habitual de la carpeta es el último que usó en esa carpeta de ese ordenador — el ordenador lo recuerda y cada ejecución se lo pregunta — o su modelo predeterminado donde no hay ninguno. Un modelo elegido aquí es el de la ejecución, sea cual sea el de la carpeta. Una ejecución nunca cambia el modelo de la carpeta. + El primero libre de sus modelos para programación + el modelo habitual de la carpeta + su modelo predeterminado + el modelo propio de la conversación Hablar Pregunta por voz o por texto, o continúa el último chat del asistente. No muestra nada de tu cuenta. Último chat diff --git a/app/src/main/res/values-fr/strings.xml b/app/src/main/res/values-fr/strings.xml index 3a24d0f..09714a6 100644 --- a/app/src/main/res/values-fr/strings.xml +++ b/app/src/main/res/values-fr/strings.xml @@ -565,6 +565,39 @@ Jetez un œil à ceci. Que doit en faire LLeMbas ? (facultatif) Posez une question + Emplacements sur cet appareil + Dernier utilisé ici : %1$s. Une nouvelle conversation dans ce dossier commence avec lui, sauf si vous en choisissez un autre. + L\'appareil n\'ouvrira pas de session ici. + Remonter d\'un niveau + Tous les emplacements + Non approuvé sur l\'appareil + Aucun dossier ici. + Cet appareil ne propose aucun dossier : ses racines distantes sont vides ou absentes. + Parcourir + Un chemin complet + Choisir + Les dossiers de cet appareil ne peuvent pas être listés pour le moment. Saisissez le chemin ci-dessous. + Modèle + Type + Conversation + S\'exécute sur ce serveur, comme une conversation : avec les outils du serveur (recherche, vos fichiers ici, mémoire) et sur un modèle de planification. + Agentique + S\'exécute sur l\'un de vos ordinateurs, dans un dossier de celui-ci, en tant qu\'agent : avec les outils de l\'agent sur cet ordinateur — ses fichiers et son shell — dans les limites propres à l\'ordinateur. Elle appartient à cet ordinateur et à ce dossier. + Aucun de vos ordinateurs n\'accepte de travail planifié pour l\'instant. Reliez-en un et activez « Accept scheduled work » dans son LLeMbas CLI (lembas service scheduled on). + n’accepte pas le travail planifié + L\'ordinateur doit l\'autoriser : « Accept scheduled work » dans son LLeMbas CLI (lembas service scheduled on). S\'il n\'est pas relié au moment d\'une exécution, l\'exécution l\'attend ; s\'il n\'est pas revenu avant que son heure soit passée, l\'exécution est enregistrée comme manquée et vous en êtes informé. + un ordinateur qui n’est plus connecté + Dossier sur l’ordinateur + Mode + Edit sauf choix contraire ; Auto exécute les commandes sans demander. L’ordinateur peut l’abaisser. + Une approbation attend (minutes) + Une commande que l’exécution doit faire approuver arrive sur votre téléphone sous forme de carte. Sans réponse d’ici là, elle compte comme refusée. + Le modèle habituel du dossier + Le modèle habituel du dossier est celui que vous avez utilisé en dernier dans ce dossier sur cet ordinateur — l\'ordinateur s\'en souvient et chaque exécution le lui demande — ou votre modèle par défaut s\'il n\'y en a pas. Un modèle choisi ici est celui de l\'exécution, quel que soit celui du dossier. Une exécution ne change jamais le modèle du dossier. + Le premier libre de vos modèles de planification + le modèle habituel du dossier + votre modèle par défaut + le modèle propre à la conversation Parler Demandez à la voix ou par écrit, ou reprenez la dernière discussion de l’assistant. N’affiche rien de votre compte. Dernière discussion diff --git a/app/src/main/res/values-hu/strings.xml b/app/src/main/res/values-hu/strings.xml index df0bcaf..666f89c 100644 --- a/app/src/main/res/values-hu/strings.xml +++ b/app/src/main/res/values-hu/strings.xml @@ -565,6 +565,39 @@ Nézze meg ezt. Mit kezdjen vele a LLeMbas? (nem kötelező) Kérdezz bármit + Helyek ezen az eszközön + Itt legutóbb használt: %1$s. Egy új csevegés ebben a mappában ezzel indul, hacsak nem választ másikat. + Az eszköz itt nem nyit munkamenetet. + Egy szinttel feljebb + Minden hely + Nem megbízható az eszközön + Itt nincsenek könyvtárak. + Ez az eszköz nem kínál könyvtárakat: a távoli gyökerei üresek vagy hiányoznak. + Tallózás + Teljes elérési út + Kiválasztás + Az eszköz könyvtárai most nem listázhatók. Adja meg az elérési utat lent. + Modell + Típus + Csevegés + Ezen a szerveren fut, mint egy csevegés: a szerver eszközeivel (keresés, az itteni fájljai, memória) és egy ütemezési modellen. + Ügynöki + Az egyik számítógépén fut, annak egy mappájában, ügynökként: az ügynök eszközeivel azon a számítógépen — a fájljaival és a shelljével — a számítógép saját korlátain belül. Ahhoz a számítógéphez és mappához tartozik. + Egyik számítógépe sem fogad most ütemezett munkát. Kapcsoljon össze egyet, és kapcsolja be az „Accept scheduled work” beállítást a LLeMbas CLI-jében (lembas service scheduled on). + nem fogad ütemezett munkát + A számítógépnek engedélyeznie kell: „Accept scheduled work” a LLeMbas CLI-jében (lembas service scheduled on). Ha egy futás idején nincs összekapcsolva, a futás megvárja; ha nem tér vissza, mielőtt a futás ideje letelik, a futás kihagyottként kerül feljegyzésre, és erről értesítést kap. + egy már nem bejelentkezett számítógép + Mappa a számítógépen + Mód + Edit, hacsak mást nem választ; az Auto kérdezés nélkül futtat parancsokat. A számítógép csökkentheti. + Egy jóváhagyás vár (perc) + A futás által jóváhagyást igénylő parancs kártyaként érkezik a telefonjára. Ha addig nem válaszol, elutasítottnak számít. + A mappa szokásos modellje + A mappa szokásos modellje az, amelyet abban a mappában azon a számítógépen legutóbb használt — a számítógép megjegyzi, és minden futás megkérdezi tőle —, vagy az alapértelmezett modellje, ha nincs ilyen. Az itt választott modell a futásé, bármi is a mappáé. Egy futás soha nem változtatja meg a mappa modelljét. + Az ütemezési modelljei közül az első szabad + a mappa szokásos modellje + az Ön alapértelmezett modellje + a beszélgetés saját modellje Beszéd Kérdezz hanggal vagy szöveggel, vagy folytasd az asszisztens legutóbbi csevegését. A fiókodból semmit sem mutat. Utolsó csevegés diff --git a/app/src/main/res/values-it/strings.xml b/app/src/main/res/values-it/strings.xml index 0c66856..78399b8 100644 --- a/app/src/main/res/values-it/strings.xml +++ b/app/src/main/res/values-it/strings.xml @@ -565,6 +565,39 @@ Dai un\'occhiata a questo. Cosa deve farne LLeMbas? (facoltativo) Chiedi qualsiasi cosa + Posizioni su questo dispositivo + Ultimo usato qui: %1$s. Una nuova chat in questa cartella parte da questo, a meno che non ne scegliate un altro. + Il dispositivo non aprirà una sessione qui. + Su di un livello + Tutte le posizioni + Non attendibile sul dispositivo + Nessuna cartella qui. + Questo dispositivo non offre cartelle: le sue radici remote sono vuote o mancanti. + Sfoglia + Un percorso completo + Scegli + Le cartelle di questo dispositivo non si possono elencare adesso. Scrivi il percorso qui sotto. + Modello + Tipo + Chat + Viene eseguita su questo server, come una chat: con gli strumenti del server (ricerca, i vostri file qui, memoria) e su un modello di pianificazione. + Agentico + Viene eseguita su uno dei vostri computer, in una cartella lì, come agente: con gli strumenti dell\'agente su quel computer — i suoi file e la sua shell — entro i limiti propri del computer. Appartiene a quel computer e a quella cartella. + Nessuno dei vostri computer accetta ora lavoro pianificato. Collegatene uno e attivate «Accept scheduled work» nel suo LLeMbas CLI (lembas service scheduled on). + non accetta lavoro pianificato + Il computer deve consentirlo: «Accept scheduled work» nel suo LLeMbas CLI (lembas service scheduled on). Se non è collegato al momento di un\'esecuzione, l\'esecuzione lo attende; se non è tornato prima che il suo orario sia passato, l\'esecuzione viene registrata come mancata e ne venite informati. + un computer non più connesso + Cartella sul computer + Modalità + Edit, salvo diversa scelta; Auto esegue i comandi senza chiedere. Il computer può abbassarla. + Un\'approvazione attende (minuti) + Un comando che l\'esecuzione deve far approvare arriva al tuo telefono come scheda. Senza risposta entro allora, conta come negato. + Il modello abituale della cartella + Il modello abituale della cartella è quello che avete usato per ultimo in quella cartella su quel computer — il computer lo ricorda e ogni esecuzione glielo chiede — oppure il vostro modello predefinito dove non ce n\'è. Un modello scelto qui è quello dell\'esecuzione, qualunque sia quello della cartella. Un\'esecuzione non cambia mai il modello della cartella. + Il primo libero dei tuoi modelli per la pianificazione + il modello abituale della cartella + il tuo modello predefinito + il modello proprio della conversazione Parla Chiedi a voce o per iscritto, o continua l’ultima chat dell’assistente. Non mostra nulla del tuo account. Ultima chat diff --git a/app/src/main/res/values-pl/strings.xml b/app/src/main/res/values-pl/strings.xml index 9161bb2..9e36aae 100644 --- a/app/src/main/res/values-pl/strings.xml +++ b/app/src/main/res/values-pl/strings.xml @@ -565,6 +565,39 @@ Zobacz to. Co LLeMbas ma z tym zrobić? (opcjonalnie) Zapytaj o cokolwiek + Miejsca na tym urządzeniu + Ostatnio używany tutaj: %1$s. Nowy czat w tym folderze zaczyna się od niego, chyba że wybierzesz inny. + Urządzenie nie otworzy tutaj sesji. + Poziom wyżej + Wszystkie miejsca + Niezaufane na urządzeniu + Brak katalogów. + To urządzenie nie udostępnia żadnych katalogów: jego zdalne katalogi główne są puste lub ich brak. + Przeglądaj + Pełna ścieżka + Wybierz + Katalogów tego urządzenia nie można teraz wyświetlić. Wpisz ścieżkę poniżej. + Model + Typ + Czat + Działa na tym serwerze, jak czat: z narzędziami serwera (wyszukiwanie, twoje pliki tutaj, pamięć) i na modelu do planowania. + Agentowy + Działa na jednym z twoich komputerów, w jednym folderze na nim, jako agent: z narzędziami agenta na tym komputerze — jego plikami i jego powłoką — w ramach własnych ograniczeń komputera. Należy do tego komputera i folderu. + Żaden z twoich komputerów nie przyjmuje teraz zaplanowanej pracy. Połącz któryś i włącz „Accept scheduled work” w jego LLeMbas CLI (lembas service scheduled on). + nie przyjmuje zaplanowanej pracy + Komputer musi na to pozwolić: „Accept scheduled work” w jego LLeMbas CLI (lembas service scheduled on). Gdy w czasie uruchomienia nie jest połączony, uruchomienie na niego czeka; jeśli nie wróci, zanim minie czas uruchomienia, zostaje ono zapisane jako pominięte i dostajesz o tym informację. + komputer, który nie jest już zalogowany + Folder na komputerze + Tryb + Edit, chyba że wybierzesz inaczej; Auto uruchamia polecenia bez pytania. Komputer może go obniżyć. + Zatwierdzenie czeka (minuty) + Polecenie, które uruchomienie musi zatwierdzić, trafia na Twój telefon jako karta. Bez odpowiedzi do tego czasu liczy się jako odrzucone. + Zwykły model folderu + Zwykły model folderu to ten, którego ostatnio użyłeś w tym folderze na tym komputerze — komputer go pamięta, a każde uruchomienie go o niego pyta — albo twój model domyślny, gdy takiego nie ma. Model wybrany tutaj jest modelem uruchomienia, niezależnie od modelu folderu. Uruchomienie nigdy nie zmienia modelu folderu. + Pierwszy wolny z modeli do harmonogramów + zwykły model folderu + Twój domyślny model + własny model rozmowy Mów Pytaj głosem lub tekstem albo kontynuuj ostatni czat asystenta. Nie pokazuje niczego z Twojego konta. Ostatni czat diff --git a/app/src/main/res/values-sk/strings.xml b/app/src/main/res/values-sk/strings.xml index fd6b888..0219e2a 100644 --- a/app/src/main/res/values-sk/strings.xml +++ b/app/src/main/res/values-sk/strings.xml @@ -565,6 +565,39 @@ Pozrite sa na toto. Čo s tým má LLeMbas urobiť? (nepovinné) Opýtajte sa na čokoľvek + Miesta na tomto zariadení + Naposledy tu použitý: %1$s. Nový chat v tomto priečinku začne na ňom, ak nevyberiete iný. + Zariadenie tu reláciu neotvorí. + O úroveň vyššie + Všetky miesta + Na zariadení nie je dôveryhodné + Nie sú tu žiadne priečinky. + Toto zariadenie neponúka žiadne priečinky: jeho vzdialené korene sú prázdne alebo chýbajú. + Prehľadávať + Úplná cesta + Vybrať + Adresáre tohto zariadenia sa teraz nedajú vypísať. Napíšte cestu nižšie. + Model + Typ + Konverzácia + Beží na tomto serveri ako chat: s nástrojmi servera (vyhľadávanie, vaše súbory tu, pamäť) a na modeli určenom na plánovanie. + Agentický + Beží na jednom z vašich počítačov, v jednom priečinku na ňom, ako agent: s nástrojmi agenta na tom počítači — jeho súbormi a jeho shellom — v rámci vlastných obmedzení počítača. Patrí k tomu počítaču a priečinku. + Žiadny z vašich počítačov teraz neprijíma naplánovanú prácu. Prepojte niektorý a zapnite „Accept scheduled work“ v jeho LLeMbas CLI (lembas service scheduled on). + neprijíma plánovanú prácu + Počítač to musí povoliť: „Accept scheduled work“ v jeho LLeMbas CLI (lembas service scheduled on). Keď v čase spustenia nie je prepojený, spustenie naň počká; ak sa nevráti, kým čas spustenia neuplynie, spustenie sa zaznamená ako zmeškané a dozviete sa o tom. + počítač, ktorý už nie je prihlásený + Priečinok na počítači + Režim + Edit, ak nevyberiete inak; Auto spúšťa príkazy bez pýtania. Počítač ho môže znížiť. + Schválenie čaká (minúty) + Príkaz, ktorý spustenie potrebuje schváliť, príde do telefónu ako karta. Ak do tej doby nebude zodpovedaný, počíta sa ako zamietnutý. + Zvyčajný model priečinka + Zvyčajný model priečinka je ten, ktorý ste v tom priečinku na tom počítači použili naposledy — počítač si ho pamätá a každé spustenie sa ho naň opýta — alebo váš predvolený model, ak žiadny nie je. Model vybraný tu je modelom spustenia, nech je model priečinka akýkoľvek. Spustenie nikdy nemení model priečinka. + Prvý voľný z vašich modelov na plánovanie + zvyčajný model priečinka + váš predvolený model + vlastný model konverzácie Hovoriť Pýtajte sa hlasom alebo textom, alebo pokračujte v poslednej konverzácii s asistentom. Neukazuje nič z vášho účtu. Posledný chat diff --git a/app/src/main/res/values/strings.xml b/app/src/main/res/values/strings.xml index ed29f86..3201190 100644 --- a/app/src/main/res/values/strings.xml +++ b/app/src/main/res/values/strings.xml @@ -567,6 +567,39 @@ Have a look at this. What should LLeMbas do with it? (optional) Ask anything + Places on this device + Last used here: %1$s. A new chat in this directory starts on it unless you choose another. + The device will not open a session here. + Up a level + All places + Not trusted on the device + No directories here. + This device offers no directories: its remote roots are empty or missing. + Browse + A full path + Choose + This device\'s directories cannot be listed right now. Type the path below. + Model + Type + Chat + Runs on this server, like a chat: with the server\'s tools (search, your files here, memory) and on a scheduling model. + Agentic + Runs on one of your computers, in one folder there, as an agent: with the agent\'s tools on that computer — its files and its shell — under the computer\'s own limits. It belongs to that computer and folder. + None of your computers accepts scheduled work now. Link one and switch on “Accept scheduled work” in its LLeMbas CLI (lembas service scheduled on). + does not accept scheduled work + The computer must allow it: “Accept scheduled work” in its LLeMbas CLI (lembas service scheduled on). When it is not linked at the time of a run, the run waits for it; if it has not come back before the run\'s time has passed, the run is recorded as missed and you are told. + a computer no longer signed in + Folder on the computer + Mode + Edit unless you choose otherwise; Auto runs commands without asking. The computer may lower it. + An approval waits (minutes) + A command the run needs approved comes to your phone as a card. Unanswered by then, it counts as denied. + The folder\'s usual model + The folder\'s usual model is the one you last used in that folder on that computer — the computer remembers it, and each run asks it — or your default model where there is none. A model chosen here is the run\'s, whatever the folder\'s is. A run never changes the folder\'s model. + The first free one of your scheduling models + the folder\'s usual model + your default model + the conversation\'s own model Speak Ask by voice or text, or carry on the last assistant chat. Shows nothing from your account. Last chat diff --git a/app/src/test/java/eu/llembas/android/DirectoriesTest.kt b/app/src/test/java/eu/llembas/android/DirectoriesTest.kt new file mode 100644 index 0000000..5c450dd --- /dev/null +++ b/app/src/test/java/eu/llembas/android/DirectoriesTest.kt @@ -0,0 +1,174 @@ +package eu.llembas.android + +import eu.llembas.android.api.ApiClient +import eu.llembas.android.api.Chat +import eu.llembas.android.api.DeviceDirectory +import eu.llembas.android.api.DeviceList +import eu.llembas.android.api.LembasJson +import eu.llembas.android.api.ModelList +import eu.llembas.android.api.StartModel +import eu.llembas.android.ui.PickerState +import eu.llembas.android.ui.canChoose +import eu.llembas.android.ui.chat.ChatState +import eu.llembas.android.ui.chat.Draft +import eu.llembas.android.ui.chat.folderModel +import eu.llembas.android.ui.chat.modelId +import eu.llembas.android.ui.refusedHere +import eu.llembas.android.ui.took +import eu.llembas.android.ui.up +import kotlinx.coroutines.test.runTest +import kotlinx.serialization.KSerializer +import okhttp3.mockwebserver.MockResponse +import okhttp3.mockwebserver.MockWebServer +import org.junit.Assert.assertEquals +import org.junit.Assert.assertFalse +import org.junit.Assert.assertNull +import org.junit.Assert.assertTrue +import org.junit.Test + +/** + * A linked device's directories and the folder's usual model (harness spec 3.9.0), from the + * server's own fixtures (`contract/device_directories*.json`, `models_agent_directory.json`): + * the shapes, the picker's walk, and which model a new agent chat shows. + */ +class DirectoriesTest { + private fun text(name: String): String = requireNotNull(javaClass.classLoader!!.getResource("$name.json")) { "contract/$name.json is missing" }.readText() + + private fun read(name: String, serializer: KSerializer): T = LembasJson.decodeFromString(serializer, text(name)) + + private val project = read("device_directories", DeviceDirectory.serializer()) + private val places = read("device_directories_places", DeviceDirectory.serializer()) + + @Test + fun aDirectoryItsEntriesAndTheModelsLastUsedThere() { + assertEquals("/home/user/project", project.path) + assertEquals("/home/user", project.parent) + assertTrue(project.accepted) + assertTrue(project.listed) + assertFalse(project.places) + assertEquals("Qwen", project.model?.label) + val (docs, server, vendor) = project.entries + assertNull(docs.model) + assertEquals("gpt-oss", server.model?.label) + assertFalse(vendor.accepted) + assertEquals("This directory is not trusted on the device.", vendor.reason) + // Without a path: the device's places, each a directory to walk into. + assertTrue(places.places) + assertEquals(listOf("/home/user", "/home/user/project"), places.entries.map { it.path }) + assertEquals("Qwen", places.entries.last().model?.label) + } + + @Test + fun noListingIsACodeAndASentence() { + val away = read("device_directories_not_linked", DeviceDirectory.serializer()) + assertFalse(away.listed) + assertEquals("device_not_linked", away.code) + assertEquals("This device is not linked right now.", away.error) + val old = read("device_directories_cli_too_old", DeviceDirectory.serializer()) + assertEquals("cli_too_old", old.code) + assertTrue(old.error.isNotBlank()) + } + + @Test + fun thePickerWalksDownAndUpAndClosesAtTheTop() { + val start = PickerState(loading = true).took(places) + assertFalse(start.loading) + // At the places there is no "up": back closes. And no path yet, so nothing to choose. + assertNull(start.up) + assertEquals("", start.typed) + assertFalse(start.canChoose) + val inside = start.took(project) + assertEquals("/home/user/project", inside.typed) + assertEquals("/home/user", inside.up) + assertTrue(inside.canChoose) + // A directory with no parent leads back to the places. + assertEquals("", inside.took(project.copy(path = "/home/user", parent = "")).up) + // Back at the places the field keeps the last path: it is still what would be chosen. + assertEquals("/home/user/project", inside.took(places).typed) + } + + @Test + fun aDirectoryTheDeviceRefusesCannotBeChosenButATypedPathCan() { + val refused = PickerState().took( + project.copy(path = "/home/user/project/vendor", accepted = false, reason = "This directory is not trusted on the device."), + ) + assertTrue(refused.refusedHere) + assertFalse(refused.canChoose) + // Another path written over it has not been refused by anybody: the instance checks it. + val typed = refused.copy(typed = "/srv/garden") + assertFalse(typed.refusedHere) + assertTrue(typed.canChoose) + assertFalse(typed.copy(typed = " ").canChoose) + } + + @Test + fun aDeviceThatCannotListKeepsTheTypedPathAndSaysWhy() { + val typed = PickerState(typed = "/home/user/garden", loading = true) + for (name in listOf("device_directories_not_linked", "device_directories_cli_too_old")) { + val answer = read(name, DeviceDirectory.serializer()) + val after = typed.took(answer, fallback = "It cannot be listed.") + assertEquals("/home/user/garden", after.typed) + assertEquals(answer.error, after.error) + assertFalse(after.loading) + assertTrue(after.canChoose) + } + // The listing shown before stays where it was; a code without a sentence gets the app's own. + val walked = PickerState().took(project) + val silent = walked.took(DeviceDirectory(code = "no_answer"), fallback = "It cannot be listed.") + assertEquals(project, silent.listing) + assertEquals("It cannot be listed.", silent.error) + // The next listing clears the sentence. + assertNull(silent.took(places).error) + } + + @Test + fun aNewAgentChatShowsTheFoldersUsualModelUnlessOneWasPicked() { + val list = read("models_agent_directory", ModelList.serializer()) + assertEquals(StartModel(model = "gpt-oss", from = "directory"), list.start) + assertTrue(list.models.none { it.interactiveOnly }) + val draft = ChatState(models = list.models, start = list.start) + // The default is Qwen; the folder's usual model is shown instead. + assertEquals("qwen", ChatState(models = list.models).modelId) + assertEquals("gpt-oss", draft.modelId) + // A model the person picked in this draft is never set aside. + assertEquals("vision-small", draft.copy(draft = Draft(model = "vision-small")).modelId) + // A model the person no longer has is not shown, and a chat that exists has its own. + assertNull(draft.copy(start = StartModel(model = "gone", from = "directory")).folderModel) + assertEquals("qwen", draft.copy(start = StartModel(model = "gone", from = "directory")).modelId) + assertEquals("qwen", draft.copy(chat = Chat(id = "c", model = "qwen")).modelId) + // Without a directory the list says nothing of it. + assertNull(read("models_agent", ModelList.serializer()).start) + } + + @Test + fun aDeviceSaysWhetherItTakesScheduledWorkAndRemembers() { + val (workstation, laptop) = read("devices", DeviceList.serializer()).devices + assertTrue(workstation.scheduled) + assertEquals("edit", workstation.maxMode) + assertTrue(workstation.directoryModel) + assertFalse(laptop.scheduled) + assertFalse(laptop.directoryModel) + assertEquals("LLeMbas CLI on laptop", laptop.label) + } + + @Test + fun theRoutesNameTheDeviceThePathAndTheDirectory() = runTest { + val server = MockWebServer().apply { start() } + try { + val api = ApiClient(server.url("/").toString().trimEnd('/'), "lmb_test") + repeat(2) { server.enqueue(MockResponse().setBody(text("device_directories_places"))) } + repeat(2) { server.enqueue(MockResponse().setBody(text("models_agent_directory"))) } + assertTrue(api.deviceDirectories("token1").places) + assertEquals("/api/v2/devices/token1/directories", server.takeRequest().path) + api.deviceDirectories("token1", "/home/user/my project") + assertEquals("/api/v2/devices/token1/directories?path=%2Fhome%2Fuser%2Fmy%20project", server.takeRequest().path) + assertEquals("gpt-oss", api.agentModelList("token1", " /home/user/project ").start?.model) + assertEquals("/api/v2/models?kind=agent&device=token1&directory=%2Fhome%2Fuser%2Fproject", server.takeRequest().path) + // No folder chosen: the question is the old one. + api.agentModelList("token1", "") + assertEquals("/api/v2/models?kind=agent&device=token1", server.takeRequest().path) + } finally { + server.shutdown() + } + } +} diff --git a/app/src/test/java/eu/llembas/android/MentionsTest.kt b/app/src/test/java/eu/llembas/android/MentionsTest.kt new file mode 100644 index 0000000..d9841f2 --- /dev/null +++ b/app/src/test/java/eu/llembas/android/MentionsTest.kt @@ -0,0 +1,72 @@ +package eu.llembas.android + +import eu.llembas.android.api.ApiClient +import eu.llembas.android.api.DeviceFiles +import eu.llembas.android.api.LembasJson +import eu.llembas.android.ui.chat.MENTION_DEVICE +import eu.llembas.android.ui.chat.asMention +import eu.llembas.android.ui.chat.mentionQuery +import eu.llembas.android.ui.chat.withMention +import eu.llembas.android.ui.chat.withoutMention +import kotlinx.coroutines.test.runTest +import okhttp3.mockwebserver.MockResponse +import okhttp3.mockwebserver.MockWebServer +import org.junit.Assert.assertEquals +import org.junit.Assert.assertNull +import org.junit.Test + +/** The composer's `@`: which word asks, what a pick leaves in the text, and a device's files. */ +class MentionsTest { + private fun text(name: String): String = requireNotNull(javaClass.classLoader!!.getResource("$name.json")) { "contract/$name.json is missing" }.readText() + + @Test + fun theWordTheTextEndsWithAsks() { + assertEquals("", mentionQuery("@")) + assertEquals("bre", mentionQuery("Read @bre")) + assertEquals("src/loa", mentionQuery("Look at\n@src/loa")) + assertEquals("https://example.org/waybread", mentionQuery("Sum up @https://example.org/waybread")) + // No `@`, an address, or a word already finished: nothing is asked. + assertNull(mentionQuery("Read the recipe")) + assertNull(mentionQuery("Write to frodo@shire.test")) + assertNull(mentionQuery("Read @bread.md and")) + assertNull(mentionQuery("")) + // The last `@` is the one that counts. + assertEquals("oven", mentionQuery("Compare @bread.md with @oven")) + } + + @Test + fun aPickLeavesTheTextWithoutTheWordOrWithThePath() { + // Attached: the word goes, the rest stays as typed. + assertEquals("Read ", withoutMention("Read @bre")) + assertEquals("", withoutMention("@")) + // A device's file: the word becomes its path, ready for the next word. + assertEquals("Look at @src/loader ", withMention("Look at @src/loa", "src/loader")) + // Nothing being asked: nothing changes. + assertEquals("Read the recipe", withoutMention("Read the recipe")) + assertEquals("a@b.test", withMention("a@b.test", "README.md")) + } + + @Test + fun aDevicesFilesAreOfferedByPath() = runTest { + val files = LembasJson.decodeFromString(DeviceFiles.serializer(), text("device_files")) + val (readme, loader) = files.files.map { it.asMention() } + assertEquals(MENTION_DEVICE, readme.kind) + assertEquals("README.md", readme.path) + assertEquals("loader", loader.name) + // A directory says so in its detail. + assertEquals("src/loader/", loader.detail) + + val server = MockWebServer().apply { start() } + try { + val api = ApiClient(server.url("/").toString().trimEnd('/'), "lmb_test") + repeat(2) { server.enqueue(MockResponse().setBody(text("device_files"))) } + // Before the chat exists: the folder chosen for it. Once it does: the chat. + api.deviceFiles("token1", "read", cwd = "/home/user/project") + assertEquals("/api/v2/devices/token1/files?q=read&cwd=%2Fhome%2Fuser%2Fproject", server.takeRequest().path) + api.deviceFiles("token1", "read", chatId = "chat1", cwd = "/home/user/project") + assertEquals("/api/v2/devices/token1/files?q=read&chat=chat1", server.takeRequest().path) + } finally { + server.shutdown() + } + } +} diff --git a/app/src/test/java/eu/llembas/android/ScheduleContractTest.kt b/app/src/test/java/eu/llembas/android/ScheduleContractTest.kt index ca90947..e1186f2 100644 --- a/app/src/test/java/eu/llembas/android/ScheduleContractTest.kt +++ b/app/src/test/java/eu/llembas/android/ScheduleContractTest.kt @@ -93,7 +93,7 @@ class ScheduleContractTest { assertWaybread(read("schedules", ScheduleList.serializer()).schedules.single()) assertWaybread(read("schedule", ScheduleEnvelope.serializer()).schedule) val frame = read("event_schedules", SchedulesFrame.serializer()) - assertEquals("d55e588277f6c90b", frame.version) + assertEquals("31f4ad7e7995d215", frame.version) assertWaybread(frame.schedules.single()) } diff --git a/app/src/test/java/eu/llembas/android/ScheduleTypesTest.kt b/app/src/test/java/eu/llembas/android/ScheduleTypesTest.kt new file mode 100644 index 0000000..e263a45 --- /dev/null +++ b/app/src/test/java/eu/llembas/android/ScheduleTypesTest.kt @@ -0,0 +1,171 @@ +package eu.llembas.android + +import eu.llembas.android.api.ApiClient +import eu.llembas.android.api.LembasJson +import eu.llembas.android.api.LinkedDevice +import eu.llembas.android.api.RunResult +import eu.llembas.android.api.ScheduleCompiled +import eu.llembas.android.api.ScheduleEnvelope +import eu.llembas.android.api.WhereToRun +import eu.llembas.android.api.agentic +import eu.llembas.android.ui.scheduled.EditState +import eu.llembas.android.ui.scheduled.agenticOffered +import eu.llembas.android.ui.scheduled.listed +import eu.llembas.android.ui.scheduled.read +import eu.llembas.android.ui.scheduled.runModelWhy +import eu.llembas.android.ui.scheduled.waitMinutes +import eu.llembas.android.ui.scheduled.whereComplete +import eu.llembas.android.ui.scheduled.whereToSend +import kotlinx.coroutines.test.runTest +import kotlinx.serialization.KSerializer +import kotlinx.serialization.json.JsonNull +import kotlinx.serialization.json.JsonObject +import kotlinx.serialization.json.jsonObject +import kotlinx.serialization.json.jsonPrimitive +import okhttp3.mockwebserver.MockResponse +import okhttp3.mockwebserver.MockWebServer +import org.junit.Assert.assertEquals +import org.junit.Assert.assertFalse +import org.junit.Assert.assertNotNull +import org.junit.Assert.assertNull +import org.junit.Assert.assertTrue +import org.junit.Test + +/** + * The two types of schedule (harness spec 3.9.0): Agentic is a schedule with a computer, Chat + * one without. What the form offers, what a save says, and what a run tells of where it ran. + */ +class ScheduleTypesTest { + private fun text(name: String): String = requireNotNull(javaClass.classLoader!!.getResource("$name.json")) { "contract/$name.json is missing" }.readText() + + private fun read(name: String, serializer: KSerializer): T = LembasJson.decodeFromString(serializer, text(name)) + + private val workstation = LinkedDevice(id = "tok1", name = "workstation", scheduled = true) + private val laptop = LinkedDevice(id = "tok2", name = "laptop", scheduled = false) + + @Test + fun agenticIsOfferedOnlyWhileAComputerAcceptsScheduledWork() { + assertFalse(EditState().agenticOffered) + assertFalse(EditState().listed(listOf(laptop)).agenticOffered) + val offered = EditState().listed(listOf(laptop, workstation)) + assertTrue(offered.agenticOffered) + // A new Agentic schedule starts on the first computer that accepts it. + assertEquals("tok1", offered.device) + assertEquals("", EditState().listed(listOf(laptop)).device) + } + + @Test + fun aNewScheduleSaysAComputerOnlyWhenItIsAgentic() { + assertEquals(WhereToRun.Leave, whereToSend(EditState(), editing = false)) + val agentic = EditState(agentic = true, device = "tok1", cwd = " /home/user/project ", agentMode = "auto", wait = "45", model = "") + assertEquals(WhereToRun.Computer("tok1", "/home/user/project", "auto", 45, ""), whereToSend(agentic, editing = false)) + // No wait typed, or nonsense: the instance's own. + assertNull(agentic.copy(wait = "").waitMinutes) + assertNull(agentic.copy(wait = "0").waitMinutes) + // It cannot be saved without its computer and its folder. + assertTrue(agentic.whereComplete) + assertFalse(agentic.copy(cwd = " ").whereComplete) + assertFalse(agentic.copy(device = "").whereComplete) + assertTrue(EditState().whereComplete) + } + + @Test + fun anEditSaysOnlyWhatTheFormKnows() { + val on = read("schedule_on_device", ScheduleEnvelope.serializer()).schedule + assertTrue(on.agentic) + // Not read: nothing is said, whatever the form shows. + assertEquals(WhereToRun.Leave, whereToSend(EditState(agentic = true, device = "tok1", cwd = "/x"), editing = true)) + // Read: the form holds the schedule's own computer, folder, mode, wait and model. + val read = EditState().listed(listOf(workstation)).read(on).copy(loaded = true) + assertTrue(read.agentic) + assertEquals("tok1", read.device) + assertEquals("/home/frodo/waybread", read.cwd) + assertEquals("edit", read.agentMode) + assertEquals("30", read.wait) + assertEquals("", read.model) + assertEquals(WhereToRun.Computer("tok1", "/home/frodo/waybread", "edit", 30, ""), whereToSend(read, editing = true)) + // Made a Chat schedule: the server is told so. A Chat schedule left alone: nothing. + assertEquals(WhereToRun.Server, whereToSend(read.copy(agentic = false), editing = true)) + val chat = EditState().read(read("schedule", ScheduleEnvelope.serializer()).schedule).copy(loaded = true) + assertFalse(chat.agentic) + assertEquals(WhereToRun.Leave, whereToSend(chat, editing = true)) + } + + @Test + fun aSchedulesOwnComputerStaysListedWhenItIsNotLinked() { + val on = read("schedule_on_device", ScheduleEnvelope.serializer()).schedule + // Read first, the computers after -- and the other way round. + val readFirst = EditState().read(on).listed(listOf(laptop)) + assertEquals(listOf("tok2", "tok1"), readFirst.devices.map { it.id }) + assertEquals("bag-end", readFirst.devices.last().label) + assertEquals("tok1", readFirst.device) + val listedFirst = EditState().listed(listOf(laptop)).read(on) + assertEquals(listOf("tok2", "tok1"), listedFirst.devices.map { it.id }) + // Linked: it is in the list once. + assertEquals(listOf("tok1"), EditState().read(on).listed(listOf(workstation)).devices.map { it.id }) + } + + @Test + fun whatThePersonChangedIsNotUndoneByTheRead() { + val on = read("schedule_on_device", ScheduleEnvelope.serializer()).schedule + val touched = EditState(agentic = false, whereTouched = true).read(on) + assertFalse(touched.agentic) + assertTrue(touched.wasAgentic) + } + + @Test + fun aRunSaysWhereItRanAndHowItsModelWasChosen() { + val run = read("schedule_run_agentic", RunResult.serializer()).run + val where = run.ranOn!! + assertEquals("workstation", where.deviceName) + assertEquals("/home/user/project", where.cwd) + assertEquals("edit", where.mode) + assertEquals("directory", run.model.reason) + assertNotNull(runModelWhy(run.model.reason)) + assertNotNull(runModelWhy("default")) + assertNotNull(runModelWhy("session")) + // A pinned model needs no word, and a switched one has its own sentence. + assertNull(runModelWhy("pinned")) + assertNull(runModelWhy("switched")) + assertNull(runModelWhy(null)) + // A Chat schedule's run ran nowhere but here. + assertNull(read("schedule_run", RunResult.serializer()).run.ranOn) + } + + @Test + fun aSaveCarriesTheTypeAsRunsOn() = runTest { + val server = MockWebServer().apply { start() } + try { + val api = ApiClient(server.url("/").toString().trimEnd('/'), "lmb_test") + val compiled = + ScheduleCompiled( + ok = true, + title = "Nightly tests", + instruction = "Run the tests.", + rule = JsonObject(mapOf("every" to JsonObject(emptyMap()))), + ) + repeat(3) { server.enqueue(MockResponse().setBody(text("schedule_on_device"))) } + fun sent(): JsonObject = LembasJson.parseToJsonElement(server.takeRequest().body.readUtf8()).jsonObject + + api.saveSchedule(compiled, "every night", where = WhereToRun.Computer("tok1", "/home/user/project", "edit", null, "")) + val agentic = sent() + val on = agentic.getValue("runs_on").jsonObject + assertEquals("tok1", on.getValue("device").jsonPrimitive.content) + assertEquals("/home/user/project", on.getValue("cwd").jsonPrimitive.content) + assertEquals("edit", on.getValue("mode").jsonPrimitive.content) + assertFalse("approval_wait_minutes" in on) + // The empty model is the folder's usual one: said, so a model set before is taken off. + assertEquals("", agentic.getValue("model").jsonPrimitive.content) + + api.saveSchedule(compiled, "every night", id = "sched3", where = WhereToRun.Server) + assertEquals(JsonNull, sent().getValue("runs_on")) + + api.saveSchedule(compiled, "every night", id = "sched3") + val left = sent() + assertFalse("runs_on" in left) + assertFalse("model" in left) + } finally { + server.shutdown() + } + } +} 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 e809a1e..485ee2a 100644 --- a/app/src/test/java/eu/llembas/android/shots/Fakes.kt +++ b/app/src/test/java/eu/llembas/android/shots/Fakes.kt @@ -9,6 +9,7 @@ import eu.llembas.android.api.Attachment import eu.llembas.android.api.Chat import eu.llembas.android.api.ContextPart import eu.llembas.android.api.DataGroup +import eu.llembas.android.api.DeviceDirectory import eu.llembas.android.api.Folder import eu.llembas.android.api.GeneratedImage import eu.llembas.android.api.LembasJson @@ -48,6 +49,7 @@ import eu.llembas.android.auth.Instance import eu.llembas.android.auth.Prefs import eu.llembas.android.share.ShareState import eu.llembas.android.share.SharedFile +import eu.llembas.android.ui.PickerState import eu.llembas.android.ui.chat.ChatState import eu.llembas.android.ui.chat.Draft import eu.llembas.android.ui.home.ChatsState @@ -742,6 +744,40 @@ object Fakes { ), ) + /** The form for an Agentic schedule: a computer that takes scheduled work and one that does not, a folder, a mode. */ + val editingAgentic: EditState get() = editing.copy( + agentic = true, + devices = listOf( + LinkedDevice(id = "d1", name = "Workstation", host = "workstation", scheduled = true), + LinkedDevice(id = "d2", name = "Laptop", host = "laptop"), + ), + device = "d1", + cwd = "/home/user/src/garden", + agentMode = "edit", + wait = "30", + ) + + /** The form where no computer accepts scheduled work: Agentic says why it cannot be chosen. */ + val editingNoComputer: EditState get() = editing.copy(devices = listOf(LinkedDevice(id = "d2", name = "Laptop", host = "laptop"))) + + /** The folder picker inside a directory: one folder with its model, one the device will not open. */ + val picker = PickerState( + listing = LembasJson.decodeFromString(DeviceDirectory.serializer(), text("device_directories")), + typed = "/home/user/project", + ) + + /** The picker where the device cannot list: the sentence, and the typed path still there. */ + val pickerNoListing = PickerState( + typed = "/home/user/src/garden", + error = LembasJson.decodeFromString(DeviceDirectory.serializer(), text("device_directories_cli_too_old")).error, + ) + + /** A run of an Agentic schedule: where it ran, on the folder's usual model. */ + val scheduleAgenticRun: ScheduleState get() = ScheduleState( + schedule = onComputer, + runs = listOf(LembasJson.decodeFromString(RunResult.serializer(), text("schedule_run_agentic")).run), + ) + /** The form with "When…" chosen and the person's own words in it. */ val editingNotify: EditState get() = editing.copy(reports = true, notify = "when", notifyWhen = "a tender for storage opens or closes") 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 2c0c4d2..3d7180d 100644 --- a/app/src/test/java/eu/llembas/android/shots/ScreenShots.kt +++ b/app/src/test/java/eu/llembas/android/shots/ScreenShots.kt @@ -35,6 +35,8 @@ import eu.llembas.android.assist.AssistUiState import eu.llembas.android.share.ShareActions import eu.llembas.android.share.ShareSheetContent import eu.llembas.android.share.ShareState +import eu.llembas.android.ui.DirectoryPickerContent +import eu.llembas.android.ui.PickerActions import eu.llembas.android.ui.chat.ActivityActions import eu.llembas.android.ui.chat.ActivityContent import eu.llembas.android.ui.chat.CardSheet @@ -272,6 +274,26 @@ class ScreenShots { shoot("11-schedule-edit-notify", Phone.SmallScroll, fontScale = 1.5f) { ScheduleEditContent(Fakes.editingNotify, editing = true) } } + @Test + fun scheduleTypes() { + // Agentic: the computer, the folder, the mode, the wait and the model -- and the form + // where no computer accepts scheduled work. + shoot("43-schedule-edit-agentic", Phone.Scroll) { ScheduleEditContent(Fakes.editingAgentic, editing = false) } + shoot("43-schedule-edit-agentic", Phone.SmallScroll, fontScale = 1.5f) { ScheduleEditContent(Fakes.editingAgentic, editing = false) } + shoot("43-schedule-edit-no-computer", Phone.Scroll) { ScheduleEditContent(Fakes.editingNoComputer, editing = false) } + // A run that says where it ran and that its model was the folder's usual one. + shoot("43-schedule-agentic-run", Phone.Scroll) { ScheduleContent(Fakes.scheduleAgenticRun) } + shoot("43-schedule-agentic-run", Phone.SmallScroll, fontScale = 1.5f) { ScheduleContent(Fakes.scheduleAgenticRun) } + } + + @Test + fun directoryPicker() { + val none = object : PickerActions {} + shoot("44-directory-picker") { DirectoryPickerContent("Workstation", Fakes.picker, none) } + shoot("44-directory-picker", Phone.Small, fontScale = 1.5f) { DirectoryPickerContent("Workstation", Fakes.picker, none) } + shoot("44-directory-picker-no-listing") { DirectoryPickerContent("Workstation", Fakes.pickerNoListing, none) } + } + @Test fun reports() { shoot("40-reports") { ReportsContent(Fakes.reports, NoReportsActions) } diff --git a/contract/device_directories.json b/contract/device_directories.json new file mode 100644 index 0000000..7a6f210 --- /dev/null +++ b/contract/device_directories.json @@ -0,0 +1,44 @@ +{ + "device": "token1", + "path": "/home/user/project", + "name": "project", + "accepted": true, + "reason": "", + "model": { + "id": "qwen", + "name": "Qwen" + }, + "parent": "/home/user", + "roots": [ + "/home/user" + ], + "entries": [ + { + "path": "/home/user/project/docs", + "name": "docs", + "accepted": true, + "reason": "", + "model": null + }, + { + "path": "/home/user/project/server", + "name": "server", + "accepted": true, + "reason": "", + "model": { + "id": "gpt-oss", + "name": "gpt-oss" + } + }, + { + "path": "/home/user/project/vendor", + "name": "vendor", + "accepted": false, + "reason": "This directory is not trusted on the device.", + "model": null + } + ], + "remembers": true, + "code": "", + "error": "" +} diff --git a/contract/device_directories_cli_too_old.json b/contract/device_directories_cli_too_old.json new file mode 100644 index 0000000..2067cee --- /dev/null +++ b/contract/device_directories_cli_too_old.json @@ -0,0 +1,16 @@ +{ + "device": "token1", + "path": "", + "name": "", + "accepted": true, + "reason": "", + "model": null, + "parent": "", + "roots": [ + "/home/user" + ], + "entries": [], + "remembers": false, + "code": "cli_too_old", + "error": "This device's LLeMbas CLI is too old to list its directories. Type the path below." +} diff --git a/contract/device_directories_not_linked.json b/contract/device_directories_not_linked.json new file mode 100644 index 0000000..a1c78e9 --- /dev/null +++ b/contract/device_directories_not_linked.json @@ -0,0 +1,14 @@ +{ + "device": "token1", + "path": "", + "name": "", + "accepted": true, + "reason": "", + "model": null, + "parent": "", + "roots": [], + "entries": [], + "remembers": false, + "code": "device_not_linked", + "error": "This device is not linked right now." +} diff --git a/contract/device_directories_places.json b/contract/device_directories_places.json new file mode 100644 index 0000000..e024780 --- /dev/null +++ b/contract/device_directories_places.json @@ -0,0 +1,34 @@ +{ + "device": "token1", + "path": "", + "name": "", + "accepted": true, + "reason": "", + "model": null, + "parent": "", + "roots": [ + "/home/user" + ], + "entries": [ + { + "path": "/home/user", + "name": "user", + "accepted": true, + "reason": "", + "model": null + }, + { + "path": "/home/user/project", + "name": "project", + "accepted": true, + "reason": "", + "model": { + "id": "qwen", + "name": "Qwen" + } + } + ], + "remembers": true, + "code": "", + "error": "" +} diff --git a/contract/devices.json b/contract/devices.json index 5286f69..aab3f4b 100644 --- a/contract/devices.json +++ b/contract/devices.json @@ -9,7 +9,8 @@ "terminal_reason": "", "terminal_hint": "", "scheduled": true, - "max_mode": "edit" + "max_mode": "edit", + "directory_model": true }, { "id": "token2", @@ -20,7 +21,8 @@ "terminal_reason": "device", "terminal_hint": "laptop does not open terminals. Switch it on there: in LLeMbas Desktop's settings, or with the LLeMbas CLI's remote.terminal setting.", "scheduled": false, - "max_mode": "" + "max_mode": "", + "directory_model": false } ] } diff --git a/contract/event_schedules.json b/contract/event_schedules.json index 917245b..a9b81d7 100644 --- a/contract/event_schedules.json +++ b/contract/event_schedules.json @@ -1,5 +1,5 @@ { - "version": "d55e588277f6c90b", + "version": "31f4ad7e7995d215", "schedules": [ { "id": "sched1", @@ -76,6 +76,7 @@ "reason": "switched", "switched_from": "Qwen" }, + "ran_on": null, "tokens": { "prompt": 1200, "completion": 340 diff --git a/contract/lock.json b/contract/lock.json index 7ccb0be..7b1ac2f 100644 --- a/contract/lock.json +++ b/contract/lock.json @@ -1,5 +1,5 @@ { - "ref": "v2.0.0-beta.13", - "commit": "3191ecf5fabb7583dd73826f54f7b37f6dae338c", - "sha256": "fcdfaca53bec6edefc22ae0d600bf284c3fe3c8880ed959ae9db8d539fed5c31" + "ref": "a6288a2", + "commit": "a6288a257376d44b6a25983dcb43c9d942870e6c", + "sha256": "f7b9077219b45767ee8cddd7718a18bb00e46f1f7edefd0cc4ed36560bc1c3e5" } diff --git a/contract/models_agent_directory.json b/contract/models_agent_directory.json new file mode 100644 index 0000000..9c8bf81 --- /dev/null +++ b/contract/models_agent_directory.json @@ -0,0 +1,88 @@ +{ + "models": [ + { + "id": "qwen", + "name": "Qwen", + "vision": false, + "tools": true, + "efforts": [ + "medium" + ], + "thinking_switch": true, + "levels": [ + "off", + "medium" + ], + "effort": "medium", + "control": "switch", + "parallel": 2, + "context": 131072, + "image": "/api/v2/models/images/0a1b2c3d4e5f.png", + "default": true, + "subagents": { + "offered": true, + "named_only": false + }, + "html_pages": false + }, + { + "id": "gpt-oss", + "name": "gpt-oss", + "vision": false, + "tools": true, + "efforts": [ + "low", + "medium", + "high" + ], + "thinking_switch": false, + "levels": [ + "low", + "medium", + "high" + ], + "effort": "high", + "control": "slider", + "parallel": 1, + "context": 0, + "image": null, + "default": false, + "subagents": { + "offered": true, + "named_only": false + }, + "html_pages": false + }, + { + "id": "vision-small", + "name": "Vision", + "vision": true, + "tools": false, + "efforts": [], + "thinking_switch": false, + "levels": [ + "default" + ], + "effort": "default", + "control": "none", + "parallel": null, + "context": 8192, + "image": null, + "default": false, + "subagents": { + "offered": true, + "named_only": false + }, + "html_pages": false + } + ], + "subagents_cap": 32, + "agent_subagents": { + "offered": true, + "device_runs": true + }, + "start": { + "model": "gpt-oss", + "from": "directory" + } +} diff --git a/contract/schedule.json b/contract/schedule.json index af57d56..1e92515 100644 --- a/contract/schedule.json +++ b/contract/schedule.json @@ -74,6 +74,7 @@ "reason": "switched", "switched_from": "Qwen" }, + "ran_on": null, "tokens": { "prompt": 1200, "completion": 340 diff --git a/contract/schedule_on_device.json b/contract/schedule_on_device.json index 44633f6..f89dfb7 100644 --- a/contract/schedule_on_device.json +++ b/contract/schedule_on_device.json @@ -78,6 +78,7 @@ "reason": null, "switched_from": null }, + "ran_on": null, "tokens": { "prompt": 0, "completion": 0 diff --git a/contract/schedule_run.json b/contract/schedule_run.json index 94fb0a0..f03019c 100644 --- a/contract/schedule_run.json +++ b/contract/schedule_run.json @@ -18,6 +18,7 @@ "reason": "switched", "switched_from": "Qwen" }, + "ran_on": null, "tokens": { "prompt": 1200, "completion": 340 diff --git a/contract/schedule_run_agentic.json b/contract/schedule_run_agentic.json new file mode 100644 index 0000000..2f1935c --- /dev/null +++ b/contract/schedule_run_agentic.json @@ -0,0 +1,44 @@ +{ + "run": { + "id": "run6", + "schedule_id": "sched3", + "status": "ok", + "timing": "on_time", + "missed": 0, + "due_at": "2026-01-02T03:04:05+00:00", + "started_at": "2026-01-02T03:04:05+00:00", + "finished_at": "2026-01-02T03:04:05+00:00", + "waiting_for": null, + "retry_at": null, + "progress": null, + "attempts": 1, + "model": { + "id": "qwen", + "name": "Qwen", + "reason": "directory", + "switched_from": null + }, + "ran_on": { + "device": "tok1", + "device_name": "workstation", + "cwd": "/home/user/project", + "mode": "edit" + }, + "tokens": { + "prompt": 0, + "completion": 0 + }, + "cost": null, + "chat_id": "chat2", + "message_id": "msg7", + "report_path": null, + "report": null, + "note": "The tests pass.", + "preview": "", + "error": null, + "notified": false, + "notification": null, + "watch": null + }, + "text": "The tests pass." +} diff --git a/contract/schedule_runs.json b/contract/schedule_runs.json index 93c290d..4d3796d 100644 --- a/contract/schedule_runs.json +++ b/contract/schedule_runs.json @@ -24,6 +24,7 @@ "reason": null, "switched_from": null }, + "ran_on": null, "tokens": { "prompt": 0, "completion": 0 @@ -62,6 +63,7 @@ "reason": "switched", "switched_from": "Qwen" }, + "ran_on": null, "tokens": { "prompt": 1200, "completion": 340 diff --git a/contract/schedule_watching.json b/contract/schedule_watching.json index 943864e..0124b45 100644 --- a/contract/schedule_watching.json +++ b/contract/schedule_watching.json @@ -65,6 +65,7 @@ "reason": null, "switched_from": null }, + "ran_on": null, "tokens": { "prompt": 0, "completion": 0 diff --git a/contract/schedules.json b/contract/schedules.json index 6fdff2f..efdbcdd 100644 --- a/contract/schedules.json +++ b/contract/schedules.json @@ -75,6 +75,7 @@ "reason": "switched", "switched_from": "Qwen" }, + "ran_on": null, "tokens": { "prompt": 1200, "completion": 340 diff --git a/scripts/strings.py b/scripts/strings.py index 0e9064f..198e504 100755 --- a/scripts/strings.py +++ b/scripts/strings.py @@ -593,6 +593,41 @@ STRINGS: dict[str, str] = { "share_default_prompt": "Have a look at this.", "share_ask_hint": "What should LLeMbas do with it? (optional)", "widget_hint": "Ask anything", + # The directory picker (spec 3.9.0): the server's dialog, in the server's words. + "directory_places": "Places on this device", + "directory_last_used": "Last used here: %1$s. A new chat in this directory starts on it unless you choose another.", + "directory_refused": "The device will not open a session here.", + "directory_up": "Up a level", + "directory_all_places": "All places", + "directory_not_trusted": "Not trusted on the device", + "directory_empty": "No directories here.", + "directory_no_places": "This device offers no directories: its remote roots are empty or missing.", + "directory_browse": "Browse", + "directory_path": "A full path", + "directory_choose": "Choose", + "directory_no_listing": "This device's directories cannot be listed right now. Type the path below.", + # The two types of schedule (spec 3.9.0), in the web form's words. + "model": "Model", + "schedule_type": "Type", + "schedule_chat": "Chat", + "schedule_chat_line": "Runs on this server, like a chat: with the server's tools (search, your files here, memory) and on a scheduling model.", + "schedule_agentic": "Agentic", + "schedule_agentic_line": "Runs on one of your computers, in one folder there, as an agent: with the agent's tools on that computer — its files and its shell — under the computer's own limits. It belongs to that computer and folder.", + "schedule_agentic_unavailable": "None of your computers accepts scheduled work now. Link one and switch on “Accept scheduled work” in its LLeMbas CLI (lembas service scheduled on).", + "schedule_computer_refuses": "does not accept scheduled work", + "schedule_computer_hint": "The computer must allow it: “Accept scheduled work” in its LLeMbas CLI (lembas service scheduled on). When it is not linked at the time of a run, the run waits for it; if it has not come back before the run's time has passed, the run is recorded as missed and you are told.", + "schedule_computer_gone": "a computer no longer signed in", + "schedule_folder": "Folder on the computer", + "schedule_agent_mode": "Mode", + "schedule_agent_mode_hint": "Edit unless you choose otherwise; Auto runs commands without asking. The computer may lower it.", + "schedule_approval_wait": "An approval waits (minutes)", + "schedule_approval_wait_hint": "A command the run needs approved comes to your phone as a card. Unanswered by then, it counts as denied.", + "schedule_folder_model": "The folder's usual model", + "schedule_folder_model_hint": "The folder's usual model is the one you last used in that folder on that computer — the computer remembers it, and each run asks it — or your default model where there is none. A model chosen here is the run's, whatever the folder's is. A run never changes the folder's model.", + "schedule_first_free_model": "The first free one of your scheduling models", + "run_model_directory": "the folder's usual model", + "run_model_default": "your default model", + "run_model_session": "the conversation's own model", "widget_speak": "Speak", "widget_description": "Ask by voice or text, or carry on the last assistant chat. Shows nothing from your account.", "shortcut_last": "Last chat", @@ -619,6 +654,7 @@ SERVER_ENGLISH: dict[str, str] = { "progress_failed": "Failed: {{reason}}", "progress_what_approval": "allow {{tool}}?", "progress_line": "{{text}} · {{elapsed}}", + "directory_last_used": "Last used here: %(model)s. A new chat in this directory starts on it unless you choose another.", "tree_open_slots": "Open slots: %(n)s", "card_asker": "%(job)s asks:", "card_subagent_asks": "Subagent %(name)s (%(id)s), %(position)s, asks:", diff --git a/scripts/strings_own.json b/scripts/strings_own.json index cee50d3..f3891ed 100644 --- a/scripts/strings_own.json +++ b/scripts/strings_own.json @@ -115,6 +115,9 @@ "code": "Kód", "composer_hint_agent": "Řekněte agentovi, co má udělat", "device_name": "LLeMbas pro Android", + "directory_choose": "Vybrat", + "directory_no_listing": "Adresáře tohoto zařízení teď nelze vypsat. Napište cestu níže.", + "directory_path": "Úplná cesta", "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.", @@ -207,7 +210,9 @@ "reports_none": "Zatím žádné zprávy. Naplánovaná úloha ji napíše, když vám má co říct.", "reports_unsupported": "Na této instanci běží LLeMbas, který Zprávy ještě nemá.", "run_missed": "Zmeškáno ×%1$s", + "run_model_default": "váš výchozí model", "run_model_instead": "%1$s, místo %2$s", + "run_model_session": "vlastní model konverzace", "run_no_text": "Tento běh nezanechal žádný text.", "run_open_report": "Otevřít její zprávu", "run_result": "Výsledek", @@ -507,6 +512,9 @@ "code": "Code", "composer_hint_agent": "Sag dem Agenten, was er tun soll", "device_name": "LLeMbas für Android", + "directory_choose": "Auswählen", + "directory_no_listing": "Die Verzeichnisse dieses Geräts können gerade nicht aufgelistet werden. Geben Sie den Pfad unten ein.", + "directory_path": "Ein vollständiger Pfad", "effort": "Aufwand", "empty_chat": "Worüber sprechen wir?", "empty_chats": "Noch keine Chats. Nicht jeder, der wandert, ist verloren — fangen Sie einen an.", @@ -600,7 +608,9 @@ "reports_none": "Noch keine Berichte. Eine geplante Aufgabe schreibt einen, wenn sie dir etwas zu sagen hat.", "reports_unsupported": "Auf dieser Instanz läuft ein LLeMbas, das noch keine Berichte hat.", "run_missed": "Verpasst ×%1$s", + "run_model_default": "Ihr Standardmodell", "run_model_instead": "%1$s statt %2$s", + "run_model_session": "das eigene Modell der Unterhaltung", "run_no_text": "Dieser Lauf hat keinen Text hinterlassen.", "run_open_report": "Zugehörigen Bericht öffnen", "run_result": "Ergebnis", @@ -900,6 +910,9 @@ "code": "Código", "composer_hint_agent": "Dile al agente qué hacer", "device_name": "LLeMbas para Android", + "directory_choose": "Elegir", + "directory_no_listing": "Ahora no se pueden listar las carpetas de este dispositivo. Escriba la ruta abajo.", + "directory_path": "Una ruta completa", "effort": "Esfuerzo", "empty_chat": "¿De qué hablamos?", "empty_chats": "Aún no hay chats. No todos los que vagan están perdidos — empiece uno.", @@ -992,7 +1005,9 @@ "reports_none": "Aún no hay informes. Una tarea programada escribe uno cuando tiene algo que decirte.", "reports_unsupported": "Esta instancia ejecuta un LLeMbas que todavía no tiene Informes.", "run_missed": "Perdida ×%1$s", + "run_model_default": "su modelo predeterminado", "run_model_instead": "%1$s, en lugar de %2$s", + "run_model_session": "el modelo propio de la conversación", "run_no_text": "Esta ejecución no dejó texto.", "run_open_report": "Abrir su informe", "run_result": "Resultado", @@ -1292,6 +1307,9 @@ "code": "Code", "composer_hint_agent": "Dites à l’agent quoi faire", "device_name": "LLeMbas pour Android", + "directory_choose": "Choisir", + "directory_no_listing": "Les dossiers de cet appareil ne peuvent pas être listés pour le moment. Saisissez le chemin ci-dessous.", + "directory_path": "Un chemin complet", "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.", @@ -1385,7 +1403,9 @@ "reports_none": "Pas encore de rapport. Une tâche planifiée en rédige un quand elle a quelque chose à vous dire.", "reports_unsupported": "Cette instance utilise un LLeMbas qui n’a pas encore les Rapports.", "run_missed": "Manquée ×%1$s", + "run_model_default": "votre modèle par défaut", "run_model_instead": "%1$s, au lieu de %2$s", + "run_model_session": "le modèle propre à la conversation", "run_no_text": "Cette exécution n’a laissé aucun texte.", "run_open_report": "Ouvrir son rapport", "run_result": "Résultat", @@ -1685,6 +1705,9 @@ "code": "Kód", "composer_hint_agent": "Mondja meg az ügynöknek, mit tegyen", "device_name": "LLeMbas Androidra", + "directory_choose": "Kiválasztás", + "directory_no_listing": "Az eszköz könyvtárai most nem listázhatók. Adja meg az elérési utat lent.", + "directory_path": "Teljes elérési út", "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.", @@ -1778,7 +1801,9 @@ "reports_none": "Még nincsenek jelentések. Egy ütemezett feladat akkor ír egyet, ha van mit mondania neked.", "reports_unsupported": "Ezen a példányon olyan LLeMbas fut, amelyben még nincsenek Jelentések.", "run_missed": "Kimaradt ×%1$s", + "run_model_default": "az Ön alapértelmezett modellje", "run_model_instead": "%1$s, %2$s helyett", + "run_model_session": "a beszélgetés saját modellje", "run_no_text": "Ez a futás nem hagyott szöveget.", "run_open_report": "A jelentésének megnyitása", "run_result": "Eredmény", @@ -2078,6 +2103,9 @@ "code": "Codice", "composer_hint_agent": "Di’ all’agente cosa fare", "device_name": "LLeMbas per Android", + "directory_choose": "Scegli", + "directory_no_listing": "Le cartelle di questo dispositivo non si possono elencare adesso. Scrivi il percorso qui sotto.", + "directory_path": "Un percorso completo", "effort": "Impegno", "empty_chat": "Di cosa parliamo?", "empty_chats": "Ancora nessuna chat. Non tutti quelli che vagano sono perduti — iniziane una.", @@ -2170,7 +2198,9 @@ "reports_none": "Ancora nessun rapporto. Un’attività pianificata ne scrive uno quando ha qualcosa da dirti.", "reports_unsupported": "Questa istanza usa un LLeMbas che non ha ancora i Rapporti.", "run_missed": "Saltata ×%1$s", + "run_model_default": "il tuo modello predefinito", "run_model_instead": "%1$s, invece di %2$s", + "run_model_session": "il modello proprio della conversazione", "run_no_text": "Questa esecuzione non ha lasciato testo.", "run_open_report": "Apri il suo rapporto", "run_result": "Risultato", @@ -2470,6 +2500,9 @@ "code": "Kod", "composer_hint_agent": "Powiedz agentowi, co ma zrobić", "device_name": "LLeMbas na Androida", + "directory_choose": "Wybierz", + "directory_no_listing": "Katalogów tego urządzenia nie można teraz wyświetlić. Wpisz ścieżkę poniżej.", + "directory_path": "Pełna ścieżka", "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.", @@ -2562,7 +2595,9 @@ "reports_none": "Nie ma jeszcze raportów. Zaplanowane zadanie pisze raport, gdy ma Ci coś do powiedzenia.", "reports_unsupported": "Na tej instancji działa LLeMbas, który nie ma jeszcze Raportów.", "run_missed": "Pominięto ×%1$s", + "run_model_default": "Twój domyślny model", "run_model_instead": "%1$s zamiast %2$s", + "run_model_session": "własny model rozmowy", "run_no_text": "To uruchomienie nie zostawiło tekstu.", "run_open_report": "Otwórz jego raport", "run_result": "Wynik", @@ -2862,6 +2897,9 @@ "code": "Kód", "composer_hint_agent": "Povedzte agentovi, čo má urobiť", "device_name": "LLeMbas pre Android", + "directory_choose": "Vybrať", + "directory_no_listing": "Adresáre tohto zariadenia sa teraz nedajú vypísať. Napíšte cestu nižšie.", + "directory_path": "Úplná cesta", "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.", @@ -2954,7 +2992,9 @@ "reports_none": "Zatiaľ žiadne správy. Naplánovaná úloha ju napíše, keď vám má čo povedať.", "reports_unsupported": "Na tejto inštancii beží LLeMbas, ktorý Správy ešte nemá.", "run_missed": "Zmeškané ×%1$s", + "run_model_default": "váš predvolený model", "run_model_instead": "%1$s, namiesto %2$s", + "run_model_session": "vlastný model konverzácie", "run_no_text": "Tento beh nezanechal žiadny text.", "run_open_report": "Otvoriť jej správu", "run_result": "Výsledok",