A folder picker for a linked computer, the folder's usual model, Chat and Agentic schedules, @ in the composer
CI / check (push) Canceled after 0s

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 <noreply@anthropic.com>
This commit is contained in:
HomerandClaude Fable 5.2 committed 2026-11-18 00:38:23 +00:00
1 parent c0dd0b5a50
commit 979a504600
42 files changed
+2150 -44

No files matched your search

@@ -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<Folder> = get<FolderList>("/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<LinkedDevice> = get<DeviceList>("/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)
@@ -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<String> = emptyList(),
val entries: List<DirectoryEntry> = 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 = "")
@@ -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<Mention> = 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<DeviceFile> = 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<Folder> = 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<LinkedDevice> = emptyList())
@@ -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
}
@@ -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<Job?>(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),
)
}
}
}
@@ -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<Mention> = 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<Uri>) {}
/** 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<Mention> {
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<Application>().packageName}.files"
/**
@@ -650,4 +749,8 @@ class ChatViewModel(app: Application) :
}
}
}
private companion object {
const val MENTION_PAUSE_MS = 250L
}
}
@@ -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<Mention>, 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 },
)
}
}
@@ -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)
@@ -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<LinkedDevice> = 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<SchedulingModel> = 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<LinkedDevice>): 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<Application>().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<Application>().api().devices() }.onSuccess { linked -> _state.update { it.listed(linked) } }
}
viewModelScope.launch {
runCatching { getApplication<Application>().api().schedulingModels() }.onSuccess { m -> _state.update { it.copy(models = m.models) } }
}
if (id == null) return
viewModelScope.launch {
runCatching { getApplication<Application>().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<Application>().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