diff --git a/CHANGELOG.md b/CHANGELOG.md index 91437b1..59097ac 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -23,8 +23,10 @@ Needs LLeMbas 2.0.0-beta.14 for what is new here; with an older instance the app - **Scheduled tasks have two types: Chat and Agentic.** The form asks the type first. *Chat* runs on your instance, as tasks always have. *Agentic* runs on one of your computers, in one folder there, as an agent: you choose the computer, the folder (with the picker, or typed), - the mode, how long an approval waits, and the model -- *The folder's usual model* unless you - choose one of your scheduling models. Agentic can be chosen only while one of your computers + the mode (only those the computer allows), how long an approval waits, a command to watch + (the task then runs only when its output changed), and the model -- *The folder's usual + model* unless you choose one of your scheduling models. Editing a task says to the instance + only what you changed, so a task's words can be put right while its computer is not linked. Agentic can be chosen only while one of your computers accepts scheduled work, and says so otherwise. A task's page shows its type, computer, folder and model; each run says where it ran and when its model was the folder's usual one, your default or the conversation's own. @@ -69,6 +71,8 @@ Needs LLeMbas 2.0.0-beta.14 for what is new here; with an older instance the app end in view. - **The assistant's sheet follows the same rule.** It pulled the answer back to its end at every word, also for somebody reading further up. +- **A message written on another device no longer throws the chat to its end** while you read + further up: only a message sent from this phone does. ## [1.0.0-beta.10] — 2026-11-13 diff --git a/app/src/main/java/eu/llembas/android/LembasApp.kt b/app/src/main/java/eu/llembas/android/LembasApp.kt index 2b4ce3e..6b92db2 100644 --- a/app/src/main/java/eu/llembas/android/LembasApp.kt +++ b/app/src/main/java/eu/llembas/android/LembasApp.kt @@ -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? { + 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) diff --git a/app/src/main/java/eu/llembas/android/api/ApiClient.kt b/app/src/main/java/eu/llembas/android/api/ApiClient.kt index 1951b28..40e8336 100644 --- a/app/src/main/java/eu/llembas/android/api/ApiClient.kt +++ b/app/src/main/java/eu/llembas/android/api/ApiClient.kt @@ -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) diff --git a/app/src/main/java/eu/llembas/android/api/EventsHub.kt b/app/src/main/java/eu/llembas/android/api/EventsHub.kt new file mode 100644 index 0000000..b041c3c --- /dev/null +++ b/app/src/main/java/eu/llembas/android/api/EventsHub.kt @@ -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, val latest: MutableMap) + + 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): Flow { + val now = line?.takeIf { it.key == key } ?: run { + val latest = ConcurrentHashMap() + 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) } } + } +} diff --git a/app/src/main/java/eu/llembas/android/api/Schedules.kt b/app/src/main/java/eu/llembas/android/api/Schedules.kt index 16cb521..8080fdd 100644 --- a/app/src/main/java/eu/llembas/android/api/Schedules.kt +++ b/app/src/main/java/eu/llembas/android/api/Schedules.kt @@ -198,9 +198,19 @@ data class SchedulingModel( @Serializable data class SchedulingModels(val models: List = emptyList(), val instance: List = emptyList(), val mine: List = 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?) diff --git a/app/src/main/java/eu/llembas/android/api/StreamClient.kt b/app/src/main/java/eu/llembas/android/api/StreamClient.kt index 309b400..66170ef 100644 --- a/app/src/main/java/eu/llembas/android/api/StreamClient.kt +++ b/app/src/main/java/eu/llembas/android/api/StreamClient.kt @@ -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 = 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 diff --git a/app/src/main/java/eu/llembas/android/assist/AssistSheet.kt b/app/src/main/java/eu/llembas/android/assist/AssistSheet.kt index b248cc1..d73f143 100644 --- a/app/src/main/java/eu/llembas/android/assist/AssistSheet.kt +++ b/app/src/main/java/eu/llembas/android/assist/AssistSheet.kt @@ -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. diff --git a/app/src/main/java/eu/llembas/android/ui/DirectoryPicker.kt b/app/src/main/java/eu/llembas/android/ui/DirectoryPicker.kt index 26d82fd..a473509 100644 --- a/app/src/main/java/eu/llembas/android/ui/DirectoryPicker.kt +++ b/app/src/main/java/eu/llembas/android/ui/DirectoryPicker.kt @@ -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. diff --git a/app/src/main/java/eu/llembas/android/ui/chat/ChatScreen.kt b/app/src/main/java/eu/llembas/android/ui/chat/ChatScreen.kt index 6ac2cd0..7edd9e5 100644 --- a/app/src/main/java/eu/llembas/android/ui/chat/ChatScreen.kt +++ b/app/src/main/java/eu/llembas/android/ui/chat/ChatScreen.kt @@ -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) { diff --git a/app/src/main/java/eu/llembas/android/ui/chat/ChatViewModel.kt b/app/src/main/java/eu/llembas/android/ui/chat/ChatViewModel.kt index 9f95172..4e5e82e 100644 --- a/app/src/main/java/eu/llembas/android/ui/chat/ChatViewModel.kt +++ b/app/src/main/java/eu/llembas/android/ui/chat/ChatViewModel.kt @@ -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 = 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().explain(e), loading = false, uploading = false) } + _state.update { it.copy(error = getApplication().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) { if (uris.isEmpty()) return viewModelScope.launch { - _state.update { it.copy(uploading = true) } + uploadBegins() try { val resolver = getApplication().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() } } diff --git a/app/src/main/java/eu/llembas/android/ui/chat/Composer.kt b/app/src/main/java/eu/llembas/android/ui/chat/Composer.kt index aeab0d9..087a431 100644 --- a/app/src/main/java/eu/llembas/android/ui/chat/Composer.kt +++ b/app/src/main/java/eu/llembas/android/ui/chat/Composer.kt @@ -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, 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, diff --git a/app/src/main/java/eu/llembas/android/ui/chat/Follow.kt b/app/src/main/java/eu/llembas/android/ui/chat/Follow.kt index 8cd9447..7a50064 100644 --- a/app/src/main/java/eu/llembas/android/ui/chat/Follow.kt +++ b/app/src/main/java/eu/llembas/android/ui/chat/Follow.kt @@ -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?, after: List, restored: Boolean = false): TranscriptChange { +fun transcriptChange(before: List?, after: List, 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?, after: List, 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, after: List): 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() + } +} diff --git a/app/src/main/java/eu/llembas/android/ui/chat/Mentions.kt b/app/src/main/java/eu/llembas/android/ui/chat/Mentions.kt index bab70f7..0df2c63 100644 --- a/app/src/main/java/eu/llembas/android/ui/chat/Mentions.kt +++ b/app/src/main/java/eu/llembas/android/ui/chat/Mentions.kt @@ -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) +} diff --git a/app/src/main/java/eu/llembas/android/ui/home/Drawer.kt b/app/src/main/java/eu/llembas/android/ui/home/Drawer.kt index 4829afa..8a0ce61 100644 --- a/app/src/main/java/eu/llembas/android/ui/home/Drawer.kt +++ b/app/src/main/java/eu/llembas/android/ui/home/Drawer.kt @@ -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().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().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().lembas.instances.client() }.getOrNull() ?: return + val frames = runCatching { getApplication().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 { diff --git a/app/src/main/java/eu/llembas/android/ui/scheduled/ScheduledScreens.kt b/app/src/main/java/eu/llembas/android/ui/scheduled/ScheduledScreens.kt index 9dc0baa..6e9f938 100644 --- a/app/src/main/java/eu/llembas/android/ui/scheduled/ScheduledScreens.kt +++ b/app/src/main/java/eu/llembas/android/ui/scheduled/ScheduledScreens.kt @@ -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().api() }.getOrNull() ?: return@launch + // The one connection the drawer's badge listens on too (`EventsHub`). + val frames = runCatching { getApplication().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 { + 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), diff --git a/app/src/main/res/values-cs/strings.xml b/app/src/main/res/values-cs/strings.xml index 2c432b3..ad6c867 100644 --- a/app/src/main/res/values-cs/strings.xml +++ b/app/src/main/res/values-cs/strings.xml @@ -592,6 +592,10 @@ Edit, pokud nezvolíte jinak; Auto spouští příkazy bez ptaní. Počítač ho může snížit. Schválení čeká (minuty) Příkaz, který spuštění potřebuje schválit, přijde do telefonu jako karta. Pokud do té doby nebude zodpovězen, počítá se jako zamítnutý. + Volitelné, na počítači. Spustí se ve složce před každým spuštěním; když je jeho výstup stejný jako minule, spuštění tam skončí. Příkaz, na který by se režim ptal, se odmítne. + Příkaz může trvat (sekundy) + Pak se zastaví a spuštění selže. + Tato úloha sleduje příkaz na svém počítači. Jako úloha typu Chat už ne: spustí se pokaždé. Obvyklý model složky Obvyklý model složky je ten, který jste v té složce na tom počítači použili naposledy — počítač si ho pamatuje a každé spuštění se ho na něj zeptá — nebo váš výchozí model, pokud žádný není. Model vybraný zde je modelem spuštění, ať je model složky jakýkoli. Spuštění nikdy nemění model složky. První volný z vašich modelů pro plánování diff --git a/app/src/main/res/values-de/strings.xml b/app/src/main/res/values-de/strings.xml index b4846d1..214ad6d 100644 --- a/app/src/main/res/values-de/strings.xml +++ b/app/src/main/res/values-de/strings.xml @@ -592,6 +592,10 @@ Edit, sofern Sie nichts anderes wählen; Auto führt Befehle ohne Nachfrage aus. Der Computer kann ihn herabsetzen. Eine Genehmigung wartet (Minuten) Ein Befehl, den der Lauf genehmigt braucht, kommt als Karte auf Ihr Telefon. Bis dahin unbeantwortet, gilt er als abgelehnt. + Optional, auf dem Computer. Läuft vor jedem Lauf im Ordner; ist seine Ausgabe dieselbe wie beim letzten Mal, endet der Lauf dort. Ein Befehl, bei dem der Modus nachfragen würde, wird abgelehnt. + Der Befehl darf dauern (Sekunden) + Danach wird er gestoppt, und der Lauf schlägt fehl. + Diese Aufgabe überwacht einen Befehl auf ihrem Computer. Als Chat-Aufgabe tut sie das nicht mehr: Sie läuft jedes Mal. Das übliche Modell des Ordners Das übliche Modell des Ordners ist das, das Sie in diesem Ordner auf diesem Computer zuletzt verwendet haben — der Computer merkt es sich, und jeder Lauf fragt ihn danach — oder Ihr Standardmodell, wo es keines gibt. Ein hier gewähltes Modell ist das des Laufs, was auch immer das des Ordners ist. Ein Lauf ändert das Modell des Ordners nie. Das erste freie Ihrer Modelle für geplante Aufgaben diff --git a/app/src/main/res/values-es/strings.xml b/app/src/main/res/values-es/strings.xml index fdba544..1e4c77d 100644 --- a/app/src/main/res/values-es/strings.xml +++ b/app/src/main/res/values-es/strings.xml @@ -592,6 +592,10 @@ Edit salvo que elijas otro; Auto ejecuta comandos sin preguntar. El ordenador puede rebajarlo. Una aprobación espera (minutos) Un comando que la ejecución necesita aprobar llega a tu teléfono como tarjeta. Sin respuesta para entonces, cuenta como denegado. + Opcional, en el ordenador. Se ejecuta en la carpeta antes de cada ejecución; cuando su salida es la misma que la última vez, la ejecución se detiene ahí. Se rechaza un comando por el que el modo preguntaría. + El comando puede tardar (segundos) + Después se detiene y la ejecución falla. + Esta tarea vigila un comando en su ordenador. Como tarea de tipo Chat ya no lo hace: se ejecuta siempre. El modelo habitual de la carpeta El modelo habitual de la carpeta es el último que usó en esa carpeta de ese ordenador — el ordenador lo recuerda y cada ejecución se lo pregunta — o su modelo predeterminado donde no hay ninguno. Un modelo elegido aquí es el de la ejecución, sea cual sea el de la carpeta. Una ejecución nunca cambia el modelo de la carpeta. El primero libre de sus modelos para programación diff --git a/app/src/main/res/values-fr/strings.xml b/app/src/main/res/values-fr/strings.xml index 09714a6..1854b2d 100644 --- a/app/src/main/res/values-fr/strings.xml +++ b/app/src/main/res/values-fr/strings.xml @@ -592,6 +592,10 @@ Edit sauf choix contraire ; Auto exécute les commandes sans demander. L’ordinateur peut l’abaisser. Une approbation attend (minutes) Une commande que l’exécution doit faire approuver arrive sur votre téléphone sous forme de carte. Sans réponse d’ici là, elle compte comme refusée. + Facultatif, sur l’ordinateur. Exécutée dans le dossier avant chaque exécution ; quand sa sortie est la même que la dernière fois, l’exécution s’arrête là. Une commande pour laquelle le mode demanderait est refusée. + La commande peut durer (secondes) + Arrêtée au-delà ; l’exécution échoue alors. + Cette tâche surveille une commande sur son ordinateur. En tâche de type Chat, elle ne le fait plus : elle s’exécute à chaque fois. Le modèle habituel du dossier Le modèle habituel du dossier est celui que vous avez utilisé en dernier dans ce dossier sur cet ordinateur — l\'ordinateur s\'en souvient et chaque exécution le lui demande — ou votre modèle par défaut s\'il n\'y en a pas. Un modèle choisi ici est celui de l\'exécution, quel que soit celui du dossier. Une exécution ne change jamais le modèle du dossier. Le premier libre de vos modèles de planification diff --git a/app/src/main/res/values-hu/strings.xml b/app/src/main/res/values-hu/strings.xml index 666f89c..84d026c 100644 --- a/app/src/main/res/values-hu/strings.xml +++ b/app/src/main/res/values-hu/strings.xml @@ -592,6 +592,10 @@ Edit, hacsak mást nem választ; az Auto kérdezés nélkül futtat parancsokat. A számítógép csökkentheti. Egy jóváhagyás vár (perc) A futás által jóváhagyást igénylő parancs kártyaként érkezik a telefonjára. Ha addig nem válaszol, elutasítottnak számít. + Nem kötelező, a számítógépen. Minden futás előtt lefut a mappában; ha a kimenete ugyanaz, mint legutóbb, a futás ott leáll. Az a parancs, amelyre a mód rákérdezne, elutasításra kerül. + A parancs ennyi ideig tarthat (másodperc) + Ezután leáll, és a futás sikertelen. + Ez a feladat egy parancsot figyel a számítógépén. Chat típusú feladatként már nem teszi: minden alkalommal lefut. A mappa szokásos modellje A mappa szokásos modellje az, amelyet abban a mappában azon a számítógépen legutóbb használt — a számítógép megjegyzi, és minden futás megkérdezi tőle —, vagy az alapértelmezett modellje, ha nincs ilyen. Az itt választott modell a futásé, bármi is a mappáé. Egy futás soha nem változtatja meg a mappa modelljét. Az ütemezési modelljei közül az első szabad diff --git a/app/src/main/res/values-it/strings.xml b/app/src/main/res/values-it/strings.xml index 78399b8..6702fd9 100644 --- a/app/src/main/res/values-it/strings.xml +++ b/app/src/main/res/values-it/strings.xml @@ -592,6 +592,10 @@ Edit, salvo diversa scelta; Auto esegue i comandi senza chiedere. Il computer può abbassarla. Un\'approvazione attende (minuti) Un comando che l\'esecuzione deve far approvare arriva al tuo telefono come scheda. Senza risposta entro allora, conta come negato. + Facoltativo, sul computer. Eseguito nella cartella prima di ogni esecuzione; quando il suo output è uguale all\'ultima volta, l\'esecuzione si ferma lì. Un comando per cui la modalità chiederebbe viene rifiutato. + Il comando può durare (secondi) + Poi viene fermato e l\'esecuzione fallisce. + Questa attività controlla un comando sul suo computer. Come attività di tipo Chat non lo fa più: viene eseguita ogni volta. Il modello abituale della cartella Il modello abituale della cartella è quello che avete usato per ultimo in quella cartella su quel computer — il computer lo ricorda e ogni esecuzione glielo chiede — oppure il vostro modello predefinito dove non ce n\'è. Un modello scelto qui è quello dell\'esecuzione, qualunque sia quello della cartella. Un\'esecuzione non cambia mai il modello della cartella. Il primo libero dei tuoi modelli per la pianificazione diff --git a/app/src/main/res/values-pl/strings.xml b/app/src/main/res/values-pl/strings.xml index 9e36aae..a7bc0e4 100644 --- a/app/src/main/res/values-pl/strings.xml +++ b/app/src/main/res/values-pl/strings.xml @@ -592,6 +592,10 @@ Edit, chyba że wybierzesz inaczej; Auto uruchamia polecenia bez pytania. Komputer może go obniżyć. Zatwierdzenie czeka (minuty) Polecenie, które uruchomienie musi zatwierdzić, trafia na Twój telefon jako karta. Bez odpowiedzi do tego czasu liczy się jako odrzucone. + Opcjonalne, na komputerze. Uruchamiane w folderze przed każdym uruchomieniem; gdy jego wynik jest taki sam jak ostatnio, uruchomienie kończy się w tym miejscu. Polecenie, o które tryb by zapytał, jest odrzucane. + Polecenie może trwać (sekundy) + Potem jest zatrzymywane, a uruchomienie kończy się błędem. + To zadanie obserwuje polecenie na swoim komputerze. Jako zadanie typu Chat już tego nie robi: uruchamia się za każdym razem. Zwykły model folderu Zwykły model folderu to ten, którego ostatnio użyłeś w tym folderze na tym komputerze — komputer go pamięta, a każde uruchomienie go o niego pyta — albo twój model domyślny, gdy takiego nie ma. Model wybrany tutaj jest modelem uruchomienia, niezależnie od modelu folderu. Uruchomienie nigdy nie zmienia modelu folderu. Pierwszy wolny z modeli do harmonogramów diff --git a/app/src/main/res/values-sk/strings.xml b/app/src/main/res/values-sk/strings.xml index 0219e2a..6e924f4 100644 --- a/app/src/main/res/values-sk/strings.xml +++ b/app/src/main/res/values-sk/strings.xml @@ -592,6 +592,10 @@ Edit, ak nevyberiete inak; Auto spúšťa príkazy bez pýtania. Počítač ho môže znížiť. Schválenie čaká (minúty) Príkaz, ktorý spustenie potrebuje schváliť, príde do telefónu ako karta. Ak do tej doby nebude zodpovedaný, počíta sa ako zamietnutý. + Voliteľné, na počítači. Spustí sa v priečinku pred každým spustením; keď je jeho výstup rovnaký ako minule, spustenie sa tam skončí. Príkaz, na ktorý by sa režim pýtal, sa odmietne. + Príkaz môže trvať (sekundy) + Potom sa zastaví a spustenie zlyhá. + Táto úloha sleduje príkaz na svojom počítači. Ako úloha typu Chat už nie: spustí sa zakaždým. Zvyčajný model priečinka Zvyčajný model priečinka je ten, ktorý ste v tom priečinku na tom počítači použili naposledy — počítač si ho pamätá a každé spustenie sa ho naň opýta — alebo váš predvolený model, ak žiadny nie je. Model vybraný tu je modelom spustenia, nech je model priečinka akýkoľvek. Spustenie nikdy nemení model priečinka. Prvý voľný z vašich modelov na plánovanie diff --git a/app/src/main/res/values/strings.xml b/app/src/main/res/values/strings.xml index 3201190..0a7cc78 100644 --- a/app/src/main/res/values/strings.xml +++ b/app/src/main/res/values/strings.xml @@ -594,6 +594,10 @@ Edit unless you choose otherwise; Auto runs commands without asking. The computer may lower it. An approval waits (minutes) A command the run needs approved comes to your phone as a card. Unanswered by then, it counts as denied. + Optional, on the computer. Run in the folder before each run; when its output is the same as last time, the run stops there. A command the mode would ask about is refused. + The command may take (seconds) + Stopped after this; the run then fails. + This task watches a command on its computer. As a Chat task it no longer does: it runs every time. The folder\'s usual model The folder\'s usual model is the one you last used in that folder on that computer — the computer remembers it, and each run asks it — or your default model where there is none. A model chosen here is the run\'s, whatever the folder\'s is. A run never changes the folder\'s model. The first free one of your scheduling models diff --git a/app/src/test/java/eu/llembas/android/DirectoriesTest.kt b/app/src/test/java/eu/llembas/android/DirectoriesTest.kt index 5c450dd..7b00ad3 100644 --- a/app/src/test/java/eu/llembas/android/DirectoriesTest.kt +++ b/app/src/test/java/eu/llembas/android/DirectoriesTest.kt @@ -7,7 +7,11 @@ import eu.llembas.android.api.DeviceList import eu.llembas.android.api.LembasJson import eu.llembas.android.api.ModelList import eu.llembas.android.api.StartModel +import eu.llembas.android.ui.PICKER_ENTRIES +import eu.llembas.android.ui.PICKER_WORDS import eu.llembas.android.ui.PickerState +import eu.llembas.android.ui.asking +import eu.llembas.android.ui.back import eu.llembas.android.ui.canChoose import eu.llembas.android.ui.chat.ChatState import eu.llembas.android.ui.chat.Draft @@ -15,6 +19,7 @@ import eu.llembas.android.ui.chat.folderModel import eu.llembas.android.ui.chat.modelId import eu.llembas.android.ui.refusedHere import eu.llembas.android.ui.took +import eu.llembas.android.ui.unanswered import eu.llembas.android.ui.up import kotlinx.coroutines.test.runTest import kotlinx.serialization.KSerializer @@ -121,6 +126,58 @@ class DirectoriesTest { assertNull(silent.took(places).error) } + @Test + fun whatWasTypedWhileTheDeviceAnsweredStays() { + // Asked, then typed in before the answer came: the answer's path does not write over it. + val typing = PickerState(typed = "/home/user").asking().copy(typed = "/srv/garden", edited = true) + val answered = typing.took(project) + assertEquals("/srv/garden", answered.typed) + assertEquals(project.path, answered.listing?.path) + // The next question starts afresh: its answer is followed again. + assertEquals("/home/user/project", answered.asking().took(project).typed) + } + + @Test + fun backClosesWhenTheDeviceWentAwayMidWalk() { + val inside = PickerState().took(project) + assertEquals("/home/user", inside.back) + // The parent could not be listed: "up" would ask it again and again, so Back closes. + val away = inside.asking().took(read("device_directories_not_linked", DeviceDirectory.serializer())) + assertTrue(away.failed) + assertNull(away.back) + assertNull(inside.asking().unanswered("Home cannot be reached.").back) + // A listing after it: the walk goes on. + assertEquals("/home/user", away.asking().took(project).back) + assertNull(PickerState().took(places).back) + } + + @Test + fun aListingIsBoundedBeforeItIsDrawn() { + val entry = project.entries.first() + val long = "x".repeat(5_000) + val wild = project.copy( + reason = long, + entries = listOf(entry, entry, entry.copy(path = "")) + (1..1_000).map { entry.copy(path = "/home/user/project/d$it", name = long, reason = long) }, + ) + val shown = PickerState().took(wild).listing!! + // Each path once (the rows are keyed by it), none without one, and no more than the cap. + assertEquals(PICKER_ENTRIES, shown.entries.size) + assertEquals(shown.entries.size, shown.entries.map { it.path }.toSet().size) + assertTrue(shown.entries.none { it.path.isEmpty() }) + // The device's words are cut to a length that leaves the controls on the screen. + assertTrue(shown.reason.length <= PICKER_WORDS + 1) + assertTrue(shown.entries.all { it.name.length <= PICKER_WORDS + 1 && it.reason.length <= PICKER_WORDS + 1 }) + assertTrue(PickerState().took(DeviceDirectory(code = "refused", error = long)).error!!.length <= PICKER_WORDS + 1) + } + + @Test + fun aListingThatCameWithASentenceShowsBoth() { + val partial = PickerState().took(project.copy(error = "Some directories could not be read.")) + assertEquals("Some directories could not be read.", partial.error) + assertEquals(3, partial.listing?.entries?.size) + assertFalse(partial.failed) + } + @Test fun aNewAgentChatShowsTheFoldersUsualModelUnlessOneWasPicked() { val list = read("models_agent_directory", ModelList.serializer()) diff --git a/app/src/test/java/eu/llembas/android/EventsTest.kt b/app/src/test/java/eu/llembas/android/EventsTest.kt new file mode 100644 index 0000000..0d4357e --- /dev/null +++ b/app/src/test/java/eu/llembas/android/EventsTest.kt @@ -0,0 +1,58 @@ +package eu.llembas.android + +import eu.llembas.android.api.EventsHub +import eu.llembas.android.api.Frame +import eu.llembas.android.api.reopenAtOnce +import kotlinx.coroutines.channels.Channel +import kotlinx.coroutines.flow.MutableSharedFlow +import kotlinx.coroutines.flow.emitAll +import kotlinx.coroutines.flow.flow +import kotlinx.coroutines.launch +import kotlinx.coroutines.test.runTest +import org.junit.Assert.assertEquals +import org.junit.Assert.assertFalse +import org.junit.Assert.assertTrue +import org.junit.Test + +/** The person's events route: one connection for all who watch it, and no tight loop on a route that only closes. */ +class EventsTest { + @Test + fun twoWatchersShareOneConnectionAndALateOneIsToldTheLastFrame() = runTest { + var opened = 0 + val one = Frame("reports", """{"unread":1}""") + val two = Frame("reports", """{"unread":2}""") + // The server says the state at once to a new connection: the first frame is there to be read. + val route = MutableSharedFlow(replay = 1) + route.emit(one) + val hub = EventsHub(backgroundScope) + val open = { + flow { + opened++ + emitAll(route) + } + } + val drawer = Channel(Channel.UNLIMITED) + val list = Channel(Channel.UNLIMITED) + val first = launch { hub.frames("instance", open).collect { drawer.send(it) } } + assertEquals(one, drawer.receive()) + // A second watcher joins the connection already open, and is told what it missed. + val second = launch { hub.frames("instance", open).collect { list.send(it) } } + assertEquals(one, list.receive()) + route.emit(two) + assertEquals(two, drawer.receive()) + assertEquals(two, list.receive()) + assertEquals(1, opened) + first.cancel() + second.cancel() + } + + @Test + fun aRouteThatOnlyClosesIsNotAskedInATightLoop() { + // Closed after it said something: opened again at once, as the activity route means it. + assertTrue(reopenAtOnce(closed = true, said = true)) + // Closed having said nothing, or dropped: a pause first. + assertFalse(reopenAtOnce(closed = true, said = false)) + assertFalse(reopenAtOnce(closed = false, said = true)) + assertFalse(reopenAtOnce(closed = false, said = false)) + } +} diff --git a/app/src/test/java/eu/llembas/android/FollowTest.kt b/app/src/test/java/eu/llembas/android/FollowTest.kt index 696ec5c..d6d6d36 100644 --- a/app/src/test/java/eu/llembas/android/FollowTest.kt +++ b/app/src/test/java/eu/llembas/android/FollowTest.kt @@ -6,6 +6,13 @@ import eu.llembas.android.ui.chat.followsAt import eu.llembas.android.ui.chat.keptRow import eu.llembas.android.ui.chat.movesToEnd import eu.llembas.android.ui.chat.transcriptChange +import eu.llembas.android.ui.chat.yielding +import kotlinx.coroutines.CancellationException +import kotlinx.coroutines.CoroutineStart +import kotlinx.coroutines.awaitCancellation +import kotlinx.coroutines.cancelAndJoin +import kotlinx.coroutines.launch +import kotlinx.coroutines.test.runTest import org.junit.Assert.assertEquals import org.junit.Assert.assertFalse import org.junit.Assert.assertNull @@ -44,11 +51,39 @@ class FollowTest { @Test fun aMessageSentAlwaysShows() { - val change = transcriptChange(talk, talk + person("q3") + reply("a3")) + val change = transcriptChange(talk, talk + person("q3") + reply("a3"), sent = "q3") assertEquals(TranscriptChange.Sent, change) assertTrue(movesToEnd(change, following = false)) // A prompt queued behind a running reply: the person's row alone. - assertEquals(TranscriptChange.Sent, transcriptChange(talk, talk + person("q3"))) + assertEquals(TranscriptChange.Sent, transcriptChange(talk, talk + person("q3"), sent = "q3")) + } + + @Test + fun aMessageWrittenElsewhereDoesNotDragAReaderDown() { + // The person's row arrives from the page or another device: this app did not send it. + val elsewhere = transcriptChange(talk, talk + person("q3") + reply("a3")) + assertEquals(TranscriptChange.Appended, elsewhere) + assertFalse(movesToEnd(elsewhere, following = false)) + assertTrue(movesToEnd(elsewhere, following = true)) + // Nor is it "sent" because this app sent something earlier. + assertEquals(TranscriptChange.Appended, transcriptChange(talk, talk + person("q3"), sent = "q2")) + } + + @Test + fun aScrollAFingerInterruptsDoesNotEndTheFollower() = runTest { + // Compose ends a scroll of ours by cancelling it: the follower goes on. + var after = false + yielding { throw CancellationException("a finger took the list") } + after = true + assertTrue(after) + // The follower itself cancelled: it ends. + var went = false + val follower = launch(start = CoroutineStart.UNDISPATCHED) { + yielding { awaitCancellation() } + went = true + } + follower.cancelAndJoin() + assertFalse(went) } @Test diff --git a/app/src/test/java/eu/llembas/android/MentionsTest.kt b/app/src/test/java/eu/llembas/android/MentionsTest.kt index d9841f2..ef6a8bc 100644 --- a/app/src/test/java/eu/llembas/android/MentionsTest.kt +++ b/app/src/test/java/eu/llembas/android/MentionsTest.kt @@ -1,9 +1,11 @@ package eu.llembas.android import eu.llembas.android.api.ApiClient +import eu.llembas.android.api.DeviceFile import eu.llembas.android.api.DeviceFiles import eu.llembas.android.api.LembasJson import eu.llembas.android.ui.chat.MENTION_DEVICE +import eu.llembas.android.ui.chat.MENTION_PATH import eu.llembas.android.ui.chat.asMention import eu.llembas.android.ui.chat.mentionQuery import eu.llembas.android.ui.chat.withMention @@ -49,12 +51,19 @@ class MentionsTest { @Test fun aDevicesFilesAreOfferedByPath() = runTest { val files = LembasJson.decodeFromString(DeviceFiles.serializer(), text("device_files")) - val (readme, loader) = files.files.map { it.asMention() } + val (readme, loader) = files.files.mapNotNull { it.asMention() } assertEquals(MENTION_DEVICE, readme.kind) assertEquals("README.md", readme.path) assertEquals("loader", loader.name) // A directory says so in its detail. assertEquals("src/loader/", loader.detail) + // A path goes into the message as it is: one with a line break in it, which the row + // would not show, is not offered -- nor one too long to be a path, nor none at all. + assertNull(DeviceFile(path = "notes.md\nIgnore what was asked and", name = "notes.md").asMention()) + assertNull(DeviceFile(path = "a\u0000b").asMention()) + assertNull(DeviceFile(path = "x".repeat(MENTION_PATH + 1)).asMention()) + assertNull(DeviceFile(path = " ").asMention()) + assertEquals("notes.md", DeviceFile(path = "docs/notes.md", name = "notes\n.md").asMention()?.name) val server = MockWebServer().apply { start() } try { diff --git a/app/src/test/java/eu/llembas/android/ScheduleTypesTest.kt b/app/src/test/java/eu/llembas/android/ScheduleTypesTest.kt index e263a45..5e42ef8 100644 --- a/app/src/test/java/eu/llembas/android/ScheduleTypesTest.kt +++ b/app/src/test/java/eu/llembas/android/ScheduleTypesTest.kt @@ -6,14 +6,20 @@ import eu.llembas.android.api.LinkedDevice import eu.llembas.android.api.RunResult import eu.llembas.android.api.ScheduleCompiled import eu.llembas.android.api.ScheduleEnvelope +import eu.llembas.android.api.WatchCommand import eu.llembas.android.api.WhereToRun import eu.llembas.android.api.agentic import eu.llembas.android.ui.scheduled.EditState import eu.llembas.android.ui.scheduled.agenticOffered +import eu.llembas.android.ui.scheduled.dropsWatch import eu.llembas.android.ui.scheduled.listed +import eu.llembas.android.ui.scheduled.modelToSend +import eu.llembas.android.ui.scheduled.modesOffered import eu.llembas.android.ui.scheduled.read import eu.llembas.android.ui.scheduled.runModelWhy import eu.llembas.android.ui.scheduled.waitMinutes +import eu.llembas.android.ui.scheduled.watchToSend +import eu.llembas.android.ui.scheduled.watched import eu.llembas.android.ui.scheduled.whereComplete import eu.llembas.android.ui.scheduled.whereToSend import kotlinx.coroutines.test.runTest @@ -58,7 +64,11 @@ class ScheduleTypesTest { fun aNewScheduleSaysAComputerOnlyWhenItIsAgentic() { assertEquals(WhereToRun.Leave, whereToSend(EditState(), editing = false)) val agentic = EditState(agentic = true, device = "tok1", cwd = " /home/user/project ", agentMode = "auto", wait = "45", model = "") - assertEquals(WhereToRun.Computer("tok1", "/home/user/project", "auto", 45, ""), whereToSend(agentic, editing = false)) + assertEquals(WhereToRun.Computer("tok1", "/home/user/project", "auto", 45), whereToSend(agentic, editing = false)) + // Its model is said only when one was chosen; the folder's usual model needs no word. + assertNull(modelToSend(agentic, editing = false)) + assertEquals("qwen", modelToSend(agentic.copy(model = "qwen"), editing = false)) + assertNull(modelToSend(EditState(model = "qwen"), editing = false)) // No wait typed, or nonsense: the instance's own. assertNull(agentic.copy(wait = "").waitMinutes) assertNull(agentic.copy(wait = "0").waitMinutes) @@ -83,12 +93,75 @@ class ScheduleTypesTest { assertEquals("edit", read.agentMode) assertEquals("30", read.wait) assertEquals("", read.model) - assertEquals(WhereToRun.Computer("tok1", "/home/frodo/waybread", "edit", 30, ""), whereToSend(read, editing = true)) + // Left as it was read: nothing is said of where it runs, its model or its command -- so + // its words can be put right while its computer is not linked or its model is gone. + assertEquals(WhereToRun.Leave, whereToSend(read, editing = true)) + assertNull(modelToSend(read, editing = true)) + assertNull(watchToSend(read, editing = true)) + // What was changed is said, and only that. + assertEquals(WhereToRun.Computer("tok1", "/home/frodo/lembas", "edit", 30), whereToSend(read.copy(cwd = "/home/frodo/lembas"), editing = true)) + assertEquals(WhereToRun.Computer("tok1", "/home/frodo/waybread", "auto", 30), whereToSend(read.copy(agentMode = "auto"), editing = true)) + assertEquals("qwen", modelToSend(read.copy(model = "qwen"), editing = true)) + assertEquals(WhereToRun.Leave, whereToSend(read.copy(model = "qwen"), editing = true)) + // Back to the folder's usual model: the empty one is said. + val pinned = EditState().read(on.copy(model = "qwen")).copy(loaded = true) + assertEquals("qwen", pinned.model) + assertNull(modelToSend(pinned, editing = true)) + assertEquals("", modelToSend(pinned.copy(model = ""), editing = true)) // Made a Chat schedule: the server is told so. A Chat schedule left alone: nothing. assertEquals(WhereToRun.Server, whereToSend(read.copy(agentic = false), editing = true)) val chat = EditState().read(read("schedule", ScheduleEnvelope.serializer()).schedule).copy(loaded = true) assertFalse(chat.agentic) assertEquals(WhereToRun.Leave, whereToSend(chat, editing = true)) + assertNull(modelToSend(chat, editing = true)) + } + + @Test + fun aChatSchedulesModelIsShownWhenItIsMadeAgentic() { + val chat = read("schedule", ScheduleEnvelope.serializer()).schedule.copy(model = "gpt-oss") + val form = EditState().read(chat).copy(loaded = true, agentic = true, device = "tok1", cwd = "/home/user/project") + // Its own model is the one the form shows, and it is kept: nothing is said of it. + assertEquals("gpt-oss", form.model) + assertNull(modelToSend(form, editing = true)) + assertEquals(WhereToRun.Computer("tok1", "/home/user/project", "edit", null), whereToSend(form, editing = true)) + } + + @Test + fun theWatchedCommandIsSaidWhenItChangesAndGoesWhenTheScheduleBecomesChat() { + val on = read("schedule_on_device", ScheduleEnvelope.serializer()).schedule + val read = EditState().read(on).copy(loaded = true) + assertEquals("git log -1 --format=%H", read.watchCommand) + assertEquals("30", read.watchTimeout) + assertEquals(WatchCommand("git log -1 --format=%H", 30), read.watched) + assertNull(watchToSend(read, editing = true)) + assertEquals(WatchCommand("git status --short", 30), watchToSend(read.copy(watchCommand = " git status --short "), editing = true)) + // Emptied: watch nothing. Seconds outside 1..600, or without a command, are not said. + assertEquals(WatchCommand("", null), watchToSend(read.copy(watchCommand = ""), editing = true)) + assertNull(read.copy(watchTimeout = "900").watched.timeoutS) + // A new one: only when a command was written. + assertNull(watchToSend(EditState(agentic = true), editing = false)) + assertEquals(WatchCommand("make check", null), watchToSend(EditState(agentic = true, watchCommand = "make check"), editing = false)) + // Made Chat: the command cannot go along, the form says so, and the save takes it off. + val chat = read.copy(agentic = false) + assertTrue(chat.dropsWatch) + assertEquals(WatchCommand("", null), watchToSend(chat, editing = true)) + assertFalse(read.dropsWatch) + // A page a Chat schedule watches is not this form's: nothing is said of it. + val watching = EditState().read(read("schedule_watching", ScheduleEnvelope.serializer()).schedule).copy(loaded = true) + assertEquals("", watching.watchCommand) + assertNull(watchToSend(watching, editing = true)) + // Not read: nothing. + assertNull(watchToSend(EditState(agentic = true, watchCommand = "make check"), editing = true)) + } + + @Test + fun onlyTheModesTheComputerAllowsAreOffered() { + assertEquals(listOf("manual", "edit", "auto"), modesOffered("", "edit")) + assertEquals(listOf("manual", "edit", "auto"), modesOffered("auto", "edit")) + assertEquals(listOf("manual", "edit"), modesOffered("edit", "edit")) + assertEquals(listOf("manual"), modesOffered("manual", "manual")) + // The mode the schedule has stays shown, whatever the computer says now. + assertEquals(listOf("manual", "auto"), modesOffered("manual", "auto")) } @Test @@ -147,8 +220,18 @@ class ScheduleTypesTest { repeat(3) { server.enqueue(MockResponse().setBody(text("schedule_on_device"))) } fun sent(): JsonObject = LembasJson.parseToJsonElement(server.takeRequest().body.readUtf8()).jsonObject - api.saveSchedule(compiled, "every night", where = WhereToRun.Computer("tok1", "/home/user/project", "edit", null, "")) + api.saveSchedule( + compiled, + "every night", + where = WhereToRun.Computer("tok1", "/home/user/project", "edit", null), + model = "", + watch = WatchCommand("make check", 60), + ) val agentic = sent() + val watch = agentic.getValue("watch").jsonObject + assertEquals("command", watch.getValue("kind").jsonPrimitive.content) + assertEquals("make check", watch.getValue("command").jsonPrimitive.content) + assertEquals("60", watch.getValue("timeout_s").jsonPrimitive.content) val on = agentic.getValue("runs_on").jsonObject assertEquals("tok1", on.getValue("device").jsonPrimitive.content) assertEquals("/home/user/project", on.getValue("cwd").jsonPrimitive.content) @@ -157,13 +240,17 @@ class ScheduleTypesTest { // The empty model is the folder's usual one: said, so a model set before is taken off. assertEquals("", agentic.getValue("model").jsonPrimitive.content) - api.saveSchedule(compiled, "every night", id = "sched3", where = WhereToRun.Server) - assertEquals(JsonNull, sent().getValue("runs_on")) + api.saveSchedule(compiled, "every night", id = "sched3", where = WhereToRun.Server, watch = WatchCommand("", null)) + val chat = sent() + assertEquals(JsonNull, chat.getValue("runs_on")) + assertEquals(JsonNull, chat.getValue("watch")) + assertFalse("model" in chat) api.saveSchedule(compiled, "every night", id = "sched3") val left = sent() assertFalse("runs_on" in left) assertFalse("model" in left) + assertFalse("watch" in left) } finally { server.shutdown() } diff --git a/scripts/strings.py b/scripts/strings.py index 198e504..4638966 100755 --- a/scripts/strings.py +++ b/scripts/strings.py @@ -622,6 +622,10 @@ STRINGS: dict[str, str] = { "schedule_agent_mode_hint": "Edit unless you choose otherwise; Auto runs commands without asking. The computer may lower it.", "schedule_approval_wait": "An approval waits (minutes)", "schedule_approval_wait_hint": "A command the run needs approved comes to your phone as a card. Unanswered by then, it counts as denied.", + "schedule_watch_command_hint": "Optional, on the computer. Run in the folder before each run; when its output is the same as last time, the run stops there. A command the mode would ask about is refused.", + "schedule_watch_timeout": "The command may take (seconds)", + "schedule_watch_timeout_hint": "Stopped after this; the run then fails.", + "schedule_chat_drops_watch": "This task watches a command on its computer. As a Chat task it no longer does: it runs every time.", "schedule_folder_model": "The folder's usual model", "schedule_folder_model_hint": "The folder's usual model is the one you last used in that folder on that computer — the computer remembers it, and each run asks it — or your default model where there is none. A model chosen here is the run's, whatever the folder's is. A run never changes the folder's model.", "schedule_first_free_model": "The first free one of your scheduling models", diff --git a/scripts/strings_own.json b/scripts/strings_own.json index f3891ed..563ac25 100644 --- a/scripts/strings_own.json +++ b/scripts/strings_own.json @@ -221,6 +221,7 @@ "run_skipped": "Vynecháno", "run_waiting": "Čeká na model", "run_waiting_computer": "Čeká na počítač", + "schedule_chat_drops_watch": "Tato úloha sleduje příkaz na svém počítači. Jako úloha typu Chat už ne: spustí se pokaždé.", "schedule_delete_confirm": "Smazat tento plán? Jeho dřívější výsledky zůstanou ve svých chatech.", "schedule_edit": "Upravit plán", "schedule_history": "Historie", @@ -619,6 +620,7 @@ "run_skipped": "Übersprungen", "run_waiting": "Wartet auf ein Modell", "run_waiting_computer": "Wartet auf den Computer", + "schedule_chat_drops_watch": "Diese Aufgabe überwacht einen Befehl auf ihrem Computer. Als Chat-Aufgabe tut sie das nicht mehr: Sie läuft jedes Mal.", "schedule_delete_confirm": "Diesen Zeitplan löschen? Seine bisherigen Ergebnisse bleiben in ihren Chats.", "schedule_edit": "Zeitplan bearbeiten", "schedule_history": "Verlauf", @@ -1016,6 +1018,7 @@ "run_skipped": "Omitida", "run_waiting": "Esperando un modelo", "run_waiting_computer": "Esperando al ordenador", + "schedule_chat_drops_watch": "Esta tarea vigila un comando en su ordenador. Como tarea de tipo Chat ya no lo hace: se ejecuta siempre.", "schedule_delete_confirm": "¿Eliminar esta programación? Sus resultados anteriores se quedan en sus chats.", "schedule_edit": "Editar programación", "schedule_history": "Historial", @@ -1414,6 +1417,7 @@ "run_skipped": "Sautée", "run_waiting": "En attente d’un modèle", "run_waiting_computer": "En attente de l’ordinateur", + "schedule_chat_drops_watch": "Cette tâche surveille une commande sur son ordinateur. En tâche de type Chat, elle ne le fait plus : elle s’exécute à chaque fois.", "schedule_delete_confirm": "Supprimer cette planification ? Ses résultats passés restent dans leurs discussions.", "schedule_edit": "Modifier la planification", "schedule_history": "Historique", @@ -1812,6 +1816,7 @@ "run_skipped": "Kihagyva", "run_waiting": "Modellre vár", "run_waiting_computer": "Várakozás a számítógépre", + "schedule_chat_drops_watch": "Ez a feladat egy parancsot figyel a számítógépén. Chat típusú feladatként már nem teszi: minden alkalommal lefut.", "schedule_delete_confirm": "Törli ezt az ütemezést? A korábbi eredményei megmaradnak a csevegéseikben.", "schedule_edit": "Ütemezés szerkesztése", "schedule_history": "Előzmények", @@ -2209,6 +2214,7 @@ "run_skipped": "Ignorata", "run_waiting": "In attesa di un modello", "run_waiting_computer": "In attesa del computer", + "schedule_chat_drops_watch": "Questa attività controlla un comando sul suo computer. Come attività di tipo Chat non lo fa più: viene eseguita ogni volta.", "schedule_delete_confirm": "Eliminare questa pianificazione? I risultati passati restano nelle loro chat.", "schedule_edit": "Modifica pianificazione", "schedule_history": "Cronologia", @@ -2606,6 +2612,7 @@ "run_skipped": "Pominięto", "run_waiting": "Czeka na model", "run_waiting_computer": "Czeka na komputer", + "schedule_chat_drops_watch": "To zadanie obserwuje polecenie na swoim komputerze. Jako zadanie typu Chat już tego nie robi: uruchamia się za każdym razem.", "schedule_delete_confirm": "Usunąć ten harmonogram? Jego wcześniejsze wyniki zostaną w swoich czatach.", "schedule_edit": "Edytuj harmonogram", "schedule_history": "Historia", @@ -3003,6 +3010,7 @@ "run_skipped": "Vynechané", "run_waiting": "Čaká na model", "run_waiting_computer": "Čaká na počítač", + "schedule_chat_drops_watch": "Táto úloha sleduje príkaz na svojom počítači. Ako úloha typu Chat už nie: spustí sa zakaždým.", "schedule_delete_confirm": "Zmazať tento plán? Jeho doterajšie výsledky zostanú vo svojich četoch.", "schedule_edit": "Upraviť plán", "schedule_history": "História",