android: one chat poller owned by the ViewModel, gated auto-scroll, Enter-to-send

The chat screen owned a LaunchedEffect(Unit) that fetched maxAttempts once and
then called loadMessages/loadOutbox every 2s forever, fed by three suspend
lambdas from MainActivity — one SDK poller per composition. The cadence now
lives in WireViewModel: openChat(peer) starts one 2s loop in viewModelScope
(closeChat stops it, re-entering the same peer is a no-op), exposed as
ChatState(messages, outbox, maxAttempts, error) and collected with
collectAsStateWithLifecycle. Same 2s cadence, maxAttempts read once, messages
and outbox refreshed together, load failures sticky on ChatState.error, and
the QUEUED notice unchanged; a send clears the load error.

Auto-scroll no longer steals the reader's place: the tail is followed only when
the last visible index is >= count - 2 (or the list has not filled yet), while
the user's own send still scrolls their message into view. The first fill keeps
its one jump to the bottom. A delivery-only change (same size) still does not
re-run the effect — documented in a comment rather than changed.

The composer keeps ImeAction.Send with maxLines = 4, documented as a deliberate
wrap limit rather than a newline affordance: the action key sends (hardware
Enter still inserts a newline inside the field).

No polling LaunchedEffect remains in ChatScreen.kt.
This commit is contained in:
agent 2026-09-14 02:53:54 -04:00
commit 04c993862c
No known key found for this signature in database
3 changed files with 198 additions and 41 deletions

View file

@ -143,15 +143,13 @@ private fun ReadyGraph(vm: WireViewModel, ready: Phase.Ready, keepAliveNote: Str
val pk = entry.arguments?.getString("pk").orEmpty()
val friend = friends.firstOrNull { it.pubkeyHex == pk }
ChatScreen(
vm = vm,
peer = pk,
title = friend?.petname?.takeIf { it.isNotBlank() }
?: friend?.fingerprint
?: pk.take(16),
fingerprint = friend?.fingerprint ?: pk.take(16),
onion = friend?.onion.orEmpty(),
loadMessages = { vm.messages(pk) },
loadOutbox = { vm.outbox(pk) },
loadMaxAttempts = { vm.outboxMaxAttempts() },
onSend = { body -> vm.send(pk, body) },
onBack = { nav.popBackStack() },
)
}

View file

