feat(android): surface outbox delivery state in chat

Renders the core's own Queued/Sending/Sent/Failed per outgoing row instead of
implying a message either sent or did not: a clock for queued, a progress
spinner for sending, a double-check for delivered and an error marker with the
short reason for a terminal failure, plus a chat-level `N queued` footer that
keeps a fail-closed `send failed: <reason>` statement on screen.

States are read verbatim from ChatMessage.delivery (Node::outbox_status_of_message
over UniFFI) — no parallel enum, nothing guessed from a timeout. A missing or
unrecognised status renders as queued, never delivered.

WireViewModel.send() now returns the SDK SendState instead of dropping it, so the
composer can say a send is queued rather than pretend it landed, and the empty-chat
copy no longer claims 'there is no outbox in v1'.

Accessibility: every marker carries an explicit contentDescription sentence and a
test tag; the glyph is never what a screen reader announces.
This commit is contained in:
apk-dev 2026-09-12 16:02:54 -04:00 • committed by agent
commit 3106562040
No known key found for this signature in database
4 changed files with 482 additions and 21 deletions

View file

@ -21,6 +21,7 @@ import uniffi.onionwire_sdk.ChatMessage
import uniffi.onionwire_sdk.FriendInfo
import uniffi.onionwire_sdk.InviteInfo
import uniffi.onionwire_sdk.RotateOutcome
import uniffi.onionwire_sdk.SendState
import uniffi.onionwire_sdk.Wire
import uniffi.onionwire_sdk.decodeInvite
import java.io.File
@ -361,7 +362,16 @@ class WireViewModel(app: Application) : AndroidViewModel(app) {
suspend fun messages(pubkeyHex: String): List<ChatMessage> =
requireWire().messages(pubkeyHex)
suspend fun send(pubkeyHex: String, body: String) =
/**
* Sends one chat message and reports what the core did with it.
*
* `SENT` — the peer's onion took the frame during this call. `QUEUED` — it
* was unreachable, so the message is in the local outbox and the retry
* worker will dial again with backoff until it lands or fails terminally.
* The state is returned rather than swallowed so the UI never shows a
* queued message as delivered.
*/
suspend fun send(pubkeyHex: String, body: String): SendState =
requireWire().send(pubkeyHex, body)
suspend fun wipeMessages() {

View file

@ -10,6 +10,7 @@ import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.items
@ -33,10 +34,14 @@ import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.platform.testTag
import androidx.compose.ui.semantics.contentDescription
import androidx.compose.ui.semantics.semantics
import androidx.compose.ui.text.font.FontFamily
import androidx.compose.ui.unit.dp
import kotlinx.coroutines.delay
import uniffi.onionwire_sdk.ChatMessage
import uniffi.onionwire_sdk.SendState
@OptIn(ExperimentalMaterial3Api::class)
@Composable
@ -45,17 +50,19 @@ fun ChatScreen(
fingerprint: String,
onion: String,
loadMessages: suspend () -> List<ChatMessage>,
onSend: suspend (String) -> Unit,
onSend: suspend (String) -> SendState,
onBack: () -> Unit,
) {
var messages by remember { mutableStateOf<List<ChatMessage>?>(null) }
var draft by remember { mutableStateOf("") }
var pending by remember { mutableStateOf<String?>(null) }
var error by remember { mutableStateOf<String?>(null) }
var notice by remember { mutableStateOf<String?>(null) }
val listState = rememberLazyListState()
// Poll: the node appends inbound messages in the background; there is no
// push channel into the UI in v1.
// 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.
LaunchedEffect(Unit) {
while (true) {
runCatching { loadMessages() }
@ -65,12 +72,22 @@ fun ChatScreen(
}
}
// Fail-closed send. `send` retries the peer's onion for up to 3 minutes and
// then errors — nothing is spooled, so a failure is a real failure.
// Send. An unreachable peer's onion is not an error any more: the core
// stores the message in its local outbox and the retry worker dials again
// with backoff (30s doubling, capped at 30 min, 8 attempts, then terminal
// `failed`). A protocol error is still a real failure here — nothing is
// queued for those.
LaunchedEffect(pending) {
val body = pending ?: return@LaunchedEffect
error = null
notice = null
runCatching { onSend(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() }
pending = null
}
@ -127,8 +144,11 @@ fun ChatScreen(
Text("No messages", style = MaterialTheme.typography.titleSmall)
Spacer(Modifier.height(6.dp))
Text(
"Sends fail closed: if their onion is down the message is " +
"not spooled anywhere. There is no outbox in v1.",
"If their onion is unreachable the message is queued in a " +
"local outbox on this device and retried with backoff " +
"(30s doubling, up to 30 min, 8 attempts) — never handed " +
"to a third party. A queued message is local-only until " +
"their onion takes it.",
style = MaterialTheme.typography.bodySmall,
color = MaterialTheme.colorScheme.onSurfaceVariant,
)
@ -149,25 +169,59 @@ fun ChatScreen(
horizontalArrangement =
if (mine) Arrangement.End else Arrangement.Start,
) {
Text(
m.body,
style = MaterialTheme.typography.bodyMedium,
color = if (mine) MaterialTheme.colorScheme.onPrimary
else MaterialTheme.colorScheme.onSurface,
modifier = Modifier
.background(
if (mine) MaterialTheme.colorScheme.primary
else MaterialTheme.colorScheme.surfaceVariant,
RoundedCornerShape(10.dp),
)
.padding(horizontal = 10.dp, vertical = 8.dp),
)
Column(
horizontalAlignment = if (mine) Alignment.End
else Alignment.Start,
) {
Text(
m.body,
style = MaterialTheme.typography.bodyMedium,
color = if (mine) MaterialTheme.colorScheme.onPrimary
else MaterialTheme.colorScheme.onSurface,
modifier = Modifier
.background(
if (mine) MaterialTheme.colorScheme.primary
else MaterialTheme.colorScheme.surfaceVariant,
RoundedCornerShape(10.dp),
)
.padding(horizontal = 10.dp, vertical = 8.dp),
)
parseDelivery(m.direction, m.delivery)?.let { d ->
DeliveryMarker(d)
}
}
}
}
}
}
}
// Chat-level outbox state: what is still coming, and whether
// anything has terminated as failed.
val summary = outboxSummary(
messages.orEmpty().map { parseDelivery(it.direction, it.delivery) },
)
summary.note?.let { note ->
Text(
note,
style = MaterialTheme.typography.labelSmall,
color = if (summary.hasFailures) MaterialTheme.colorScheme.error
else MaterialTheme.colorScheme.onSurfaceVariant,
modifier = Modifier
.padding(horizontal = 12.dp, vertical = 2.dp)
.testTag("outbox-summary"),
)
}
notice?.let {
Text(
it,
style = MaterialTheme.typography.bodySmall,
color = MaterialTheme.colorScheme.onSurfaceVariant,
modifier = Modifier.padding(horizontal = 12.dp, vertical = 4.dp),
)
}
error?.let {
Text(
it,
@ -204,3 +258,44 @@ fun ChatScreen(
}
}
}
/**
* One message's delivery marker, straight from the core's outbox state.
*
* The row carries an explicit [Delivery.contentDescription] so a screen reader
* announces "Queued, not delivered yet" instead of reading a clock glyph, and a
* [Delivery.testTag] so a UI test can find the state without depending on the
* glyph. `send` shows a small indeterminate spinner while the worker has an
* attempt in flight.
*/
@Composable
private fun DeliveryMarker(d: Delivery) {
val tint = when (d) {
is Delivery.Failed -> MaterialTheme.colorScheme.error
Delivery.Sent -> MaterialTheme.colorScheme.onSurfaceVariant
else -> MaterialTheme.colorScheme.primary
}
Row(
verticalAlignment = Alignment.CenterVertically,
modifier = Modifier
.padding(horizontal = 4.dp, vertical = 1.dp)
.testTag(d.testTag)
.semantics(mergeDescendants = true) {
contentDescription = d.contentDescription
},
) {
if (d is Delivery.Sending) {
CircularProgressIndicator(
modifier = Modifier.size(10.dp),
strokeWidth = 1.5.dp,
color = tint,
)
Spacer(Modifier.width(4.dp))
}
Text(
d.marker,
style = MaterialTheme.typography.labelSmall,
color = tint,
)
}
}

View file

@ -0,0 +1,176 @@
package com.siriusdevops.onionwire.ui
/**
* Delivery state of one outgoing chat row.
*
* The states are the core's own — `Queued` / `Sending` / `Sent` / `Failed`
* (`src/store.rs::OutboxStatus`), surfaced verbatim over UniFFI as
* `ChatMessage.delivery` (`crates/onionwire-sdk/src/lib.rs::delivery_of`, fed by
* `Node::outbox_status_of_message`). There is no parallel model here and nothing
* is inferred from a timeout: if the state is not in that string it is not
* rendered.
*
* [testTag] and [contentDescription] are the assertable handles: the Composable
* applies exactly these values, and `MessageDeliveryTest` asserts on them, so a
* change to the marker without a change to the announcement fails a test.
* A screen reader must never be left hearing a bare glyph like "clock" — that is
* why every state carries a sentence.
*/
sealed interface Delivery {
/** Stable handle for Compose semantics and tests. */
val testTag: String
/** What a screen reader announces. Always a sentence, never a glyph. */
val contentDescription: String
/** Marker drawn next to the message body. */
val glyph: String
/** Short text drawn after the glyph. Empty for a wordless state. */
val label: String
/** The frame reached the peer's onion during the send call. */
data object Sent : Delivery {
override val testTag: String = "delivery-sent"
override val contentDescription: String = "Delivered"
override val glyph: String = "✓✓"
override val label: String = ""
}
/**
* The peer's onion was unreachable: the message is in the local outbox and
* the retry worker will dial again with backoff. Local-only — not delivered.
*/
data object Queued : Delivery {
override val testTag: String = "delivery-queued"
override val contentDescription: String =
"Queued, not delivered yet: retrying their onion"
override val glyph: String = "◷"
override val label: String = "queued"
}
/** The worker has a delivery attempt in flight right now. */
data object Sending : Delivery {
override val testTag: String = "delivery-sending"
override val contentDescription: String = "Sending"
override val glyph: String = "»"
override val label: String = "sending"
}
/** Terminal: retries are exhausted or the failure cannot be retried. */
data class Failed(val reason: String) : Delivery {
override val testTag: String = "delivery-failed"
override val contentDescription: String = "Failed: $reason"
override val glyph: String = "✗"
override val label: String = "failed: $reason"
}
/** `"◷ queued"`, `"✓✓"`, `"✗ failed: no route"` — the row's marker text. */
val marker: String
get() = if (label.isEmpty()) glyph else "$glyph $label"
}
/** Longest short-form failure reason rendered in a chat row. Mirrors
* `src/tui.rs::FAIL_REASON_BUDGET` so both clients cut the same way. */
const val FAIL_REASON_BUDGET: Int = 24
private val STRIPPED: CharRange = '\u0000'..'\u001f'
private val STRIPPED_C1: CharRange = '\u007f'..'\u009f'
/** C0/C1 controls and bidi/format marks — mirrors `src/sanitize.rs`. */
internal fun isControlOrBidi(c: Char): Boolean =
c in STRIPPED || c in STRIPPED_C1 ||
c in '\u202a'..'\u202e' || c in '\u2066'..'\u2069' ||
c == '\u200e' || c == '\u200f' || c == '\u200b' || c == '\u200c'
/**
* Transport failure text, short form: sanitized, tail of the `a: b: c` chain,
* capped at [budget] cells so one peer's error cannot blow out the row.
* Mirrors `src/tui.rs::short_send_reason`.
*/
fun shortSendReason(why: String, budget: Int = FAIL_REASON_BUDGET): String {
val clean = why.filterNot(::isControlOrBidi)
val tail = clean.split(": ").lastOrNull().orEmpty().trim()
val text = tail.ifEmpty { clean.trim() }
if (text.length <= budget) return text
if (budget <= 1) return "…".take(budget)
return text.take(budget - 1) + "…"
}
/**
* Maps one history row onto a [Delivery], or `null` for anything that is not an
* outgoing message.
*
* [delivery] is `ChatMessage.delivery`: `"sent"`, `"queued"`, `"sending"`,
* `"failed: <reason>"`, or `null` for inbound rows. The SDK already resolves an
* outgoing row with no outbox row to `"sent"` (it was accepted on the first
* attempt), so a *missing* value on an outgoing row means the core did not
* confirm anything — and that is reported as [Delivery.Queued], never as
* delivered. Same rule for a status this build does not recognise: the only
* direction that cannot lie is "not confirmed delivered yet".
*/
fun parseDelivery(direction: String, delivery: String?): Delivery? {
if (direction != "out") return null
return when (val raw = delivery?.trim().orEmpty()) {
"" -> Delivery.Queued
"sent" -> Delivery.Sent
"sending" -> Delivery.Sending
"queued" -> Delivery.Queued
else ->
if (raw.startsWith("failed")) {
val why = raw.substringAfter(':', "").trim().ifEmpty { "unknown" }
Delivery.Failed(shortSendReason(why))
} else {
Delivery.Queued
}
}
}
/**
* Chat-level delivery summary derived from the rendered rows.
*
* Mirrors `src/tui.rs::OutboxSummary`: `Queued` + `Sending` are "still coming",
* `Failed` is terminal and keeps a fail-closed statement on screen.
*/
data class OutboxSummary(
val queued: Int = 0,
val failed: Int = 0,
val firstError: String? = null,
) {
/** Footer note, or `null` when nothing is outstanding. */
val note: String?
get() {
val reason = shortSendReason(firstError ?: "unknown")
return when {
queued == 0 && failed == 0 -> null
failed == 0 -> "$queued queued"
queued == 0 && failed == 1 -> "send failed: $reason"
queued == 0 -> "send failed: $reason ($failed failed)"
else -> "$queued queued, send failed: $reason"
}
}
/** `true` when at least one send has terminated as failed. */
val hasFailures: Boolean get() = failed > 0
}
/** Summarizes the rows currently on screen. */
fun outboxSummary(deliveries: Iterable<Delivery?>): OutboxSummary {
var queued = 0
var failed = 0
var firstError: String? = null
for (d in deliveries) {
when (d) {
null, Delivery.Sent -> Unit
is Delivery.Failed -> {
failed++
if (firstError == null) firstError = d.reason
}
Delivery.Queued, Delivery.Sending -> queued++
}
}
return OutboxSummary(queued = queued, failed = failed, firstError = firstError)
}

View file

@ -0,0 +1,180 @@
package com.siriusdevops.onionwire.ui
import org.junit.Assert.assertEquals
import org.junit.Assert.assertFalse
import org.junit.Assert.assertNull
import org.junit.Assert.assertTrue
import org.junit.Test
/**
* Renders each of the four core outbox states and asserts the semantic the
* Composable applies for it — the same `testTag` / `contentDescription` values
* `ChatScreen`'s delivery row uses, so a marker change without an announcement
* change fails here.
*
* `compose.ui.test` is not on the JVM unit-test classpath (and adding it is
* outside this card's scope), so the assertion target is the state model that
* the Composable renders from, not a laid-out node. Same shape as
* `InviteAddFlowTest`.
*/
class MessageDeliveryTest {
private val glyphs = listOf("✓", "◷", "»", "✗")
private fun out(delivery: String?) = parseDelivery("out", delivery)
@Test
fun every_core_state_is_rendered_with_its_own_handle_and_sentence() {
val sent = requireNotNull(out("sent"))
val queued = requireNotNull(out("queued"))
val sending = requireNotNull(out("sending"))
val failed = requireNotNull(out("failed: connection timed out"))
assertEquals(Delivery.Sent, sent)
assertEquals(Delivery.Queued, queued)
assertEquals(Delivery.Sending, sending)
assertEquals(Delivery.Failed("connection timed out"), failed)
assertEquals("delivery-sent", sent.testTag)
assertEquals("delivery-queued", queued.testTag)
assertEquals("delivery-sending", sending.testTag)
assertEquals("delivery-failed", failed.testTag)
assertEquals("Delivered", sent.contentDescription)
assertEquals("Queued, not delivered yet: retrying their onion", queued.contentDescription)
assertEquals("Sending", sending.contentDescription)
assertEquals("Failed: connection timed out", failed.contentDescription)
// Four states, four distinct handles and four distinct sentences.
val all = listOf(sent, queued, sending, failed)
assertEquals(4, all.map { it.testTag }.toSet().size)
assertEquals(4, all.map { it.contentDescription }.toSet().size)
}
@Test
fun markers_are_visually_distinct_per_state() {
assertEquals("✓✓", Delivery.Sent.marker)
assertEquals("◷ queued", Delivery.Queued.marker)
assertEquals("» sending", Delivery.Sending.marker)
assertEquals("✗ failed: no route", Delivery.Failed("no route").marker)
val all = listOf(
Delivery.Sent.marker,
Delivery.Queued.marker,
Delivery.Sending.marker,
Delivery.Failed("no route").marker,
)
assertEquals(4, all.toSet().size)
}
@Test
fun every_state_announces_words_not_a_bare_glyph() {
val all = listOf(
Delivery.Sent,
Delivery.Queued,
Delivery.Sending,
Delivery.Failed("no route"),
)
for (d in all) {
for (glyph in glyphs) {
assertFalse(
"${d.testTag} announces a glyph: ${d.contentDescription}",
d.contentDescription.contains(glyph),
)
}
assertTrue(
"${d.testTag} must announce words, not an icon name: ${d.contentDescription}",
d.contentDescription.length >= 7 && d.contentDescription.any { it.isLetter() },
)
}
}
@Test
fun failed_reason_is_sanitized_tailed_and_capped_like_the_tui() {
// C0 controls and bidi marks are stripped.
assertEquals("badsignature", shortSendReason("bad\u0007\u202esignature"))
// Tail of the `a: b: c` chain.
assertEquals(
"connection timed out",
shortSendReason("dial 7f4k.onion: onion: connection timed out"),
)
// Capped at the row budget, with the ellipsis inside it.
val long = "x".repeat(80)
val cut = shortSendReason(long)
assertEquals(FAIL_REASON_BUDGET, cut.length)
assertTrue(cut.endsWith("…"))
assertEquals(long, shortSendReason(long, budget = 80))
}
@Test
fun an_unrecognised_status_is_queued_never_delivered() {
// A status this build does not know must not read as delivered.
assertEquals(Delivery.Queued, out("spooling"))
assertEquals(Delivery.Queued, out("SENDING"))
}
@Test
fun a_missing_delivery_on_an_outgoing_row_is_not_called_delivered() {
// The SDK reports "sent" explicitly for an outgoing row with no outbox
// row, so a missing value means nothing was confirmed.
assertEquals(Delivery.Queued, out(null))
assertEquals(Delivery.Queued, out(" "))
}
@Test
fun the_core_reporting_sent_is_the_only_way_to_render_delivered() {
assertEquals(Delivery.Sent, out("sent"))
assertEquals(Delivery.Sent, out(" sent "))
}
@Test
fun inbound_rows_carry_no_delivery_state() {
assertNull(parseDelivery("in", null))
assertNull(parseDelivery("in", "sent"))
}
@Test
fun blank_failure_reason_still_says_failed() {
val d = out("failed:") as Delivery.Failed
assertEquals("unknown", d.reason)
assertEquals("Failed: unknown", d.contentDescription)
}
@Test
fun footer_reports_pending_sends_and_keeps_a_failure_statement() {
// Nothing outstanding: no note at all.
assertNull(outboxSummary(listOf(Delivery.Sent, null)).note)
// Anything still coming is counted, queued and sending alike.
assertEquals(
"2 queued",
outboxSummary(listOf(Delivery.Queued, Delivery.Sending, Delivery.Sent)).note,
)
// A terminal failure is stated, not hidden behind the queue count.
val withFailure = outboxSummary(listOf(Delivery.Queued, Delivery.Failed("no route")))
assertEquals(1, withFailure.queued)
assertEquals(1, withFailure.failed)
assertTrue(withFailure.hasFailures)
assertEquals("1 queued, send failed: no route", withFailure.note)
// No queue, one failure.
assertEquals(
"send failed: no route",
outboxSummary(listOf(Delivery.Failed("no route"))).note,
)
// No queue, several failures: first reason plus how many.
assertEquals(
"send failed: no route (3 failed)",
outboxSummary(
listOf(
Delivery.Failed("no route"),
Delivery.Failed("timeout"),
Delivery.Failed("bad identity"),
),
).note,
)
// Nothing pending and nothing failed: silent.
assertFalse(outboxSummary(listOf(Delivery.Sent)).hasFailures)
}
}