diff --git a/CHANGELOG.md b/CHANGELOG.md index d3acefb..6b68820 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -14,10 +14,13 @@ What is said here of replies that start by themselves needs an instance newer th and the main agent answers, when a scheduled task's result or a finished generation wakes the chat, or when the linked computer starts a turn itself, the reply appears and is written in front of you, with its tools and cards, instead of only after the chat was opened again. - Coming back to the app reads the chat once, for what happened meanwhile. Nothing is asked of - the instance while the phone is locked or the app is not in front. -- **The list of chats moves by itself.** A chat a reply starts in goes to the top of the drawer - and shows its dot without the drawer being closed and opened. + Coming back to the app reads the chat once, for what happened meanwhile. Such a reply is + followed only while the app is in front of an unlocked phone: locked or in the background the + app lets it go and asks the instance nothing, and on your return it picks up where the chat + is then. A reply you asked for yourself goes on being received, as before. +- **The list of chats moves by itself.** While the drawer is open, a chat a reply starts in + 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. ### Changed @@ -36,6 +39,8 @@ What is said here of replies that start by themselves needs an instance newer th - The app's own scroll to the end can no longer be taken for you scrolling away, which stopped the chat from following a reply although you had not touched it. The assistant's sheet has the same fix. + - Scrolling up with a mouse wheel, a keyboard or a screen reader while a reply arrives no + longer throws you back to the end: only a finger used to count as you scrolling. - A reply's foot is as tall while it is written as when it has finished, so the end of a reply no longer changes the height of the page. diff --git a/app/src/main/java/eu/llembas/android/InstanceGate.kt b/app/src/main/java/eu/llembas/android/InstanceGate.kt index 54fd934..314eafa 100644 --- a/app/src/main/java/eu/llembas/android/InstanceGate.kt +++ b/app/src/main/java/eu/llembas/android/InstanceGate.kt @@ -1,9 +1,15 @@ package eu.llembas.android +import kotlinx.coroutines.CancellationException +import kotlinx.coroutines.async +import kotlinx.coroutines.coroutineScope +import kotlinx.coroutines.currentCoroutineContext +import kotlinx.coroutines.ensureActive import kotlinx.coroutines.flow.MutableStateFlow import kotlinx.coroutines.flow.StateFlow import kotlinx.coroutines.flow.asStateFlow import kotlinx.coroutines.flow.first +import kotlinx.coroutines.launch import kotlinx.coroutines.withTimeoutOrNull import java.util.concurrent.atomic.AtomicInteger @@ -57,11 +63,49 @@ class InstanceGate(private val locked: () -> Boolean) { } } + /** + * [pass], for a wait that may last as long as the phone lies locked or the app is away: it + * sleeps until the gate is told of a change (an activity starting, the unlock) instead of + * looking at the lock every second, and only then takes its turn as [pass] does. + */ + suspend fun passLater() { + if (!look()) state.first { it } + pass() + } + companion object { const val AGAIN_MS = 1_000L } } +/** + * [work], for as long as a request may start: something nobody asked for (a reply that began by + * itself) is followed only while the app is in front of an unlocked phone. When the gate closes + * the work is let go -- cancelled, with its connection -- and the answer is null; so it is when + * the gate is closed already, and then nothing is started. [stays] says the work is the + * person's own after all (they asked for it while it ran): that goes on behind the gate, as a + * request under way does. The caller's own cancellation is not taken for a letting go. + */ +suspend fun InstanceGate.whileOpen(stays: () -> Boolean = { false }, work: suspend () -> T): T? { + if (!look() && !stays()) return null + return coroutineScope { + val doing = async { work() } + val watch = launch { + open.first { !it && !stays() } + doing.cancel() + } + try { + doing.await() + } catch (e: CancellationException) { + // The caller's own end is the caller's; only the gate's is "let go". + currentCoroutineContext().ensureActive() + null + } finally { + watch.cancel() + } + } +} + /** * [send] for each of [items] from the one at [from], each after its [turn] at the gate, and * [done] hears how many are through after each. A failure leaves the count where it was, so diff --git a/app/src/main/java/eu/llembas/android/LembasApp.kt b/app/src/main/java/eu/llembas/android/LembasApp.kt index a081a2b..320cb33 100644 --- a/app/src/main/java/eu/llembas/android/LembasApp.kt +++ b/app/src/main/java/eu/llembas/android/LembasApp.kt @@ -29,11 +29,16 @@ class LembasApp : Application() { /** 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. */ + /** + * The events route of the instance in use, as its frames; null when not signed in. Whoever + * collects them does so only while its screen is in front (`repeatOnLifecycle`), never from + * a scope that outlives the screen: the connection is open for as long as anybody listens. + */ 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() } } + // Every opening of the route waits at the gate: it is not opened, or opened again, behind a lock. + return events.frames(instance.id) { StreamClient(api).watch(turn = { gate.pass() }) { api.events() } } } /** Whether a new request with the account's files may start: the app in front, the phone unlocked. */ diff --git a/app/src/main/java/eu/llembas/android/MainActivity.kt b/app/src/main/java/eu/llembas/android/MainActivity.kt index c18dd83..42d3910 100644 --- a/app/src/main/java/eu/llembas/android/MainActivity.kt +++ b/app/src/main/java/eu/llembas/android/MainActivity.kt @@ -212,9 +212,18 @@ class MainActivity : ComponentActivity() { } // The list is read again each time the drawer opens, so a new title or a finished // reply's dot is there without a pull. - LaunchedEffect(drawer.isOpen) { if (drawer.isOpen) chats.load() } - // The badge on Reports follows the instance while the app is in front. + // While it is open the list follows the replies; closed, nothing reads it. val lifecycle = LocalLifecycleOwner.current.lifecycle + LaunchedEffect(drawer.isOpen) { + chats.shown(drawer.isOpen) + if (drawer.isOpen) { + chats.load() + lifecycle.repeatOnLifecycle(Lifecycle.State.STARTED) { chats.watchRunning() } + } + } + // The chat on screen: the end of its reply is not something new in the list. + LaunchedEffect(current) { chats.open = current } + // The badge on Reports follows the instance while the app is in front. LaunchedEffect(instance.id) { lifecycle.repeatOnLifecycle(Lifecycle.State.STARTED) { chats.watchReports() } } LaunchedEffect(open) { open?.let { 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 0454b89..1a26c5d 100644 --- a/app/src/main/java/eu/llembas/android/api/Display.kt +++ b/app/src/main/java/eu/llembas/android/api/Display.kt @@ -158,22 +158,28 @@ val Message.byMachine: Boolean get() = machine || origin == ORIGIN_HARNESS * ([asked], the row before it): what was said to that turn was never written into the chat * (instances from before the reply to a harness turn followed the device hold a few). One quiet * line says so in its place -- the server's rule for its own page, never a blank row with - * buttons. A reply still being written, one that was stopped or failed, and an empty reply to - * something a person asked are not this. + * buttons. A reply still being written, one that was stopped or failed, one that holds a plan + * and nothing else, and an empty reply to something a person asked are not this. + * + * [live] is the reply this screen knows is being written, by its id: that one is never this, + * whatever its row says. A row says `complete` only when the server does, and a row that says + * nothing reads as complete ([Message.complete]); the rule does not rest on that alone. */ -fun replyUnrecorded(reply: Message, asked: Message?): Boolean = !reply.isUser && +fun replyUnrecorded(reply: Message, asked: Message?, live: String? = null): Boolean = !reply.isUser && + reply.id != live && reply.complete && !reply.stopped && reply.error.isNullOrBlank() && reply.end == null && reply.text.isNullOrBlank() && reply.steps.isEmpty() && + reply.plan == null && reply.attachments.isEmpty() && asked != null && asked.isUser && asked.byMachine -/** The replies of [messages] that are [replyUnrecorded], by id. */ -fun unrecordedReplies(messages: List): Set = messages.indices - .filter { replyUnrecorded(messages[it], messages.getOrNull(it - 1)) } +/** The replies of [messages] that are [replyUnrecorded], by id; [live] is the one being written, if any. */ +fun unrecordedReplies(messages: List, live: String? = null): Set = messages.indices + .filter { replyUnrecorded(messages[it], messages.getOrNull(it - 1), live) } .mapTo(HashSet()) { messages[it].id } 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 66170ef..84638d2 100644 --- a/app/src/main/java/eu/llembas/android/api/StreamClient.kt +++ b/app/src/main/java/eu/llembas/android/api/StreamClient.kt @@ -22,48 +22,29 @@ data class Frame(val event: String, val data: String) * what [LiveReply.apply] wants. * * A refusal (a 4xx: the chat was deleted, the token signed out) ends the flow with the error; - * only a broken connection is retried. + * only a broken connection is retried -- and each opening after the first is a new request, so + * it waits for its `turn` (the gate: nothing new is asked behind a lock). */ class StreamClient(private val api: ApiClient) { private val http = api.http.newBuilder().readTimeout(0, TimeUnit.SECONDS).build() - fun follow(chatId: String, messageId: String): Flow = flow { - var wait = 1_000L - while (true) { - var closed = false - var refused: ApiException? = null - once(api.streamRequest(chatId, messageId)).collect { result -> - when (result) { - is Outcome.Event -> { - wait = 1_000L - emit(result.frame) - if (result.frame.event == "close") closed = true - } - - is Outcome.Refused -> refused = result.error - - is Outcome.Dropped -> Unit - } - } - refused?.let { throw it } - if (closed) return@flow - delay(wait) - wait = (wait * 2).coerceAtMost(30_000L) - } - } + fun follow(chatId: String, messageId: String, turn: suspend () -> Unit = {}): Flow = reopened(turn) { once(api.streamRequest(chatId, messageId)) } /** * 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 or closes without a frame. It runs until - * its collector stops; a refusal (4xx) ends it with the error. + * its collector stops; a refusal (4xx) ends it with the error. Each opening, the first + * too, waits for its [turn]. */ - fun watch(request: () -> Request): Flow = flow { + fun watch(turn: suspend () -> Unit = {}, request: () -> Request): Flow = flow { var wait = 1_000L while (true) { var closed = false var said = false var refused: ApiException? = null + // Every opening is a request of its own: it waits for its turn (the gate). + turn() once(request()).collect { result -> when (result) { is Outcome.Event -> { @@ -91,12 +72,6 @@ class StreamClient(private val api: ApiClient) { } } - private sealed interface Outcome { - data class Event(val frame: Frame) : Outcome - data class Refused(val error: ApiException) : Outcome - data object Dropped : Outcome - } - private fun once(request: Request): Flow = callbackFlow { val source = EventSources.createFactory(http).newEventSource( request, @@ -125,5 +100,44 @@ class StreamClient(private val api: ApiClient) { } } +/** What one opening of a stream gave: a frame, a refusal (4xx), or a connection that broke. */ +sealed interface Outcome { + data class Event(val frame: Frame) : Outcome + data class Refused(val error: ApiException) : Outcome + data object Dropped : Outcome +} + +/** + * A reply's stream, [open]ed again whenever it ends before `close`: after a pause of 1, 2, 4, 8 … + * up to 30 seconds, and after its [turn] -- every opening but the first is a request nobody is + * waiting for at that moment, so it asks first whether it may start. A refusal ends the flow + * with the error. + */ +fun reopened(turn: suspend () -> Unit, open: () -> Flow): Flow = flow { + var wait = 1_000L + while (true) { + var closed = false + var refused: ApiException? = null + open().collect { result -> + when (result) { + is Outcome.Event -> { + wait = 1_000L + emit(result.frame) + if (result.frame.event == "close") closed = true + } + + is Outcome.Refused -> refused = result.error + + is Outcome.Dropped -> Unit + } + } + refused?.let { throw it } + if (closed) return@flow + delay(wait) + wait = (wait * 2).coerceAtMost(30_000L) + turn() + } +} + /** 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/ui/chat/ChatScreen.kt b/app/src/main/java/eu/llembas/android/ui/chat/ChatScreen.kt index 96416d6..6d9bfe0 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 @@ -287,7 +287,7 @@ fun ChatContent( val rows = state.messages val info = state.modelInfo // Only in an agent chat: there a turn's reply is the linked computer's, and may never have been written here. - val unrecorded = remember(rows, chat?.isAgent) { if (chat?.isAgent == true) unrecordedReplies(rows) else emptySet() } + val unrecorded = remember(rows, chat?.isAgent, live?.messageId) { if (chat?.isAgent == true) unrecordedReplies(rows, live?.messageId) else emptySet() } // The view keeps to the end while a reply is written only for a person who is there // (`Follow.kt` has the rule): a finger on the list ends the following at once, and where the @@ -297,6 +297,10 @@ fun ChatContent( val slack = with(LocalDensity.current) { 48.dp.roundToPx() } // Whether a finger has been on the list since it last came to rest. val touched = remember { booleanArrayOf(false) } + // How many of this app's own scrolls are under way (`ownScroll`): any other scroll is the person's. + val own = remember { intArrayOf(0) } + // The model drops the far end of a long transcript only under a person who is at its end. + LaunchedEffect(following) { actions.reading(atEnd = following) } LaunchedEffect(list) { list.interactionSource.interactions.collect { if (it is DragInteraction.Start) { @@ -309,15 +313,21 @@ fun ChatContent( var moving = false var fromIndex = list.firstVisibleItemIndex var fromOffset = list.firstVisibleItemScrollOffset + var startedByApp = false snapshotFlow { list.isScrollInProgress }.collect { now -> if (now && !moving) { fromIndex = list.firstVisibleItemIndex fromOffset = list.firstVisibleItemScrollOffset + startedByApp = own[0] > 0 } if (moving && !now) { // Only the person's own scroll ends the following (`restFollows`): this app's // scroll to the end, overtaken by a line that arrived meanwhile, does not. - val byPerson = touched[0] || wentBack(fromIndex, fromOffset, list.firstVisibleItemIndex, list.firstVisibleItemScrollOffset) + val byPerson = scrollWasPersons( + touched = touched[0], + wentBack = wentBack(fromIndex, fromOffset, list.firstVisibleItemIndex, list.firstVisibleItemScrollOffset), + startedByApp = startedByApp, + ) following = restFollows(following, byPerson, list.distanceToEnd(), slack) touched[0] = false } @@ -335,18 +345,19 @@ fun ChatContent( // 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) yielding { list.scrollToItem(kept + if (state.more) 1 else 0) } - } else if (movesToEnd(change, following)) { + if (kept != null && list.firstVisibleItemIndex == 0) ownScroll(own) { list.scrollToItem(kept + if (state.more) 1 else 0) } + } else if (movesToEnd(change, following, personScrolls(list.isScrollInProgress, own[0]))) { + // A list the person is moving is left to them: where it rests says whether it follows. following = true - yielding { list.toEnd() } + ownScroll(own) { 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.isScrollInProgress) yielding { list.toEnd() } } + LaunchedEffect(growth) { if (growth > 0 && following && !list.isScrollInProgress) ownScroll(own) { list.toEnd() } } // The keyboard opening takes the list's foot away: a person at the end stays at the end. LaunchedEffect(list) { // 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() } } + snapshotFlow { list.layoutInfo.viewportSize.height }.drop(1).collect { if (following && !list.isScrollInProgress) ownScroll(own) { list.toEnd() } } } CompositionLocalProvider(LocalCopy provides copy, LocalChatMedia provides chatMedia) { 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 d37cde1..1ec8c67 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 @@ -45,6 +45,7 @@ import eu.llembas.android.api.whereabouts import eu.llembas.android.lembas import eu.llembas.android.ui.explain import eu.llembas.android.ui.files.noSuchRoute +import eu.llembas.android.whileOpen import kotlinx.coroutines.CancellationException import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.Job @@ -53,10 +54,9 @@ import kotlinx.coroutines.delay import kotlinx.coroutines.flow.MutableStateFlow import kotlinx.coroutines.flow.asStateFlow import kotlinx.coroutines.flow.first +import kotlinx.coroutines.flow.takeWhile import kotlinx.coroutines.flow.update import kotlinx.coroutines.launch -import kotlinx.coroutines.sync.Mutex -import kotlinx.coroutines.sync.withLock import kotlinx.coroutines.withContext import kotlinx.serialization.json.JsonObject import kotlinx.serialization.json.JsonPrimitive @@ -254,6 +254,24 @@ fun ChatState.withNewest(read: ChatDetail): ChatState { return copy(chat = read.chat, messages = messages.subList(0, at).filterNot { it.id in newest } + read.messages) } +/** Past this many rows a transcript left open is cut back to [KEPT_ROWS]: several times what a person scrolls through. */ +const val KEPT_MOST = 600 + +/** How many of the newest rows stay when a transcript is cut back. */ +const val KEPT_ROWS = 400 + +/** + * The transcript, held to a size: a chat left open while replies arrive by themselves (an + * agent's wakes, a schedule) would otherwise grow for as long as it is open. Past [most] rows + * the oldest go, down to the newest [keep], and "older" is offered again, which reads them + * back. Only for a person who is [atEnd]: someone reading further up is reading the very rows + * that would go, and nothing is taken from under them. + */ +fun ChatState.capped(atEnd: Boolean, most: Int = KEPT_MOST, keep: Int = KEPT_ROWS): ChatState { + if (!atEnd || messages.size <= most) return this + return copy(messages = messages.takeLast(keep), more = true) +} + /** * Whether the events route's `reply` frame [said] is news to this screen: a reply in the chat * that is open here, which is neither the one being followed nor a row already drawn as @@ -324,6 +342,9 @@ interface ChatActions { fun delete(then: () -> Unit) {} fun older() {} fun clearUnsent() {} + + /** Whether the person is at the transcript's end ([atEnd]) or reading further up: the screen's word, for what may be dropped. */ + fun reading(atEnd: Boolean) {} } /** @@ -416,7 +437,8 @@ class ChatViewModel(app: Application) : _state.update { it.copy(chat = detail.chat, messages = detail.messages, more = detail.more, models = models, loading = false) } - detail.live?.let { follow(it) } + // Being written when the chat was opened: whoever started it, nobody asked for it from here just now. + detail.live?.let { follow(it, own = false) } // Whether a team is offered and what runs in the background: the cheap read, // without the context count. A server without the panel has no answer. runCatching { client.activity(chatId, context = false) }.onSuccess { a -> @@ -454,91 +476,167 @@ class ChatViewModel(app: Application) : } } - /** Follow a reply to its end, then whatever the queue started after it. */ - private fun follow(messageId: String) { + private val gate get() = getApplication().lembas.gate + + /** The transcript's reads, one at a time and none twice for the same news. */ + private val reads = Reads() + + /** The reply the person asked for from this screen last, by its id: the one that goes on behind a lock. */ + private var ownReply: String? = null + + /** Whether the person is at the transcript's end, as the screen last said. */ + private var atEnd = true + + override fun reading(atEnd: Boolean) { + this.atEnd = atEnd + } + + /** How a reply's stream ended. */ + private sealed interface Through { + /** With `done`; [next] is the reply the queue started after it. */ + data class Done(val next: String?) : Through + + /** Without a `done`: the row is gone on the server, or it ended some way the stream did not tell. */ + data object Closed : Through + + /** With an error, which has been said. */ + data object Failed : Through + } + + /** + * Follow a reply to its end, then whatever the queue started after it. + * + * [own]: the person asked for this reply from this screen (a message sent, an edit, Regenerate, + * Continue). Its stream is the request they started, and goes on when the phone locks or the + * app leaves the front, as any request under way does. Every other reply -- one the events + * route said, one found being written when the chat was opened or read again, the queue's + * next -- is followed only while the app is in front of an unlocked phone ([whileOpen]): when + * that ends its stream is let go, and on the return one read catches up and follows what is + * being written then. Without that an agent's chat with wakes queued would chain a read and a + * stream for hours behind the lock. + * + * Whatever follows a stream is a new request and waits at the gate, the person's own reply's + * too: a broken connection opened again, the read after `done` with a `next`, the read after + * a stream that closed without `done`. + */ + private fun follow(messageId: String, own: Boolean) { val chat = _state.value.chat ?: return + if (own) ownReply = messageId // Already followed, and still being written: the events route says this app's own replies // too, and a second stream for one reply would start its drawing over. if (following?.isActive == true && _state.value.live?.let { it.messageId == messageId && it.finished == null } == true) return following?.cancel() following = viewModelScope.launch { _state.update { it.copy(live = LiveReply(messageId)) } - // Set at `done`, which is the end of the reply: from then on the stream is followed - // only for the name a model may still give the chat (the `title` frame). - var ended: LiveReply? = null - try { - StreamClient(api()).follow(chat.id, messageId).collect { frame -> - val before = ended - if (before != null) { - val named = before.apply(frame.event, frame.data) - ended = named - if (named.title != before.title) _state.update { s -> s.copy(chat = s.chat?.let { c -> named.title?.let { c.copy(title = it) } ?: c }) } - return@collect - } - val live = (_state.value.live ?: LiveReply(messageId)).apply(frame.event, frame.data) - val finished = live.finished - if (finished == null) { - // The tree outlives the reply: kept for the activity sheet once it ends. - _state.update { s -> s.copy(live = live, tree = live.tree ?: s.tree) } - return@collect - } - ended = live - _state.update { s -> - s.copy( - live = null, - tree = live.tree ?: s.tree, - messages = s.messages.map { if (it.id == finished.id) finished else it }, - chat = s.chat?.let { c -> live.title?.let { c.copy(title = it) } ?: c }, - ) - } - // The queue handed a waiting prompt to a fresh reply: the transcript has moved - // on the server, so it is read again rather than patched -- and that reply is - // followed instead of this stream's tail. - live.next?.let { next -> - refresh() - follow(next) - } + when (val through = gate.whileOpen(stays = { ownReply == messageId }) { stream(chat, messageId) }) { + // Let go at the gate. What the stream had shown stays in the row; once the app + // is in front again the chat is read, and what is being written then followed. + // A stream let go after its `done` (it was open for the chat's name) left nothing unread. + null -> { + val mark = reads.mark() + val unfinished = _state.value.live?.messageId == messageId + _state.update { it.closedUnfinished(messageId, null) } + if (unfinished) rereadAndFollow(rounds = 1, mark = mark) } - } catch (e: CancellationException) { - throw e - } catch (e: Exception) { - // After `done` only the name was still to come: nothing to say, nothing to redo. - if (ended != null) return@launch - fail(e) + + // The queue handed a waiting prompt to a fresh reply: the transcript has moved + // on the server, so it is read again rather than patched, and what the read says + // is being written is followed (the stream's word for it, where the read failed). + is Through.Done -> through.next?.let { next -> + gate.passLater() + val read = refresh() + (if (read != null) read.live else next)?.let { follow(it, own = false) } + } + + // The transcript is read again, so what was written is still there; where it + // cannot be read, what the stream had shown stays. + Through.Closed -> { + gate.passLater() + val reread = try { + api().chat(chat.id) + } catch (e: CancellationException) { + throw e + } catch (_: Exception) { + null + } + _state.update { it.closedUnfinished(messageId, reread).capped(atEnd) } + // Another reply is being written there (a queued turn): that one is followed. + reread?.live?.takeIf { it != messageId }?.let { follow(it, own = false) } + } + // The reply goes on on the server; what it has written so far is read back // rather than left half-drawn. - _state.update { it.copy(live = null) } - refresh() - return@launch - } - // The stream closed without a `done`: the row is gone on the server, or it ended some - // way the stream did not tell. The transcript is read again, so what was written is - // still there; where it cannot be read, what the stream had shown stays. - if (ended == null) { - val reread = try { - api().chat(chat.id) - } catch (e: CancellationException) { - throw e - } catch (_: Exception) { - null + Through.Failed -> { + gate.passLater() + refresh() } - _state.update { it.closedUnfinished(messageId, reread) } - // Another reply is being written there (a queued turn): that one is followed. - reread?.live?.takeIf { it != messageId }?.let { follow(it) } } } } - /** - * The transcript as the server has it now. The older pages the person loaded stay - * ([withNewest]); [whole] is for a change that rewrote the transcript itself (a compaction), - * after which only what was read is true. - */ - private suspend fun refresh(whole: Boolean = false) { - val chat = _state.value.chat ?: return - runCatching { api().chat(chat.id) }.onSuccess { d -> - _state.update { if (whole) it.copy(chat = d.chat, messages = d.messages, more = d.more) else it.withNewest(d) } + /** The stream of the reply [messageId], drawn as it comes, to its end; a connection that breaks is opened again at the gate. */ + private suspend fun stream(chat: Chat, messageId: String): Through { + // Set at `done`, which is the end of the reply: from then on the stream is followed + // only for the name a model may still give the chat (the `title` frame). + var ended: LiveReply? = null + var next: String? = null + try { + StreamClient(api()).follow(chat.id, messageId, turn = { gate.passLater() }).takeWhile { frame -> + val before = ended + if (before != null) { + val named = before.apply(frame.event, frame.data) + ended = named + if (named.title != before.title) _state.update { s -> s.copy(chat = s.chat?.let { c -> named.title?.let { c.copy(title = it) } ?: c }) } + return@takeWhile true + } + val live = (_state.value.live ?: LiveReply(messageId)).apply(frame.event, frame.data) + val finished = live.finished + if (finished == null) { + // The tree outlives the reply: kept for the activity sheet once it ends. + _state.update { s -> s.copy(live = live, tree = live.tree ?: s.tree) } + return@takeWhile true + } + ended = live + _state.update { s -> + s.copy( + live = null, + tree = live.tree ?: s.tree, + messages = s.messages.map { if (it.id == finished.id) finished else it }, + chat = s.chat?.let { c -> live.title?.let { c.copy(title = it) } ?: c }, + ) + } + // With a `next` the queue's reply is followed instead of this stream's tail. + next = live.next + live.next == null + }.collect { } + } catch (e: CancellationException) { + throw e + } catch (e: Exception) { + // After `done` only the name was still to come: nothing to say, nothing to redo. + if (ended != null) return Through.Done(next) + fail(e) + _state.update { it.copy(live = null) } + return Through.Failed } + return if (ended != null) Through.Done(next) else Through.Closed + } + + /** + * The transcript as the server has it now, or null where it could not be read. The older + * pages the person loaded stay ([withNewest]); [whole] is for a change that rewrote the + * transcript itself (a compaction), after which only what was read is true. + */ + private suspend fun refresh(whole: Boolean = false): ChatDetail? { + val chat = _state.value.chat ?: return null + val read = try { + api().chat(chat.id) + } catch (e: CancellationException) { + throw e + } catch (_: Exception) { + return null + } + _state.update { if (whole) it.copy(chat = read.chat, messages = read.messages, more = read.more) else it.withNewest(read).capped(atEnd) } + return read } private fun took(turn: Turn) { @@ -548,7 +646,7 @@ class ChatViewModel(app: Application) : lastSent = turn.message?.id ?: s.lastSent, ) } - turn.reply?.let { follow(it.id) } + turn.reply?.let { follow(it.id, own = true) } } /** @@ -592,7 +690,7 @@ class ChatViewModel(app: Application) : forceTool = if (picture) IMAGE_TOOL else null, ) _state.update { it.copy(chat = made.chat, messages = listOfNotNull(made.message, made.reply), lastSent = made.message?.id) } - made.reply?.let { follow(it.id) } + made.reply?.let { follow(it.id, own = true) } } else { took(client.sendMessage(chat.id, text, files, forceTool = if (picture) IMAGE_TOOL else null)) } @@ -613,14 +711,14 @@ class ChatViewModel(app: Application) : override fun regenerate(message: Message) = control { api, chat -> val turn = api.regenerate(chat.id, message.id) _state.update { s -> s.copy(messages = s.messages.map { if (it.id == message.id) turn.reply ?: it else it }) } - turn.reply?.let { follow(it.id) } + turn.reply?.let { follow(it.id, own = true) } } override fun edit(message: Message, text: String) = control { api, chat -> val turn = api.edit(chat.id, message.id, text) // Everything after the edited turn is gone on the server; read it back. refresh() - turn.reply?.let { follow(it.id) } + turn.reply?.let { follow(it.id, own = true) } } override fun continueChat() = control { api, chat -> took(api.continueChat(chat.id)) } @@ -688,7 +786,7 @@ class ChatViewModel(app: Application) : } } try { - StreamClient(client).watch { client.activityEvents(chat.id) }.collect { frame -> + StreamClient(client).watch(turn = { gate.pass() }) { client.activityEvents(chat.id) }.collect { frame -> if (frame.event != "activity") return@collect val read = runCatching { LembasJson.decodeFromString(ActivityFrame.serializer(), frame.data) }.getOrNull() ?: return@collect val changed = read.version != _state.value.activity?.version @@ -712,12 +810,17 @@ class ChatViewModel(app: Application) : * there is no stream frame for a job. One that ends by itself wakes the chat with a reply this * app did not start: when a job says the chat was told, the transcript is read again and that * reply followed. Runs until cancelled (the screen left, or no longer in front). An instance - * without these routes has no jobs, and nothing is asked again. + * without these routes has no jobs, and nothing is asked again. Every request waits at the + * gate; how often a finished job was asked whether the chat was told is kept for as long as + * the chat is open ([toldWaits]), so a return to the screen does not start that count over. */ + private val toldWaits = mutableMapOf() + suspend fun watchMedia() { val chat = _state.value.chat ?: return val client = runCatching { api() }.getOrNull() ?: return try { + gate.pass() val jobs = client.mediaJobs(chat.id) val before = _state.value.mediaJobs _state.update { it.withJobs(jobs, SystemClock.elapsedRealtime()) } @@ -728,14 +831,15 @@ class ChatViewModel(app: Application) : } catch (_: Exception) { // An older instance, or one out of reach: the cards say what the calls said. } - val waited = mutableMapOf() while (true) { delay(JOB_POLL_MS) val now = _state.value - val telling = now.mediaJobs.values.filter { awaitsTelling(it.job) && it.at > 0 && (waited[it.job.id] ?: 0) < TELL_ROUNDS }.map { it.job.id } + val telling = now.mediaJobs.values.filter { awaitsTelling(it.job) && it.at > 0 && (toldWaits[it.job.id] ?: 0) < TELL_ROUNDS }.map { it.job.id } var woken = false for (id in (now.jobsToRead() + telling).distinct()) { val before = _state.value.mediaJobs[id]?.job + // Each a request of its own: none behind a lock, or with the app not in front. + gate.pass() val read = try { client.mediaJob(id) } catch (e: CancellationException) { @@ -748,7 +852,7 @@ class ChatViewModel(app: Application) : } catch (_: Exception) { continue } - if (awaitsTelling(read)) waited[id] = (waited[id] ?: 0) + 1 + if (awaitsTelling(read)) toldWaits[id] = (toldWaits[id] ?: 0) + 1 _state.update { it.withJobs(listOf(read), SystemClock.elapsedRealtime()) } if (woke(before, read)) woken = true } @@ -757,38 +861,48 @@ class ChatViewModel(app: Application) : } /** - * The chat was woken (a job ended): its transcript as the server has it now, and the reply - * being written there followed. The telling is written a moment before the reply exists, so - * where none is live yet the chat is read once more shortly after. While this screen follows - * a reply of its own nothing is touched: the wake waits in the queue, and the stream's `next` - * brings it. + * The chat has news (a job ended and told it, the events route said a reply, the app is back + * in front): its transcript as the server has it now, and the reply being written there + * followed. A job's telling is written a moment before the reply exists, so with two + * [rounds], where none is live yet, the chat is read once more shortly after. While this + * screen follows a reply nothing is touched: the news waits in the queue, and the stream's + * `next` brings it. + * + * Each read waits at the gate, and goes through [reads]: [mark] is the moment the news was + * learned, and a read that began after it has answered already is not made again -- a + * burst of frames, or a return that several watchers notice, is one read. [wanted] is asked + * once more when it is this one's turn. */ - private suspend fun rereadAndFollow(rounds: Int = 2) { + private suspend fun rereadAndFollow(rounds: Int = 2, mark: Long = reads.mark(), wanted: () -> Boolean = { true }) { val chat = _state.value.chat ?: return - // One at a time: a job's telling and the events route may both say the same reply. - rereading.withLock { - repeat(rounds) { round -> - if (_state.value.live != null) return + var since = mark + for (round in 0 until rounds) { + if (round > 0) { + delay(WAKE_PAUSE_MS) + // The later round is there to read after the pause: only a read from now on stands for it. + since = reads.mark() + } + gate.passLater() + var failed = false + reads.since(since, wanted = { _state.value.live == null && wanted() }) { val read = try { api().chat(chat.id) } catch (e: CancellationException) { throw e } catch (_: Exception) { - return + failed = true + return@since false } - if (_state.value.live != null) return - _state.update { it.withNewest(read) } - read.live?.let { - follow(it) - return + if (_state.value.live == null) { + _state.update { it.withNewest(read).capped(atEnd) } + read.live?.let { follow(it, own = false) } } - if (round < rounds - 1) delay(WAKE_PAUSE_MS) + true } + if (failed || _state.value.live != null) return } } - private val rereading = Mutex() - // --- Replies this app did not start ------------------------------------------------------- /** Whether this chat's screen has been in front before: the next time is a return. */ @@ -804,31 +918,33 @@ class ChatViewModel(app: Application) : * (`reply`), and the one for this chat that is not followed already is read and followed as * any reply is. Runs until cancelled (the screen left, or no longer in front). * - * On a return to the front the chat is read once, before listening: a reply that started and - * ended meanwhile is said by nobody. Nothing is asked while the phone is locked or the app is + * On a return to the front the chat is read once: a reply that started and ended meanwhile + * is said by nobody. The route is listened to while that read is under way, so a reply that + * starts just then is not missed; what it says then is checked against what the read found + * before anything is read again. Nothing is asked while the phone is locked or the app is * not in front (`InstanceGate`); what was heard then is taken up on the return. An instance * that does not send the frame changes nothing here but that one read. */ suspend fun watchReplies() { if (_state.value.chat == null) return val app = getApplication().lembas - if (watchedReplies) { - app.gate.pass() - rereadAndFollow(rounds = 1) - } + val back = watchedReplies watchedReplies = true - val frames = runCatching { app.eventFrames() }.getOrNull() ?: return + val returned = reads.mark() + val frames = runCatching { app.eventFrames() }.getOrNull() try { coroutineScope { - frames.collect { frame -> + if (back) launch { rereadAndFollow(rounds = 1, mark = returned) } + frames?.collect { frame -> if (frame.event != "reply") return@collect val said = runCatching { LembasJson.decodeFromString(ReplyFrame.serializer(), frame.data) }.getOrNull() ?: return@collect if (!_state.value.asksFor(said) || !heard.add(said.messageId)) return@collect + val learned = reads.mark() // Not in the collector: the one connection is shared, and a watcher that // waits holds the others' frames back. launch { try { - takeUp(said) + takeUp(said, learned) } finally { heard -= said.messageId } @@ -843,17 +959,19 @@ class ChatViewModel(app: Application) : } /** - * A reply the events route said, for this chat. While this screen follows a reply of its own - * nothing is touched -- what was said waits in the queue behind it, and that stream's `next` - * brings it; once nothing is being written here, and if it is still news, the transcript is - * read (it holds the turn the reply answers, which this screen has not seen either) and the - * reply being written followed. + * A reply the events route said, for this chat -- that it started, or (`live` false) that it + * ended. While this screen follows a reply of its own nothing is touched: what was said waits + * in the queue behind it, and that stream's `next` brings it; once nothing is being written + * here, and if it is still news, the transcript is read (it holds the turn the reply answers, + * which this screen has not seen either) and the reply being written followed. News that a + * read begun since [learned] has already brought costs nothing: the end of a reply this + * screen followed to its `done` is no news at all ([asksFor]). */ - private suspend fun takeUp(said: ReplyFrame) { - getApplication().lembas.gate.pass() + private suspend fun takeUp(said: ReplyFrame, learned: Long) { + gate.pass() _state.first { !it.running } if (!_state.value.asksFor(said)) return - rereadAndFollow(rounds = 1) + rereadAndFollow(rounds = 1, mark = learned) { _state.value.asksFor(said) } } /** 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 c15f0cc..611481d 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 @@ -60,14 +60,32 @@ fun transcriptChange(before: List?, after: List, restored: Boo /** * Whether the view goes to the end after [change], given whether it was [following]. Opening a * chat and sending a message always do; an older page never does; everything else -- and a reply - * growing, a keyboard opening -- only for a person who is at the end already. + * growing, a keyboard opening -- only for a person who is at the end already, and never while + * the list is being scrolled by the person ([personScrolling]): a wheel, a key or a screen + * reader moving it upwards has not come to rest yet, so the following has not ended yet, and + * going to the end now would cancel that scroll and throw the reader back down. */ -fun movesToEnd(change: TranscriptChange, following: Boolean): Boolean = when (change) { +fun movesToEnd(change: TranscriptChange, following: Boolean, personScrolling: Boolean = false): Boolean = when (change) { TranscriptChange.Opened, TranscriptChange.Sent -> true TranscriptChange.None, TranscriptChange.Older -> false - TranscriptChange.Appended, TranscriptChange.Changed -> following + TranscriptChange.Appended, TranscriptChange.Changed -> following && !personScrolling } +/** + * Whether a scroll is the person's. One that is [inProgress] and that this app did not start + * ([ownScrolls]: how many of the app's own scrolls are under way) is theirs, whatever moved + * the list -- a finger, a wheel, a keyboard, a screen reader. The app marks its own; everything + * else is somebody. + */ +fun personScrolls(inProgress: Boolean, ownScrolls: Int): Boolean = inProgress && ownScrolls <= 0 + +/** + * Whether a scroll that has come to rest was the person's: a finger was on the list + * ([touched]), the list went back towards its start ([wentBack]), or the scroll began with + * none of this app's own under way ([startedByApp] false). + */ +fun scrollWasPersons(touched: Boolean, wentBack: Boolean, startedByApp: Boolean): Boolean = touched || wentBack || !startedByApp + /** * Whether the view follows, once a scroll has come to rest [distance] pixels short of the end. * Within [slack] counts as the end: a line that arrived while the list was settling must not @@ -116,3 +134,17 @@ suspend fun yielding(scroll: suspend () -> Unit) { currentCoroutineContext().ensureActive() } } + +/** + * [yielding], counted in [own] while it runs: how the list's watchers tell this app's scroll + * from the person's ([personScrolls]). A count and not a flag: one of the app's scrolls may + * overtake another, and the first one's end must not unmark the second. + */ +suspend fun ownScroll(own: IntArray, scroll: suspend () -> Unit) { + own[0]++ + try { + yielding(scroll) + } finally { + own[0]-- + } +} diff --git a/app/src/main/java/eu/llembas/android/ui/chat/Reads.kt b/app/src/main/java/eu/llembas/android/ui/chat/Reads.kt new file mode 100644 index 0000000..f60233e --- /dev/null +++ b/app/src/main/java/eu/llembas/android/ui/chat/Reads.kt @@ -0,0 +1,37 @@ +package eu.llembas.android.ui.chat + +import kotlinx.coroutines.sync.Mutex +import kotlinx.coroutines.sync.withLock + +/** + * The reads of one thing (a chat's transcript) that several pieces of news ask for, one at a + * time and none twice for the same news. Whoever learns something that needs a read takes a + * [mark] at that moment -- before waiting for anything -- and asks [since] it; a read that began + * after the mark and came back has seen what the mark's news was about, so the asker's own is + * not made. A burst of frames, or a return to the front that several watchers notice, is then + * one read; news that arrives while a read is under way is newer than that read, and gets its own. + */ +class Reads { + private val one = Mutex() + + /** How many reads have begun. */ + private var begun = 0L + + /** The last read that came back with an answer, by its number. */ + private var answered = 0L + + /** The moment some news was learned: every read that begins from now on covers it. */ + fun mark(): Long = begun + + /** + * [read], unless a read that began after [mark] has already answered, or [wanted] says -- once + * it is this asker's turn -- that nothing is asked for any more. [read] says whether it got + * an answer; one that did not covers nobody. True when [read] ran. + */ + suspend fun since(mark: Long, wanted: () -> Boolean = { true }, read: suspend () -> Boolean): Boolean = one.withLock { + if (answered > mark || !wanted()) return@withLock false + val mine = ++begun + if (read()) answered = mine + true + } +} 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 bc083ec..cd5ef63 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 @@ -79,6 +79,7 @@ import eu.llembas.android.api.ChatPage import eu.llembas.android.api.Doorstep import eu.llembas.android.api.Folder import eu.llembas.android.api.LembasJson +import eu.llembas.android.api.ReplyFrame import eu.llembas.android.api.ReportsFrame import eu.llembas.android.api.SearchHit import eu.llembas.android.api.fit @@ -91,12 +92,17 @@ import kotlinx.coroutines.Job import kotlinx.coroutines.delay import kotlinx.coroutines.flow.MutableStateFlow import kotlinx.coroutines.flow.asStateFlow +import kotlinx.coroutines.flow.first import kotlinx.coroutines.flow.update import kotlinx.coroutines.launch +import kotlinx.coroutines.sync.Mutex +import kotlinx.coroutines.sync.withLock import kotlinx.serialization.json.JsonObject import kotlinx.serialization.json.buildJsonObject import kotlinx.serialization.json.put +import java.time.Instant import java.time.LocalDate +import java.time.OffsetDateTime import java.time.ZoneId data class ChatsState( @@ -126,17 +132,57 @@ fun ChatsState.reported(data: String): ChatsState { } /** - * The list's newest page read again ([page]), put where it was: the chats as the server orders - * and marks them now (the one a reply just started in first, running or unread). What a person - * had loaded below the page stays below it -- the rows after the last one the page still names -- - * and no chat is listed twice. + * The list's newest page read again ([page]), merged by id: the page's chats first, as the server + * orders and marks them now (the one a reply just started in first, running or unread), then + * every chat this list held that the page does not name, in the order it had. A chat that came + * up from a later page a person had loaded is in the page, so it moves; the ones around its old + * place stay. No chat is listed twice. + * + * The list is ordered by when a chat last changed, so the page holds every chat that changed + * since its own last one did: a chat held here from after that moment which the page does not + * name is no longer in the list (deleted, archived or filed away elsewhere), and goes. A page + * with nothing after it is the whole list. */ fun ChatsState.withNewest(page: ChatPage): ChatsState { + if (!page.more) return copy(chats = page.chats, more = false) val newest = page.chats.mapTo(HashSet()) { it.id } - val older = chats.drop(chats.indexOfLast { it.id in newest } + 1) - // Nothing shown joins the page: it is the whole list, as a first read is. - if (older.size == chats.size || older.isEmpty()) return copy(chats = page.chats, more = page.more) - return copy(chats = page.chats + older) + val floor = page.chats.lastOrNull()?.updatedAt?.let(::moment) + val older = chats.filter { it.id !in newest && !gone(it, floor) } + // Nothing below the page: whether there is more is the page's word. + return copy(chats = page.chats + older, more = if (older.isEmpty()) page.more else more) +} + +/** Whether [chat], which the newest page does not name, changed after the page's last chat did ([floor]): it would be in the page were it still listed. */ +private fun gone(chat: Chat, floor: Instant?): Boolean { + val changed = chat.updatedAt?.let(::moment) ?: return false + return floor != null && changed.isAfter(floor) +} + +/** A time as the server writes it (ISO 8601 with an offset); null for anything else. */ +private fun moment(stamp: String): Instant? = runCatching { OffsetDateTime.parse(stamp).toInstant() }.getOrNull() + +/** + * Whether the events route's `reply` frame [said] asks for the list to be read again. Only + * while something shows the list ([shown]; the drawer reads it whenever it opens), and only for + * what the list does not show already: a reply that started in a chat whose row says it is + * running is no news (every reconnection of the route says all of those again), and the end + * of a reply in a chat that is listed is marked on its row without a read ([ended]). A list + * not read yet is left to its first read. + */ +fun ChatsState.readsFor(said: ReplyFrame, shown: Boolean): Boolean { + if (!shown || chats.isEmpty() || said.chatId.isBlank()) return false + val row = chats.firstOrNull { it.id == said.chatId } + return if (said.live) row?.running != true else row == null +} + +/** + * A reply ended in the chat [said] names (`live` false): its row is no longer running, and shows + * that it has something new -- unless it is the chat [open] on screen, where the person watched + * it end. Nothing is read for it. + */ +fun ChatsState.ended(said: ReplyFrame, open: String?): ChatsState { + if (said.live || chats.none { it.id == said.chatId }) return this + return copy(chats = chats.map { if (it.id == said.chatId) it.copy(running = false, unread = it.unread || it.id != open) else it }) } /** The drawer's list: every chat of the instance in use, both kinds, newest first. */ @@ -212,10 +258,7 @@ class ChatsViewModel(app: Application) : AndroidViewModel(app) { reportsTold++ _state.update { it.reported(frame.data) } } - // A reply started in one of the person's chats (an instance that says so): the list - // is read again shortly, so that chat moves up and shows its dot as it would - // have at the drawer's next opening. - if (frame.event == "reply" && refused == null) listSoon() + if (frame.event == "reply" && refused == null) replySaid(frame.data) } } catch (e: CancellationException) { throw e @@ -224,23 +267,83 @@ class ChatsViewModel(app: Application) : AndroidViewModel(app) { } } - private var listing: Job? = null + /** Whether the list is on screen (the drawer is open): only then is it read again by itself. */ + private var shown = false + + /** The chat open on screen, by its id: the end of its reply is not something new. */ + var open: String? = null + + /** Whether this instance says when replies end; until it has, a running row is read again now and then. */ + private val ends = ReplyEnds() + + fun shown(now: Boolean) { + shown = now + // What was asked for while it was open is the next opening's read. + if (!now) soon.forget() + } + + /** + * The events route said a reply started or ended in one of the person's chats. An end is + * marked on the chat's row at once, with no read; a start in a chat the list does not show + * as running moves that chat up and gives it its dot at the list's next read, shortly -- + * while the drawer is open. Closed, nothing is read: it reads the list when it opens. + */ + private fun replySaid(data: String) { + val said = runCatching { LembasJson.decodeFromString(ReplyFrame.serializer(), data) }.getOrNull() ?: return + ends.hear(said) + val reads = _state.value.readsFor(said, shown) + if (!said.live) _state.update { it.ended(said, open) } + if (reads) soon.ask() + } /** * The newest page of the list, read once things have been quiet for a moment: several - * replies starting together (a queue, a team) are one read. It waits at the gate, so a - * frame heard just before the phone locked or the app left the front is one read on the - * return, not a request behind the lock. A list not read yet is left to its first read. + * replies starting together (a queue, a team) are one read, and a run of them that never + * falls quiet still gets one every few seconds. It waits at the gate, so a frame heard just + * before the phone locked or the app left the front is one read on the return, not a + * request behind the lock. A read under way is never cut short by the next frame. */ - private fun listSoon() { - listing?.cancel() - listing = viewModelScope.launch { - delay(LIST_PAUSE_MS) - val app = getApplication().lembas - app.gate.pass() - if (refused != null || _state.value.chats.isEmpty()) return@launch - val page = runCatching { app.instances.client()?.chats() }.getOrNull() ?: return@launch - _state.update { it.withNewest(page) } + private val soon by lazy { + Soon(viewModelScope, LIST_PAUSE_MS, LIST_MOST_MS, before = { getApplication().lembas.gate.pass() }) { readNewest() } + } + + private val reading = Mutex() + + /** The list's newest page, merged into what is shown. A list not read yet is left to its first read. */ + private suspend fun readNewest() = reading.withLock { + if (refused != null || _state.value.chats.isEmpty()) return@withLock + val page = try { + getApplication().lembas.instances.client()?.chats() + } catch (e: CancellationException) { + throw e + } catch (_: Exception) { + null + } ?: return@withLock + _state.update { it.withNewest(page) } + } + + /** + * While the list is on screen and the app in front: an instance that does not say when a + * reply ends leaves a row's running mark as old as the list's last read, so while any row + * shows one the list is read again at a bounded rate ([runningPause]), at the gate, and no + * more once none does. An instance that says the ends ([ReplyEnds]) is never asked: its + * frames clear the marks. Runs until cancelled (the drawer closed, the app left the front). + */ + suspend fun watchRunning() { + val gate = getApplication().lembas.gate + var round = 0 + while (true) { + _state.first { state -> state.chats.any { it.running } } + if (ends.said) return + delay(runningPause(round)) + gate.pass() + if (ends.said) return + if (_state.value.chats.none { it.running }) { + round = 0 + continue + } + round++ + readNewest() } } @@ -356,6 +459,9 @@ private const val SEARCH_PAUSE_MS = 400L /** Between a `reply` frame and the list's read: a reply is said about a quarter of a second after it starts. */ private const val LIST_PAUSE_MS = 1500L +/** The longest a read of the list waits for the replies' frames to fall quiet. */ +private const val LIST_MOST_MS = 6000L + /** Where the drawer can go, besides a chat. */ interface DrawerActions { fun newChat() {} diff --git a/app/src/main/java/eu/llembas/android/ui/home/Soon.kt b/app/src/main/java/eu/llembas/android/ui/home/Soon.kt new file mode 100644 index 0000000..dd0fa42 --- /dev/null +++ b/app/src/main/java/eu/llembas/android/ui/home/Soon.kt @@ -0,0 +1,123 @@ +package eu.llembas.android.ui.home + +import eu.llembas.android.api.ReplyFrame +import kotlinx.coroutines.CoroutineScope +import kotlinx.coroutines.Job +import kotlinx.coroutines.delay +import kotlinx.coroutines.launch + +/** + * Something done shortly after it was asked for, once for many askings: [work] runs when nobody + * has asked for [pause] milliseconds, and at the latest [most] milliseconds after the first + * asking -- so a stream of askings closer together than the pause (a team's replies starting + * one after another) still gets its work, every [most], instead of none until it falls quiet. + * + * Work under way is never cancelled by a new asking; an asking that comes while it runs is + * answered by one more run after it. [before] is what the work waits for before it starts (its + * turn at the gate): an asking during that wait is still answered by the run it waits for. + * + * Everything here runs on [scope]'s one thread. + */ +class Soon( + private val scope: CoroutineScope, + private val pause: Long, + private val most: Long, + private val before: suspend () -> Unit = {}, + private val work: suspend () -> Unit, +) { + private var quiet: Job? = null + private var latest: Job? = null + + /** Whether a run is under way, from before its turn to its end. */ + private var running = false + + /** Whether the run under way has started its work: an asking from then on is newer than it. */ + private var started = false + private var again = false + + fun ask() { + if (running) { + if (started) again = true + return + } + quiet?.cancel() + quiet = scope.launch { + delay(pause) + run() + } + if (latest?.isActive != true) { + latest = scope.launch { + delay(most) + run() + } + } + } + + /** What was asked for and has not started is dropped (nobody is looking any more); work under way finishes. */ + fun forget() { + quiet?.cancel() + latest?.cancel() + quiet = null + latest = null + again = false + } + + private fun run() { + if (running) return + val timers = listOf(quiet, latest) + quiet = null + latest = null + started = false + running = true + // Not a child of either timer: cancelling them below must not reach the work. + scope.launch { + try { + before() + started = true + work() + } finally { + running = false + if (again) { + again = false + ask() + } + } + } + // One of the two is the caller; it has nothing left to do. + timers.forEach { it?.cancel() } + } +} + +/** + * Whether the instance says when a reply ends: the events route's `reply` frame with `live` + * false, for a reply it had said was being written. One such frame is the proof, and from then + * on the list's running marks are cleared by the frames alone. An instance from before that + * never proves it, and the list is read again now and then instead ([runningPause]). + */ +class ReplyEnds { + private val started = LinkedHashSet() + + var said = false + private set + + fun hear(frame: ReplyFrame) { + if (frame.messageId.isBlank()) return + if (frame.live) { + started += frame.messageId + if (started.size > REMEMBERED) started.remove(started.first()) + } else if (started.remove(frame.messageId)) { + said = true + } + } + + private companion object { + const val REMEMBERED = 64 + } +} + +/** + * How long to wait before the list is read again because a row shows a reply being written and + * nothing has said it ended: 5, 10, 20, 40 seconds, then every minute ([round] counts the + * reads since a row last showed one). A bounded rate, and only while such a row is on screen. + */ +fun runningPause(round: Int): Long = (5_000L shl round.coerceIn(0, 4)).coerceAtMost(60_000L) 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 bcad7aa..b59e77e 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 @@ -117,6 +117,9 @@ import kotlinx.coroutines.flow.asStateFlow import kotlinx.coroutines.flow.update import kotlinx.coroutines.launch +/** Whether the Scheduled list starts listening to the events route now: only [inFront], and only once ([listening]). */ +fun listens(inFront: Boolean, listening: Boolean): Boolean = inFront && !listening + /** A server without the scheduling routes answers 404 (or 405): it is older, not broken. */ private fun Throwable.unsupported(): Boolean = this is ApiException && (status == 404 || status == 405) @@ -137,6 +140,19 @@ class ScheduledViewModel(app: Application) : AndroidViewModel(app) { private var live: Job? = null + /** + * Whether the list is on screen, in front. The events route is listened to only then: a read + * that comes back after the screen was left (or the phone locked) must not open it, for + * nothing would close it again while this model lives. + */ + private var front = false + + /** The screen came to the front: the list is read, and followed until [stop]. */ + fun shown() { + front = true + load() + } + fun load() { viewModelScope.launch { _state.update { it.copy(loading = true, error = null) } @@ -164,7 +180,7 @@ class ScheduledViewModel(app: Application) : AndroidViewModel(app) { * Without it the list is what the last read said, and a pull reads it again. */ private fun watch() { - if (live?.isActive == true) return + if (!listens(front, live?.isActive == true)) return live = viewModelScope.launch { // The one connection the drawer's badge listens on too (`EventsHub`). val frames = runCatching { getApplication().lembas.eventFrames() }.getOrNull() ?: return@launch @@ -183,6 +199,7 @@ class ScheduledViewModel(app: Application) : AndroidViewModel(app) { } fun stop() { + front = false live?.cancel() live = null } @@ -210,7 +227,7 @@ class ScheduledViewModel(app: Application) : AndroidViewModel(app) { fun ScheduledScreen(onBack: () -> Unit, onOpen: (String) -> Unit, onNew: () -> Unit, onModels: () -> Unit, model: ScheduledViewModel = viewModel()) { val state by model.state.collectAsStateWithLifecycle() LifecycleResumeEffect(Unit) { - model.load() + model.shown() onPauseOrDispose { model.stop() } } ScheduledContent(state, onBack = onBack, onOpen = onOpen, onNew = onNew, onModels = onModels, onPause = model::pause, onRetry = model::load) diff --git a/app/src/test/java/eu/llembas/android/SecondReviewTest.kt b/app/src/test/java/eu/llembas/android/SecondReviewTest.kt new file mode 100644 index 0000000..72b794c --- /dev/null +++ b/app/src/test/java/eu/llembas/android/SecondReviewTest.kt @@ -0,0 +1,573 @@ +package eu.llembas.android + +import eu.llembas.android.api.Chat +import eu.llembas.android.api.ChatDetail +import eu.llembas.android.api.ChatPage +import eu.llembas.android.api.Frame +import eu.llembas.android.api.LiveReply +import eu.llembas.android.api.Message +import eu.llembas.android.api.Outcome +import eu.llembas.android.api.ReplyFrame +import eu.llembas.android.api.Step +import eu.llembas.android.api.reopened +import eu.llembas.android.api.replyUnrecorded +import eu.llembas.android.api.unrecordedReplies +import eu.llembas.android.ui.chat.ChatState +import eu.llembas.android.ui.chat.KEPT_MOST +import eu.llembas.android.ui.chat.KEPT_ROWS +import eu.llembas.android.ui.chat.Reads +import eu.llembas.android.ui.chat.TranscriptChange +import eu.llembas.android.ui.chat.asksFor +import eu.llembas.android.ui.chat.capped +import eu.llembas.android.ui.chat.movesToEnd +import eu.llembas.android.ui.chat.ownScroll +import eu.llembas.android.ui.chat.personScrolls +import eu.llembas.android.ui.chat.restFollows +import eu.llembas.android.ui.chat.scrollWasPersons +import eu.llembas.android.ui.chat.transcriptChange +import eu.llembas.android.ui.chat.withNewest +import eu.llembas.android.ui.home.ChatsState +import eu.llembas.android.ui.home.ReplyEnds +import eu.llembas.android.ui.home.Soon +import eu.llembas.android.ui.home.ended +import eu.llembas.android.ui.home.readsFor +import eu.llembas.android.ui.home.runningPause +import eu.llembas.android.ui.home.withNewest +import eu.llembas.android.ui.scheduled.listens +import kotlinx.coroutines.CompletableDeferred +import kotlinx.coroutines.ExperimentalCoroutinesApi +import kotlinx.coroutines.async +import kotlinx.coroutines.awaitCancellation +import kotlinx.coroutines.cancelAndJoin +import kotlinx.coroutines.delay +import kotlinx.coroutines.flow.flowOf +import kotlinx.coroutines.flow.toList +import kotlinx.coroutines.launch +import kotlinx.coroutines.test.advanceTimeBy +import kotlinx.coroutines.test.advanceUntilIdle +import kotlinx.coroutines.test.runCurrent +import kotlinx.coroutines.test.runTest +import kotlinx.serialization.json.JsonObject +import kotlinx.serialization.json.JsonPrimitive +import org.junit.Assert.assertEquals +import org.junit.Assert.assertFalse +import org.junit.Assert.assertNull +import org.junit.Assert.assertSame +import org.junit.Assert.assertTrue +import org.junit.Test +import java.time.OffsetDateTime +import java.time.ZoneOffset + +/** + * What a second review found, each as the rule it became: the list of chats is merged by id, a + * reply nobody asked for is not followed behind a lock, a long transcript is held to a size, a + * list the person is scrolling is theirs, the list of chats is read when it is seen and no + * oftener than needed, a reply's end is marked without a read, and several pieces of one news + * are one read. + */ +@OptIn(ExperimentalCoroutinesApi::class) +class SecondReviewTest { + // --- The list of chats, read again ----------------------------------------------------------- + + private val noon = OffsetDateTime.of(2026, 1, 2, 12, 0, 0, 0, ZoneOffset.UTC) + + /** The chat [n]: the higher its number, the longer ago it changed -- the list's own order. */ + private fun row(n: Int, changed: Int = n, running: Boolean = false, pinned: Boolean = false) = + Chat(id = "c$n", title = "Chat $n", running = running, pinned = pinned, updatedAt = noon.minusMinutes(changed.toLong()).toString()) + + private fun rows(range: IntRange) = range.map { row(it) } + + @Test + fun aChatThatComesUpFromALaterPageTakesNoOtherChatWithIt() { + // Three pages loaded; a reply starts in a chat of the last one, which goes to the top. + val shown = ChatsState(chats = rows(1..90), more = false) + val page = ChatPage(chats = listOf(row(80, changed = 0, running = true)) + rows(1..49), more = true) + val read = shown.withNewest(page) + assertEquals(listOf("c80") + (1..79).map { "c$it" } + (81..90).map { "c$it" }, read.chats.map { it.id }) + assertTrue(read.chats.first().running) + // "More" still asks for what comes after the oldest chat shown, and there was none. + assertEquals("c90", read.chats.last().id) + assertFalse(read.more) + } + + @Test + fun aPinnedChatFurtherDownStaysAndTheNewestPageSaysWhatItIsNow() { + val shown = ChatsState(chats = rows(1..59) + row(60, pinned = true) + rows(61..70), more = true) + // Pinned elsewhere meanwhile: the page's own row says so. + val page = ChatPage(chats = listOf(row(3, changed = 0, pinned = true)) + rows(1..2) + rows(4..50), more = true) + val read = shown.withNewest(page) + assertEquals(70, read.chats.size) + assertEquals(70, read.chats.map { it.id }.toSet().size) + assertTrue(read.chats.first { it.id == "c60" }.pinned) + assertTrue(read.chats.first { it.id == "c3" }.pinned) + assertEquals("c3", read.chats.first().id) + assertTrue(read.more) + } + + @Test + fun aChatDeletedElsewhereGoesFromTheList() { + val shown = ChatsState(chats = rows(1..70), more = true) + // c7 is gone on the server: the page reaches one chat further down instead. + val page = ChatPage(chats = rows(1..6) + rows(8..51), more = true) + val read = shown.withNewest(page) + assertFalse(read.chats.any { it.id == "c7" }) + // What lies below the page was not looked at, and stays. + assertEquals((1..6).map { "c$it" } + (8..70).map { "c$it" }, read.chats.map { it.id }) + // A page with nothing after it is the whole list: whatever it does not name is gone. + val whole = shown.withNewest(ChatPage(chats = rows(1..3), more = false)) + assertEquals(listOf("c1", "c2", "c3"), whole.chats.map { it.id }) + assertFalse(whole.more) + // A row with no time the app can read is never taken for gone. + val undated = ChatsState(chats = rows(1..50) + Chat(id = "x", updatedAt = "yesterday"), more = true) + assertEquals("x", undated.withNewest(ChatPage(chats = rows(1..50), more = true)).chats.last().id) + } + + // --- A reply nobody asked for, and the gate --------------------------------------------------- + + private class Door { + var locked = false + val gate = InstanceGate { locked }.also { it.activityStarted() } + + fun lock() { + locked = true + gate.look() + } + + fun unlock() { + locked = false + gate.look() + } + } + + @Test + fun aReplyNobodyAskedForIsLetGoWhenThePhoneLocks() = runTest { + val door = Door() + var open = false + val following = async { + door.gate.whileOpen { + open = true + try { + awaitCancellation() + } finally { + open = false + } + } + } + runCurrent() + assertTrue(open) + door.lock() + runCurrent() + // Let go: its stream is closed, and the answer says so. + assertFalse(open) + assertNull(following.await()) + } + + @Test + fun aReplyThatEndsInFrontIsFollowedToItsEnd() = runTest { + val door = Door() + assertEquals("done", door.gate.whileOpen { "done" }) + // The app leaving the front is the gate closing as well. + door.gate.activityStopped() + var started = false + assertNull( + door.gate.whileOpen { + started = true + "done" + }, + ) + // Behind the gate nothing nobody asked for is even started. + assertFalse(started) + } + + @Test + fun thePersonsOwnReplyGoesOnBehindTheLock() = runTest { + val door = Door() + val end = CompletableDeferred() + var own = true + val following = async { door.gate.whileOpen(stays = { own }) { end.await() } } + runCurrent() + door.lock() + runCurrent() + assertTrue(following.isActive) + end.complete("done") + assertEquals("done", following.await()) + // One that became the person's while it ran (they asked, the events route was first) stays too; + // one that is not theirs goes at the next closing. + own = false + door.unlock() + val other = async { door.gate.whileOpen(stays = { own }) { awaitCancellation() } } + runCurrent() + door.lock() + runCurrent() + assertNull(other.await()) + } + + @Test + fun aFollowThatIsCancelledIsNotTakenForOneLetGo() = runTest { + val door = Door() + var after = false + val following = launch { + door.gate.whileOpen { awaitCancellation() } + after = true + } + runCurrent() + following.cancelAndJoin() + // The caller's own end: nothing of "let go, read again on the return" runs. + assertFalse(after) + } + + @Test + fun aBrokenStreamIsOpenedAgainOnlyAtItsTurn() = runTest { + val door = Door() + var opened = 0 + val frames = mutableListOf() + val following = launch { + reopened(turn = { door.gate.pass() }) { + opened++ + if (opened == 1) flowOf(Outcome.Event(Frame("tail", "{}")), Outcome.Dropped) else flowOf(Outcome.Event(Frame("close", "{}"))) + }.toList(frames) + } + runCurrent() + assertEquals(1, opened) + // The connection broke and the phone is locked: an hour later nothing has been asked. + door.lock() + advanceTimeBy(3_600_000) + assertEquals(1, opened) + door.unlock() + advanceUntilIdle() + assertEquals(2, opened) + assertEquals(listOf("tail", "close"), frames.map { it.event }) + assertTrue(following.isCompleted) + } + + // --- A transcript left open ------------------------------------------------------------------ + + private fun person(id: String) = Message(id = id, role = "user", text = "How many cakes are left?") + + 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 fun note(id: String) = Message(id = id, role = "user", machine = true, origin = "harness", text = "The baker has finished.") + + private val chat = Chat(id = "chat1") + + private fun talk(range: IntRange) = range.map { if (it % 2 == 1) person("m$it") else reply("m$it") } + + @Test + fun aLongTranscriptIsCutBackOnlyUnderAPersonAtItsEnd() { + val long = ChatState(chat = chat, messages = talk(1..KEPT_MOST + 2), more = false) + val cut = long.capped(atEnd = true) + assertEquals(KEPT_ROWS, cut.messages.size) + // The newest stay, and "older" reads the rest back. + assertEquals("m${KEPT_MOST + 2}", cut.messages.last().id) + assertEquals("m${KEPT_MOST + 2 - KEPT_ROWS + 1}", cut.messages.first().id) + assertTrue(cut.more) + // Somebody reading further up keeps every row. + assertSame(long, long.capped(atEnd = false)) + // Under the limit nothing goes, so it is not cut at every read. + val fits = ChatState(chat = chat, messages = talk(1..KEPT_MOST)) + assertSame(fits, fits.capped(atEnd = true)) + // The list keeps its rows by their ids: to it this is rows changed in place, and it stays at its end. + assertEquals(TranscriptChange.None, transcriptChange(cut.messages, cut.messages)) + assertEquals(TranscriptChange.Changed, transcriptChange(long.messages, cut.messages)) + } + + @Test + fun aRewindElsewhereLeavesNoRowTheServerNoLongerHas() { + // 120 rows shown, of which the last 50 were the newest page. From another client the + // chat is rewound to row 60 and answered again: 61..120 are gone, n1 and n2 are new. + val shown = ChatState(chat = chat, messages = talk(1..120), more = true) + val after = talk(13..60) + person("n1") + reply("n2") + val read = shown.withNewest(ChatDetail(chat = chat, messages = after, more = true)) + // The page joins at m13: what is above it is older than anything a rewind that left m13 could touch. + assertEquals(talk(1..12).map { it.id } + after.map { it.id }, read.messages.map { it.id }) + // Rewound to above everything the page holds: the page joins nothing here and is the transcript. + val far = listOf(person("x1"), reply("x2")) + assertEquals(far, shown.withNewest(ChatDetail(chat = chat, messages = far, more = false)).messages) + } + + // --- Whose scroll it is ------------------------------------------------------------------------ + + @Test + fun aListThePersonIsScrollingIsNotMovedWhenRowsArrive() { + // A wheel, a key or a screen reader moving the list: no finger, so the following has not + // ended yet -- and rows that arrive now must not cancel that scroll. + val wheel = personScrolls(inProgress = true, ownScrolls = 0) + assertTrue(wheel) + assertFalse(movesToEnd(TranscriptChange.Appended, following = true, personScrolling = wheel)) + assertFalse(movesToEnd(TranscriptChange.Changed, following = true, personScrolling = wheel)) + // A message the person sends, and a chat opened, still show. + assertTrue(movesToEnd(TranscriptChange.Sent, following = false, personScrolling = wheel)) + assertTrue(movesToEnd(TranscriptChange.Opened, following = false, personScrolling = wheel)) + // The app's own scroll to the end, still under way when more arrives, is not the person's. + assertFalse(personScrolls(inProgress = true, ownScrolls = 1)) + assertTrue(movesToEnd(TranscriptChange.Appended, following = true, personScrolling = false)) + // A list at rest is nobody's scroll. + assertFalse(personScrolls(inProgress = false, ownScrolls = 0)) + } + + @Test + fun aScrollTheAppDidNotStartIsThePersonsWhereItRests() { + // Not a finger and not (by where it rests) a move back -- but nothing of the app's started it. + assertTrue(scrollWasPersons(touched = false, wentBack = false, startedByApp = false)) + assertFalse( + restFollows(following = true, byPerson = scrollWasPersons(touched = false, wentBack = false, startedByApp = false), distance = 900, slack = 48), + ) + // The app's own, left short of the end by a line that arrived: nobody left. + assertFalse(scrollWasPersons(touched = false, wentBack = false, startedByApp = true)) + assertTrue(restFollows(following = true, byPerson = false, distance = 900, slack = 48)) + // A finger or a move back on a scroll the app started is still the person's. + assertTrue(scrollWasPersons(touched = true, wentBack = false, startedByApp = true)) + assertTrue(scrollWasPersons(touched = false, wentBack = true, startedByApp = true)) + } + + @Test + fun theAppsOwnScrollsAreCountedWhileTheyRun() = runTest { + val own = intArrayOf(0) + val first = launch { ownScroll(own) { awaitCancellation() } } + val second = launch { ownScroll(own) { awaitCancellation() } } + runCurrent() + assertEquals(2, own[0]) + // One overtaken by the other: its end does not unmark the one still running. + first.cancelAndJoin() + assertEquals(1, own[0]) + assertFalse(personScrolls(inProgress = true, ownScrolls = own[0])) + second.cancelAndJoin() + assertEquals(0, own[0]) + } + + // --- The drawer's list and the replies' frames ----------------------------------------------- + + private fun said(chatId: String, message: String = "r1", live: Boolean = true) = ReplyFrame(chatId = chatId, messageId = message, live = live) + + @Test + fun theListIsReadOnlyWhenItIsSeenAndOnlyForWhatItDoesNotShow() { + val list = ChatsState(chats = listOf(row(1, running = true), row(2)), more = false) + // The drawer is closed: it reads the list when it opens, and nothing before. + assertFalse(list.readsFor(said("c2"), shown = false)) + // Open: a reply started in a chat not shown as running, or in one not listed yet. + assertTrue(list.readsFor(said("c2"), shown = true)) + assertTrue(list.readsFor(said("c9"), shown = true)) + // The route says every reply being written again at each reconnection: that row runs already. + assertFalse(list.readsFor(said("c1"), shown = true)) + // An end in a listed chat is marked on its row; one in a chat not listed is read. + assertFalse(list.readsFor(said("c1", live = false), shown = true)) + assertTrue(list.readsFor(said("c9", live = false), shown = true)) + // A list not read yet is left to its first read. + assertFalse(ChatsState().readsFor(said("c1"), shown = true)) + } + + @Test + fun aReplysEndClearsTheRunningMarkAndShowsSomethingNewWithoutARead() { + val list = ChatsState(chats = listOf(row(1, running = true), row(2, running = true), row(3)), more = false) + val ended = list.ended(said("c1", live = false), open = "c2") + assertFalse(ended.chats[0].running) + assertTrue(ended.chats[0].unread) + // The others are as they were. + assertEquals(list.chats.drop(1), ended.chats.drop(1)) + // The chat on screen: the person watched it end, so nothing is new. + val watched = list.ended(said("c2", live = false), open = "c2") + assertFalse(watched.chats[1].running) + assertFalse(watched.chats[1].unread) + // A start is not an end, and a chat not listed changes nothing. + assertSame(list, list.ended(said("c1"), open = null)) + assertSame(list, list.ended(said("c9", live = false), open = null)) + } + + @Test + fun anInstanceProvesItSaysTheEndsWithOneEndOfAReplyItSaidStarted() { + val ends = ReplyEnds() + // "Already ended" at the start, which instances before the end frame say too, proves nothing. + ends.hear(said("c1", "r0", live = false)) + assertFalse(ends.said) + ends.hear(said("c1", "r1")) + assertFalse(ends.said) + ends.hear(said("c1", "r1", live = false)) + assertTrue(ends.said) + } + + @Test + fun aRunningRowIsReadAgainAtABoundedRate() { + assertEquals(listOf(5_000L, 10_000L, 20_000L, 40_000L, 60_000L, 60_000L), (0..5).map { runningPause(it) }) + assertEquals(60_000L, runningPause(1_000)) + assertEquals(5_000L, runningPause(-1)) + } + + @Test + fun framesThatNeverFallQuietStillGetTheirRead() = runTest { + var reads = 0 + val soon = Soon(backgroundScope, pause = 1_500, most = 6_000) { reads++ } + // A team: a reply starts every second, for nineteen seconds. + repeat(19) { + soon.ask() + advanceTimeBy(1_000) + } + runCurrent() + // At the latest six seconds after the first asking, and again six after the next: never "not until it is quiet". + assertEquals(2, reads) + // And once more when it has fallen quiet. + advanceTimeBy(1_600) + runCurrent() + assertEquals(3, reads) + // Nothing asked, nothing read. + advanceTimeBy(60_000) + assertEquals(3, reads) + } + + @Test + fun askingsCloseTogetherAreOneRead() = runTest { + var reads = 0 + val soon = Soon(backgroundScope, pause = 1_500, most = 6_000) { reads++ } + repeat(5) { + soon.ask() + advanceTimeBy(200) + } + assertEquals(0, reads) + advanceTimeBy(1_500) + runCurrent() + assertEquals(1, reads) + } + + @Test + fun aReadUnderWayIsNotCutShortByTheNextFrame() = runTest { + var began = 0 + var finished = 0 + val soon = Soon(backgroundScope, pause = 1_500, most = 6_000) { + began++ + delay(5_000) + finished++ + } + soon.ask() + advanceTimeBy(1_600) + assertEquals(1, began) + // Frames while the list is being read: that read finishes, and one more follows it. + soon.ask() + advanceTimeBy(1_000) + soon.ask() + advanceTimeBy(4_100) + assertEquals(1, finished) + advanceTimeBy(1_600) + assertEquals(2, began) + advanceTimeBy(5_100) + assertEquals(2, finished) + advanceTimeBy(60_000) + assertEquals(2, began) + } + + @Test + fun whatIsAskedWhileAReadWaitsForItsTurnIsThatRead() = runTest { + val turn = CompletableDeferred() + var reads = 0 + val soon = Soon(backgroundScope, pause = 1_500, most = 6_000, before = { turn.await() }) { reads++ } + soon.ask() + advanceTimeBy(1_600) + // Waiting at the gate (the phone is locked): more is heard meanwhile. + soon.ask() + soon.ask() + turn.complete(Unit) + advanceTimeBy(60_000) + // One read on the return, not one per frame and not two. + assertEquals(1, reads) + // The drawer closed before the pause was over: nothing is read for it. + soon.ask() + soon.forget() + advanceTimeBy(60_000) + assertEquals(1, reads) + } + + // --- A reply's end, and one news read once ----------------------------------------------------- + + @Test + fun theEndOfAReplyThisScreenFollowsOrHasDrawnAsksForNoRead() { + val following = ChatState(chat = chat, messages = listOf(person("q1"), reply("a1", complete = false)), live = LiveReply("a1")) + // The stream's own `done` brings the end: the events route's word for it costs nothing. + assertFalse(following.asksFor(said("chat1", "a1", live = false))) + val drawn = ChatState(chat = chat, messages = listOf(person("q1"), reply("a1"))) + assertFalse(drawn.asksFor(said("chat1", "a1", live = false))) + // The end of a reply this screen never heard of (it was shorter than the news of it) is read once. + assertTrue(drawn.asksFor(said("chat1", "a2", live = false))) + } + + @Test + fun aBurstOfNewsIsOneRead() = runTest { + val reads = Reads() + var made = 0 + val answer = CompletableDeferred() + // Five frames before anything was read. + val asked = List(5) { reads.mark() }.map { mark -> + launch { + reads.since(mark) { + made++ + answer.await() + true + } + } + } + runCurrent() + assertEquals(1, made) + // News that arrives while that read is under way is newer than it. + val later = reads.mark() + answer.complete(Unit) + advanceUntilIdle() + assertTrue(asked.all { it.isCompleted }) + assertEquals(1, made) + assertTrue(reads.since(later) { true }) + // And what was learned before a read that has answered is not read again. + assertFalse(reads.since(0) { true }) + } + + @Test + fun aReadThatFailedStandsForNobodyAndOneNoLongerWantedIsNotMade() = runTest { + val reads = Reads() + val first = reads.mark() + val second = reads.mark() + assertTrue(reads.since(first) { false }) + // The first one's read got no answer: the second still makes its own. + var made = false + assertTrue( + reads.since(second) { + made = true + true + }, + ) + assertTrue(made) + // Asked again when its turn comes: no longer news, no read. + assertFalse(reads.since(reads.mark(), wanted = { false }) { error("not made") }) + } + + // --- The line that says a reply was not recorded ----------------------------------------------- + + @Test + fun aReplyThatHoldsOnlyAPlanWasRecorded() { + val empty = Message(id = "a1", role = "assistant") + assertTrue(replyUnrecorded(empty, note("n1"))) + val plan = empty.copy(plan = JsonObject(mapOf("title" to JsonPrimitive("Bake more")))) + assertFalse(replyUnrecorded(plan, note("n1"))) + assertEquals(emptySet(), unrecordedReplies(listOf(note("n1"), plan))) + } + + @Test + fun theReplyBeingWrittenIsNeverNotRecordedWhateverItsRowSays() { + // A row that says nothing of `complete` reads as complete; the screen knows better. + val row = Message(id = "a1", role = "assistant") + assertFalse(replyUnrecorded(row, note("n1"), live = "a1")) + assertEquals(emptySet(), unrecordedReplies(listOf(note("n1"), row), live = "a1")) + // Once it has ended, or for another row, the rule is as it was. + assertEquals(setOf("a1"), unrecordedReplies(listOf(note("n1"), row), live = "a9")) + assertEquals(setOf("a1"), unrecordedReplies(listOf(note("n1"), row))) + } + + // --- The Scheduled list ------------------------------------------------------------------------ + + @Test + fun theScheduledListListensOnlyWhileItIsInFront() { + assertTrue(listens(inFront = true, listening = false)) + // A read that comes back after the screen was left opens nothing. + assertFalse(listens(inFront = false, listening = false)) + assertFalse(listens(inFront = true, listening = true)) + } +}