diff --git a/android/README.md b/android/README.md index 7649e47f..56587261 100644 --- a/android/README.md +++ b/android/README.md @@ -5331,3 +5331,126 @@ open in a chosen directory — the brief keeps implementation verification to th build and the unit tests, and visual review owns the device. The chip, menu and dialog are Compose UI, which this module has no unit harness for; they are covered by compilation only. + +## A conversation opens at the newest message, and follows it (17 Oct 2026) + +Opening a conversation used to start at the top of the transcript, so the first +thing the operator did was scroll down past everything already said to find the +current turn. This item is the scroll and follow behaviour plus a jump-to-latest +affordance; the transcript rendering, streaming, tool chips, diff cards and +approval cards are unchanged. `android/` only; nothing in the Pipelines server, +its Go source, the installer or the Docker files was touched, no dependency was +added beyond the already-declared material-icons-extended, and no run is started +from the app. + +- **Opening at the newest message.** The transcript's list state is now created + the moment the conversation first has content, with its first visible item set + by `chatFirstScroll` (`ui/chat/ChatScroll.kt`): a conversation the operator has a + position of their own in is restored, and every other conversation — i.e. every + freshly opened chat — starts at its newest message. "A position of their own" is + explicit now: `ChatThread.scroll` is nullable, null meaning the operator has + never left a position here, so a chat they deliberately left at the very top + (`ChatScrollPosition(0, 0)`) is restored rather than mistaken for "new". The + restore/clamp rule is the app's existing shared one (`restoredScrollAnchor`, + `ui/components/ListScroll.kt`): the saved index is clamped to the messages that + still exist and the offset is kept only when the saved message survived, so a + conversation that shrank underneath neither throws nor draws part-way down an + unrelated message. Placement happens on the list's *first* measure — it waits + for the viewport to be measured — so opening a chat never shows the top first, + and it goes through the same `scrollToEnd(itemCount, animated = false)` the + follow uses, never animated: a fresh conversation is placed at its newest item + (and a last message taller than the viewport has the part still below the fold + closed in the same settling), and a position the operator left is restored. + Because placement and follow share the one path, they cannot disagree about what + the newest item is — the earlier split (placement closed the gap directly) left a + conversation that grew between state creation and first measure showing the older + anchor with the newest item below the fold. Leaving a chat still persists its + position (a list state that never held content saves nothing), so returning to it + restores where the operator was. The placement flag and the follow state are + `rememberSaveable` too, so a rotation or process death while the operator is + reading history does not re-place the transcript and yank them back to the + bottom. +- **One scroll path, changed deliberately.** The existing follow scroll, the app + bar's approval jump and the new jump-to-latest all go through one helper: + `LazyListState.scrollToEnd(itemCount, animated)`. When the newest item sits + entirely below the fold — an item appended exactly at the viewport edge, with no + pixel on screen, so the distance to the end cannot be measured — it is brought + into view first (`animateScrollToItem`/`scrollToItem`); any part of it still + below the fold (a message taller than the viewport) is then closed by exactly + that distance (`closeBottomGap`). An item that is already partly visible is only + gap-closed, never moved up first, so following a growing stream never bounces. + There is no second scroll mechanism beside it. The distance is measured against + the transcript's *content* count (`bottomDistancePx(itemCount)`), not the count + the layout has measured: the follow effect is dispatched ahead of the measure + that appends the new item, so on that frame the layout still describes the + previous items and its own last visible item reads as the end — a stale + `totalItemsCount` makes an appended item look like the already-visible end, no + gap is detected and the item is never brought in. Reconciling the two counts is + what makes an arriving message, the local prompt plus running indicator appended + together, or an approval card actually arrive in view. +- **Follow while reading the newest part.** Following is the operator's position, + not only their intent: only their own drag changes it (a `DragInteraction.Start` + stops it, and a `Stop`/`Cancel` resumes it when the scroll settles at — or + within `CHAT_FOLLOW_THRESHOLD_DP` of — the bottom, `chatFollowsAt`), and it is + settled at placement from the live distance so a position restored away from the + bottom does not follow. While it holds, an arriving message (including one that + lands entirely below the fold), a streamed delta, a tool chip, a freshly arrived + approval card, a grown composer or the appearing keyboard re-follows smoothly; + the whole viewport height is an input to the follow effect, so the newest + message is never left hidden behind the composer or the IME. Programmatic + scrolls never touch the list's `interactionSource`, so they cannot un-stick the + view. The item count the decisions measure against is read at use time + (`rememberUpdatedState`): the drag collector and the affordance's derived state + outlive a recomposition, so a captured count would go stale as messages arrive + and the follow would measure against how many items there used to be. +- **Threshold.** `CHAT_FOLLOW_THRESHOLD_DP` (`ui/theme/Dimens.kt`) is **32dp**: + about one comfortable line of text, so the operator can be slightly off the + exact bottom (the list's own bottom gutter included) and still be pulled along, + while a deliberate scroll up stops the view moving under them. +- **Jump to latest.** A small Material 3 `SmallFloatingActionButton` (the + already-declared `KeyboardArrowDown` icon, at the transcript's bottom-end on the + shared gutter token) is offered while the view is *not* following and there is + genuinely something below the fold (`chatShowJumpToLatest`), and hidden at the + bottom or for an empty transcript. Tapping it re-engages the follow and returns + to the newest message. A pending permission/approval is still brought into view + the way the existing code did — it is the transcript's last item, so the follow + brings it in when the operator is reading the newest part, and the app bar's + approval action still jumps straight to it on demand. +- **Tests.** `ChatScrollTest` (11 cases) pins the pure decisions: the distance to + the end (overflow past the viewport, 0 once in view, null when a whole item is + below the fold — the case an item appended at the viewport edge creates, which + the follow must bring into view rather than only gap-close — or the list is + unmeasured), the same distance reconciled against the content count while the + layout still lags it by one item (the stale frame the follow runs on: read + against the layout's own count it is 0 and nothing moves; read against the + content count it is unknown and the item is brought in), the follow resuming + at/within the threshold but not beyond it, the jump-to-latest visibility (offered + only while away from the bottom, hidden at the bottom and for an empty + transcript), and the first placement (a fresh conversation — no position of its + own — at its newest message, a left position restored and clamped, a position at + the very top kept distinct from "new", and nothing to place when empty). + +Evidence (this run's implementer pass, macOS, Kotlin `jvmTarget` 17, Gradle 9.7.1 +launcher on JVM 25.0.4.1, `ANDROID_HOME=/Users/alan/Library/Android/sdk`, +cached/offline): `gradle --no-daemon --offline :app:testDebugUnitTest +:app:assembleDebug` → `BUILD SUCCESSFUL`, and `:app:testDebugUnitTest +--rerun-tasks` re-executed every test: the JUnit XMLs total **50 suites / 458 +tests / 0 failures / 0 errors / 0 skipped**, including the new `ChatScrollTest` +(11 cases) and the existing chat suites (`ChatStreamTest`, `ChatApprovalTest`, +`MultiChatStateTest`, `ChatSessionManagementTest`, `ChatDirectoriesTest`, +`ChatFormatTest`, `ChatProtocolTest`) green. The APK was published to this run's +artifacts directory as `pipelines-debug-wip-311a015.apk` (18,601,229 bytes, sha256 +`a3b45c3518e524f53719de243916fe4fcf120a82fad7c2de09b634bff717b1b6`; `311a015` is +`git rev-parse --short HEAD`, the tree being uncommitted WIP on top of it) and is +served at +`http://10.0.0.75:8080/artifacts/247/1/pipelines-debug-wip-311a015.apk` +(`HTTP/1.1 200 OK`, `Content-Type: application/vnd.android.package-archive`, +`Content-Length: 18601229`). + +Not verified in this pass: the follow/affordance behaviour on a device and every +claim about first-display smoothness — the brief keeps implementation +verification to the build and the unit tests, and visual review owns the device. +The composable's frame timing (placing the list before its first draw, the +instant correction for a last message taller than the viewport, and the fallback +that brings an item appended below the fold into view) is argued from the pinned +Compose BOM (2024.10.00) and the pure decisions it delegates to, not observed. diff --git a/android/app/src/main/java/net/awan/pipelines/ui/chat/ChatScreen.kt b/android/app/src/main/java/net/awan/pipelines/ui/chat/ChatScreen.kt index bbe89ac5..dd2b9607 100644 --- a/android/app/src/main/java/net/awan/pipelines/ui/chat/ChatScreen.kt +++ b/android/app/src/main/java/net/awan/pipelines/ui/chat/ChatScreen.kt @@ -3,6 +3,8 @@ package net.awan.pipelines.ui.chat import androidx.compose.foundation.BorderStroke import androidx.compose.foundation.background import androidx.compose.foundation.clickable +import androidx.compose.foundation.gestures.animateScrollBy +import androidx.compose.foundation.gestures.scrollBy import androidx.compose.foundation.horizontalScroll import androidx.compose.foundation.interaction.DragInteraction import androidx.compose.foundation.layout.Arrangement @@ -20,8 +22,8 @@ import androidx.compose.foundation.layout.padding import androidx.compose.foundation.layout.size import androidx.compose.foundation.layout.widthIn import androidx.compose.foundation.lazy.LazyColumn +import androidx.compose.foundation.lazy.LazyListState import androidx.compose.foundation.lazy.items -import androidx.compose.foundation.lazy.rememberLazyListState import androidx.compose.foundation.rememberScrollState import androidx.compose.foundation.verticalScroll import androidx.compose.foundation.shape.CircleShape @@ -62,6 +64,7 @@ import androidx.compose.material3.SnackbarDuration import androidx.compose.material3.SnackbarHost import androidx.compose.material3.SnackbarHostState import androidx.compose.material3.SnackbarResult +import androidx.compose.material3.SmallFloatingActionButton import androidx.compose.material3.Surface import androidx.compose.material3.Text import androidx.compose.material3.TextButton @@ -69,12 +72,15 @@ import androidx.compose.material3.TopAppBar import androidx.compose.runtime.Composable import androidx.compose.runtime.DisposableEffect import androidx.compose.runtime.LaunchedEffect +import androidx.compose.runtime.derivedStateOf import androidx.compose.runtime.getValue import androidx.compose.runtime.key import androidx.compose.runtime.mutableLongStateOf import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.remember import androidx.compose.runtime.rememberCoroutineScope +import androidx.compose.runtime.rememberUpdatedState +import androidx.compose.runtime.saveable.rememberSaveable import androidx.compose.runtime.setValue import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier @@ -116,6 +122,7 @@ import net.awan.pipelines.ui.components.RunStatusPalette import net.awan.pipelines.ui.components.SlidingPaneStack import net.awan.pipelines.ui.formatDuration import net.awan.pipelines.ui.theme.CHAT_BUBBLE_MAX_WIDTH_DP +import net.awan.pipelines.ui.theme.CHAT_FOLLOW_THRESHOLD_DP import net.awan.pipelines.ui.theme.CHAT_TITLE_MAX_WIDTH_DP import net.awan.pipelines.ui.theme.HAIRLINE_DP import net.awan.pipelines.ui.theme.ICON_BUTTON_SMALL_DP @@ -693,24 +700,42 @@ private fun ChatConversationPane( thread: ChatThread, modifier: Modifier, ) { - val listState = rememberLazyListState( - initialFirstVisibleItemIndex = thread.scroll.index, - initialFirstVisibleItemScrollOffset = thread.scroll.offset, - ) - // Persist the scroll position when the operator leaves this chat, so switching - // away and back returns them exactly where they were. - DisposableEffect(thread.sessionId) { - onDispose { vm.saveChatScroll(thread.sessionId, listState.firstVisibleItemIndex, listState.firstVisibleItemScrollOffset) } - } - val approval = approvalCard(thread.permission, thread.permissionAnswer) val awaiting = approval?.actionable == true // A turn blocked on an approval is not generating, so the running indicator // (and its ticking clock) stands down while the card is unanswered. val showRunning = thread.running && !awaiting - // The card is the transcript's last item; the top bar's approval action jumps - // to it so a pending request is reachable without scrolling the whole chat. - val approvalIndex = thread.messages.size + if (showRunning) 1 else 0 + // The count of the transcript's items: the messages, the running indicator + // while a turn is in flight and a pending approval card, which is the last item + // the top bar's approval action jumps to. + val itemCount = thread.messages.size + (if (showRunning) 1 else 0) + (if (approval != null) 1 else 0) + // The position the operator left this conversation at, read once: a + // conversation with none of its own opens at its newest message instead (see + // chatOpensAtNewest), so the current turn is never hunted for. + val savedScroll = remember(thread.sessionId) { thread.scroll } + // The list state is created the moment the conversation first has content, so + // its very first measure is already at the newest item rather than at the top: + // opening a chat must not show anything else first. It is still saveable, so a + // rotation or process death keeps the operator's position. + val listState = rememberSaveable(thread.sessionId, itemCount > 0, saver = LazyListState.Saver) { + val first = chatFirstScroll(savedScroll, itemCount) + LazyListState( + firstVisibleItemIndex = first.index, + firstVisibleItemScrollOffset = first.offset, + ) + } + // Persist the scroll position when the operator leaves this chat, so switching + // away and back returns them exactly where they were. Keyed on the list state, + // so the position saved is the one that was actually shown; a state that never + // held content (replaced when the conversation first loaded) saves nothing, + // leaving the conversation with no position of its own to open at its newest. + DisposableEffect(listState) { + onDispose { + if (listState.layoutInfo.totalItemsCount > 0) { + vm.saveChatScroll(thread.sessionId, listState.firstVisibleItemIndex, listState.firstVisibleItemScrollOffset) + } + } + } val scope = rememberCoroutineScope() Scaffold( @@ -733,7 +758,10 @@ private fun ChatConversationPane( if (awaiting) { IconButton( onClick = { - scope.launch { listState.animateScrollToItem(approvalIndex.coerceAtLeast(0)) } + // The transcript's one scroll path, so a pending + // request is brought into view the same way new + // content is. + scope.launch { listState.scrollToEnd(itemCount, animated = true) } }, ) { Icon( @@ -771,6 +799,8 @@ private fun ChatConversationPane( else -> ChatTranscript( thread = thread, listState = listState, + savedScroll = savedScroll, + itemCount = itemCount, approval = approval, showRunning = showRunning, onDecision = { decision -> @@ -802,64 +832,200 @@ private fun ChatConversationPane( * freshly opened chat sits against the composer) and the running indicator sits * at the newest end while a turn is in flight. * - * While a turn streams it follows the newest content with a hard jump (not an - * animation, which a fast-growing reply outruns), exactly like the reference - * transcript, unless the operator has scrolled up to read; returning to the end - * resumes following. + * The transcript has one scroll path ([scrollToEnd] / [closeBottomGap]) and one + * decision for whether it follows new content. It opens at the newest message + * (placed by the pane's initial position, with any part of a last message taller + * than the viewport closed instantly here), and then — while the operator intends + * to read the newest part — every arrival (a message, a streamed delta, a tool + * chip, a grown composer or the appearing keyboard) is followed smoothly, so the + * newest content stays in view. An item that arrives entirely below the fold is + * brought in rather than left there. A freshly arrived approval card is followed + * the same way. Once the operator has scrolled up to read history nothing moves + * under them, and the jump-to-latest affordance is offered instead. */ @Composable private fun ChatTranscript( thread: ChatThread, - listState: androidx.compose.foundation.lazy.LazyListState, + listState: LazyListState, + savedScroll: ChatScrollPosition?, + itemCount: Int, approval: ApprovalCard?, showRunning: Boolean, onDecision: (String) -> Unit, ) { - var follow by remember(thread.sessionId) { mutableStateOf(true) } - // Only a *user* drag changes whether the transcript follows: programmatic - // jumps (below) never touch `interactionSource`, so they cannot un-stick the - // view. A drag away from the end stops the follow; releasing at the very end - // (no content below) resumes it. - LaunchedEffect(listState) { + val scope = rememberCoroutineScope() + val density = LocalDensity.current + val thresholdPx = remember(density) { with(density) { CHAT_FOLLOW_THRESHOLD_DP.roundToPx() } } + // The transcript's item count, read at use time: the drag collector and the + // derived state below outlive any single recomposition, so a count captured + // when they were created would go stale as messages arrive and the follow + // would measure against how many items there used to be. + val currentItemCount by rememberUpdatedState(itemCount) + // Whether the operator wants the newest content kept in view. Only their own + // drag changes it — a programmatic scroll never touches the list's + // interactionSource, so it cannot un-stick the view — and a drag that settles + // at (or within the threshold of) the bottom resumes the follow. Its real + // value is settled once the transcript is placed, when the live distance to + // the bottom is known. + // Saved, so a rotation or process death while the operator is reading history + // restores "not following" too, rather than the restored transcript being + // yanked to the bottom by the placement the new composition would otherwise run. + var following by rememberSaveable(thread.sessionId) { mutableStateOf(true) } + LaunchedEffect(listState, thresholdPx) { listState.interactionSource.interactions.collect { interaction -> when (interaction) { - is DragInteraction.Start -> follow = false + is DragInteraction.Start -> following = false is DragInteraction.Stop, is DragInteraction.Cancel -> - follow = !listState.canScrollForward + following = chatFollowsAt( + distanceFromBottomPx = listState.bottomDistancePx(currentItemCount), + thresholdPx = thresholdPx, + itemCount = currentItemCount, + ) else -> Unit } } } - val awaiting = approval?.actionable == true - val itemCount = thread.messages.size + (if (showRunning) 1 else 0) + (if (approval != null) 1 else 0) - // Follow the newest content while a turn streams, and scroll a freshly - // arrived approval card into view the same way so a pending request is not - // left below the fold. - LaunchedEffect(thread.running, thread.messages, follow, itemCount, awaiting) { - if (follow && itemCount > 0 && (thread.running || awaiting)) { - listState.scrollToItem(itemCount - 1) + // The distance to the transcript's end, read through a derived state so the + // affordance's visibility is recomputed only when it actually changes rather + // than on every scrolled pixel. The item count is read through + // [currentItemCount] so the derived value also recomputes as content arrives. + val showJumpToLatest by remember(listState, thresholdPx) { + derivedStateOf { + chatShowJumpToLatest( + following = following, + distanceFromBottomPx = listState.bottomDistancePx(currentItemCount), + thresholdPx = thresholdPx, + itemCount = currentItemCount, + ) } } - LazyColumn( - state = listState, - modifier = Modifier.fillMaxSize(), - contentPadding = PaddingValues(horizontal = CHAT_GUTTER, vertical = CHAT_ITEM_GAP), - verticalArrangement = Arrangement.spacedBy(CHAT_ITEM_GAP, Alignment.Bottom), - ) { - items(thread.messages, key = { it.id }) { message -> - MessageItem(message) + // The transcript is placed once, when it first has content, and only after it + // has been measured; the viewport height is an input too, so a grown composer + // or the appearing keyboard re-follows rather than leaving the newest message + // hidden behind it. Placement itself is saved, so restoring a rotation does not + // re-place (and re-follow) a transcript the operator had scrolled up. + var placed by rememberSaveable(thread.sessionId) { mutableStateOf(false) } + val viewportHeight by remember(listState) { derivedStateOf { listState.layoutInfo.viewportSize.height } } + LaunchedEffect(thread.messages, thread.running, approval?.requestId, viewportHeight) { + if (itemCount <= 0) return@LaunchedEffect + if (!placed) { + // Wait for the first measure: placement run before it would no-op and + // leave the first display to the measured re-run, which animates, and + // the first display must not animate. + if (viewportHeight <= 0) return@LaunchedEffect + placed = true + if (chatOpensAtNewest(savedScroll)) { + // No position of the operator's own: bring the newest item fully + // into view, instantly — the first display must not animate — and + // through the same path the follow uses, so placement and follow + // cannot disagree about what the newest item is (a last message + // taller than the viewport has its below-the-fold part closed by + // the same call), then follow. + listState.scrollToEnd(itemCount, animated = false) + following = true + } else { + // A position the operator left: follow only if it was the bottom, so + // returning to a chat never yanks the view. + following = chatFollowsAt(listState.bottomDistancePx(itemCount), thresholdPx, itemCount) + } + return@LaunchedEffect } - if (showRunning) { - item(key = "pending") { RunningIndicator(thread) } + if (following) listState.scrollToEnd(itemCount, animated = true) + } + Box(Modifier.fillMaxSize()) { + LazyColumn( + state = listState, + modifier = Modifier.fillMaxSize(), + contentPadding = PaddingValues(horizontal = CHAT_GUTTER, vertical = CHAT_ITEM_GAP), + verticalArrangement = Arrangement.spacedBy(CHAT_ITEM_GAP, Alignment.Bottom), + ) { + items(thread.messages, key = { it.id }) { message -> + MessageItem(message) + } + if (showRunning) { + item(key = "pending") { RunningIndicator(thread) } + } + if (approval != null) { + // Keyed by request id so switching between requests swaps the card + // instead of reusing the previous one's state. + item(key = "approval-" + approval.requestId) { ApprovalCardItem(approval, onDecision) } + } } - if (approval != null) { - // Keyed by request id so switching between requests swaps the card - // instead of reusing the previous one's state. - item(key = "approval-" + approval.requestId) { ApprovalCardItem(approval, onDecision) } + // Offered only once the transcript is placed and the operator has left the + // bottom, so it never covers the newest content it would return to. + if (placed && showJumpToLatest) { + SmallFloatingActionButton( + onClick = { + following = true + scope.launch { listState.scrollToEnd(itemCount, animated = true) } + }, + modifier = Modifier.align(Alignment.BottomEnd).padding(CHAT_GUTTER), + ) { + Icon(Icons.Default.KeyboardArrowDown, contentDescription = "Jump to latest") + } } } } +/** + * The transcript's one scroll path, shared by the first placement, the follow, + * the app-bar approval jump and the jump-to-latest affordance. The newest item is + * brought into view when it sits entirely below the fold — an item appended past + * the viewport's edge, so no pixel of it is on screen and the remaining distance + * cannot be measured — and any part of it still below the fold (a message taller + * than the viewport) is then closed by exactly that distance. An item that is + * already partly visible is only gap-closed, never moved up first. [animated] is + * false only for the first placement, which must not animate. + * + * [itemCount] is the transcript's *content* count, which can be ahead of the + * layout's: an appended item exists in the content before the recomposition that + * measures it, and the effect that follows it is dispatched ahead of that measure, + * so the layout still describes the previous items and its own last visible item + * reads as the end. Measuring against [itemCount] — see [bottomDistancePx] — is + * what stops an appended item from being mistaken for the already-visible end and + * left below the fold: it has no pixel on screen, so it is unknown-distance and is + * brought into view rather than gap-closed at zero. + */ +private suspend fun LazyListState.scrollToEnd(itemCount: Int, animated: Boolean) { + if (itemCount <= 0) return + if (bottomDistancePx(itemCount) == null) { + if (animated) animateScrollToItem(itemCount - 1) else scrollToItem(itemCount - 1) + } + closeBottomGap(itemCount, animated) +} + +/** + * Scrolls the transcript's end into view by exactly the distance it sits below + * the viewport, measured against the same [itemCount] the decisions above use. + */ +private suspend fun LazyListState.closeBottomGap(itemCount: Int, animated: Boolean) { + val remaining = bottomDistancePx(itemCount) ?: return + if (remaining <= 0) return + if (animated) animateScrollBy(remaining.toFloat()) else scrollBy(remaining.toFloat()) +} + +/** + * The distance from the transcript's end to the viewport's bottom, measured + * against [itemCount] — the transcript's *content* count, not the layout's. The + * two differ on the frame content arrives: the layout still describes the + * previous items, so its own last visible item reads as the end and the appended + * item's absence is invisible. Measuring against the content count makes the + * appended item read exactly as [chatBottomDistancePx] defines it — no pixel on + * screen — so the scroll path above brings it into view rather than trusting a + * stale layout's "already at the end". [itemCount] is what the transcript + * renders, so the two counts agree as soon as the layout catches up. + */ +private fun LazyListState.bottomDistancePx(itemCount: Int): Int? { + val info = layoutInfo + val last = info.visibleItemsInfo.lastOrNull() + return chatBottomDistancePx( + lastVisibleIndex = last?.index ?: -1, + lastVisibleEndPx = last?.let { it.offset + it.size } ?: 0, + itemCount = itemCount, + viewportEndPx = info.viewportEndOffset, + ) +} + /** * The in-flight turn indicator: a spinner, `Working…` and the turn's live elapsed * time. The elapsed value is derived from the turn's own start ([ChatThread.elapsedMillis]), diff --git a/android/app/src/main/java/net/awan/pipelines/ui/chat/ChatScroll.kt b/android/app/src/main/java/net/awan/pipelines/ui/chat/ChatScroll.kt new file mode 100644 index 00000000..27e565e2 --- /dev/null +++ b/android/app/src/main/java/net/awan/pipelines/ui/chat/ChatScroll.kt @@ -0,0 +1,80 @@ +package net.awan.pipelines.ui.chat + +import net.awan.pipelines.ui.components.ListScrollAnchor +import net.awan.pipelines.ui.components.restoredScrollAnchor + +/** + * The pixels the end of the transcript still sits below the viewport's bottom + * edge, or null when the viewport does not show the last item at all (a whole + * item is still below the fold) or the list has not been measured yet. A value of + * 0 means the end is in view. [lastVisibleIndex] is the index of the last item + * the viewport shows (or -1 before measurement), [lastVisibleEndPx] where that + * item ends and [viewportEndPx] the viewport's own bottom edge, both in the + * list's pixel space. + * + * A null — the last item is entirely below the fold — is also what tells the + * follow path that it must bring the item into view before any gap can be + * measured: an item appended exactly at the viewport's edge has no visible pixel + * yet, so it is not in the layout's visible items and the gap reads as unknown. + * + * Pure and Android-free, so the decisions built on it are checked without a + * device. + */ +internal fun chatBottomDistancePx( + lastVisibleIndex: Int, + lastVisibleEndPx: Int, + itemCount: Int, + viewportEndPx: Int, +): Int? { + if (itemCount <= 0 || lastVisibleIndex != itemCount - 1) return null + return (lastVisibleEndPx - viewportEndPx).coerceAtLeast(0) +} + +/** + * Whether the view sits at the bottom: the end is in view and within + * [thresholdPx] of the bottom edge. Used for both decisions that depend on where + * the operator is — resuming the follow when a scroll settles, and offering the + * jump-to-latest affordance — so the two can never disagree about "at the + * bottom". + */ +internal fun chatFollowsAt(distanceFromBottomPx: Int?, thresholdPx: Int, itemCount: Int): Boolean = + itemCount > 0 && distanceFromBottomPx != null && distanceFromBottomPx <= thresholdPx + +/** + * Whether the jump-to-latest affordance is offered: only while the transcript is + * *not* following [following] and there is genuinely something below the fold to + * return to ([distanceFromBottomPx] null or further than [thresholdPx]). Hidden + * when already at the bottom, and never shown for an empty transcript. + */ +internal fun chatShowJumpToLatest( + following: Boolean, + distanceFromBottomPx: Int?, + thresholdPx: Int, + itemCount: Int, +): Boolean = !following && itemCount > 0 && !chatFollowsAt(distanceFromBottomPx, thresholdPx, itemCount) + +/** + * Whether opening a conversation should land on its newest message: only when the + * operator has no position of their own there yet (a null [saved]), which is + * every freshly opened chat, so the current turn is in view without hunting for + * it. A position the operator deliberately left behind — including the very top of + * the transcript, [ChatScrollPosition]`(0, 0)` — is restored instead; a saved + * position is never confused with the absence of one. + */ +internal fun chatOpensAtNewest(saved: ChatScrollPosition?): Boolean = saved == null + +/** + * The position a conversation's transcript is placed at when it first shows: the + * newest message for a conversation with no position of the operator's own, + * otherwise the position they left. The clamp rule is the same one every other + * list in the app uses ([restoredScrollAnchor]): the saved index is clamped to the + * messages that still exist, and the pixel offset is kept only when the saved item + * survived, so a conversation that shrank underneath neither throws nor draws + * nothing part-way down an unrelated message. + */ +internal fun chatFirstScroll(saved: ChatScrollPosition?, itemCount: Int): ChatScrollPosition { + if (itemCount <= 0) return ChatScrollPosition() + val position = saved ?: return ChatScrollPosition(index = itemCount - 1, offset = 0) + val anchor = restoredScrollAnchor(ListScrollAnchor(position.index, position.offset), itemCount) + return ChatScrollPosition(index = anchor.index, offset = anchor.offset) +} diff --git a/android/app/src/main/java/net/awan/pipelines/ui/chat/ChatStore.kt b/android/app/src/main/java/net/awan/pipelines/ui/chat/ChatStore.kt index 60320f9e..afc48ade 100644 --- a/android/app/src/main/java/net/awan/pipelines/ui/chat/ChatStore.kt +++ b/android/app/src/main/java/net/awan/pipelines/ui/chat/ChatStore.kt @@ -46,7 +46,14 @@ data class ChatThread( val runningSince: Long = 0, /** The unsent composer text for this chat. */ val draft: String = "", - val scroll: ChatScrollPosition = ChatScrollPosition(), + /** + * Where the operator left this conversation's transcript, or null while they + * have not been there yet. Null is distinct from any position — including the + * top, `ChatScrollPosition(0, 0)` — so opening a fresh chat lands on its + * newest message while a position the operator deliberately left, even at the + * top, is restored instead. + */ + val scroll: ChatScrollPosition? = null, /** The server's pending approval for this session, answered with chat_reply. */ val permission: ChatPermissionFrame? = null, /** diff --git a/android/app/src/main/java/net/awan/pipelines/ui/theme/Dimens.kt b/android/app/src/main/java/net/awan/pipelines/ui/theme/Dimens.kt index 53b32a3b..fbb5bdc4 100644 --- a/android/app/src/main/java/net/awan/pipelines/ui/theme/Dimens.kt +++ b/android/app/src/main/java/net/awan/pipelines/ui/theme/Dimens.kt @@ -227,3 +227,11 @@ internal val CHAT_TITLE_MAX_WIDTH_DP = 160.dp /** A chat message bubble's maximum width, so long prose stays readable. */ internal val CHAT_BUBBLE_MAX_WIDTH_DP = 560.dp + +/** + * How close to the end of the transcript the viewport must be for new content to + * keep following it: about one comfortable line of text, so the operator can be a + * touch off the exact bottom and still be pulled along, while a deliberate scroll + * up to read history stops the view moving under them. + */ +internal val CHAT_FOLLOW_THRESHOLD_DP = 32.dp diff --git a/android/app/src/test/java/net/awan/pipelines/ui/chat/ChatScrollTest.kt b/android/app/src/test/java/net/awan/pipelines/ui/chat/ChatScrollTest.kt new file mode 100644 index 00000000..4bc5403a --- /dev/null +++ b/android/app/src/test/java/net/awan/pipelines/ui/chat/ChatScrollTest.kt @@ -0,0 +1,173 @@ +package net.awan.pipelines.ui.chat + +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 conversation transcript's scroll behaviour is pure where it is decided, so + * it is checked here without a device: the distance from the end of the + * transcript, whether a settled scroll leaves the view at the bottom (so new + * content follows), whether the jump-to-latest affordance is offered instead, and + * where a conversation is first placed (its newest message). The composable reads + * the same functions from the live layout. + */ +class ChatScrollTest { + + // A comfortable line of slack, as CHAT_FOLLOW_THRESHOLD_DP is at runtime. + private val threshold = 96 + + @Test + fun theFollowResumesAtTheBottomAndWithinTheThreshold() { + // At the very end, and as far as the threshold allows. + assertTrue(chatFollowsAt(distanceFromBottomPx = 0, thresholdPx = threshold, itemCount = 5)) + assertTrue(chatFollowsAt(distanceFromBottomPx = threshold, thresholdPx = threshold, itemCount = 5)) + // One pixel further up is the operator reading history: no follow. + assertFalse(chatFollowsAt(distanceFromBottomPx = threshold + 1, thresholdPx = threshold, itemCount = 5)) + } + + @Test + fun theFollowDoesNotResumeWhenTheEndIsNotInViewOrTheConversationIsEmpty() { + // A whole item still below the fold is not "at the bottom". + assertFalse(chatFollowsAt(distanceFromBottomPx = null, thresholdPx = threshold, itemCount = 5)) + assertFalse(chatFollowsAt(distanceFromBottomPx = 0, thresholdPx = threshold, itemCount = 0)) + } + + @Test + fun theJumpToLatestIsOfferedOnlyWhileTheOperatorIsAwayFromTheBottom() { + // Following, so there is nothing to jump to. + assertFalse( + chatShowJumpToLatest(following = true, distanceFromBottomPx = 0, thresholdPx = threshold, itemCount = 5), + ) + // Scrolled up with content below: offered, whether the last item is under + // the fold or merely further than the threshold. + assertTrue( + chatShowJumpToLatest(following = false, distanceFromBottomPx = null, thresholdPx = threshold, itemCount = 5), + ) + assertTrue( + chatShowJumpToLatest( + following = false, + distanceFromBottomPx = threshold + 1, + thresholdPx = threshold, + itemCount = 5, + ), + ) + // Hidden once the view is back at the bottom, and for an empty transcript. + assertFalse( + chatShowJumpToLatest(following = false, distanceFromBottomPx = 0, thresholdPx = threshold, itemCount = 5), + ) + assertFalse( + chatShowJumpToLatest(following = false, distanceFromBottomPx = null, thresholdPx = threshold, itemCount = 0), + ) + } + + @Test + fun theDistanceToTheEndIsTheOverflowPastTheViewport() { + assertEquals( + 250, + chatBottomDistancePx(lastVisibleIndex = 4, lastVisibleEndPx = 1250, itemCount = 5, viewportEndPx = 1000), + ) + // The end has reached the edge (or is above it): nothing left below. + assertEquals( + 0, + chatBottomDistancePx(lastVisibleIndex = 4, lastVisibleEndPx = 1000, itemCount = 5, viewportEndPx = 1000), + ) + assertEquals( + 0, + chatBottomDistancePx(lastVisibleIndex = 4, lastVisibleEndPx = 900, itemCount = 5, viewportEndPx = 1000), + ) + } + + @Test + fun theDistanceIsUnknownWhenTheEndIsNotInViewOrUnmeasured() { + // A whole item below the fold, however the last visible item reads. + assertNull( + chatBottomDistancePx(lastVisibleIndex = 3, lastVisibleEndPx = 900, itemCount = 5, viewportEndPx = 1000), + ) + // Before the list has been measured, and for an empty conversation. + assertNull( + chatBottomDistancePx(lastVisibleIndex = -1, lastVisibleEndPx = 0, itemCount = 5, viewportEndPx = 1000), + ) + assertNull( + chatBottomDistancePx(lastVisibleIndex = -1, lastVisibleEndPx = 0, itemCount = 0, viewportEndPx = 1000), + ) + } + + @Test + fun theFollowMeasuresAgainstTheContentNotTheLayoutThatStillLagsIt() { + // The follow effect is dispatched ahead of the measure that appends the new + // item, so the layout has measured one item fewer than the content: its last + // visible item (index 3) is the end *it* knows. Measured against the layout's + // own count (4) that reads 0 — the pre-fix call — so the follow would + // gap-close by nothing and leave the new item below the fold. Measured + // against the content count (5) index 3 is not the end and the distance is + // unknown — the appended item has no pixel on screen — so it is brought in. + assertEquals( + 0, + chatBottomDistancePx(lastVisibleIndex = 3, lastVisibleEndPx = 1000, itemCount = 4, viewportEndPx = 1000), + ) + assertNull( + chatBottomDistancePx(lastVisibleIndex = 3, lastVisibleEndPx = 1000, itemCount = 5, viewportEndPx = 1000), + ) + } + + @Test + fun anItemAppendedPastTheFoldHasNoMeasurableGapSoItMustBeBroughtIntoView() { + // At rest the previously-last item (index 4 of 5) is the last *visible* one; + // an item appended at the viewport's edge starts with no pixel on screen, so + // it is not among the layout's visible items and the distance reads unknown. + // Closing a gap cannot recover from this — the follow must bring the item in. + assertNull( + chatBottomDistancePx(lastVisibleIndex = 4, lastVisibleEndPx = 1000, itemCount = 6, viewportEndPx = 1000), + ) + assertFalse(chatFollowsAt(distanceFromBottomPx = null, thresholdPx = threshold, itemCount = 6)) + } + + @Test + fun aFreshConversationOpensAtItsNewestMessage() { + // No position of the operator's own: land on the last message. + assertTrue(chatOpensAtNewest(null)) + assertEquals( + ChatScrollPosition(index = 6, offset = 0), + chatFirstScroll(null, itemCount = 7), + ) + } + + @Test + fun aSavedPositionAtTheVeryTopIsRestoredRatherThanTreatedAsNew() { + // A position the operator deliberately left, even at the top, is a position: + // only the absence of one opens at the newest message. + assertFalse(chatOpensAtNewest(ChatScrollPosition(0, 0))) + assertEquals( + ChatScrollPosition(index = 0, offset = 0), + chatFirstScroll(ChatScrollPosition(0, 0), itemCount = 7), + ) + } + + @Test + fun aPositionTheOperatorLeftIsRestoredAndClampedToTheMessagesThatRemain() { + // Still in range: restored exactly. + assertFalse(chatOpensAtNewest(ChatScrollPosition(index = 2, offset = 30))) + assertEquals( + ChatScrollPosition(index = 2, offset = 30), + chatFirstScroll(ChatScrollPosition(index = 2, offset = 30), itemCount = 9), + ) + // The conversation shrank underneath: the index clamps to its last message + // and the offset is dropped, as every other restored list does, because the + // clamped index points at a different message. + assertEquals( + ChatScrollPosition(index = 4, offset = 0), + chatFirstScroll(ChatScrollPosition(index = 7, offset = 30), itemCount = 5), + ) + } + + @Test + fun anEmptyConversationHasNothingToPlace() { + assertEquals( + ChatScrollPosition(), + chatFirstScroll(ChatScrollPosition(index = 7, offset = 30), itemCount = 0), + ) + } +} diff --git a/android/app/src/test/java/net/awan/pipelines/ui/chat/MultiChatStateTest.kt b/android/app/src/test/java/net/awan/pipelines/ui/chat/MultiChatStateTest.kt index ae520bd6..eaf2bfa1 100644 --- a/android/app/src/test/java/net/awan/pipelines/ui/chat/MultiChatStateTest.kt +++ b/android/app/src/test/java/net/awan/pipelines/ui/chat/MultiChatStateTest.kt @@ -9,6 +9,7 @@ import net.awan.pipelines.data.protocol.ChatSession import org.junit.Assert.assertEquals import org.junit.Assert.assertFalse import org.junit.Assert.assertNotNull +import org.junit.Assert.assertNull import org.junit.Assert.assertTrue import org.junit.Test @@ -101,6 +102,10 @@ class MultiChatStateTest { val store = ChatStore() store.open(session("a")) store.open(session("b")) + // A conversation the operator has not left a position in has none, which is + // distinct from leaving it at the top: that is what opens a chat at its + // newest message. + assertNull(store.value.thread("a")!!.scroll) store.scroll("a", 7, 12) store.scroll("b", 1, 0) assertEquals(ChatScrollPosition(7, 12), store.value.thread("a")!!.scroll)