Review: a save says only what changed, the picker and the @ list are bounded, followers survive a finger
CI / check (push) Canceled after 0s

- Schedule form: `runs_on`, `model` and the watched command are sent only
  where they differ from what was read (whereToSend, modelToSend,
  watchToSend). The type is not choosable until an edited schedule was
  read. A Chat schedule's model is shown when it is made Agentic. Modes by
  the computer's `max_mode`. The Agentic form has the watched command and
  its timeout; Agentic to Chat takes the command off and says so.
- Picker: each path once and at most 500 entries, the device's words cut
  and ellipsised, Back closes after a question that got no listing, what
  was typed while the device answered stays, a listing's own sentence shown.
- @: at most 50 entries; a device path with control characters or over 512
  characters is not offered; asked again when the computer or folder
  changes; attaching no longer ends another upload's "uploading".
- Followers: a scroll a finger interrupts no longer ends the collector
  (yielding), and nothing is scrolled while a scroll is under way. Only a
  message this app sent counts as Sent.
- /events: one shared connection for the drawer and the Scheduled list
  (EventsHub); a route that closes without a frame backs off; a slow list
  read no longer overwrites a newer `reports` count.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
This commit is contained in:
HomerandClaude Fable 5.2 committed 2026-11-18 01:04:24 +00:00
1 parent 979a504600
commit 1d3154cefa
31 files changed
+738 -91

No files matched your search

