An open chat follows a reply it did not start; the chat keeps its place
CI / check (push) Canceled after 0s

The person's events route says every reply that starts (the reply frame).
For the chat that is open, one that is neither followed already nor drawn
as finished is read and followed as any reply is, once nothing of this
screen's own is being written; a return to the front reads the chat once.
Nothing is asked behind the lock or out of the front. The drawer reads its
newest page again shortly after a frame. The frame is a moment, so the
shared connection does not repeat it to a watcher that joins later.

A turn the linked computer's harness started is a quiet note, and an empty
finished reply after a turn nobody typed, in an agent chat, is the server's
one line.

The chat's position: reading the chat again keeps the older pages a person
loaded; only the person's own scroll can end the following; a reply's foot
is as tall while it is written as once it has finished.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
This commit is contained in:
HomerandClaude Fable 5.2 committed 2026-11-23 12:05:58 +00:00
1 parent 6e08795a5c
commit c4813831f5
22 files changed
+620 -37

No files matched your search

+36
View File
@@ -3,6 +3,42 @@
What changed in each release of LLeMbas for Android. Versions follow SemVer; until 1.0.0 the app
is in alpha and releases come off `main`.
## Unreleased
What is said here of replies that start by themselves needs an instance newer than LLeMbas
2.0.0-beta.17. On an older one the app behaves as before.
### Added
- **An open chat shows a reply it did not ask for, as it is written.** When a subagent finishes
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.
### Changed
- **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
this was not recorded." in one line. Older instances left a few of these as blank rows.
### Fixed
- **The chat keeps its place.** At the end of the chat you stay at the end; anywhere else, what
you are reading does not move.
- Reading the chat again (after an edit, a queued message, a reply that woke the chat) no
longer takes away the earlier messages you had loaded, and with them the row you were
reading.
- 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.
- 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.
## [1.0.0-beta.13] — 2026-11-19
For Files, generated media and MCP servers as described here the instance must be newer than
@@ -136,11 +136,44 @@ enum class Drawn {
* instruction, the line that opens a report's conversation) is not something the person said,
* so it is never their bubble: a quiet note -- and in a report's conversation ([reportChat]) the
* [first] such line, which only tells the model what the conversation continues, is left out,
* since the report itself is one tap back.
* since the report itself is one tap back. A turn the linked computer's harness started
* (`origin` `harness`: a job's end, a team member's report) is such a line whatever else the
* row says: nobody typed it, here or in a terminal.
*/
fun drawn(message: Message, first: Boolean, reportChat: Boolean): Drawn = when {
!message.isUser -> Drawn.Reply
!message.machine -> Drawn.Person
!message.byMachine -> Drawn.Person
reportChat && first -> Drawn.Hidden
else -> Drawn.Note
}
/** The `origin` of a turn the linked computer's harness started by itself. */
const val ORIGIN_HARNESS = "harness"
/** 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
/**
* Whether [reply] is a finished reply that holds nothing at all and answers a turn nobody typed
* ([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.
*/
fun replyUnrecorded(reply: Message, asked: Message?): Boolean = !reply.isUser &&
reply.complete &&
!reply.stopped &&
reply.error.isNullOrBlank() &&
reply.end == null &&
reply.text.isNullOrBlank() &&
reply.steps.isEmpty() &&
reply.attachments.isEmpty() &&
asked != null &&
asked.isUser &&
asked.byMachine
/** The replies of [messages] that are [replyUnrecorded], by id. */
fun unrecordedReplies(messages: List<Message>): Set<String> = messages.indices
.filter { replyUnrecorded(messages[it], messages.getOrNull(it - 1)) }
.mapTo(HashSet()) { messages[it].id }
@@ -16,9 +16,13 @@ import java.util.concurrent.ConcurrentHashMap
* the drawer's Reports badge, the Scheduled list -- instead of one each. It is open while
* somebody watches and closed when nobody does.
*
* Every frame of the route is a whole state (`schedules`, `reports`), which the server sends at
* A frame of the route is a whole state (`schedules`, `reports`), which the server sends at
* once to a new connection. A watcher that joins a connection already open missed that, so it
* is first told the last frame of each kind this connection carried.
* is first told the last frame of each such kind this connection carried.
*
* `reply` is the exception ([MOMENTS]): something that happened, not how things are. It is
* passed on to whoever is watching and never said again -- a watcher that joins later would
* take a reply long finished for one that has just started.
*
* A route that refuses (an older server) ends quietly: its watchers hear nothing, as they did
* when each asked for itself.
@@ -36,11 +40,16 @@ class EventsHub(private val scope: CoroutineScope) {
val shared = open()
// A connection opened anew is told everything again: what the last one said is stale.
.onStart { latest.clear() }
.onEach { latest[it.event] = it }
.onEach { if (it.event !in MOMENTS) latest[it.event] = it }
.catch { }
.shareIn(scope, SharingStarted.WhileSubscribed(), replay = 0)
Line(key, shared, latest).also { line = it }
}
return now.frames.onSubscription { now.latest.values.toList().forEach { emit(it) } }
}
companion object {
/** The frames that say something happened, rather than how things are: never told again to a late watcher. */
val MOMENTS = setOf("reply")
}
}
@@ -453,6 +453,15 @@ data class ChatPage(val chats: List<Chat> = emptyList(), val more: Boolean = fal
@Serializable
data class ChatDetail(val chat: Chat, val messages: List<Message> = emptyList(), val more: Boolean = false, val live: String? = null)
/**
* `GET /events`, frame `reply`: a reply started in the chat [chatId] -- whoever started it, this
* app's own too. [messageId] is the reply's row; [live] false says it had already ended when the
* frame was sent. An event, not a state: it is said once (and, on a connection just opened, for
* every reply being written then).
*/
@Serializable
data class ReplyFrame(@SerialName("chat_id") val chatId: String = "", @SerialName("message_id") val messageId: String = "", val live: Boolean = false)
@Serializable
data class MessagePage(val messages: List<Message> = emptyList(), val more: Boolean = false)
@@ -97,7 +97,7 @@ import eu.llembas.android.ui.ModelAvatar
import eu.llembas.android.ui.ProgressStatus
import eu.llembas.android.ui.chat.PhoneCard
import eu.llembas.android.ui.chat.Steps
import eu.llembas.android.ui.chat.followsAt
import eu.llembas.android.ui.chat.restFollows
import eu.llembas.android.ui.chat.yielding
import eu.llembas.android.ui.progressLineOf
import eu.llembas.android.ui.theme.LocalPalette
@@ -227,13 +227,26 @@ fun ColumnScope.AssistSheetContent(
// come to rest says whether it is taken up again, and a question asked always shows.
var following by remember { mutableStateOf(true) }
val slack = with(LocalDensity.current) { 48.dp.roundToPx() }
val touched = remember { booleanArrayOf(false) }
LaunchedEffect(scroll) {
scroll.interactionSource.interactions.collect { if (it is DragInteraction.Start) following = false }
scroll.interactionSource.interactions.collect {
if (it is DragInteraction.Start) {
touched[0] = true
following = false
}
}
}
LaunchedEffect(scroll) {
var moving = false
var from = scroll.value
snapshotFlow { scroll.isScrollInProgress }.collect { now ->
if (moving && !now) following = followsAt(scroll.maxValue - scroll.value, slack)
if (now && !moving) from = scroll.value
if (moving && !now) {
// Only the person's own scroll ends the following (`restFollows`), not one of ours
// that an arriving line left short of the end.
following = restFollows(following, touched[0] || scroll.value < from, scroll.maxValue - scroll.value, slack)
touched[0] = false
}
moving = now
}
}
@@ -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.unrecordedReplies
import eu.llembas.android.ui.ModelAvatar
import eu.llembas.android.ui.ProgressStatus
import eu.llembas.android.ui.files.TransferHost
@@ -155,6 +156,12 @@ fun ChatScreen(
LaunchedEffect(state.chat?.id) {
if (state.chat?.id != null && !isAgent) lifecycle.repeatOnLifecycle(Lifecycle.State.STARTED) { model.watchMedia() }
}
// Replies nobody asked for from this screen (a subagent that woke the main agent, a schedule,
// a turn the linked computer started): heard on the person's events route while the screen is
// in front, and caught up with once on every return to it.
LaunchedEffect(state.chat?.id) {
if (state.chat?.id != null) lifecycle.repeatOnLifecycle(Lifecycle.State.STARTED) { model.watchReplies() }
}
LaunchedEffect(state.error, state.notice) {
(state.error ?: state.notice)?.let {
snackbar.showSnackbar(it)
@@ -279,6 +286,8 @@ fun ChatContent(
val live = state.live
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() }
// 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
@@ -286,13 +295,32 @@ fun ChatContent(
var following by rememberSaveable { mutableStateOf(true) }
var drawnBefore by rememberSaveable { mutableStateOf(false) }
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) }
LaunchedEffect(list) {
list.interactionSource.interactions.collect { if (it is DragInteraction.Start) following = false }
list.interactionSource.interactions.collect {
if (it is DragInteraction.Start) {
touched[0] = true
following = false
}
}
}
LaunchedEffect(list) {
var moving = false
var fromIndex = list.firstVisibleItemIndex
var fromOffset = list.firstVisibleItemScrollOffset
snapshotFlow { list.isScrollInProgress }.collect { now ->
if (moving && !now) following = followsAt(list.distanceToEnd(), slack)
if (now && !moving) {
fromIndex = list.firstVisibleItemIndex
fromOffset = list.firstVisibleItemScrollOffset
}
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)
following = restFollows(following, byPerson, list.distanceToEnd(), slack)
touched[0] = false
}
moving = now
}
}
@@ -453,6 +481,8 @@ fun ChatContent(
item { TextButton(onClick = actions::older) { Text(stringResource(R.string.older)) } }
}
items(rows, key = { it.id }) { message ->
// One key for a reply while it is written and once it is stored: the row
// is the same row at `done`, so the list has nothing to put elsewhere.
// The first row is the chat's first message only once nothing older is left to load.
val first = !state.more && message.id == rows.firstOrNull()?.id
when (drawn(message, first, reportChat = report != null || chat?.report != null)) {
@@ -465,7 +495,11 @@ fun ChatContent(
// 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`.
Drawn.Reply -> {
// A finished reply with nothing in it, after a turn nobody typed: one
// quiet line in its place, not a blank row with buttons.
Drawn.Reply -> if (message.id in unrecorded) {
MachineNote(stringResource(R.string.reply_unrecorded))
} else {
val writing = live?.takeIf { it.messageId == message.id && it.finished == null }
AssistantMessage(
message,
@@ -33,6 +33,7 @@ import eu.llembas.android.api.Mention
import eu.llembas.android.api.Message
import eu.llembas.android.api.MessagePage
import eu.llembas.android.api.ModelInfo
import eu.llembas.android.api.ReplyFrame
import eu.llembas.android.api.StartModel
import eu.llembas.android.api.StreamClient
import eu.llembas.android.api.SubagentTree
@@ -47,11 +48,15 @@ import eu.llembas.android.ui.files.noSuchRoute
import kotlinx.coroutines.CancellationException
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.Job
import kotlinx.coroutines.coroutineScope
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.coroutines.withContext
import kotlinx.serialization.json.JsonObject
import kotlinx.serialization.json.JsonPrimitive
@@ -233,6 +238,34 @@ fun ChatState.withOlder(before: String, page: MessagePage): ChatState {
return copy(messages = page.messages.distinctBy { it.id }.filterNot { it.id in have } + messages, more = page.more)
}
/**
* The transcript read again ([read]: the chat and its newest page), put where the newest page
* was. The older pages a person loaded stay above it -- taking them away would take the row
* they are reading from under them -- as long as the page still joins them: its first row is
* one this screen holds, and the server says there is more above it. A page that joins nothing
* here (the chat was rewound past it, or compacted) is the whole transcript, as before. No row
* is there twice: the list's rows are keyed by id.
*/
fun ChatState.withNewest(read: ChatDetail): ChatState {
val first = read.messages.firstOrNull()?.id
val at = if (first == null) -1 else messages.indexOfFirst { it.id == first }
if (at <= 0 || !read.more) return copy(chat = read.chat, messages = read.messages, more = read.more)
val newest = read.messages.mapTo(HashSet()) { it.id }
return copy(chat = read.chat, messages = messages.subList(0, at).filterNot { it.id in newest } + read.messages)
}
/**
* 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
* finished. The server says every reply that starts, this app's own too, so most frames for an
* open chat are not news.
*/
fun ChatState.asksFor(said: ReplyFrame): Boolean {
if (chat == null || chat.id != said.chatId || said.messageId.isBlank()) return false
if (live?.messageId == said.messageId) return false
return messages.none { it.id == said.messageId && !it.isUser && it.complete }
}
/**
* The stream of the reply [messageId] closed without a `done`. What was written stays in view:
* the transcript as the server has it now ([reread]), or -- where that could not be read -- the
@@ -242,7 +275,7 @@ fun ChatState.withOlder(before: String, page: MessagePage): ChatState {
fun ChatState.closedUnfinished(messageId: String, reread: ChatDetail?): ChatState {
val was = live?.takeIf { it.messageId == messageId }
if (live != null && was == null) return this
if (reread != null) return copy(chat = reread.chat, messages = reread.messages, more = reread.more, live = null)
if (reread != null) return withNewest(reread).copy(live = null)
if (was == null || was.shown.isEmpty()) return copy(live = null)
val kept = was.shown.map { it.copy(open = false) }
return copy(
@@ -424,6 +457,9 @@ class ChatViewModel(app: Application) :
/** Follow a reply to its end, then whatever the queue started after it. */
private fun follow(messageId: String) {
val chat = _state.value.chat ?: return
// 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)) }
@@ -493,10 +529,15 @@ class ChatViewModel(app: Application) :
}
}
private suspend fun refresh() {
/**
* 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 { it.copy(chat = d.chat, messages = d.messages, more = d.more) }
_state.update { if (whole) it.copy(chat = d.chat, messages = d.messages, more = d.more) else it.withNewest(d) }
}
}
@@ -722,27 +763,99 @@ class ChatViewModel(app: Application) :
* a reply of its own nothing is touched: the wake waits in the queue, and the stream's `next`
* brings it.
*/
private suspend fun rereadAndFollow() {
private suspend fun rereadAndFollow(rounds: Int = 2) {
val chat = _state.value.chat ?: return
repeat(2) { round ->
if (_state.value.live != null) return
val read = try {
api().chat(chat.id)
} catch (e: CancellationException) {
throw e
} catch (_: Exception) {
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
val read = try {
api().chat(chat.id)
} catch (e: CancellationException) {
throw e
} catch (_: Exception) {
return
}
if (_state.value.live != null) return
_state.update { it.withNewest(read) }
read.live?.let {
follow(it)
return
}
if (round < rounds - 1) delay(WAKE_PAUSE_MS)
}
if (_state.value.live != null) return
_state.update { it.copy(chat = read.chat, messages = read.messages, more = read.more) }
read.live?.let {
follow(it)
return
}
if (round == 0) delay(WAKE_PAUSE_MS)
}
}
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. */
private var watchedReplies = false
/** The replies the events route said and that are waiting their turn, so each is taken up once. */
private val heard = mutableSetOf<String>()
/**
* Learn of replies nobody asked for from this screen -- a subagent that finished and woke the
* main agent, a schedule's result, a helper's wake, a turn the linked computer started --
* while the chat is in front: the person's events route says each reply as it starts
* (`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
* 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<Application>().lembas
if (watchedReplies) {
app.gate.pass()
rereadAndFollow(rounds = 1)
}
watchedReplies = true
val frames = runCatching { app.eventFrames() }.getOrNull() ?: return
try {
coroutineScope {
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
// Not in the collector: the one connection is shared, and a watcher that
// waits holds the others' frames back.
launch {
try {
takeUp(said)
} finally {
heard -= said.messageId
}
}
}
}
} catch (e: CancellationException) {
throw e
} catch (_: Exception) {
// An older instance, or the route refused: the chat is read when it is opened, as before.
}
}
/**
* 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.
*/
private suspend fun takeUp(said: ReplyFrame) {
getApplication<Application>().lembas.gate.pass()
_state.first { !it.running }
if (!_state.value.asksFor(said)) return
rereadAndFollow(rounds = 1)
}
/**
* "Open in Files" for a generated file: the instance is asked where the file is now, by its
* id, and [open] gets that directory. One in the trash, or gone, is said; an instance that
@@ -825,7 +938,7 @@ class ChatViewModel(app: Application) :
_state.update { it.copy(compacting = true) }
try {
api().compact(chat.id)
refresh()
refresh(whole = true)
loadActivity()
} catch (e: Exception) {
fail(e)
@@ -75,6 +75,25 @@ fun movesToEnd(change: TranscriptChange, following: Boolean): Boolean = when (ch
*/
fun followsAt(distance: Int, slack: Int): Boolean = distance <= slack
/**
* Whether the view follows once a scroll has come to rest. Only a scroll the person made
* ([byPerson]: a finger on the list, or the list gone back towards its start, which this
* app's own scroll to the end never does) can end the following, by where it rests. Any other scroll is this
* app's own keeping to the end; a line, a card or a picture that arrived before it settled
* leaves it short of the end without anybody having left, and reading that as "scrolled away"
* is what switches the following off under a person who never moved. Such a scroll can only
* take the following up (it rested at the end), never end it.
*/
fun restFollows(following: Boolean, byPerson: Boolean, distance: Int, slack: Int): Boolean = if (byPerson) {
followsAt(distance, slack)
} else {
following ||
followsAt(distance, slack)
}
/** Whether a list that stood at row [fromIndex], [fromOffset] pixels into it, has gone back towards its start. */
fun wentBack(fromIndex: Int, fromOffset: Int, toIndex: Int, toOffset: Int): Boolean = toIndex < fromIndex || (toIndex == fromIndex && toOffset < fromOffset)
/**
* The row that keeps its place when an older page arrives while the list stands at its very
* top: the first row there was before, by its place in [after]. Null when it is gone.
@@ -126,6 +126,14 @@ fun GeneratedPicture(media: GeneratedMedia, modifier: Modifier = Modifier) {
}
}
/**
* The shape a picture's place is given before its bytes are there: width over height, from the
* size the server said, kept between a quarter and four. A size the server did not say is a
* square. The place is that shape from its first draw to its last, so the picture arriving (or
* not arriving) moves nothing in the transcript.
*/
internal fun pictureRatio(width: Int, height: Int): Float = if (width > 0 && height > 0) (width.toFloat() / height).coerceIn(0.25f, 4f) else 1f
@Composable
private fun Picture(key: String, width: Int, height: Int, modifier: Modifier, fetch: suspend (ApiClient) -> ByteArray) {
val palette = LocalPalette.current
@@ -140,14 +148,14 @@ private fun Picture(key: String, width: Int, height: Int, modifier: Modifier, fe
gone = Pictures.isGone(key)
}
}
val ratio = if (width > 0 && height > 0) width.toFloat() / height else 1f
val ratio = pictureRatio(width, height)
val shape = RoundedCornerShape(16.dp)
val described = stringResource(R.string.image_generated)
Box(
modifier
.widthIn(max = 480.dp)
.fillMaxWidth()
.aspectRatio(ratio.coerceIn(0.25f, 4f))
.aspectRatio(ratio)
.clip(shape)
.background(palette.surfaceRaised)
.border(1.dp, palette.border, shape)
@@ -112,6 +112,10 @@ private val Bubble = RoundedCornerShape(topStart = 20.dp, topEnd = 6.dp, bottomS
private val Block = RoundedCornerShape(12.dp)
private val Pill = RoundedCornerShape(50)
/** A reply's foot: the gap above it, and the height of its row of buttons (an icon button's 48 dp). */
private val FootTop = 2.dp
private val FootHeight = 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.
@@ -253,7 +257,10 @@ fun AssistantMessage(
}
}
if (writing) {
Writing(Modifier.padding(top = if (steps.isEmpty()) 0.dp else 8.dp), withLine = steps.isEmpty())
// Once there is something written, the pulse stands in the finished reply's foot --
// the same top and the same height as its row of buttons -- so the reply ending
// does not change the row's height under a person at the end of it.
if (steps.isEmpty()) Writing(withLine = true) else Writing(Modifier.padding(top = FootTop), minHeight = FootHeight)
} else {
// How a reply that did not finish ended (display.md §4): the progress text alone --
// "Stopped: by you", "Failed: …" -- staying at the end of the reply; an error in
@@ -267,7 +274,7 @@ fun AssistantMessage(
)
}
// The actions and the foot share one row: the icons keep their 48 dp, the foot gives.
Row(verticalAlignment = Alignment.CenterVertically, modifier = Modifier.padding(top = 2.dp)) {
Row(verticalAlignment = Alignment.CenterVertically, modifier = Modifier.padding(top = FootTop)) {
if (words.isNotBlank()) {
IconButton(onClick = { copy(words) }) {
Icon(
@@ -354,13 +361,13 @@ internal fun footLine(message: Message, models: List<ModelInfo> = emptyList()):
/** Three dots that breathe, and (before the first word) the loading line beside them. */
@Composable
fun Writing(modifier: Modifier = Modifier, withLine: Boolean = false) {
fun Writing(modifier: Modifier = Modifier, withLine: Boolean = false, minHeight: Dp = 32.dp) {
val palette = LocalPalette.current
// Still in a preview or a screenshot, where an animation that never ends never lets the
// picture be taken.
val still = LocalInspectionMode.current
val pulse = rememberInfiniteTransition(label = "writing")
Row(modifier.heightIn(min = 32.dp), verticalAlignment = Alignment.CenterVertically) {
Row(modifier.heightIn(min = minHeight), verticalAlignment = Alignment.CenterVertically) {
repeat(3) { i ->
val alpha = if (still) {
listOf(1f, 0.6f, 0.3f)[i]
@@ -75,6 +75,7 @@ import androidx.lifecycle.viewModelScope
import eu.llembas.android.R
import eu.llembas.android.api.ApiException
import eu.llembas.android.api.Chat
import eu.llembas.android.api.ChatPage
import eu.llembas.android.api.Doorstep
import eu.llembas.android.api.Folder
import eu.llembas.android.api.LembasJson
@@ -124,6 +125,20 @@ fun ChatsState.reported(data: String): ChatsState {
return copy(unreadReports = frame.unread.coerceAtLeast(0), reports = true)
}
/**
* 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.
*/
fun ChatsState.withNewest(page: ChatPage): ChatsState {
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)
}
/** The drawer's list: every chat of the instance in use, both kinds, newest first. */
class ChatsViewModel(app: Application) : AndroidViewModel(app) {
private val _state = MutableStateFlow(ChatsState())
@@ -197,6 +212,10 @@ 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()
}
} catch (e: CancellationException) {
throw e
@@ -205,6 +224,26 @@ class ChatsViewModel(app: Application) : AndroidViewModel(app) {
}
}
private var listing: Job? = null
/**
* 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.
*/
private fun listSoon() {
listing?.cancel()
listing = viewModelScope.launch {
delay(LIST_PAUSE_MS)
val app = getApplication<Application>().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) }
}
}
/** How many `reports` frames have come: a list read that began before the last one is older than it. */
private var reportsTold = 0
@@ -314,6 +353,9 @@ class ChatsViewModel(app: Application) : AndroidViewModel(app) {
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
/** Where the drawer can go, besides a chat. */
interface DrawerActions {
fun newChat() {}
+1
View File
@@ -51,6 +51,7 @@
<string name="continue_reply">Pokračovat</string>
<string name="older">Starší zprávy</string>
<string name="queued">Čeká na odeslání</string>
<string name="reply_unrecorded">Odpověď na toto nebyla zaznamenána.</string>
<string name="thinking">Přemýšlí</string>
<string name="thought">Přemýšlel</string>
<string name="output_cut">Výstup je zde zkrácen. Celý ho najdete na webové stránce.</string>
+1
View File
@@ -51,6 +51,7 @@
<string name="continue_reply">Fortsetzen</string>
<string name="older">Frühere Nachrichten</string>
<string name="queued">Wartet auf das Senden</string>
<string name="reply_unrecorded">Die Antwort darauf wurde nicht aufgezeichnet.</string>
<string name="thinking">Denkt nach</string>
<string name="thought">Nachgedacht</string>
<string name="output_cut">Die Ausgabe ist hier verkürzt. Vollständig finden Sie sie auf der Webseite.</string>
+1
View File
@@ -51,6 +51,7 @@
<string name="continue_reply">Continuar</string>
<string name="older">Mensajes anteriores</string>
<string name="queued">Esperando para enviarse</string>
<string name="reply_unrecorded">La respuesta a esto no se registró.</string>
<string name="thinking">Pensando</string>
<string name="thought">Pensamiento</string>
<string name="output_cut">La salida está acortada aquí. La tiene completa en la página web.</string>
+1
View File
@@ -51,6 +51,7 @@
<string name="continue_reply">Continuer</string>
<string name="older">Messages précédents</string>
<string name="queued">En attente d\'envoi</string>
<string name="reply_unrecorded">La réponse à ceci n’a pas été enregistrée.</string>
<string name="thinking">Réflexion</string>
<string name="thought">Réflexion</string>
<string name="output_cut">La sortie est raccourcie ici. Vous la trouverez en entier sur la page web.</string>
+1
View File
@@ -51,6 +51,7 @@
<string name="continue_reply">Folytatás</string>
<string name="older">Korábbi üzenetek</string>
<string name="queued">Küldésre vár</string>
<string name="reply_unrecorded">Az erre adott válasz nem lett rögzítve.</string>
<string name="thinking">Gondolkodás</string>
<string name="thought">Gondolkodott</string>
<string name="output_cut">A kimenet itt lerövidítve jelenik meg. A teljes szöveg a weblapon található.</string>
+1
View File
@@ -51,6 +51,7 @@
<string name="continue_reply">Continua</string>
<string name="older">Messaggi precedenti</string>
<string name="queued">In attesa di invio</string>
<string name="reply_unrecorded">La risposta a questo non è stata registrata.</string>
<string name="thinking">Ragionamento</string>
<string name="thought">Ha ragionato</string>
<string name="output_cut">L\'output qui è abbreviato. Lo trovi per intero sulla pagina web.</string>
+1
View File
@@ -51,6 +51,7 @@
<string name="continue_reply">Kontynuuj</string>
<string name="older">Wcześniejsze wiadomości</string>
<string name="queued">Czeka na wysłanie</string>
<string name="reply_unrecorded">Odpowiedź na to nie została zapisana.</string>
<string name="thinking">Rozumowanie</string>
<string name="thought">Rozumowanie</string>
<string name="output_cut">Wynik jest tu skrócony. Cały znajduje się na stronie internetowej.</string>
+1
View File
@@ -51,6 +51,7 @@
<string name="continue_reply">Pokračovať</string>
<string name="older">Staršie správy</string>
<string name="queued">Čaká na odoslanie</string>
<string name="reply_unrecorded">Odpoveď na toto nebola zaznamenaná.</string>
<string name="thinking">Premýšľa</string>
<string name="thought">Premýšľal</string>
<string name="output_cut">Výstup je tu skrátený. Celý nájdete na webovej stránke.</string>
+1
View File
@@ -52,6 +52,7 @@
<string name="continue_reply">Continue</string>
<string name="older">Earlier messages</string>
<string name="queued">Waiting to be sent</string>
<string name="reply_unrecorded">The reply to this was not recorded.</string>
<string name="thinking">Thinking</string>
<string name="thought">Thought</string>
<string name="output_cut">Output shortened here. The whole of it is on the web page.</string>
@@ -0,0 +1,249 @@
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.Drawn
import eu.llembas.android.api.EventsHub
import eu.llembas.android.api.Frame
import eu.llembas.android.api.LembasJson
import eu.llembas.android.api.LiveReply
import eu.llembas.android.api.Message
import eu.llembas.android.api.MessageEnd
import eu.llembas.android.api.ReplyFrame
import eu.llembas.android.api.Step
import eu.llembas.android.api.drawn
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.TranscriptChange
import eu.llembas.android.ui.chat.asksFor
import eu.llembas.android.ui.chat.movesToEnd
import eu.llembas.android.ui.chat.pictureRatio
import eu.llembas.android.ui.chat.restFollows
import eu.llembas.android.ui.chat.transcriptChange
import eu.llembas.android.ui.chat.wentBack
import eu.llembas.android.ui.chat.withNewest
import eu.llembas.android.ui.home.ChatsState
import eu.llembas.android.ui.home.withNewest
import kotlinx.coroutines.channels.Channel
import kotlinx.coroutines.flow.receiveAsFlow
import kotlinx.coroutines.launch
import kotlinx.coroutines.test.runTest
import org.junit.Assert.assertEquals
import org.junit.Assert.assertFalse
import org.junit.Assert.assertTrue
import org.junit.Test
/**
* A reply this app did not start (the events route's `reply` frame, `contract/event_reply.json`):
* which frames are news to an open chat, what reading the chat again keeps, how a turn nobody
* typed and its reply are drawn -- and where the transcript stands through all of it.
*/
class ReplyEventTest {
private fun text(name: String): String = requireNotNull(javaClass.classLoader!!.getResource("$name.json")) { "contract/$name.json is missing" }.readText()
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, origin: String = "") = Message(id = id, role = "user", machine = true, origin = origin, text = "The baker has finished.")
private val chat = Chat(id = "chat1")
private fun frame(message: String, chatId: String = "chat1", live: Boolean = true) = ReplyFrame(chatId = chatId, messageId = message, live = live)
@Test
fun theFrameIsReadAsTheServerWritesIt() {
val said = LembasJson.decodeFromString(ReplyFrame.serializer(), text("event_reply"))
assertEquals(ReplyFrame(chatId = "chat1", messageId = "msg2", live = true), said)
// A frame with more in it than this app knows is still read; one with less says nothing is live.
assertEquals(frame("m9", live = false), LembasJson.decodeFromString(ReplyFrame.serializer(), """{"chat_id":"chat1","message_id":"m9","kind":"wake"}"""))
}
@Test
fun onlyAReplyThisScreenDoesNotHoldIsNews() {
val open = ChatState(chat = chat, messages = listOf(person("q1"), reply("a1")))
// A reply nobody asked for from here: news.
assertTrue(open.asksFor(frame("a2")))
// Said as already ended: the chat is still read, the row is not there yet.
assertTrue(open.asksFor(frame("a2", live = false)))
// Another chat's, or a frame that names no reply: not this screen's.
assertFalse(open.asksFor(frame("a2", chatId = "chat2")))
assertFalse(open.asksFor(frame("")))
// A chat not made yet has no replies to hear of.
assertFalse(ChatState().asksFor(frame("a2")))
// The reply being followed -- this app's own, said back by the server: not news.
val writing = open.copy(messages = open.messages + person("q2") + reply("a2", complete = false), live = LiveReply("a2"))
assertFalse(writing.asksFor(frame("a2")))
// One drawn as finished: not news either, however late its frame is heard.
assertFalse(open.asksFor(frame("a1")))
// A row that is there but was never finished and is followed by nobody (its stream was lost): news.
val lost = open.copy(messages = open.messages + person("q2") + reply("a2", complete = false))
assertTrue(lost.asksFor(frame("a2")))
// While another reply is followed, the frame for the next one is still news -- it is taken up after.
assertTrue(writing.asksFor(frame("a3")))
}
@Test
fun readingTheChatAgainKeepsTheOlderPagesAPersonLoaded() {
val rows = listOf(person("q1"), reply("a1"), person("q2"), reply("a2"), person("q3"), reply("a3"))
// Two older pages were loaded: the transcript goes back to the chat's first message.
val shown = ChatState(chat = chat, messages = rows, more = false)
// The newest page as the server has it now: a turn nobody typed and its reply are new.
val page = listOf(person("q3"), reply("a3"), note("n1", "harness"), reply("a4", complete = false))
val read = shown.withNewest(ChatDetail(chat = chat.copy(title = "Waybread"), messages = page, more = true, live = "a4"))
assertEquals(listOf("q1", "a1", "q2", "a2", "q3", "a3", "n1", "a4"), read.messages.map { it.id })
// What is above is what this screen loaded, not what the page says of itself.
assertFalse(read.more)
assertEquals("Waybread", read.chat?.title)
// The rows a reader looks at are the same rows, so the list keeps them where they are.
assertEquals(TranscriptChange.Appended, transcriptChange(shown.messages, read.messages))
// The page is the whole chat (nothing above it), or joins nothing shown: it replaces the transcript.
val whole = shown.withNewest(ChatDetail(chat = chat, messages = page, more = false))
assertEquals(page.map { it.id }, whole.messages.map { it.id })
val elsewhere = listOf(person("x1"), reply("y1"))
assertEquals(elsewhere, shown.withNewest(ChatDetail(chat = chat, messages = elsewhere, more = true)).messages)
// Only the newest page was shown: it is replaced, with the server's word on what is above.
val one = ChatState(chat = chat, messages = listOf(person("q3"), reply("a3")), more = true)
assertEquals(ChatState(chat = chat, messages = page, more = true), one.withNewest(ChatDetail(chat = chat, messages = page, more = true)))
// A rewind: the rows after the edited turn are gone on the server, and go here.
val rewound = shown.withNewest(ChatDetail(chat = chat, messages = listOf(reply("a1"), person("q2"), reply("a5")), more = true))
assertEquals(listOf("q1", "a1", "q2", "a5"), rewound.messages.map { it.id })
// No row twice, whatever the page repeats of the rows above it.
val repeating = shown.withNewest(ChatDetail(chat = chat, messages = listOf(person("q2"), reply("a2"), person("q1")), more = true))
assertEquals(repeating.messages.map { it.id }.distinct(), repeating.messages.map { it.id })
}
@Test
fun aReplyNobodyAskedForFollowsOnlyForAPersonAtTheEnd() {
val before = listOf(person("q1"), reply("a1"))
val after = before + note("n1", "harness") + reply("a2", complete = false)
val change = transcriptChange(before, after, sent = "q1")
assertEquals(TranscriptChange.Appended, change)
assertTrue(movesToEnd(change, following = true))
assertFalse(movesToEnd(change, following = false))
// The stored reply in place of the one being written is the same row under the same key.
val stored = before + note("n1", "harness") + reply("a2")
assertEquals(after.map { it.id }, stored.map { it.id })
assertEquals(TranscriptChange.Changed, transcriptChange(after, stored))
assertFalse(movesToEnd(TranscriptChange.Changed, following = false))
}
@Test
fun aReplyFrameIsNotToldAgainToAWatcherThatJoinsLater() = runTest {
// The one connection, as a line whose frames wait for whoever reads it.
val route = Channel<Frame>(Channel.UNLIMITED)
val hub = EventsHub(backgroundScope)
val open = { route.receiveAsFlow() }
val drawer = Channel<Frame>(Channel.UNLIMITED)
val screen = Channel<Frame>(Channel.UNLIMITED)
val first = launch { hub.frames("instance", open).collect { drawer.send(it) } }
val reports = Frame("reports", """{"unread":1}""")
val started = Frame("reply", text("event_reply"))
route.send(reports)
route.send(started)
assertEquals(reports, drawer.receive())
assertEquals(started, drawer.receive())
// A chat opened later hears the state it missed, and not the reply that started before it listened.
val second = launch { hub.frames("instance", open).collect { screen.send(it) } }
assertEquals(reports, screen.receive())
val next = Frame("reply", """{"chat_id":"chat1","message_id":"msg3","live":true}""")
route.send(next)
assertEquals(next, screen.receive())
assertEquals(next, drawer.receive())
first.cancel()
second.cancel()
}
@Test
fun theListReadAgainMovesTheChatUpAndKeepsWhatWasLoadedBelow() {
fun row(id: String, running: Boolean = false, unread: Boolean = false) = Chat(id = id, title = id, running = running, unread = unread)
val shown = ChatsState(chats = listOf(row("c1"), row("c2"), row("c3"), row("c4"), row("c5")), more = true)
// The first page is three rows; c4 and c5 were loaded with "more".
val page = ChatPage(chats = listOf(row("c3", running = true), row("c1"), row("c2")), more = true)
val read = shown.withNewest(page)
assertEquals(listOf("c3", "c1", "c2", "c4", "c5"), read.chats.map { it.id })
assertTrue(read.chats.first().running)
assertTrue(read.more)
// A new chat pushed the page's last row off it: that row is kept below, once.
val pushed = shown.withNewest(ChatPage(chats = listOf(row("c0", unread = true), row("c1"), row("c2")), more = true))
assertEquals(listOf("c0", "c1", "c2", "c3", "c4", "c5"), pushed.chats.map { it.id })
// Only the page was shown, or nothing shown is on it: the page is the list.
val short = ChatsState(chats = listOf(row("c1"), row("c2")), more = false)
assertEquals(ChatsState(chats = page.chats, more = true), short.withNewest(page))
val other = ChatPage(chats = listOf(row("x1")), more = false)
assertEquals(ChatsState(chats = other.chats, more = false), shown.withNewest(other))
}
@Test
fun aTurnTheComputersHarnessStartedIsNeverThePersonsBubble() {
val harness = note("n1", "harness")
assertEquals(Drawn.Note, drawn(harness, first = false, reportChat = false))
// By its origin alone, should a server say it without `machine`.
assertEquals(Drawn.Note, drawn(harness.copy(machine = false), first = false, reportChat = false))
// Typed in the terminal: a person wrote it, and an origin this app does not know is nobody's mark.
assertEquals(Drawn.Person, drawn(person("q1").copy(origin = "terminal"), first = false, reportChat = false))
assertEquals(Drawn.Person, drawn(person("q1").copy(origin = "later"), first = false, reportChat = false))
}
@Test
fun anEmptyFinishedReplyToATurnNobodyTypedSaysSoInOneLine() {
val empty = Message(id = "a2", role = "assistant")
assertTrue(replyUnrecorded(empty, note("n1", "harness")))
assertTrue(replyUnrecorded(empty, note("n1")))
// To something a person asked, an empty reply is just that.
assertFalse(replyUnrecorded(empty, person("q1")))
assertFalse(replyUnrecorded(empty, null))
assertFalse(replyUnrecorded(empty, reply("a1")))
// Still being written, stopped, failed, or holding anything at all: drawn as a reply.
assertFalse(replyUnrecorded(empty.copy(complete = false), note("n1")))
assertFalse(replyUnrecorded(empty.copy(stopped = true), note("n1")))
assertFalse(replyUnrecorded(empty.copy(error = "The device did not answer."), note("n1")))
assertFalse(replyUnrecorded(empty.copy(end = MessageEnd(phase = "stopped")), note("n1")))
assertFalse(replyUnrecorded(empty.copy(text = "Seven."), note("n1")))
assertFalse(replyUnrecorded(reply("a2"), note("n1")))
// In a transcript: by the row before each reply.
val rows = listOf(person("q1"), reply("a1"), note("n1", "harness"), empty, note("n2", "harness"), reply("a3"), person("q2"), empty.copy(id = "a4"))
assertEquals(setOf("a2"), unrecordedReplies(rows))
assertEquals(emptySet<String>(), unrecordedReplies(listOf(empty)))
}
@Test
fun onlyThePersonsOwnScrollEndsTheFollowing() {
// This app's scroll to the end, left short of it by a card that arrived meanwhile: still following.
assertTrue(restFollows(following = true, byPerson = false, distance = 600, slack = 96))
// The same rest after a finger: the person is reading above, and is left there.
assertFalse(restFollows(following = true, byPerson = true, distance = 600, slack = 96))
// Back at the end, however it got there: the following is taken up.
assertTrue(restFollows(following = false, byPerson = true, distance = 40, slack = 96))
assertTrue(restFollows(following = false, byPerson = false, distance = 0, slack = 96))
// Not following and resting away from the end: nothing takes it up.
assertFalse(restFollows(following = false, byPerson = false, distance = 600, slack = 96))
// A list gone back towards its start was moved by a person (a wheel, a key, a reader's gesture).
assertTrue(wentBack(fromIndex = 8, fromOffset = 0, toIndex = 6, toOffset = 120))
assertTrue(wentBack(fromIndex = 8, fromOffset = 300, toIndex = 8, toOffset = 40))
// Further down, or where it was: this app's own keeping to the end.
assertFalse(wentBack(fromIndex = 8, fromOffset = 300, toIndex = 8, toOffset = 300))
assertFalse(wentBack(fromIndex = 8, fromOffset = 300, toIndex = 9, toOffset = 0))
assertFalse(wentBack(fromIndex = 8, fromOffset = 300, toIndex = 8, toOffset = 900))
}
@Test
fun aPicturesPlaceHasItsShapeBeforeItsBytes() {
assertEquals(1.6f, pictureRatio(1024, 640), 0.001f)
assertEquals(0.75f, pictureRatio(768, 1024), 0.001f)
// A size the server did not say: a square, not nothing.
assertEquals(1f, pictureRatio(0, 0), 0f)
assertEquals(1f, pictureRatio(1024, 0), 0f)
// A strip is kept within what a phone can show.
assertEquals(4f, pictureRatio(4000, 100), 0f)
assertEquals(0.25f, pictureRatio(100, 4000), 0f)
}
}
+2
View File
@@ -64,6 +64,8 @@ STRINGS: dict[str, str] = {
"continue_reply": "Continue",
"older": "Earlier messages",
"queued": "Waiting to be sent",
# 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",
"thought": "Thought",
"output_cut": "Output shortened here. The whole of it is on the web page.",