diff --git a/CHANGELOG.md b/CHANGELOG.md index 2f40624..20c5572 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -22,11 +22,20 @@ What is said here of replies that start by themselves needs an instance newer th goes to the top and shows its dot, and the dot of a reply being written goes when the reply ends, without the drawer being closed and opened. +- **A message that waits can be sent now or discarded.** Under a message that has not been + given to a model yet -- queued behind a reply, or waiting on a linked computer -- there are + "Send now" and "Discard", as on the web page. Send now starts its reply, which is written in + front of you like any you asked for; Discard asks once and takes the message away. Where the + instance refuses (a reply is still being written; the message is no longer waiting), it says + so in its own words and the chat is read again. A waiting message is not offered Edit: the + instance refuses that. Needs an instance that has these two actions. + ### Changed -- **A message of which it is not known whether it reached the linked computer says so**, in - the instance's words, instead of looking queued: the instance does not send it by itself. - Sending it again or discarding it is done on the web page for now. +- **A waiting message says how it waits**, in the instance's words. One of which it is not + known whether it reached the linked computer says so, instead of looking queued: the + instance does not send it by itself. One the computer holds says that the computer has it + and takes it in with its next turn. - **A turn the linked computer started is a quiet note**, as a schedule's line is: it never looks like something you typed. - In an agent chat, a finished reply that holds nothing, after such a turn, says "The reply to 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 649655b..b12faf9 100644 --- a/app/src/main/java/eu/llembas/android/api/ApiClient.kt +++ b/app/src/main/java/eu/llembas/android/api/ApiClient.kt @@ -342,6 +342,17 @@ class ApiClient(val base: String, private val token: String, val http: OkHttpCli }, ) + /** + * Send a message that waits (`queued`) now: the message as it is after, and the reply started + * for it, as a message sent answers. 409 in the instance's words while a reply is being + * written in the chat, and when the message no longer waits. + */ + suspend fun sendWaiting(chatId: String, messageId: String): Turn = send("POST", "/chats/$chatId/messages/${segment(messageId)}/send", DECLARED) + + /** Withdraw a message that waits: its row is gone. 409 in words when it no longer waits, 404 when it is not there. */ + suspend fun discardWaiting(chatId: String, messageId: String): Discarded = + call(authed("$v2/chats/$chatId/messages/${segment(messageId)}/discard").post(emptyBody()).build(), Discarded.serializer()) + suspend fun regenerate(chatId: String, messageId: String): Turn = send("POST", "/chats/$chatId/messages/$messageId/regenerate", DECLARED) suspend fun continueChat(chatId: String): Turn = send("POST", "/chats/$chatId/continue", DECLARED) diff --git a/app/src/main/java/eu/llembas/android/api/Display.kt b/app/src/main/java/eu/llembas/android/api/Display.kt index ad26584..2be224e 100644 --- a/app/src/main/java/eu/llembas/android/api/Display.kt +++ b/app/src/main/java/eu/llembas/android/api/Display.kt @@ -161,6 +161,41 @@ const val ORIGIN_UNSURE = "unsure" */ val Message.fateUnknown: Boolean get() = isUser && queued && origin == ORIGIN_UNSURE +/** The `origin` of a message the linked computer has said it holds for its next turn. */ +const val ORIGIN_CARRIED = "carried" + +/** Why a message of the person's has not been given to a model yet. */ +enum class Waiting { + /** A reply was being written when it was sent: it goes when its turn comes. */ + Queued, + + /** Handed to the linked computer, its arrival never heard: the instance never sends it by itself. */ + Unsure, + + /** The linked computer holds it and takes it in with its next turn. */ + Carried, +} + +/** + * How this message waits, or null for one that does not: a message of the person's with + * `queued` true. Such a message is not a turn yet, so it is sent now or discarded, never + * edited. An origin this app does not know waits as a plain queued one does. + */ +val Message.waiting: Waiting? + get() = when { + !isUser || !queued -> null + origin == ORIGIN_UNSURE -> Waiting.Unsure + origin == ORIGIN_CARRIED -> Waiting.Carried + else -> Waiting.Queued + } + +/** + * Whether Edit is offered on this message of the person's: not while a reply is being + * [writing], and never on one that still waits -- the instance refuses that, since it has not + * been a turn yet and a linked computer may still hold its old words. + */ +fun Message.editable(writing: Boolean): Boolean = isUser && !writing && !queued + /** Whether nobody typed this row: the server wrote it (`machine`), or a device's harness did. */ val Message.byMachine: Boolean get() = machine || origin == ORIGIN_HARNESS diff --git a/app/src/main/java/eu/llembas/android/api/Models.kt b/app/src/main/java/eu/llembas/android/api/Models.kt index 2d3010d..9733aa7 100644 --- a/app/src/main/java/eu/llembas/android/api/Models.kt +++ b/app/src/main/java/eu/llembas/android/api/Models.kt @@ -725,6 +725,10 @@ data class Message( @Serializable data class Turn(val message: Message? = null, val reply: Message? = null) +/** The answer to discarding a waiting message: the row that is gone, by its id. */ +@Serializable +data class Discarded(val id: String = "", val discarded: Boolean = false) + @Serializable data class NewChat(val chat: Chat, val message: Message? = null, val reply: Message? = null) 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 6d9bfe0..fee2d8b 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 @@ -103,6 +103,7 @@ import eu.llembas.android.api.Message import eu.llembas.android.api.Raw import eu.llembas.android.api.ShowCard import eu.llembas.android.api.drawn +import eu.llembas.android.api.editable import eu.llembas.android.api.unrecordedReplies import eu.llembas.android.ui.ModelAvatar import eu.llembas.android.ui.ProgressStatus @@ -275,6 +276,7 @@ fun ChatContent( var tuning by remember { mutableStateOf(false) } var renaming by remember { mutableStateOf(false) } var editing by remember { mutableStateOf(null) } + var discarding by remember { mutableStateOf(null) } var suggestion by remember { mutableStateOf("") } var suggested by remember { mutableIntStateOf(0) } val copy: (String) -> Unit = { text -> @@ -502,7 +504,15 @@ fun ChatContent( Drawn.Note -> MachineNote(message.text.orEmpty()) - Drawn.Person -> UserMessage(message, canEdit = live == null, onEdit = { editing = message }) + // A message that waits is sent now or discarded, never edited. + Drawn.Person -> UserMessage( + message, + canEdit = message.editable(writing = live != null), + onEdit = { editing = message }, + busy = state.acting != null, + onSendNow = { actions.sendNow(message) }, + onDiscard = { discarding = message }, + ) // One call for a reply being written and the same reply finished: // what the person opened in it (a thinking chip) stays open at `done`. @@ -571,6 +581,21 @@ fun ChatContent( ) } + // Discarding cannot be taken back, so it is asked once -- in the page's own words. + discarding?.let { message -> + AlertDialog( + onDismissRequest = { discarding = null }, + text = { Text(stringResource(R.string.discard_message_confirm)) }, + confirmButton = { + TextButton(onClick = { + actions.discard(message) + discarding = null + }) { Text(stringResource(R.string.discard)) } + }, + dismissButton = { TextButton(onClick = { discarding = null }) { Text(stringResource(R.string.cancel)) } }, + ) + } + editing?.let { message -> var text by remember(message.id) { mutableStateOf(message.text.orEmpty()) } AlertDialog( 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 1ec8c67..77bbdaf 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 @@ -115,6 +115,8 @@ data class ChatState( val picked: String? = null, /** The chat's long generations (a video, a track, a 3D model), by id, as each was last read. */ val mediaJobs: Map = emptyMap(), + /** The waiting message that is being sent now or discarded, by its id, until the instance has answered. */ + val acting: String? = null, ) /** @@ -311,6 +313,12 @@ interface ChatActions { fun stop() {} fun regenerate(message: Message) {} fun edit(message: Message, text: String) {} + + /** Send a message that waits ([Message.waiting]) now, as a turn with a reply of its own. */ + fun sendNow(message: Message) {} + + /** Withdraw a message that waits: it was never given to a model, and its row goes. */ + fun discard(message: Message) {} fun continueChat() {} fun executePlan() {} fun answer(card: Card, answer: CardAnswer) {} @@ -721,6 +729,34 @@ class ChatViewModel(app: Application) : turn.reply?.let { follow(it.id, own = true) } } + /** + * A waiting message's two actions. Each is one request a tap starts. The reply a send + * starts is the person's own, followed as one they typed for; a refusal's read waits until + * nothing is being written on this screen (a reply's own stream says everything until + * then, and a read beside it could draw a stale row over a finished one), and at the gate. + */ + private val waiting = WaitingActions( + state = _state, + read = { refresh() }, + follow = { follow(it.reply, it.own) }, + say = ::fail, + catchUp = { + val mark = reads.mark() + _state.first { !it.running } + rereadAndFollow(rounds = 1, mark = mark) + }, + ) + + override fun sendNow(message: Message) { + val chat = _state.value.chat ?: return + viewModelScope.launch { waiting.sendNow(message) { api().sendWaiting(chat.id, message.id) } } + } + + override fun discard(message: Message) { + val chat = _state.value.chat ?: return + viewModelScope.launch { waiting.discard(message) { api().discardWaiting(chat.id, message.id) } } + } + override fun continueChat() = control { api, chat -> took(api.continueChat(chat.id)) } override fun executePlan() = control { api, chat -> diff --git a/app/src/main/java/eu/llembas/android/ui/chat/Transcript.kt b/app/src/main/java/eu/llembas/android/ui/chat/Transcript.kt index f22f782..97320c7 100644 --- a/app/src/main/java/eu/llembas/android/ui/chat/Transcript.kt +++ b/app/src/main/java/eu/llembas/android/ui/chat/Transcript.kt @@ -19,6 +19,8 @@ import androidx.compose.foundation.horizontalScroll import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.Column +import androidx.compose.foundation.layout.ExperimentalLayoutApi +import androidx.compose.foundation.layout.FlowRow import androidx.compose.foundation.layout.Row import androidx.compose.foundation.layout.Spacer import androidx.compose.foundation.layout.fillMaxSize @@ -91,10 +93,11 @@ import eu.llembas.android.api.ModelInfo import eu.llembas.android.api.ShowCard import eu.llembas.android.api.Step import eu.llembas.android.api.ToolCall +import eu.llembas.android.api.Waiting import eu.llembas.android.api.ending -import eu.llembas.android.api.fateUnknown import eu.llembas.android.api.replyModel import eu.llembas.android.api.shownMarkdown +import eu.llembas.android.api.waiting import eu.llembas.android.lembas import eu.llembas.android.ui.MarkdownText import eu.llembas.android.ui.Segment @@ -117,13 +120,28 @@ private val Pill = RoundedCornerShape(50) private val FootTop = 2.dp private val FootHeight = 48.dp +/** A waiting message's two buttons: a tap target's height. */ +private val WaitingButton = 48.dp + /** * The person's turn: their words in a bubble on the right (never markdown), what they attached * above it as thumbnails. A long press offers Copy and, where the turn can still change, Edit. + * + * A message that waits says how it waits in words under the bubble, and -- where [onSendNow] + * and [onDiscard] are given, which only the chat's own screen does -- offers the two things a + * person does with it. They rest while [busy]: one of them is being asked of the instance. */ -@OptIn(ExperimentalFoundationApi::class) +@OptIn(ExperimentalFoundationApi::class, ExperimentalLayoutApi::class) @Composable -fun UserMessage(message: Message, canEdit: Boolean, onEdit: () -> Unit, modifier: Modifier = Modifier) { +fun UserMessage( + message: Message, + canEdit: Boolean, + onEdit: () -> Unit, + modifier: Modifier = Modifier, + busy: Boolean = false, + onSendNow: (() -> Unit)? = null, + onDiscard: (() -> Unit)? = null, +) { val palette = LocalPalette.current val copy = LocalCopy.current var menu by remember { mutableStateOf(false) } @@ -170,15 +188,32 @@ fun UserMessage(message: Message, canEdit: Boolean, onEdit: () -> Unit, modifier } } } - if (message.queued) { - // The server's queued progress ("Queued, 2 ahead · 12s") where it sends one. - // Not one whose arrival at the computer is unknown: that one waits for the person, not for its turn. + message.waiting?.let { waiting -> + // How it waits, in words. Queued behind a reply: the server's progress ("Queued: 2 + // ahead · 12s") where it sends one. Not for one a linked computer was handed: that + // one waits for the person or for the computer, not for its turn here. Text( - if (message.fateUnknown) stringResource(R.string.fate_unknown) else progressLineOf(message.progress) ?: stringResource(R.string.queued), + when (waiting) { + Waiting.Unsure -> stringResource(R.string.fate_unknown) + Waiting.Carried -> stringResource(R.string.fate_carried) + Waiting.Queued -> progressLineOf(message.progress) ?: stringResource(R.string.queued) + }, style = MaterialTheme.typography.labelSmall, - color = if (message.fateUnknown) palette.warning else palette.inkFaint, + color = if (waiting == Waiting.Unsure) palette.warning else palette.inkFaint, modifier = Modifier.padding(top = 4.dp, end = 4.dp), ) + if (onSendNow != null && onDiscard != null) { + // Two buttons of unknown width (eight languages, any type size): they share a + // row that wraps, each a full tap target, from the bubble's edge. + FlowRow(horizontalArrangement = Arrangement.spacedBy(4.dp, Alignment.End)) { + TextButton(onClick = onDiscard, enabled = !busy, modifier = Modifier.heightIn(min = WaitingButton)) { + Text(stringResource(R.string.discard)) + } + TextButton(onClick = onSendNow, enabled = !busy, modifier = Modifier.heightIn(min = WaitingButton)) { + Text(stringResource(R.string.send_now)) + } + } + } } } } diff --git a/app/src/main/java/eu/llembas/android/ui/chat/Waiting.kt b/app/src/main/java/eu/llembas/android/ui/chat/Waiting.kt new file mode 100644 index 0000000..9bd7a87 --- /dev/null +++ b/app/src/main/java/eu/llembas/android/ui/chat/Waiting.kt @@ -0,0 +1,98 @@ +package eu.llembas.android.ui.chat + +import eu.llembas.android.api.ApiException +import eu.llembas.android.api.ChatDetail +import eu.llembas.android.api.Message +import eu.llembas.android.api.Turn +import kotlinx.coroutines.CancellationException +import kotlinx.coroutines.flow.MutableStateFlow +import kotlinx.coroutines.flow.update + +/** + * A waiting message was sent now ([turn], the instance's answer): its row is the message as it + * is after -- no longer waiting -- where it stood, and the reply started for it is the last row. + * No row is there twice: the list's rows are keyed by id. + */ +fun ChatState.sentNow(turn: Turn): ChatState { + val sent = turn.message + val reply = turn.reply + val rows = messages.filterNot { it.id == reply?.id }.map { if (it.id == sent?.id) sent else it } + return copy(messages = rows + listOfNotNull(reply), lastSent = sent?.id ?: lastSent) +} + +/** A waiting message was discarded: its row is gone, and nothing else moved. */ +fun ChatState.discarded(id: String): ChatState = copy(messages = messages.filterNot { it.id == id }) + +/** + * Whether a refusal says the screen showed a message as waiting that is not so any more, or + * could not be acted on as shown: 409 (a reply is being written; the message no longer waits) + * and 404 (it is not there). The chat is then read again. Anything else -- no network, a server + * error -- says nothing about the message, and the row stays as it is. + */ +fun staleWaiting(e: Throwable): Boolean = e is ApiException && (e.status == 409 || e.status == 404) + +/** A reply to follow, and whether the person asked for it from this screen. */ +data class Followed(val reply: String, val own: Boolean) + +/** + * Which reply is followed once a waiting message was sent now: the one the send started + * ([reply]), as a reply the person asked for from this screen -- unless the chat, [read] after + * the send, no longer holds it as being written. That happens by design: a linked computer + * that still knew the message does not run it a second time, and the reply started for it is + * removed. Then whatever else the read says is being written is followed, as nobody's. + */ +fun followedAfterSend(reply: String?, read: ChatDetail?): Followed? { + if (reply != null && (read == null || read.live == reply || read.messages.any { it.id == reply && !it.complete })) { + return Followed(reply, own = true) + } + return read?.live?.let { Followed(it, own = false) } +} + +/** + * The two things a person does with a message that waits, as the chat's screen does them. The + * instance is asked through each action's own request; what the screen shows is [state]. + * + * Sent: the row stops waiting at once, the chat is read ([read]; a chat on a linked computer + * sorts the message to where it was sent), and the reply started for it is followed ([follow]) + * exactly as one the person asked for by typing. Discarded: the row is gone. Refused with a + * 409 or a 404: the instance's sentence is said ([say]) and the chat is read again + * ([catchUp]), because what the screen showed as waiting is not so any more. While one of the + * two is under way for a message, [ChatState.acting] names it and its buttons rest. + */ +class WaitingActions( + private val state: MutableStateFlow, + private val read: suspend () -> ChatDetail?, + private val follow: (Followed) -> Unit, + private val say: (Throwable) -> Unit, + private val catchUp: suspend () -> Unit, +) { + suspend fun sendNow(message: Message, send: suspend () -> Turn) = act(message) { + val turn = send() + state.update { it.sentNow(turn) } + followedAfterSend(turn.reply?.id, read())?.let(follow) + } + + suspend fun discard(message: Message, withdraw: suspend () -> Unit) = act(message) { + withdraw() + state.update { it.discarded(message.id) } + } + + /** One action at a time: a second tap while the first is asked is not a second request. */ + private suspend fun act(message: Message, action: suspend () -> Unit) { + if (state.value.acting != null) return + state.update { it.copy(acting = message.id) } + var stale = false + try { + action() + } catch (e: CancellationException) { + throw e + } catch (e: Exception) { + say(e) + stale = staleWaiting(e) + } finally { + state.update { if (it.acting == message.id) it.copy(acting = null) else it } + } + // After the buttons are free again: the read may wait for a reply being written here. + if (stale) catchUp() + } +} diff --git a/app/src/main/res/values-cs/strings.xml b/app/src/main/res/values-cs/strings.xml index 91a960b..7ca4e47 100644 --- a/app/src/main/res/values-cs/strings.xml +++ b/app/src/main/res/values-cs/strings.xml @@ -52,6 +52,9 @@ Starší zprávy Čeká na odeslání Není známo, zda se tato zpráva dostala do počítače. Odešlete ji znovu, nebo ji zahoďte. + Počítač tuto zprávu má a převezme ji při svém dalším tahu. + Odeslat teď + Zahodit tuto zprávu? Odpověď na toto nebyla zaznamenána. Přemýšlí Přemýšlel diff --git a/app/src/main/res/values-de/strings.xml b/app/src/main/res/values-de/strings.xml index 703312f..a5c55e6 100644 --- a/app/src/main/res/values-de/strings.xml +++ b/app/src/main/res/values-de/strings.xml @@ -52,6 +52,9 @@ Frühere Nachrichten Wartet auf das Senden Es ist nicht bekannt, ob dies den Computer erreicht hat. Senden Sie es erneut oder verwerfen Sie es. + Der Computer hat diese Nachricht und übernimmt sie bei seinem nächsten Zug. + Jetzt senden + Diese Nachricht verwerfen? Die Antwort darauf wurde nicht aufgezeichnet. Denkt nach Nachgedacht diff --git a/app/src/main/res/values-es/strings.xml b/app/src/main/res/values-es/strings.xml index b94a8b2..8d648ac 100644 --- a/app/src/main/res/values-es/strings.xml +++ b/app/src/main/res/values-es/strings.xml @@ -52,6 +52,9 @@ Mensajes anteriores Esperando para enviarse No se sabe si esto llegó al ordenador. Envíalo de nuevo o descártalo. + El ordenador tiene este mensaje y lo incorporará en su próximo turno. + Enviar ahora + ¿Descartar este mensaje? La respuesta a esto no se registró. Pensando Pensamiento diff --git a/app/src/main/res/values-fr/strings.xml b/app/src/main/res/values-fr/strings.xml index 2ae1290..37487c0 100644 --- a/app/src/main/res/values-fr/strings.xml +++ b/app/src/main/res/values-fr/strings.xml @@ -52,6 +52,9 @@ Messages précédents En attente d\'envoi On ne sait pas si ce message est parvenu à l’ordinateur. Renvoyez-le ou supprimez-le. + L’ordinateur a ce message et le prendra en compte à son prochain tour. + Envoyer maintenant + Abandonner ce message ? La réponse à ceci n’a pas été enregistrée. Réflexion Réflexion diff --git a/app/src/main/res/values-hu/strings.xml b/app/src/main/res/values-hu/strings.xml index 5c4875b..0f60d7d 100644 --- a/app/src/main/res/values-hu/strings.xml +++ b/app/src/main/res/values-hu/strings.xml @@ -52,6 +52,9 @@ Korábbi üzenetek Küldésre vár Nem tudni, hogy ez eljutott-e a számítógéphez. Küldje el újra, vagy vesse el. + A számítógépnél van ez az üzenet, és a következő körében veszi figyelembe. + Küldés most + Elveti ezt az üzenetet? Az erre adott válasz nem lett rögzítve. Gondolkodás Gondolkodott diff --git a/app/src/main/res/values-it/strings.xml b/app/src/main/res/values-it/strings.xml index f5df297..4c81d08 100644 --- a/app/src/main/res/values-it/strings.xml +++ b/app/src/main/res/values-it/strings.xml @@ -52,6 +52,9 @@ Messaggi precedenti In attesa di invio Non si sa se questo messaggio abbia raggiunto il computer. Invialo di nuovo o scartalo. + Il computer ha questo messaggio e lo accoglierà al suo prossimo turno. + Invia ora + Scartare questo messaggio? La risposta a questo non è stata registrata. Ragionamento Ha ragionato diff --git a/app/src/main/res/values-pl/strings.xml b/app/src/main/res/values-pl/strings.xml index f49a45a..8f0d154 100644 --- a/app/src/main/res/values-pl/strings.xml +++ b/app/src/main/res/values-pl/strings.xml @@ -52,6 +52,9 @@ Wcześniejsze wiadomości Czeka na wysłanie Nie wiadomo, czy ta wiadomość dotarła do komputera. Wyślij ją ponownie albo odrzuć. + Komputer ma tę wiadomość i uwzględni ją w swojej następnej turze. + Wyślij teraz + Odrzucić tę wiadomość? Odpowiedź na to nie została zapisana. Rozumowanie Rozumowanie diff --git a/app/src/main/res/values-sk/strings.xml b/app/src/main/res/values-sk/strings.xml index 708dd99..439733f 100644 --- a/app/src/main/res/values-sk/strings.xml +++ b/app/src/main/res/values-sk/strings.xml @@ -52,6 +52,9 @@ Staršie správy Čaká na odoslanie Nie je známe, či sa táto správa dostala do počítača. Odošlite ju znova alebo ju zahoďte. + Počítač túto správu má a prevezme ju pri svojom ďalšom ťahu. + Poslať teraz + Zahodiť túto správu? Odpoveď na toto nebola zaznamenaná. Premýšľa Premýšľal diff --git a/app/src/main/res/values/strings.xml b/app/src/main/res/values/strings.xml index 59de0c8..01610fc 100644 --- a/app/src/main/res/values/strings.xml +++ b/app/src/main/res/values/strings.xml @@ -53,6 +53,9 @@ Earlier messages Waiting to be sent It is not known whether this reached the computer. Send it again, or discard it. + The computer has this message and takes it in with its next turn. + Send now + Discard this message? The reply to this was not recorded. Thinking Thought diff --git a/app/src/test/java/eu/llembas/android/ClientTest.kt b/app/src/test/java/eu/llembas/android/ClientTest.kt index 8b5e9b1..7ea7051 100644 --- a/app/src/test/java/eu/llembas/android/ClientTest.kt +++ b/app/src/test/java/eu/llembas/android/ClientTest.kt @@ -137,13 +137,14 @@ class ClientTest { val api = client() val declared = "\"client\":[\"phone_actions\"]" val answer = """{"chat":{"id":"c1"}}""" - repeat(6) { server.enqueue(MockResponse().setResponseCode(201).setBody(answer)) } + repeat(7) { server.enqueue(MockResponse().setResponseCode(201).setBody(answer)) } api.createChat("Hello") api.sendMessage("c1", "And then?") api.edit("c1", "m1", "Hello again") api.regenerate("c1", "m2") api.continueChat("c1") api.executePlan("c1") + api.sendWaiting("c1", "m3") val paths = listOf( "/api/v2/chats", "/api/v2/chats/c1/messages", @@ -151,6 +152,7 @@ class ClientTest { "/api/v2/chats/c1/messages/m2/regenerate", "/api/v2/chats/c1/continue", "/api/v2/chats/c1/plan/execute", + "/api/v2/chats/c1/messages/m3/send", ) for (path in paths) { val request = server.takeRequest() diff --git a/app/src/test/java/eu/llembas/android/WaitingMessageTest.kt b/app/src/test/java/eu/llembas/android/WaitingMessageTest.kt new file mode 100644 index 0000000..ec67210 --- /dev/null +++ b/app/src/test/java/eu/llembas/android/WaitingMessageTest.kt @@ -0,0 +1,375 @@ +package eu.llembas.android + +import eu.llembas.android.api.ApiClient +import eu.llembas.android.api.ApiException +import eu.llembas.android.api.Chat +import eu.llembas.android.api.ChatDetail +import eu.llembas.android.api.Discarded +import eu.llembas.android.api.Drawn +import eu.llembas.android.api.LembasJson +import eu.llembas.android.api.Message +import eu.llembas.android.api.Step +import eu.llembas.android.api.Turn +import eu.llembas.android.api.Waiting +import eu.llembas.android.api.drawn +import eu.llembas.android.api.editable +import eu.llembas.android.api.fateUnknown +import eu.llembas.android.api.waiting +import eu.llembas.android.ui.chat.ChatState +import eu.llembas.android.ui.chat.Followed +import eu.llembas.android.ui.chat.WaitingActions +import eu.llembas.android.ui.chat.discarded +import eu.llembas.android.ui.chat.followedAfterSend +import eu.llembas.android.ui.chat.sentNow +import eu.llembas.android.ui.chat.staleWaiting +import kotlinx.coroutines.CompletableDeferred +import kotlinx.coroutines.ExperimentalCoroutinesApi +import kotlinx.coroutines.flow.MutableStateFlow +import kotlinx.coroutines.launch +import kotlinx.coroutines.test.runCurrent +import kotlinx.coroutines.test.runTest +import okhttp3.mockwebserver.MockResponse +import okhttp3.mockwebserver.MockWebServer +import org.junit.Assert.assertEquals +import org.junit.Assert.assertFalse +import org.junit.Assert.assertNull +import org.junit.Assert.assertTrue +import org.junit.Assert.fail +import org.junit.Test +import java.net.ConnectException + +/** + * A message that waits (`queued`: behind a reply, of unknown arrival at a linked computer, or + * held by it) and the two things its person does with it: read as the server writes it + * (`contract/message_unsure.json`, `message_carried.json`, `message_sent_now.json`, + * `message_discarded.json`), sent now and its reply followed, discarded and gone, and refused + * in the instance's own words with the chat read again. + */ +@OptIn(ExperimentalCoroutinesApi::class) +class WaitingMessageTest { + private fun fixture(name: String): String = + requireNotNull(javaClass.classLoader!!.getResource("$name.json")) { "contract/$name.json is missing" }.readText() + + private fun message(name: String) = LembasJson.decodeFromString(Message.serializer(), fixture(name)) + + private fun person(id: String, queued: Boolean = false, origin: String = "") = + Message(id = id, role = "user", text = "And the bread?", queued = queued, origin = origin) + + private fun reply(id: String, complete: Boolean = true) = Message( + id = id, + role = "assistant", + complete = complete, + steps = if (complete) listOf(Step(index = 0, kind = "text", markdown = "Seven.")) else emptyList(), + ) + + private val chat = Chat(id = "chat1") + + // --- The fixtures ----------------------------------------------------------------------------- + + @Test + fun aWaitingMessageSaysHowItWaitsAsTheServerWritesIt() { + val queued = message("message_queued") + val unsure = message("message_unsure") + val carried = message("message_carried") + assertEquals(Waiting.Queued, queued.waiting) + assertEquals(Waiting.Unsure, unsure.waiting) + assertEquals(Waiting.Carried, carried.waiting) + // Each is the person's own bubble, waiting, with its words. + for (waits in listOf(queued, unsure, carried)) { + assertTrue(waits.isUser && waits.queued) + assertEquals("And the leaves?", waits.text) + assertEquals(Drawn.Person, drawn(waits, first = false, reportChat = false)) + } + // Only the one whose arrival nobody heard of is drawn as a warning. + assertTrue(unsure.fateUnknown) + assertFalse(carried.fateUnknown) + assertFalse(queued.fateUnknown) + // The queue's place is the plain queued one's alone. + assertEquals(2, queued.progress?.ahead) + assertNull(unsure.progress?.ahead) + assertNull(carried.progress?.ahead) + } + + @Test + fun onlyAPersonsQueuedMessageWaits() { + // Sent, it is a turn like any other; a reply never waits, whatever its row says. + assertNull(person("q1").waiting) + assertNull(person("q1", origin = "carried").waiting) + assertNull(reply("a1").copy(queued = true).waiting) + // An origin this app does not know waits as a plain queued message does. + assertEquals(Waiting.Queued, person("q1", queued = true, origin = "somewhere").waiting) + } + + @Test + fun aWaitingMessageIsNeverOfferedEdit() { + for (name in listOf("message_queued", "message_unsure", "message_carried")) { + assertFalse(name, message(name).editable(writing = false)) + } + // A delivered one is, while nothing is being written; a reply never. + assertTrue(person("q1").editable(writing = false)) + assertFalse(person("q1").editable(writing = true)) + assertFalse(reply("a1").editable(writing = false)) + // The message a send-now answers with has stopped waiting. + val sent = LembasJson.decodeFromString(Turn.serializer(), fixture("message_sent_now")) + assertTrue(requireNotNull(sent.message).editable(writing = false)) + } + + @Test + fun theAnswersToSendNowAndDiscardAreReadAsTheServerWritesThem() { + val sent = LembasJson.decodeFromString(Turn.serializer(), fixture("message_sent_now")) + val message = requireNotNull(sent.message) + val started = requireNotNull(sent.reply) + assertEquals("msg1", message.id) + assertFalse(message.queued) + assertEquals("", message.origin) + assertNull(message.waiting) + assertNull(message.progress) + // The reply started for it: the model's, not finished, nothing written yet. + assertEquals("msg4", started.id) + assertFalse(started.isUser) + assertFalse(started.complete) + assertTrue(started.steps.isEmpty()) + + assertEquals(Discarded(id = "msg3", discarded = true), LembasJson.decodeFromString(Discarded.serializer(), fixture("message_discarded"))) + } + + // --- The two requests ------------------------------------------------------------------------- + + @Test + fun sendNowAndDiscardAreTheMessagesOwnRoutes() = runTest { + val server = MockWebServer().apply { start() } + try { + val api = ApiClient(server.url("/").toString().trimEnd('/'), "lmb_test") + server.enqueue(MockResponse().setBody(fixture("message_sent_now"))) + server.enqueue(MockResponse().setBody(fixture("message_discarded"))) + server.enqueue(MockResponse().setResponseCode(409).setBody("""{"detail":"Wait for the current reply to finish, or stop it."}""")) + server.enqueue(MockResponse().setResponseCode(404).setBody("""{"detail":"That message is not waiting to be sent."}""")) + + assertEquals("msg4", api.sendWaiting("chat1", "msg1").reply?.id) + val send = server.takeRequest() + assertEquals("POST", send.method) + assertEquals("/api/v2/chats/chat1/messages/msg1/send", send.path) + assertEquals("Bearer lmb_test", send.getHeader("Authorization")) + // It starts a reply, so it says what this app can do, as a message does. + assertTrue(send.body.readUtf8().contains("\"client\":[\"phone_actions\"]")) + + assertTrue(api.discardWaiting("chat1", "msg3").discarded) + val discard = server.takeRequest() + assertEquals("POST", discard.method) + assertEquals("/api/v2/chats/chat1/messages/msg3/discard", discard.path) + + // A refusal is the instance's own sentence, with its status. + try { + api.sendWaiting("chat1", "msg1") + fail("a 409 must throw") + } catch (e: ApiException) { + assertEquals(409, e.status) + assertEquals("Wait for the current reply to finish, or stop it.", e.message) + } + try { + api.discardWaiting("chat1", "msg3") + fail("a 404 must throw") + } catch (e: ApiException) { + assertEquals(404, e.status) + assertEquals("That message is not waiting to be sent.", e.message) + } + } finally { + server.shutdown() + } + } + + // --- What the transcript becomes --------------------------------------------------------------- + + @Test + fun aMessageSentNowStopsWaitingWhereItStoodAndItsReplyIsTheLastRow() { + val shown = ChatState( + chat = chat, + messages = listOf(person("q1"), reply("a1"), person("w1", queued = true, origin = "unsure"), person("w2", queued = true)), + ) + val turn = Turn(message = person("w1"), reply = reply("a2", complete = false)) + val after = shown.sentNow(turn) + assertEquals(listOf("q1", "a1", "w1", "w2", "a2"), after.messages.map { it.id }) + assertNull(after.messages[2].waiting) + // The other waiting message still waits. + assertEquals(Waiting.Queued, after.messages[3].waiting) + assertEquals("w1", after.lastSent) + // Told twice (the answer, then the same rows from a read): no row is there twice. + assertEquals(after.messages.map { it.id }, after.sentNow(turn).messages.map { it.id }) + // An answer that names no reply changes the message alone. + assertEquals(listOf("q1", "a1", "w1", "w2"), shown.sentNow(Turn(message = person("w1"))).messages.map { it.id }) + } + + @Test + fun aDiscardedMessageIsGoneAndNothingElseMoves() { + val shown = ChatState(chat = chat, messages = listOf(person("q1"), reply("a1"), person("w1", queued = true), person("w2", queued = true)), more = true) + val after = shown.discarded("w1") + assertEquals(listOf("q1", "a1", "w2"), after.messages.map { it.id }) + assertTrue(after.more) + // One that is not shown (any more): nothing to take away. + assertEquals(after, after.discarded("w1")) + } + + @Test + fun theReplyASendStartedIsFollowedAsThePersonsOwnUnlessTheChatNoLongerHoldsIt() { + val message = person("w1") + val started = reply("a2", complete = false) + // The read could not be made: the answer's word stands. + assertEquals(Followed("a2", own = true), followedAfterSend("a2", null)) + // The read says it is being written, by `live` or by its row. + assertEquals(Followed("a2", own = true), followedAfterSend("a2", ChatDetail(chat = chat, messages = listOf(message, started), live = "a2"))) + assertEquals(Followed("a2", own = true), followedAfterSend("a2", ChatDetail(chat = chat, messages = listOf(message, started)))) + // A linked computer that still knew the message did not run it again: the reply's row is + // gone, and there is nothing to follow -- or only what else is being written, as nobody's. + assertNull(followedAfterSend("a2", ChatDetail(chat = chat, messages = listOf(person("w1", queued = true, origin = "carried"))))) + assertEquals( + Followed("a9", own = false), + followedAfterSend("a2", ChatDetail(chat = chat, messages = listOf(message, reply("a9", complete = false)), live = "a9")), + ) + // Already finished by the time it was read: drawn from the read, not followed. + assertNull(followedAfterSend("a2", ChatDetail(chat = chat, messages = listOf(message, reply("a2"))))) + // An answer without a reply follows whatever the read says is live. + assertNull(followedAfterSend(null, null)) + assertEquals(Followed("a9", own = false), followedAfterSend(null, ChatDetail(chat = chat, live = "a9"))) + } + + @Test + fun onlyARefusalAboutTheMessageAsksForTheChatAgain() { + assertTrue(staleWaiting(ApiException(409, "Wait for the current reply to finish, or stop it."))) + assertTrue(staleWaiting(ApiException(409, "That message is not waiting to be sent."))) + assertTrue(staleWaiting(ApiException(404, "That message is not waiting to be sent."))) + // A server that failed, or one out of reach, says nothing about the message. + assertFalse(staleWaiting(ApiException(500, "Something went wrong."))) + assertFalse(staleWaiting(ConnectException("refused"))) + } + + // --- The actions, as the screen does them ------------------------------------------------------- + + /** The screen's side of the two actions, recorded: what was read, followed and said. */ + private class Screen(start: ChatState, private val server: ChatDetail? = null) { + val state = MutableStateFlow(start) + val followed = mutableListOf() + val said = mutableListOf() + var reads = 0 + var catchUps = 0 + + /** What the buttons were when the chat was read again after a refusal. */ + var actingAtCatchUp: String? = "never" + + val actions = WaitingActions( + state = state, + read = { + reads++ + server + }, + follow = { followed += it }, + say = { said += it.message.orEmpty() }, + catchUp = { + catchUps++ + actingAtCatchUp = state.value.acting + }, + ) + } + + private val waitingChat = ChatState(chat = chat, messages = listOf(person("q1"), reply("a1"), person("w1", queued = true, origin = "unsure"))) + + @Test + fun sendNowStartsAReplyThatIsFollowedAsOneThePersonAskedFor() = runTest { + val turn = Turn(message = person("w1"), reply = reply("a2", complete = false)) + val screen = + Screen( + waitingChat, + server = ChatDetail(chat = chat, messages = listOf(person("q1"), reply("a1"), person("w1"), reply("a2", complete = false)), live = "a2"), + ) + screen.actions.sendNow(waitingChat.messages.last()) { turn } + // The row no longer waits, the reply is there, and it is followed as the person's own. + assertEquals(listOf("q1", "a1", "w1", "a2"), screen.state.value.messages.map { it.id }) + assertNull(screen.state.value.messages[2].waiting) + assertEquals(listOf(Followed("a2", own = true)), screen.followed) + // The chat was read once (a linked computer's chat sorts the message to where it was sent). + assertEquals(1, screen.reads) + assertTrue(screen.said.isEmpty()) + assertEquals(0, screen.catchUps) + assertNull(screen.state.value.acting) + } + + @Test + fun theButtonsRestWhileTheInstanceIsAskedAndASecondTapIsNoSecondRequest() = runTest { + val screen = Screen(waitingChat) + val answer = CompletableDeferred() + var asked = 0 + val first = launch { + screen.actions.sendNow(waitingChat.messages.last()) { + asked++ + answer.await() + } + } + runCurrent() + assertEquals("w1", screen.state.value.acting) + // A second tap, on either button, while the first is under way: nothing is asked. + screen.actions.sendNow(waitingChat.messages.last()) { + asked++ + Turn() + } + screen.actions.discard(waitingChat.messages.last()) { asked++ } + assertEquals(1, asked) + assertEquals(3, screen.state.value.messages.size) + answer.complete(Turn(message = person("w1"), reply = reply("a2", complete = false))) + first.join() + assertNull(screen.state.value.acting) + assertEquals(listOf(Followed("a2", own = true)), screen.followed) + } + + @Test + fun discardTakesTheRowAwayAndAsksNothingElse() = runTest { + val screen = Screen(waitingChat) + var asked = 0 + screen.actions.discard(waitingChat.messages.last()) { asked++ } + assertEquals(1, asked) + assertEquals(listOf("q1", "a1"), screen.state.value.messages.map { it.id }) + assertEquals(0, screen.reads) + assertEquals(0, screen.catchUps) + assertTrue(screen.followed.isEmpty()) + assertTrue(screen.said.isEmpty()) + assertNull(screen.state.value.acting) + } + + @Test + fun aRefusalIsSaidInTheInstancesWordsAndTheChatIsReadAgain() = runTest { + // Send now while a reply is being written; send now and discard for a message that waits no more; discard for one that is gone. + val refusals = listOf( + ApiException(409, "Wait for the current reply to finish, or stop it."), + ApiException(409, "That message is not waiting to be sent."), + ApiException(404, "That message is not waiting to be sent."), + ) + for (refusal in refusals) { + for (send in listOf(true, false)) { + val screen = Screen(waitingChat) + val waits = waitingChat.messages.last() + if (send) screen.actions.sendNow(waits) { throw refusal } else screen.actions.discard(waits) { throw refusal } + assertEquals(listOf(refusal.message), screen.said) + assertEquals(1, screen.catchUps) + // The buttons were free again before the read: it may wait for a reply to end. + assertNull(screen.actingAtCatchUp) + // Nothing was changed on a guess, and nothing followed: the read says what is true. + assertEquals(waitingChat.messages, screen.state.value.messages) + assertTrue(screen.followed.isEmpty()) + assertNull(screen.state.value.acting) + } + } + } + + @Test + fun aFailureThatSaysNothingOfTheMessageLeavesItWaitingAndReadsNothing() = runTest { + for (failure in listOf(ConnectException("refused"), ApiException(500, "Something went wrong."))) { + val screen = Screen(waitingChat) + screen.actions.sendNow(waitingChat.messages.last()) { throw failure } + assertEquals(1, screen.said.size) + assertEquals(0, screen.catchUps) + assertEquals(Waiting.Unsure, screen.state.value.messages.last().waiting) + assertNull(screen.state.value.acting) + // The person can try again. + screen.actions.discard(waitingChat.messages.last()) { } + assertEquals(listOf("q1", "a1"), screen.state.value.messages.map { it.id }) + } + } +} diff --git a/app/src/test/java/eu/llembas/android/shots/Fakes.kt b/app/src/test/java/eu/llembas/android/shots/Fakes.kt index 9426b83..6d6da58 100644 --- a/app/src/test/java/eu/llembas/android/shots/Fakes.kt +++ b/app/src/test/java/eu/llembas/android/shots/Fakes.kt @@ -182,6 +182,22 @@ object Fakes { summary = ActivitySummary(working = 2, queued = 1, done = 4, finished = 4, active = 3, total = 7), ) + /** + * Three messages that wait, each its own way: queued behind a reply, handed to the linked + * computer with its arrival unknown, and held by the computer for its next turn. + */ + val waiting = ChatState( + chat = chat, + messages = listOf( + question, + answer, + Message(id = "w1", role = "user", text = "And how long does it keep?", queued = true, progress = Progress(phase = "queued", ahead = 1)), + Message(id = "w2", role = "user", text = "Then run the tests once more.", queued = true, origin = "unsure"), + Message(id = "w3", role = "user", text = "And tidy the notes when that is done.", queued = true, origin = "carried"), + ), + models = models, + ) + private val fixture = LembasJson.decodeFromString(ActivityEnvelope.serializer(), text("activity")).activity private fun job(id: String, type: String, role: String, brief: String, state: String, seconds: Int, stoppable: Boolean = true) = ActivityAgent( diff --git a/app/src/test/java/eu/llembas/android/shots/ScreenShots.kt b/app/src/test/java/eu/llembas/android/shots/ScreenShots.kt index d26deb1..47fac1f 100644 --- a/app/src/test/java/eu/llembas/android/shots/ScreenShots.kt +++ b/app/src/test/java/eu/llembas/android/shots/ScreenShots.kt @@ -133,6 +133,14 @@ class ScreenShots { shoot("03-transcript", Phone.Small, fontScale = 1.5f) { ChatContent(Fakes.transcript, NoChatActions, agent = false) } } + @Test + fun waitingMessages() { + // How each waits, in words, and Send now / Discard under it; the rows must hold at a small phone's width and large type. + shoot("03-waiting") { ChatContent(Fakes.waiting, NoChatActions, agent = false) } + shoot("03-waiting", Phone.Small) { ChatContent(Fakes.waiting, NoChatActions, agent = false) } + shoot("03-waiting", Phone.Small, fontScale = 1.5f) { ChatContent(Fakes.waiting, NoChatActions, agent = false) } + } + @Test fun writing() { // The 3.4.0 progress line under the reply: `{{text}} · {{elapsed}}`, the clock still. diff --git a/scripts/strings.py b/scripts/strings.py index 29a8736..21d8241 100755 --- a/scripts/strings.py +++ b/scripts/strings.py @@ -66,6 +66,11 @@ STRINGS: dict[str, str] = { "queued": "Waiting to be sent", # A message handed to the linked computer whose arrival was never heard (`origin` `unsure`): the server's sentence. "fate_unknown": "It is not known whether this reached the computer. Send it again, or discard it.", + # A message the linked computer has said it holds (`origin` `carried`): the server's sentence. + "fate_carried": "The computer has this message and takes it in with its next turn.", + # A waiting message's two actions (the page's own words; "Discard" is `discard`), and what Discard asks first. + "send_now": "Send now", + "discard_message_confirm": "Discard this message?", # In place of a finished reply that holds nothing, after a turn nobody typed (the server's sentence). "reply_unrecorded": "The reply to this was not recorded.", "thinking": "Thinking",