@@ -5,14 +5,31 @@ import android.app.Application
import android.app.NotificationChannel
import android.app.NotificationManager
import android.os.Bundle
import eu.llembas.android.api.EventsHub
import eu.llembas.android.api.Frame
import eu.llembas.android.api.StreamClient
import eu.llembas.android.auth.InstanceStore
import eu.llembas.android.wake.AppVisibility
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.SupervisorJob
import kotlinx.coroutines.flow.Flow
/** The process: one store of instances, and the notification channels, made once. */
class LembasApp : Application() {
lateinit var instances: InstanceStore
private set
/** The one connection to the person's events route, shared by all that watch it. */
val events = EventsHub(CoroutineScope(SupervisorJob() + Dispatchers.Default))
/** The events route of the instance in use, as its frames; null when not signed in. */
suspend fun eventFrames(): Flow<Frame>? {
val instance = instances.current() ?: return null
val api = instances.clientFor(instance)
return events.frames(instance.id) { StreamClient(api).watch { api.events() } }
}
override fun onCreate() {
super.onCreate()
instances = InstanceStore(this)
@@ -408,6 +408,8 @@ class ApiClient(val base: String, private val token: String, val http: OkHttpCli
notify: String? = null,
notifyWhen: String = "",
where: WhereToRun = WhereToRun.Leave,
model: String? = null,
watch: WatchCommand? = null,
): Schedule {
val body = buildJsonObject {
// The type (spec 3.9.0): Agentic is a schedule with a computer, Chat one without. Left
@@ -427,8 +429,24 @@ class ApiClient(val base: String, private val token: String, val http: OkHttpCli
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)
}
}
// The model, where the form says one: empty is the folder's usual model for an
// Agentic schedule, asked of the computer as each run starts.
model?.let { put("model", it) }
// The watched command, where the form says one: none at all is "watch nothing".
watch?.let { said ->
if (said.command.isBlank()) {
put("watch", JsonNull)
} else {
put(
"watch",
buildJsonObject {
put("kind", "command")
put("command", said.command)
said.timeoutS?.let { put("timeout_s", it) }
},
)
}
}
put("title", compiled.title)
@@ -0,0 +1,46 @@
package eu.llembas.android.api
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.SharedFlow
import kotlinx.coroutines.flow.SharingStarted
import kotlinx.coroutines.flow.catch
import kotlinx.coroutines.flow.onEach
import kotlinx.coroutines.flow.onStart
import kotlinx.coroutines.flow.onSubscription
import kotlinx.coroutines.flow.shareIn
import java.util.concurrent.ConcurrentHashMap
/**
* One connection to a person's events route (`GET /events`) for everything that watches it --
* the drawer's Reports badge, the Scheduled list -- instead of one each. It is open while
* somebody watches and closed when nobody does.
*
* Every frame of the route is a whole state (`schedules`, `reports`), which the server sends at
* once to a new connection. A watcher that joins a connection already open missed that, so it
* is first told the last frame of each kind this connection carried.
*
* A route that refuses (an older server) ends quietly: its watchers hear nothing, as they did
* when each asked for itself.
*/
class EventsHub(private val scope: CoroutineScope) {
private class Line(val key: String, val frames: SharedFlow<Frame>, val latest: MutableMap<String, Frame>)
private var line: Line? = null
/** The frames of the route [key] names (an instance's id), opened by [open] when nobody watches it yet. */
@Synchronized
fun frames(key: String, open: () -> Flow<Frame>): Flow<Frame> {
val now = line?.takeIf { it.key == key } ?: run {
val latest = ConcurrentHashMap<String, Frame>()
val shared = open()
// A connection opened anew is told everything again: what the last one said is stale.
.onStart { latest.clear() }
.onEach { latest[it.event] = it }
.catch { }
.shareIn(scope, SharingStarted.WhileSubscribed(), replay = 0)
Line(key, shared, latest).also { line = it }
}
return now.frames.onSubscription { now.latest.values.toList().forEach { emit(it) } }
}
}
@@ -198,9 +198,19 @@ data class SchedulingModel(
@Serializable
data class SchedulingModels(val models: List<SchedulingModel> = emptyList(), val instance: List<String> = emptyList(), val mine: List<String> = emptyList())
/** What a watching schedule looks at before each run: [kind] `url` and the address. */
/**
* What a watching schedule looks at before each run: [kind] `url` and the address, or -- on a
* linked computer -- `command`, the [command] run in the schedule's folder and how many seconds
* it may take ([timeoutS]). [target] is either, as one string.
*/
@Serializable
data class ScheduleWatch(val kind: String = "", val target: String = "", @SerialName("changed_at") val changedAt: String? = null)
data class ScheduleWatch(
val kind: String = "",
val target: String = "",
val command: String = "",
@SerialName("timeout_s") val timeoutS: Int? = null,
@SerialName("changed_at") val changedAt: String? = null,
)
/** One run's look: whether the address [changed] since the last one, or why the look failed. */
@Serializable
@@ -255,13 +265,18 @@ 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.
* mode, with an approval's wait in minutes (null: the server's default).
*/
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
data class Computer(val device: String, val cwd: String, val mode: String, val approvalWaitMinutes: Int?) : WhereToRun
}
/**
* The command an Agentic schedule watches before each run, as a save says it: the [command]
* (empty: watch nothing) and how many seconds it may take (null: the server's own).
*/
data class WatchCommand(val command: String, val timeoutS: Int?)
@@ -55,19 +55,25 @@ class StreamClient(private val api: ApiClient) {
/**
* Follow an events route that ends itself now and then (`close` after a while, as the
* activity panel's does): opened again at once after a `close`, and after a pause that
* grows to 30 seconds when the connection drops. It runs until its collector stops; a
* refusal (4xx) ends it with the error.
* grows to 30 seconds when the connection drops or closes without a frame. It runs until
* its collector stops; a refusal (4xx) ends it with the error.
*/
fun watch(request: () -> Request): Flow<Frame> = flow {
var wait = 1_000L
while (true) {
var closed = false
var said = false
var refused: ApiException? = null
once(request()).collect { result ->
when (result) {
is Outcome.Event -> {
wait = 1_000L
if (result.frame.event == "close") closed = true else emit(result.frame)
if (result.frame.event == "close") {
closed = true
} else {
said = true
wait = 1_000L
emit(result.frame)
}
}
is Outcome.Refused -> refused = result.error
@@ -76,7 +82,10 @@ class StreamClient(private val api: ApiClient) {
}
}
refused?.let { throw it }
if (closed) continue
// A route that closes after it has said something is opened again at once. One
// that closes having said nothing waits as a dropped one does: a server that only
// ever answers `close` must not be asked in a tight loop.
if (reopenAtOnce(closed, said)) continue
delay(wait)
wait = (wait * 2).coerceAtMost(30_000L)
}
@@ -115,3 +124,6 @@ class StreamClient(private val api: ApiClient) {
awaitClose { source.cancel() }
}
}
/** Whether an events route that ended is opened again without a pause: only one that [closed] itself after it [said] something. */
fun reopenAtOnce(closed: Boolean, said: Boolean): Boolean = closed && said
@@ -97,6 +97,7 @@ import eu.llembas.android.ui.ProgressStatus
import eu.llembas.android.ui.chat.PhoneCard
import eu.llembas.android.ui.chat.Steps
import eu.llembas.android.ui.chat.followsAt
import eu.llembas.android.ui.chat.yielding
import eu.llembas.android.ui.progressLineOf
import eu.llembas.android.ui.theme.LocalPalette
import kotlinx.coroutines.launch
@@ -239,7 +240,10 @@ fun ColumnScope.AssistSheetContent(
// The end moves when the answer grows and when the keyboard opens; before the first layout
// it is not known yet.
LaunchedEffect(scroll) {
snapshotFlow { if (following) scroll.maxValue else -1 }.collect { end -> if (end in 0 until Int.MAX_VALUE) scroll.scrollTo(end) }
// Never against a finger: nothing is moved while a scroll is under way, and one of
// ours that a finger interrupts does not end this follower (`yielding`).
snapshotFlow { if (following && !scroll.isScrollInProgress) scroll.maxValue else -1 }
.collect { end -> if (end in 0 until Int.MAX_VALUE) yielding { scroll.scrollTo(end) } }
}
// The top: the handle and the bar. Both drag the sheet.
@@ -60,21 +60,67 @@ 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]).
* listing that could not be had, or that came with one ([error]). [edited]: the person wrote in
* the field since the device was last asked, so its answer does not write over them.
* [failed]: the last question got no listing.
*/
data class PickerState(val listing: DeviceDirectory? = null, val loading: Boolean = false, val typed: String = "", val error: String? = null)
data class PickerState(
val listing: DeviceDirectory? = null,
val loading: Boolean = false,
val typed: String = "",
val error: String? = null,
val edited: Boolean = false,
val failed: Boolean = false,
)
/** The most subdirectories shown; a device that names more is cut there. */
const val PICKER_ENTRIES = 500
/** The longest a device's own words are kept: a name, a reason, a sentence. */
const val PICKER_WORDS = 300
private fun String.kept(): String = if (length > PICKER_WORDS) take(PICKER_WORDS) + "…" else this
/**
* 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).
* A listing as the picker holds it: each path once (the rows are keyed by it), at most
* [PICKER_ENTRIES] of them, and the device's words -- names, reasons, a model's name -- cut to
* a length that cannot push the controls away.
*/
fun DeviceDirectory.bounded(): DeviceDirectory = copy(
reason = reason.kept(),
error = error.kept(),
model = model?.let { it.copy(name = it.name.kept(), id = it.id.kept()) },
entries = entries.filter { it.path.isNotEmpty() }.distinctBy { it.path }.take(PICKER_ENTRIES).map { entry ->
entry.copy(name = entry.name.kept(), reason = entry.reason.kept(), model = entry.model?.let { it.copy(name = it.name.kept(), id = it.id.kept()) })
},
)
/** The device is being asked: what is typed from now on is the person's, newer than the answer. */
fun PickerState.asking(): PickerState = copy(loading = true, error = null, edited = false)
/**
* The device's answer. A listing is shown ([bounded]) and the field follows it -- unless the
* person wrote in the field while the device was answering, or the listing is the places,
* which have no path: then the field keeps what it has. A listing may come with a sentence
* (part of it could not be read): it is shown with it. 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 })
answer.listed -> copy(
listing = answer.bounded(),
loading = false,
failed = false,
error = answer.error.kept().ifBlank { null },
typed = if (edited) typed else answer.path.ifEmpty { typed },
)
else -> copy(loading = false, failed = true, error = answer.error.kept().ifBlank { fallback })
}
/** The device could not be asked at all ([said]: why): as an answer without a listing. */
fun PickerState.unanswered(said: String): PickerState = copy(loading = false, failed = true, error = said.kept())
/**
* 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
@@ -83,6 +129,13 @@ fun PickerState.took(answer: DeviceDirectory, fallback: String = ""): PickerStat
val PickerState.up: String?
get() = listing?.takeIf { !it.places }?.parent
/**
* Where Back leads: up a level, or null to close -- at the top, and after a question that got
* no listing (the device went away mid-walk), where "up" would only ask it again for ever.
*/
val PickerState.back: String?
get() = if (failed) null else up
/**
* 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
@@ -117,16 +170,16 @@ fun DirectoryPicker(title: String, initial: String, load: suspend (String) -> De
val fallback = stringResource(R.string.directory_no_listing)
val read: (String) -> Unit = { path ->
reading?.cancel()
state = state.copy(loading = true, error = null)
state = state.asking()
reading = scope.launch {
try {
val answer = load(path)
// Applied to the state as it is now: what was typed while the device answered stays.
// Applied to the state as it is now: `took` leaves what was typed meanwhile.
state = state.took(answer, fallback)
} catch (e: CancellationException) {
throw e
} catch (e: Exception) {
state = state.copy(loading = false, error = context.explain(e))
state = state.unanswered(context.explain(e))
}
}
}
@@ -135,7 +188,7 @@ fun DirectoryPicker(title: String, initial: String, load: suspend (String) -> De
override fun open(path: String) = read(path)
override fun typed(text: String) {
state = state.copy(typed = text)
state = state.copy(typed = text, edited = true)
}
override fun choose() {
@@ -143,7 +196,7 @@ fun DirectoryPicker(title: String, initial: String, load: suspend (String) -> De
}
override fun back() {
val up = state.up
val up = state.back
if (up == null) onDismiss() else read(up)
}
@@ -181,16 +234,26 @@ fun DirectoryPickerContent(title: String, state: PickerState, actions: PickerAct
overflow = TextOverflow.Ellipsis,
)
listing?.model?.let {
Text(stringResource(R.string.directory_last_used, it.label), style = MaterialTheme.typography.bodySmall, color = palette.inkMuted)
Text(
stringResource(R.string.directory_last_used, it.label),
style = MaterialTheme.typography.bodySmall,
color = palette.inkMuted,
maxLines = 3,
overflow = TextOverflow.Ellipsis,
)
}
if (listing != null && !listing.places && !listing.accepted) {
Text(
listing.reason.ifBlank { stringResource(R.string.directory_refused) },
style = MaterialTheme.typography.bodySmall,
color = palette.warning,
maxLines = 3,
overflow = TextOverflow.Ellipsis,
)
}
state.error?.let { Text(it, style = MaterialTheme.typography.bodyMedium, color = palette.danger) }
state.error?.let {
Text(it, style = MaterialTheme.typography.bodyMedium, color = palette.danger, maxLines = 4, overflow = TextOverflow.Ellipsis)
}
}
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.
@@ -242,23 +242,24 @@ fun ChatContent(
LaunchedEffect(rows) {
val before = known[0]
known[0] = rows
val change = transcriptChange(before, rows, restored = drawnBefore)
val change = transcriptChange(before, rows, restored = drawnBefore, sent = state.lastSent)
if (rows.isNotEmpty()) drawnBefore = true
if (change == TranscriptChange.Older) {
// An older page above the very top: the row that was first stays first, so reading
// goes on upwards from it. Anywhere else the list keeps its place by the rows' keys.
val kept = keptRow(before.orEmpty(), rows)
if (kept != null && list.firstVisibleItemIndex == 0) list.scrollToItem(kept + if (state.more) 1 else 0)
if (kept != null && list.firstVisibleItemIndex == 0) yielding { list.scrollToItem(kept + if (state.more) 1 else 0) }
} else if (movesToEnd(change, following)) {
following = true
list.toEnd()
yielding { list.toEnd() }
}
}
val growth = live?.let { it.shown.size * 100_000 + (it.tail.text.length + it.tail.thinking.length) } ?: 0
LaunchedEffect(growth) { if (growth > 0 && following) list.toEnd() }
LaunchedEffect(growth) { if (growth > 0 && following && !list.isScrollInProgress) yielding { list.toEnd() } }
// The keyboard opening takes the list's foot away: a person at the end stays at the end.
LaunchedEffect(list) {
snapshotFlow { list.layoutInfo.viewportSize.height }.drop(1).collect { if (following) list.toEnd() }
// A finger on the list ends a scroll of ours by cancelling it: this follower goes on.
snapshotFlow { list.layoutInfo.viewportSize.height }.drop(1).collect { if (following && !list.isScrollInProgress) yielding { list.toEnd() } }
}
CompositionLocalProvider(LocalCopy provides copy) {
@@ -95,6 +95,8 @@ data class ChatState(
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(),
/** The message this app sent last, by its id: what the transcript shows whoever has scrolled where. */
val lastSent: String? = null,
)
/**
@@ -254,7 +256,7 @@ class ChatViewModel(app: Application) :
private fun fail(e: Throwable) {
// A follow that was replaced by a newer one is cancelled, not failed: nothing to say.
if (e is CancellationException) return
_state.update { it.copy(error = getApplication<Application>().explain(e), loading = false, uploading = false) }
_state.update { it.copy(error = getApplication<Application>().explain(e), loading = false, uploading = uploads > 0) }
}
fun clearError() = _state.update { it.copy(error = null, notice = null) }
@@ -442,7 +444,10 @@ class ChatViewModel(app: Application) :
private fun took(turn: Turn) {
_state.update { s ->
s.copy(messages = s.messages.filterNot { m -> m.id == turn.message?.id || m.id == turn.reply?.id } + listOfNotNull(turn.message, turn.reply))
s.copy(
messages = s.messages.filterNot { m -> m.id == turn.message?.id || m.id == turn.reply?.id } + listOfNotNull(turn.message, turn.reply),
lastSent = turn.message?.id ?: s.lastSent,
)
}
turn.reply?.let { follow(it.id) }
}
@@ -487,7 +492,7 @@ class ChatViewModel(app: Application) :
agents = agents,
forceTool = if (picture) IMAGE_TOOL else null,
)
_state.update { it.copy(chat = made.chat, messages = listOfNotNull(made.message, made.reply)) }
_state.update { it.copy(chat = made.chat, messages = listOfNotNull(made.message, made.reply), lastSent = made.message?.id) }
made.reply?.let { follow(it.id) }
} else {
took(client.sendMessage(chat.id, text, files, forceTool = if (picture) IMAGE_TOOL else null))
@@ -649,10 +654,23 @@ class ChatViewModel(app: Application) :
then()
}
/** How many uploads and attachings are under way: `uploading` holds until the last has ended. */
private var uploads = 0
private fun uploadBegins() {
uploads++
_state.update { it.copy(uploading = true) }
}
private fun uploadEnds() {
uploads = (uploads - 1).coerceAtLeast(0)
_state.update { it.copy(uploading = uploads > 0) }
}
override fun attach(uris: List<Uri>) {
if (uris.isEmpty()) return
viewModelScope.launch {
_state.update { it.copy(uploading = true) }
uploadBegins()
try {
val resolver = getApplication<Application>().contentResolver
for (uri in uris) {
@@ -671,7 +689,7 @@ class ChatViewModel(app: Application) :
} catch (e: Exception) {
fail(e)
}
_state.update { it.copy(uploading = false) }
uploadEnds()
}
}
@@ -686,6 +704,7 @@ class ChatViewModel(app: Application) :
suggesting = viewModelScope.launch {
// Asked once the typing pauses, not at every letter.
delay(MENTION_PAUSE_MS)
val where = _state.value.let { Triple(it.chat?.id, it.device?.id, it.draft.directory) }
val found = try {
offered(query)
} catch (e: CancellationException) {
@@ -694,7 +713,8 @@ class ChatViewModel(app: Application) :
// An older server, or a device that cannot answer: nothing is offered.
emptyList()
}
_state.update { it.copy(mentions = found) }
// Another computer or folder was chosen meanwhile: these were its files, not this one's.
_state.update { if (Triple(it.chat?.id, it.device?.id, it.draft.directory) == where) it.copy(mentions = found) else it }
}
}
@@ -704,21 +724,22 @@ class ChatViewModel(app: Application) :
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().deviceFiles(device, query, chatId = chat?.id, cwd = now.draft.directory).files.mapNotNull { it.asMention() }.take(MENTION_LIMIT)
}
return api().mentions(query, chat?.id).items
return api().mentions(query, chat?.id).items.take(MENTION_LIMIT)
}
override fun mention(item: Mention) {
_state.update { it.copy(mentions = emptyList(), uploading = true) }
_state.update { it.copy(mentions = emptyList()) }
viewModelScope.launch {
uploadBegins()
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) }
uploadEnds()
}
}
@@ -214,7 +214,9 @@ 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)) }
// Asked again when the words change -- and when the computer or the folder does: an
// agent chat's `@` is that folder's files.
LaunchedEffect(text, state.chat?.id, state.device?.id, state.draft.directory) { 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)
@@ -446,7 +448,7 @@ fun Composer(state: ChatState, actions: ChatActions, agent: Boolean, onTune: ()
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 ->
items.take(MENTION_LIMIT).forEach { item ->
Row(
Modifier.fillMaxWidth().clickable { onPick(item) }.heightIn(min = 48.dp).padding(horizontal = 16.dp, vertical = 6.dp),
verticalAlignment = Alignment.CenterVertically,
@@ -1,6 +1,9 @@
package eu.llembas.android.ui.chat
import eu.llembas.android.api.Message
import kotlinx.coroutines.CancellationException
import kotlinx.coroutines.currentCoroutineContext
import kotlinx.coroutines.ensureActive
/*
* Whether a list keeps to its end while something is written into it. The rule, the same for the
@@ -17,7 +20,7 @@ enum class TranscriptChange {
/** A chat shown for the first time, or another chat in the same place. */
Opened,
/** The person's own message is new at the end: sending always shows what was sent. */
/** A message this app just sent is new at the end: sending always shows what was sent. */
Sent,
/** New rows at the end that the person did not write: a reply, the queue's next turn. */
@@ -33,9 +36,12 @@ enum class TranscriptChange {
/**
* What changed from [before] to [after]. [before] is null when this draw is the first one this
* list makes; [restored] then says the list had rows before (a rotation, a return to the
* screen), so its place is the one it kept, not a chat being opened.
* screen), so its place is the one it kept, not a chat being opened. [sent] is the id of the
* message this app sent last: only that one is "sent". The person's row arriving from
* elsewhere -- written on the page or another device while this chat is open here -- is a row
* like a reply's, and does not pull a reader down.
*/
fun transcriptChange(before: List<Message>?, after: List<Message>, restored: Boolean = false): TranscriptChange {
fun transcriptChange(before: List<Message>?, after: List<Message>, restored: Boolean = false, sent: String? = null): TranscriptChange {
if (after.isEmpty()) return TranscriptChange.None
if (before == null) return if (restored) TranscriptChange.Changed else TranscriptChange.Opened
val known = before.mapTo(HashSet()) { it.id }
@@ -43,7 +49,7 @@ fun transcriptChange(before: List<Message>?, after: List<Message>, restored: Boo
if (firstKept < 0) return TranscriptChange.Opened
val added = after.subList(after.indexOfLast { it.id in known } + 1, after.size)
return when {
added.any { it.isUser && !it.machine } -> TranscriptChange.Sent
sent != null && added.any { it.id == sent } -> TranscriptChange.Sent
added.isNotEmpty() -> TranscriptChange.Appended
firstKept > 0 -> TranscriptChange.Older
before == after -> TranscriptChange.None
@@ -77,3 +83,17 @@ fun keptRow(before: List<Message>, after: List<Message>): Int? {
val first = before.firstOrNull() ?: return null
return after.indexOfFirst { it.id == first.id }.takeIf { it >= 0 }
}
/**
* A scroll this app makes for the person ([scroll]: to the end, as the reply grows). A finger
* on the list takes it over, and Compose ends the scroll by cancelling it -- which, left
* alone, would also end whatever follower called it, for good. So that cancellation is taken
* here, and only that one: when the follower itself is cancelled, it still ends.
*/
suspend fun yielding(scroll: suspend () -> Unit) {
try {
scroll()
} catch (e: CancellationException) {
currentCoroutineContext().ensureActive()
}
}
@@ -27,5 +27,20 @@ fun withoutMention(text: String): String = if (mentionQuery(text) == null) text
/** [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)
/** The most entries the `@` list shows. */
const val MENTION_LIMIT = 50
/** The longest path a device's file may have to be offered. */
const val MENTION_PATH = 512
/**
* A device's file as an entry of the `@` list: its name, and its path as the detail. Null for
* one that is not offered: its path goes into the message as it is, so a path with a line
* break or another control character in it -- which the one-line row would not show -- or one
* too long to be a path is left out.
*/
fun DeviceFile.asMention(): Mention? {
if (path.isBlank() || path.length > MENTION_PATH || path.any { it.isISOControl() }) return null
val shown = name.filterNot { it.isISOControl() }.take(MENTION_PATH).ifBlank { path }
return Mention(kind = MENTION_DEVICE, path = path, name = shown, detail = if (kind == "dir") "$path/" else path)
}
@@ -80,7 +80,6 @@ import eu.llembas.android.api.Folder
import eu.llembas.android.api.LembasJson
import eu.llembas.android.api.ReportsFrame
import eu.llembas.android.api.SearchHit
import eu.llembas.android.api.StreamClient
import eu.llembas.android.api.fit
import eu.llembas.android.lembas
import eu.llembas.android.ui.explain
@@ -152,6 +151,7 @@ class ChatsViewModel(app: Application) : AndroidViewModel(app) {
_state.value = ChatsState(error = getApplication<Application>().getString(said))
return@launch
}
val told = reportsTold
val page = api.chats()
// Folders are a side dish: the chats show without them if they cannot be read.
val folders = runCatching { api.folders() }.getOrDefault(_state.value.folders)
@@ -166,12 +166,15 @@ class ChatsViewModel(app: Application) : AndroidViewModel(app) {
} else {
_state.value.reports
}
// The events route may have said the count while this was being read: its
// word is the newer one, and a slow read does not write over it.
val newer = reportsTold != told
_state.value = ChatsState(
chats = page.chats,
more = page.more,
folders = folders,
unreadReports = unread.getOrDefault(_state.value.unreadReports),
reports = has,
unreadReports = if (newer) _state.value.unreadReports else unread.getOrDefault(_state.value.unreadReports),
reports = has || (newer && _state.value.reports),
)
} catch (e: Exception) {
_state.update { it.copy(loading = false, error = getApplication<Application>().explain(e)) }
@@ -186,11 +189,14 @@ class ChatsViewModel(app: Application) : AndroidViewModel(app) {
* badge is then what the drawer's own read said.
*/
suspend fun watchReports() {
val api = runCatching { getApplication<Application>().lembas.instances.client() }.getOrNull() ?: return
val frames = runCatching { getApplication<Application>().lembas.eventFrames() }.getOrNull() ?: return
try {
StreamClient(api).watch { api.events() }.collect { frame ->
frames.collect { frame ->
// An instance this app refuses shows its refusal and nothing else.
if (frame.event == "reports" && refused == null) _state.update { it.reported(frame.data) }
if (frame.event == "reports" && refused == null) {
reportsTold++
_state.update { it.reported(frame.data) }
}
}
} catch (e: CancellationException) {
throw e
@@ -199,6 +205,9 @@ class ChatsViewModel(app: Application) : AndroidViewModel(app) {
}
}
/** How many `reports` frames have come: a list read that began before the last one is older than it. */
private var reportsTold = 0
fun more() {
val last = _state.value.chats.lastOrNull() ?: return
viewModelScope.launch {
@@ -95,7 +95,7 @@ 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.WatchCommand
import eu.llembas.android.api.WhereToRun
import eu.llembas.android.api.agentic
import eu.llembas.android.api.computerAway
@@ -162,9 +162,10 @@ class ScheduledViewModel(app: Application) : AndroidViewModel(app) {
private fun watch() {
if (live?.isActive == true) return
live = viewModelScope.launch {
val client = runCatching { getApplication<Application>().api() }.getOrNull() ?: return@launch
// The one connection the drawer's badge listens on too (`EventsHub`).
val frames = runCatching { getApplication<Application>().lembas.eventFrames() }.getOrNull() ?: return@launch
try {
StreamClient(client).watch { client.events() }.collect { frame ->
frames.collect { frame ->
if (frame.event != "schedules") return@collect
val read = runCatching { LembasJson.decodeFromString(SchedulesFrame.serializer(), frame.data) }.getOrNull() ?: return@collect
_state.update { it.copy(schedules = read.schedules) }
@@ -883,8 +884,38 @@ data class EditState(
val whereTouched: Boolean = false,
/** What the schedule being edited was when it was read: Agentic or Chat. */
val wasAgentic: Boolean = false,
/** Where the schedule being edited ran, its model and its watched command, as they were read: a save says only what differs. */
val readWhere: WhereToRun.Computer? = null,
val readModel: String = "",
val readWatch: WatchCommand = WatchCommand("", null),
/** An Agentic schedule's watched command (empty: none), and the seconds it may take, as typed. */
val watchCommand: String = "",
val watchTimeout: String = "",
)
/** The agent modes, narrowest first. */
val AGENT_MODES = listOf("manual", "edit", "auto")
/**
* The modes the form offers for a computer whose widest is [maxMode]: none wider than it
* (every one where it names none, as an older computer does), and the mode the schedule
* already has ([current]) whatever the computer says now -- it lowers it itself.
*/
fun modesOffered(maxMode: String, current: String): List<String> {
val widest = AGENT_MODES.indexOf(maxMode).takeIf { it >= 0 } ?: AGENT_MODES.lastIndex
return AGENT_MODES.filterIndexed { i, mode -> i <= widest || mode == current }
}
/** Where the form says the schedule runs, as a save would say it. */
val EditState.computer: WhereToRun.Computer get() = WhereToRun.Computer(device, cwd.trim(), agentMode, waitMinutes)
/** The watched command as the form holds it: the seconds only between 1 and 600, and only with a command. */
val EditState.watched: WatchCommand
get() = watchCommand.trim().let { command -> WatchCommand(command, watchTimeout.trim().toIntOrNull()?.takeIf { command.isNotEmpty() && it in 1..600 }) }
/** An Agentic schedule that watches a command is being made a Chat one: the command cannot go with it. */
val EditState.dropsWatch: Boolean get() = !agentic && wasAgentic && readWatch.command.isNotEmpty()
/** Agentic is offered only while one of the person's computers accepts scheduled work. */
val EditState.agenticOffered: Boolean get() = devices.any { it.scheduled }
@@ -899,24 +930,55 @@ val EditState.whereComplete: Boolean get() = !agentic || (device.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 and nothing otherwise (the server's own default is Chat). An edit says only what
* the form knows and what differs from what it read: nothing where the schedule could not be
* read, nothing for a schedule whose computer, folder, mode and wait are as they were (so its
* words can be put right while its computer is not linked), 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)
state.agentic -> state.computer.takeUnless { editing && it == state.readWhere } ?: WhereToRun.Leave
editing && state.wasAgentic -> WhereToRun.Server
else -> WhereToRun.Leave
}
/**
* The model a save says, or null for none: an Agentic schedule's, when it is new and one was
* chosen, or when it differs from the one read (the empty one is then said too: back to the
* folder's usual model). A Chat schedule's model is not this form's to change.
*/
fun modelToSend(state: EditState, editing: Boolean): String? = when {
!state.agentic || (editing && !state.loaded) -> null
editing -> state.model.takeIf { it != state.readModel }
else -> state.model.ifBlank { null }
}
/**
* The watched command a save says, or null for none: an Agentic schedule's when it differs
* from the one read (an emptied field is said: watch nothing), a new one's when one was
* written -- and "watch nothing" for a schedule made Chat that watched a command, which the
* server would otherwise refuse.
*/
fun watchToSend(state: EditState, editing: Boolean): WatchCommand? = when {
editing && !state.loaded -> null
state.agentic -> state.watched.takeIf { if (editing) it != state.readWatch else it.command.isNotEmpty() }
state.dropsWatch -> WatchCommand("", null)
else -> null
}
/** 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 }
val watch = s.watch?.takeIf { it.kind == "command" }?.let { WatchCommand(it.command.ifBlank { it.target }.trim(), it.timeoutS) } ?: WatchCommand("", null)
return copy(
wasAgentic = on != null,
readWhere = on?.let {
WhereToRun.Computer(it.device, it.cwd.trim(), it.mode.ifBlank { "edit" }, it.approvalWaitMinutes?.takeIf { minutes -> minutes > 0 })
},
readModel = s.model.orEmpty(),
readWatch = watch,
// 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,
@@ -924,7 +986,10 @@ fun EditState.read(s: Schedule): EditState {
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(),
// A Chat schedule's own model too: made Agentic, it is shown as the model it keeps.
model = if (whereTouched) model else s.model.orEmpty(),
watchCommand = if (whereTouched) watchCommand else watch.command,
watchTimeout = if (whereTouched) watchTimeout else watch.timeoutS?.toString().orEmpty(),
)
}
@@ -1039,6 +1104,8 @@ class ScheduleEditViewModel(app: Application) : AndroidViewModel(app) {
notify = notifyToSend(now, editing = editing != null),
notifyWhen = now.notifyWhen,
where = whereToSend(now, editing = editing != null),
model = modelToSend(now, editing = editing != null),
watch = watchToSend(now, editing = editing != null),
)
then(saved.id)
} catch (e: Exception) {
@@ -1109,7 +1176,8 @@ fun ScheduleEditContent(
verticalArrangement = Arrangement.spacedBy(12.dp),
) {
// The type comes first: it decides where the task runs and what else the form asks.
TypeChoice(state, onWhere)
// Not until a schedule being edited has been read: a choice made before would be the form's guess.
TypeChoice(state, onWhere, ready = !editing || state.loaded)
if (state.agentic) OnComputer(state, onWhere, directories)
Text(stringResource(R.string.schedule_words_hint), style = MaterialTheme.typography.bodyMedium, color = palette.inkMuted)
OutlinedTextField(
@@ -1146,30 +1214,43 @@ fun ScheduleEditContent(
* 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) {
private fun TypeChoice(state: EditState, onWhere: ((EditState) -> EditState) -> Unit, ready: Boolean = true) {
val palette = LocalPalette.current
val offered = state.agenticOffered || state.agentic
val offered = ready && (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),
)
Row(Modifier.padding(horizontal = 16.dp), verticalAlignment = Alignment.CenterVertically) {
Text(
stringResource(R.string.schedule_type),
style = MaterialTheme.typography.labelLarge,
color = palette.accent,
modifier = Modifier.weight(1f),
)
// The schedule is still being read: its type is not known yet, and not to be chosen.
if (!ready && !state.loadFailed) CircularProgressIndicator(strokeWidth = 2.dp, modifier = Modifier.size(16.dp))
}
ChoiceRow(
selected = !state.agentic,
selected = ready && !state.agentic,
enabled = ready,
title = stringResource(R.string.schedule_chat),
line = stringResource(R.string.schedule_chat_line),
onClick = { onWhere { it.copy(agentic = false) } },
)
ChoiceRow(
selected = state.agentic,
selected = ready && 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),
line = stringResource(if (offered || !ready) R.string.schedule_agentic_line else R.string.schedule_agentic_unavailable),
onClick = { onWhere { it.copy(agentic = true) } },
)
if (state.dropsWatch) {
Text(
stringResource(R.string.schedule_chat_drops_watch),
style = MaterialTheme.typography.bodySmall,
color = palette.warning,
modifier = Modifier.padding(horizontal = 16.dp, vertical = 4.dp),
)
}
}
}
}
@@ -1244,10 +1325,13 @@ private fun OnComputer(state: EditState, onWhere: ((EditState) -> EditState) ->
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)) })
// Only the modes the chosen computer allows, and the one the schedule has.
modesOffered(state.chosenDevice?.maxMode.orEmpty(), state.agentMode).forEach { value ->
FilterChip(
selected = state.agentMode == value,
onClick = { onWhere { it.copy(agentMode = value) } },
label = { Text(agentModeWords(value) ?: value) },
)
}
}
Text(
@@ -1268,6 +1352,28 @@ private fun OnComputer(state: EditState, onWhere: ((EditState) -> EditState) ->
modifier = Modifier.fillMaxWidth().padding(horizontal = 16.dp),
)
FieldLabel(stringResource(R.string.schedule_watching_command))
OutlinedTextField(
value = state.watchCommand,
onValueChange = { text -> onWhere { it.copy(watchCommand = text.take(1000)) } },
singleLine = true,
supportingText = { Text(stringResource(R.string.schedule_watch_command_hint)) },
shape = RoundedCornerShape(16.dp),
modifier = Modifier.fillMaxWidth().padding(horizontal = 16.dp),
)
if (state.watchCommand.isNotBlank()) {
FieldLabel(stringResource(R.string.schedule_watch_timeout))
OutlinedTextField(
value = state.watchTimeout,
onValueChange = { text -> onWhere { it.copy(watchTimeout = text.filter(Char::isDigit).take(3)) } },
singleLine = true,
keyboardOptions = KeyboardOptions(keyboardType = KeyboardType.Number),
supportingText = { Text(stringResource(R.string.schedule_watch_timeout_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),