diff --git a/CHANGELOG.md b/CHANGELOG.md index bd14c60..fc7417d 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -5,6 +5,20 @@ is in alpha and releases come off `main`. ## [Unreleased] +### Fixed + +- **The chat no longer pulls you away from what you are reading while a reply is written.** The + view follows the reply only while you are at the end. Once you scroll up it stays exactly + where you are -- a finger on the list ends the following at once -- and scrolling back to the + end takes it up again. Before, the next queued turn starting, a transcript read again and a + rotation could each throw the view to the end. +- **Older messages no longer throw the chat to its end.** Tapping *Older* keeps the message you + were at in place, with the older ones above it. +- **The keyboard no longer covers the last lines**: opening it at the end of a chat keeps the + end in view. +- **The assistant's sheet follows the same rule.** It pulled the answer back to its end at every + word, also for somebody reading further up. + ## [1.0.0-beta.10] — 2026-11-13 ### Added diff --git a/app/src/main/java/eu/llembas/android/assist/AssistSheet.kt b/app/src/main/java/eu/llembas/android/assist/AssistSheet.kt index bc02bde..b248cc1 100644 --- a/app/src/main/java/eu/llembas/android/assist/AssistSheet.kt +++ b/app/src/main/java/eu/llembas/android/assist/AssistSheet.kt @@ -10,6 +10,7 @@ import androidx.compose.foundation.gestures.Orientation import androidx.compose.foundation.gestures.draggable import androidx.compose.foundation.gestures.rememberDraggableState import androidx.compose.foundation.horizontalScroll +import androidx.compose.foundation.interaction.DragInteraction import androidx.compose.foundation.interaction.MutableInteractionSource import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Box @@ -75,6 +76,7 @@ import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.remember import androidx.compose.runtime.rememberCoroutineScope import androidx.compose.runtime.setValue +import androidx.compose.runtime.snapshotFlow import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.draw.clip @@ -94,6 +96,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.progressLineOf import eu.llembas.android.ui.theme.LocalPalette import kotlinx.coroutines.launch @@ -217,8 +220,27 @@ fun ColumnScope.AssistSheetContent( val palette = LocalPalette.current var text by remember { mutableStateOf("") } val scroll = rememberScrollState() - val growth = state.turns.lastOrNull()?.steps?.sumOf { (it.markdown?.length ?: 0) + (it.text?.length ?: 0) } ?: 0 - LaunchedEffect(state.turns.size, growth) { if (state.turns.isNotEmpty()) scroll.animateScrollTo(scroll.maxValue) } + // The turns keep to their end while an answer is written only for a person who is there + // (`ui/chat/Follow.kt`, the chat's rule): a finger on them ends the following, where they + // 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() } + LaunchedEffect(scroll) { + scroll.interactionSource.interactions.collect { if (it is DragInteraction.Start) following = false } + } + LaunchedEffect(scroll) { + var moving = false + snapshotFlow { scroll.isScrollInProgress }.collect { now -> + if (moving && !now) following = followsAt(scroll.maxValue - scroll.value, slack) + moving = now + } + } + LaunchedEffect(state.turns.size) { following = true } + // The end moves when the answer grows and when the keyboard opens; before the first layout + // it is not known yet. + LaunchedEffect(scroll) { + snapshotFlow { if (following) scroll.maxValue else -1 }.collect { end -> if (end in 0 until Int.MAX_VALUE) scroll.scrollTo(end) } + } // The top: the handle and the bar. Both drag the sheet. Column(handle.fillMaxWidth()) { 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 422bc28..eed44e6 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 @@ -8,6 +8,7 @@ import android.os.Build import androidx.compose.foundation.background import androidx.compose.foundation.gestures.scrollBy import androidx.compose.foundation.horizontalScroll +import androidx.compose.foundation.interaction.DragInteraction import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.BoxWithConstraints @@ -78,9 +79,11 @@ import androidx.compose.runtime.remember import androidx.compose.runtime.rememberCoroutineScope import androidx.compose.runtime.saveable.rememberSaveable import androidx.compose.runtime.setValue +import androidx.compose.runtime.snapshotFlow import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.platform.LocalContext +import androidx.compose.ui.platform.LocalDensity import androidx.compose.ui.res.stringResource import androidx.compose.ui.text.style.TextAlign import androidx.compose.ui.text.style.TextOverflow @@ -99,6 +102,7 @@ import eu.llembas.android.ui.ModelAvatar import eu.llembas.android.ui.ProgressStatus import eu.llembas.android.ui.theme.LocalPalette import eu.llembas.android.ui.viewer.FileViewer +import kotlinx.coroutines.flow.drop import kotlinx.coroutines.launch /** @@ -217,15 +221,45 @@ fun ChatContent( val rows = state.messages val info = state.modelInfo - // To the end when the transcript grows, and while a reply is being written -- but only if - // the person is at the end already: reading back up is not interrupted by the next line. - var following by remember { mutableStateOf(true) } - LaunchedEffect(list.isScrollInProgress) { - if (!list.isScrollInProgress) following = !list.canScrollForward + // 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 + // list comes to rest says whether it is taken up again. Kept over a rotation, with the place. + var following by rememberSaveable { mutableStateOf(true) } + var drawnBefore by rememberSaveable { mutableStateOf(false) } + val slack = with(LocalDensity.current) { 48.dp.roundToPx() } + LaunchedEffect(list) { + list.interactionSource.interactions.collect { if (it is DragInteraction.Start) following = false } + } + LaunchedEffect(list) { + var moving = false + snapshotFlow { list.isScrollInProgress }.collect { now -> + if (moving && !now) following = followsAt(list.distanceToEnd(), slack) + moving = now + } + } + // The rows as they were at the last draw, to tell a message sent from an older page loaded. + val known = remember { arrayOfNulls>(1) } + LaunchedEffect(rows) { + val before = known[0] + known[0] = rows + val change = transcriptChange(before, rows, restored = drawnBefore) + if (rows.isNotEmpty()) drawnBefore = true + if (change == TranscriptChange.Older) { + // An older page above the very top: the row that was first stays first, so reading + // goes on upwards from it. Anywhere else the list keeps its place by the rows' keys. + val kept = keptRow(before.orEmpty(), rows) + if (kept != null && list.firstVisibleItemIndex == 0) list.scrollToItem(kept + if (state.more) 1 else 0) + } else if (movesToEnd(change, following)) { + following = true + list.toEnd() + } } - LaunchedEffect(rows.size) { if (rows.isNotEmpty()) list.toEnd() } val growth = live?.let { it.shown.size * 100_000 + (it.tail.text.length + it.tail.thinking.length) } ?: 0 LaunchedEffect(growth) { if (growth > 0 && following) list.toEnd() } + // The keyboard opening takes the list's foot away: a person at the end stays at the end. + LaunchedEffect(list) { + snapshotFlow { list.layoutInfo.viewportSize.height }.drop(1).collect { if (following) list.toEnd() } + } CompositionLocalProvider(LocalCopy provides copy) { Scaffold( @@ -461,6 +495,14 @@ private suspend fun LazyListState.toEnd() { scrollBy(1_000_000f) } +/** How far the list stands from its very end, in pixels; a last row not on screen is "far". */ +private fun LazyListState.distanceToEnd(): Int { + val info = layoutInfo + val last = info.visibleItemsInfo.lastOrNull() ?: return 0 + if (last.index < info.totalItemsCount - 1) return Int.MAX_VALUE + return last.offset + last.size + info.afterContentPadding - info.viewportEndOffset +} + /** * A new chat's empty page: what kind of chat it is ([onKind], Chat or Agent, one line each), then * the model's picture and a greeting. A new agent chat says where it will run instead, and that 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 new file mode 100644 index 0000000..8cd9447 --- /dev/null +++ b/app/src/main/java/eu/llembas/android/ui/chat/Follow.kt @@ -0,0 +1,79 @@ +package eu.llembas.android.ui.chat + +import eu.llembas.android.api.Message + +/* + * Whether a list keeps to its end while something is written into it. The rule, the same for the + * chat's transcript and the assistant's sheet: the view follows only while the person is at the + * end; once they have scrolled away it stays exactly where they are, and coming back to the end + * takes the following up again. Nothing here knows Compose, so the tests read it as it is. + */ + +/** What happened to the transcript's rows between two draws. */ +enum class TranscriptChange { + /** Nothing to follow: no rows, or the same rows. */ + None, + + /** A chat shown for the first time, or another chat in the same place. */ + Opened, + + /** The person's own message is new at the end: sending always shows what was sent. */ + Sent, + + /** New rows at the end that the person did not write: a reply, the queue's next turn. */ + Appended, + + /** An older page was put in front; the end has not moved. */ + Older, + + /** Rows changed in place: a finished reply for the one being written, a transcript read again. */ + Changed, +} + +/** + * What changed from [before] to [after]. [before] is null when this draw is the first one this + * list makes; [restored] then says the list had rows before (a rotation, a return to the + * screen), so its place is the one it kept, not a chat being opened. + */ +fun transcriptChange(before: List?, after: List, restored: Boolean = false): TranscriptChange { + if (after.isEmpty()) return TranscriptChange.None + if (before == null) return if (restored) TranscriptChange.Changed else TranscriptChange.Opened + val known = before.mapTo(HashSet()) { it.id } + val firstKept = after.indexOfFirst { it.id in known } + if (firstKept < 0) return TranscriptChange.Opened + val added = after.subList(after.indexOfLast { it.id in known } + 1, after.size) + return when { + added.any { it.isUser && !it.machine } -> TranscriptChange.Sent + added.isNotEmpty() -> TranscriptChange.Appended + firstKept > 0 -> TranscriptChange.Older + before == after -> TranscriptChange.None + else -> TranscriptChange.Changed + } +} + +/** + * 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. + */ +fun movesToEnd(change: TranscriptChange, following: Boolean): Boolean = when (change) { + TranscriptChange.Opened, TranscriptChange.Sent -> true + TranscriptChange.None, TranscriptChange.Older -> false + TranscriptChange.Appended, TranscriptChange.Changed -> following +} + +/** + * 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 + * read as "scrolled away". + */ +fun followsAt(distance: Int, slack: Int): Boolean = distance <= slack + +/** + * 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. + */ +fun keptRow(before: List, after: List): Int? { + val first = before.firstOrNull() ?: return null + return after.indexOfFirst { it.id == first.id }.takeIf { it >= 0 } +} diff --git a/app/src/test/java/eu/llembas/android/FollowTest.kt b/app/src/test/java/eu/llembas/android/FollowTest.kt new file mode 100644 index 0000000..696ec5c --- /dev/null +++ b/app/src/test/java/eu/llembas/android/FollowTest.kt @@ -0,0 +1,120 @@ +package eu.llembas.android + +import eu.llembas.android.api.Message +import eu.llembas.android.ui.chat.TranscriptChange +import eu.llembas.android.ui.chat.followsAt +import eu.llembas.android.ui.chat.keptRow +import eu.llembas.android.ui.chat.movesToEnd +import eu.llembas.android.ui.chat.transcriptChange +import org.junit.Assert.assertEquals +import org.junit.Assert.assertFalse +import org.junit.Assert.assertNull +import org.junit.Assert.assertTrue +import org.junit.Test + +/** + * The view follows a reply only for a person who is at the end; scrolled away, it stays where + * they are, whatever the transcript does; back at the end, it follows again. + */ +class FollowTest { + private fun person(id: String) = Message(id = id, role = "user", text = "A question") + + private fun reply(id: String, text: String = "") = Message(id = id, role = "assistant", text = text) + + private fun note(id: String) = Message(id = id, role = "user", machine = true, text = "A task finished") + + private val talk = listOf(person("q1"), reply("a1"), person("q2"), reply("a2")) + + @Test + fun aChatOpenedGoesToItsEnd() { + assertEquals(TranscriptChange.Opened, transcriptChange(null, talk)) + assertEquals(TranscriptChange.Opened, transcriptChange(emptyList(), talk)) + // Another chat in the same place is opened too: nothing of the old one is left. + assertEquals(TranscriptChange.Opened, transcriptChange(talk, listOf(person("x1"), reply("y1")))) + assertTrue(movesToEnd(TranscriptChange.Opened, following = false)) + } + + @Test + fun aRotationKeepsThePlaceOfAPersonWhoScrolledAway() { + val change = transcriptChange(null, talk, restored = true) + assertEquals(TranscriptChange.Changed, change) + assertFalse(movesToEnd(change, following = false)) + assertTrue(movesToEnd(change, following = true)) + } + + @Test + fun aMessageSentAlwaysShows() { + val change = transcriptChange(talk, talk + person("q3") + reply("a3")) + assertEquals(TranscriptChange.Sent, change) + assertTrue(movesToEnd(change, following = false)) + // A prompt queued behind a running reply: the person's row alone. + assertEquals(TranscriptChange.Sent, transcriptChange(talk, talk + person("q3"))) + } + + @Test + fun aReplyTheQueueStartedDoesNotDragAReaderDown() { + // The transcript read again after `done` with a `next`: the queued prompt was there, its reply is new. + val queued = talk + person("q3") + val change = transcriptChange(queued, queued + reply("a3")) + assertEquals(TranscriptChange.Appended, change) + assertFalse(movesToEnd(change, following = false)) + assertTrue(movesToEnd(change, following = true)) + } + + @Test + fun theInstancesOwnLineIsNotThePersonSending() { + val change = transcriptChange(talk, talk + note("n1") + reply("a3")) + assertEquals(TranscriptChange.Appended, change) + assertFalse(movesToEnd(change, following = false)) + } + + @Test + fun anOlderPageNeverMovesToTheEnd() { + val older = listOf(person("q0"), reply("a0")) + val change = transcriptChange(talk, older + talk) + assertEquals(TranscriptChange.Older, change) + assertFalse(movesToEnd(change, following = true)) + assertFalse(movesToEnd(change, following = false)) + // The row that was first keeps its place. + assertEquals(2, keptRow(talk, older + talk)) + assertNull(keptRow(talk, older)) + assertNull(keptRow(emptyList(), talk)) + } + + @Test + fun theFinishedReplyInPlaceOfTheWrittenOneFollowsOnlyAtTheEnd() { + val done = talk.dropLast(1) + reply("a2", text = "The whole answer.") + val change = transcriptChange(talk, done) + assertEquals(TranscriptChange.Changed, change) + assertFalse(movesToEnd(change, following = false)) + assertTrue(movesToEnd(change, following = true)) + } + + @Test + fun aReplyMadeAgainIsNotAMessageSent() { + // Regenerate puts a new row where the old reply was; an edit cuts the turns after it. + assertEquals(TranscriptChange.Appended, transcriptChange(talk, talk.dropLast(1) + reply("a2b"))) + assertEquals(TranscriptChange.Appended, transcriptChange(talk, talk.take(1) + reply("a1b"))) + assertEquals(TranscriptChange.Changed, transcriptChange(talk, talk.take(2))) + } + + @Test + fun nothingChangedMovesNothing() { + assertEquals(TranscriptChange.None, transcriptChange(talk, talk.toList())) + assertEquals(TranscriptChange.None, transcriptChange(talk, emptyList())) + assertEquals(TranscriptChange.None, transcriptChange(null, emptyList())) + assertFalse(movesToEnd(TranscriptChange.None, following = true)) + } + + @Test + fun theEndIsTakenUpAgainWhereTheScrollCameToRest() { + assertTrue(followsAt(distance = 0, slack = 96)) + // A line that arrived while the list was settling is still the end. + assertTrue(followsAt(distance = 96, slack = 96)) + assertFalse(followsAt(distance = 97, slack = 96)) + // The last row not on screen at all. + assertFalse(followsAt(distance = Int.MAX_VALUE, slack = 96)) + // Overscrolled past the end, or a list shorter than its window. + assertTrue(followsAt(distance = -24, slack = 96)) + } +}