@ -12,9 +12,14 @@ import com.siriusdevops.onionwire.keepalive.KeepAliveService
import com.siriusdevops.onionwire.keepalive.KeepAliveStatus
import com.siriusdevops.onionwire.keepalive.NodeHost
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.Job
import kotlinx.coroutines.currentCoroutineContext
import kotlinx.coroutines.delay
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.asStateFlow
import kotlinx.coroutines.flow.update
import kotlinx.coroutines.isActive
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import uniffi.onionwire_sdk.ChatMessage
@ -61,6 +66,22 @@ sealed interface Unlock {
data class OneTap(val backing: KeyBacking) : Unlock
}
/**
* Everything one open chat screen renders, refreshed on a single cadence.
*
* [messages] is null until the first read lands — the screen shows its spinner
* on that, exactly as it did reading the SDK itself. [error] is the last load
* failure and is sticky on purpose: it survives the ticks that succeed, so a
* transient store error is still on screen after the next 2s tick rather than
* blinking away. A send clears it (the user has acted on it).
*/
data class ChatState(
val messages: List<ChatMessage>? = null,
val outbox: List<OutboxRow> = emptyList(),
val maxAttempts: UInt? = null,
val error: String? = null,
)
/**
* Owns the UI side of the process's single node.
*
@ -101,6 +122,22 @@ class WireViewModel(app: Application) : AndroidViewModel(app) {
private val _keepAliveNote = MutableStateFlow<String?>(null)
val keepAliveNote: StateFlow<String?> = _keepAliveNote.asStateFlow()
/**
* The currently open chat, or null when no chat screen is composed.
*
* There is exactly one node and one chat on screen at a time, so this is
* one state object rather than a map keyed by peer: a second poller for a
* second peer would double the SDK traffic for a screen nobody is looking
* at, and the node's store reads are not free.
*/
private val _chat = MutableStateFlow<ChatState?>(null)
val chat: StateFlow<ChatState?> = _chat.asStateFlow()
/** The peer [chat] belongs to; guards a stale tick from a previous peer. */
private var chatPeer: String? = null
private var chatPoller: Job? = null
init {
// A node the foreground service kept alive is still open. Adopt it and
// go straight to the roster: showing an unlock screen for a store that
@ -177,6 +214,10 @@ class WireViewModel(app: Application) : AndroidViewModel(app) {
*/
fun lock() {
if (NodeHost.current() == null) return
// Stop the chat tick before the node goes: the next read of a closed
// store would surface as a chat load error on a screen the user has
// already left, and every tick would keep re-reporting it.
stopChatPoller()
KeepAliveService.stop(getApplication())
NodeHost.lock()
_friends.value = emptyList()
@ -381,6 +422,87 @@ class WireViewModel(app: Application) : AndroidViewModel(app) {
*/
suspend fun outboxMaxAttempts(): UInt = uniffi.onionwire_sdk.outboxMaxAttempts()
/**
* Starts the one 2s refresh loop for [pubkeyHex] and resets the chat state.
*
* Called from the chat screen entering the composition. Re-entering the
* same peer while its poller is alive is a no-op — navigating to the chat
* and back must never stack a second loop on top of the first.
*/
fun openChat(pubkeyHex: String) {
if (chatPeer == pubkeyHex && chatPoller?.isActive == true) return
chatPoller?.cancel()
chatPeer = pubkeyHex
_chat.value = ChatState()
chatPoller = viewModelScope.launch { pollChat(pubkeyHex) }
}
/**
* Stops the loop when the chat screen leaves. Ignored when another peer has
* taken over in the meantime (navigating chat A → chat B disposes A after B
* has already opened).
*/
fun closeChat(pubkeyHex: String) {
if (chatPeer != pubkeyHex) return
stopChatPoller()
}
private fun stopChatPoller() {
chatPoller?.cancel()
chatPoller = null
chatPeer = null
_chat.value = null
}
/**
* Drops the last load error. The send path calls this: the user has acted,
* so a stale "could not read" line must not sit under the composer while
* the send is in flight.
*/
fun clearChatError() {
_chat.update { it?.copy(error = null) }
}
/**
* The cadence, in the ViewModel: inbound messages are appended by the node
* in the background and the retry worker moves queued rows along, and in v1
* there is no push channel into the UI, so messages and outbox are read
* together on one 2s tick. The outbox rows are read on that tick too —
* their `next_attempt_at` is a fixed instant, so a row saying "retry 45s"
* turns into "retry now" here without the store having to change.
*
* The retry budget is read once per open chat (it is a constant of the
* outbox, not per-peer state); a failure leaves it null and the rows fall
* back to the flat marker.
*/
private suspend fun pollChat(pk: String) {
runCatching { outboxMaxAttempts() }.onSuccess { budget ->
if (chatPeer == pk) _chat.update { it?.copy(maxAttempts = budget) }
}
while (currentCoroutineContext().isActive) {
val loaded = runCatching { messages(pk) }
val out = runCatching { outbox(pk) }
// A cancelled loop can still be sitting in a completed SDK read:
// writing that peer's rows into a state that now belongs to another
// peer would show the wrong conversation.
if (chatPeer != pk) return
_chat.update { state ->
val base = state ?: ChatState()
base.copy(
messages = loaded.getOrNull() ?: base.messages,
outbox = out.getOrNull() ?: base.outbox,
// Same order the screen's own loop reported them in, and
// sticky on success — a new failure replaces the last one,
// a successful tick does not clear the last one.
error = out.exceptionOrNull()?.let { it.message ?: it.toString() }
?: loaded.exceptionOrNull()?.let { it.message ?: it.toString() }
?: base.error,
)
}
delay(2_000)
}
}
/**
* Sends one chat message and reports what the core did with it.
*

View file

@ -34,6 +34,7 @@ import androidx.compose.material3.Text
import androidx.compose.material3.TopAppBar
import androidx.compose.material3.TopAppBarDefaults
import androidx.compose.runtime.Composable
import androidx.compose.runtime.DisposableEffect
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
@ -50,21 +51,19 @@ import androidx.compose.ui.text.font.FontFamily
import androidx.compose.ui.text.input.ImeAction
import androidx.compose.ui.text.input.KeyboardCapitalization
import androidx.compose.ui.unit.dp
import kotlinx.coroutines.delay
import uniffi.onionwire_sdk.ChatMessage
import uniffi.onionwire_sdk.OutboxRow
import androidx.lifecycle.compose.collectAsStateWithLifecycle
import com.siriusdevops.onionwire.WireViewModel
import uniffi.onionwire_sdk.SendState
@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun ChatScreen(
vm: WireViewModel,
/** The peer's ed25519 pubkey hex — the key the open chat's poller runs for. */
peer: String,
title: String,
fingerprint: String,
onion: String,
loadMessages: suspend () -> List<ChatMessage>,
loadOutbox: suspend () -> List<OutboxRow>,
loadMaxAttempts: suspend () -> UInt,
onSend: suspend (String) -> SendState,
onBack: () -> Unit,
/**
* Wall clock in unix seconds. `next_attempt_at` is absolute, so the
@ -73,17 +72,32 @@ fun ChatScreen(
*/
nowSeconds: () -> Long = { System.currentTimeMillis() / 1_000L },
) {
var messages by remember { mutableStateOf<List<ChatMessage>?>(null) }
var outbox by remember { mutableStateOf<List<OutboxRow>>(emptyList()) }
// The core's retry budget, fetched once: `try 3/8` renders against this and
// never against a constant in the app.
var maxAttempts by remember { mutableStateOf<UInt?>(null) }
// The refresh cadence lives in the ViewModel: one poller per open chat, not
// one per composition. Collecting here means a re-composition (or a
// configuration change) does not start a second loop against the SDK.
val chat by vm.chat.collectAsStateWithLifecycle()
val messages = chat?.messages
val outbox = chat?.outbox.orEmpty()
// The core's retry budget, fetched once per open chat: `try 3/8` renders
// against this and never against a constant in the app.
val maxAttempts = chat?.maxAttempts
var draft by remember { mutableStateOf("") }
var pending by remember { mutableStateOf<String?>(null) }
var error by remember { mutableStateOf<String?>(null) }
// Send-path failures are the screen's own state; load failures come back on
// [ChatState.error]. Both render in the same place under the list.
var sendError by remember { mutableStateOf<String?>(null) }
var notice by remember { mutableStateOf<String?>(null) }
val error = sendError ?: chat?.error
val listState = rememberLazyListState()
// Auto-scroll bookkeeping. `firstFillDone` keeps the one-jump-to-the-bottom
// on the first load (and again after leaving and re-entering the chat);
// `ownSendPending` is the user's own message asking for the list to follow
// even though they may have scrolled up in history.
var firstFillDone by remember { mutableStateOf(false) }
var ownSendPending by remember { mutableStateOf(false) }
// The composer is the only place a message can be sent from, so after a
// send the keyboard is left up and the caret goes back into the field —
// the next message is one keystroke away instead of a re-tap.
@ -92,27 +106,19 @@ fun ChatScreen(
if (draft.isNotBlank() && pending == null) {
pending = draft
draft = ""
// The user's own message is the one case where the list is allowed
// to move while they are scrolled up in history.
ownSendPending = true
inputFocus.requestFocus()
}
}
// Poll: the node appends inbound messages in the background and the retry
// worker moves queued rows along; there is no push channel into the UI in
// v1, so the delivery markers refresh on the same cadence as the bodies.
// The outbox rows are read on that cadence too — their `next_attempt_at` is
// a fixed instant, so a row saying "retry 45s" turns into "retry now" here
// without the store having to change.
LaunchedEffect(Unit) {
runCatching { loadMaxAttempts() }.onSuccess { maxAttempts = it }
while (true) {
runCatching { loadMessages() }
.onSuccess { messages = it }
.onFailure { error = it.message ?: it.toString() }
runCatching { loadOutbox() }
.onSuccess { outbox = it }
.onFailure { error = it.message ?: it.toString() }
delay(2_000)
}
// The poller's lifetime is the chat screen's: entering starts it, leaving
// stops it, and re-entering the same peer is a no-op in the ViewModel, so
// there is exactly one loop no matter how the nav stack is walked.
DisposableEffect(peer) {
vm.openChat(peer)
onDispose { vm.closeChat(peer) }
}
// Send. An unreachable peer's onion is not an error any more: the core
@ -122,22 +128,45 @@ fun ChatScreen(
// queued for those.
LaunchedEffect(pending) {
val body = pending ?: return@LaunchedEffect
error = null
sendError = null
notice = null
runCatching { onSend(body) }
// The user has acted on whatever the poller last reported.
vm.clearChatError()
runCatching { vm.send(peer, body) }
.onSuccess {
if (it == SendState.QUEUED) {
notice = "Queued: their onion is unreachable. The message stays on " +
"this device and is retried until it lands."
}
}
.onFailure { error = it.message ?: it.toString() }
.onFailure { sendError = it.message ?: it.toString() }
pending = null
}
// Known and accepted: this is keyed on the message count, so a delivery-only
// change (a row flipping `queued` → `sent`, same size, different marker)
// does not re-run it. That has always been the behaviour here and it is the
// safe one — the list never moves for a marker.
LaunchedEffect(messages?.size) {
val n = messages?.size ?: 0
if (n > 0) listState.animateScrollToItem(n - 1)
if (n == 0) return@LaunchedEffect
if (!firstFillDone) {
// First load: one jump to the bottom so the newest message is the
// one on screen, without an animation nobody asked for.
listState.scrollToItem(n - 1)
firstFillDone = true
return@LaunchedEffect
}
// Follow the tail only when the reader is already there. `n - 2`
// rather than `!canScrollForward`: the append has already made the list
// scrollable by the time this runs, so "can I scroll further" is true
// even for someone who was glued to the bottom a frame ago — and
// `lastVisible >= n - 2` tolerates the last row being partly on screen.
val lastVisible = listState.layoutInfo.visibleItemsInfo.lastOrNull()?.index ?: -1
if (ownSendPending || lastVisible >= n - 2) {
listState.animateScrollToItem(n - 1)
}
ownSendPending = false
}
Scaffold(
@ -332,9 +361,17 @@ fun ChatScreen(
.testTag("chat-input"),
maxLines = 4,
label = { Text("message") },
// The IME gets its own send affordance: on a phone in
// landscape, or with the keyboard covering the button, the
// action key is the shortest path to sending.
// DECISION (item 3 of the follow-up card): the IME's action
// key sends; the soft keyboard cannot insert a manual
// newline. `ImeAction.Send` and `maxLines = 4` are not in
// conflict — `maxLines` is a wrap limit (a long message
// grows to four lines, then scrolls inside the field), not
// a newline affordance. Chat convention wins: Enter-to-send
// is what a messenger's users reach for, and the Send button
// is on the same row. Nothing is unreachable either — a
// hardware keyboard's Enter never goes through the IME
// action, so Shift+Enter still inserts a real newline in
// the field.
keyboardOptions = KeyboardOptions(
capitalization = KeyboardCapitalization.Sentences,
imeAction = ImeAction.Send,