feat(sdk): expose outbox rows (attempts + next attempt time) behind a queued chat message #58

Merged
sirius merged 3 commits from feat/sdk-outbox-rows into feat/android-outbox-state 2026-09-12 23:58:01 +00:00
6 changed files with 725 additions and 20 deletions

View file

@ -143,6 +143,8 @@ private fun ReadyGraph(vm: WireViewModel, ready: Phase.Ready, keepAliveNote: Str
fingerprint = friend?.fingerprint ?: pk.take(16), fingerprint = friend?.fingerprint ?: pk.take(16),
onion = friend?.onion.orEmpty(), onion = friend?.onion.orEmpty(),
loadMessages = { vm.messages(pk) }, loadMessages = { vm.messages(pk) },
loadOutbox = { vm.outbox(pk) },
loadMaxAttempts = { vm.outboxMaxAttempts() },
onSend = { body -> vm.send(pk, body) }, onSend = { body -> vm.send(pk, body) },
onBack = { nav.popBackStack() }, onBack = { nav.popBackStack() },
) )

View file

@ -20,6 +20,7 @@ import kotlinx.coroutines.withContext
import uniffi.onionwire_sdk.ChatMessage import uniffi.onionwire_sdk.ChatMessage
import uniffi.onionwire_sdk.FriendInfo import uniffi.onionwire_sdk.FriendInfo
import uniffi.onionwire_sdk.InviteInfo import uniffi.onionwire_sdk.InviteInfo
import uniffi.onionwire_sdk.OutboxRow
import uniffi.onionwire_sdk.RotateOutcome import uniffi.onionwire_sdk.RotateOutcome
import uniffi.onionwire_sdk.SendState import uniffi.onionwire_sdk.SendState
import uniffi.onionwire_sdk.Wire import uniffi.onionwire_sdk.Wire
@ -362,6 +363,23 @@ class WireViewModel(app: Application) : AndroidViewModel(app) {
suspend fun messages(pubkeyHex: String): List<ChatMessage> = suspend fun messages(pubkeyHex: String): List<ChatMessage> =
requireWire().messages(pubkeyHex) requireWire().messages(pubkeyHex)
/**
* The core's outbox rows for one friend: the `"queued"` / `"sending"` /
* `"failed"` rows behind [ChatMessage.delivery], each with the attempt count
* and absolute next-attempt time the store holds. Empty means nothing is
* outstanding for them. Read this instead of guessing a retry schedule in
* the app.
*/
suspend fun outbox(pubkeyHex: String): List<OutboxRow> =
requireWire().outbox(pubkeyHex)
/**
* The core's retry budget — the denominator in `try n/8`. A constant of the
* outbox, not per-node state, so it is fetched from the SDK rather than
* duplicated here; the app must not hardcode it.
*/
suspend fun outboxMaxAttempts(): UInt = uniffi.onionwire_sdk.outboxMaxAttempts()
/** /**
* Sends one chat message and reports what the core did with it. * Sends one chat message and reports what the core did with it.
* *

View file

@ -13,7 +13,7 @@ import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size import androidx.compose.foundation.layout.size
import androidx.compose.foundation.layout.width import androidx.compose.foundation.layout.width
import androidx.compose.foundation.lazy.LazyColumn import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.items import androidx.compose.foundation.lazy.itemsIndexed
import androidx.compose.foundation.lazy.rememberLazyListState import androidx.compose.foundation.lazy.rememberLazyListState
import androidx.compose.foundation.shape.RoundedCornerShape import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material3.Button import androidx.compose.material3.Button
@ -41,6 +41,7 @@ import androidx.compose.ui.text.font.FontFamily
import androidx.compose.ui.unit.dp import androidx.compose.ui.unit.dp
import kotlinx.coroutines.delay import kotlinx.coroutines.delay
import uniffi.onionwire_sdk.ChatMessage import uniffi.onionwire_sdk.ChatMessage
import uniffi.onionwire_sdk.OutboxRow
import uniffi.onionwire_sdk.SendState import uniffi.onionwire_sdk.SendState
@OptIn(ExperimentalMaterial3Api::class) @OptIn(ExperimentalMaterial3Api::class)
@ -50,10 +51,22 @@ fun ChatScreen(
fingerprint: String, fingerprint: String,
onion: String, onion: String,
loadMessages: suspend () -> List<ChatMessage>, loadMessages: suspend () -> List<ChatMessage>,
loadOutbox: suspend () -> List<OutboxRow>,
loadMaxAttempts: suspend () -> UInt,
onSend: suspend (String) -> SendState, onSend: suspend (String) -> SendState,
onBack: () -> Unit, onBack: () -> Unit,
/**
* Wall clock in unix seconds. `next_attempt_at` is absolute, so the
* countdown is computed here rather than baked into the store — injectable
* so a test can pin "now" instead of racing the clock.
*/
nowSeconds: () -> Long = { System.currentTimeMillis() / 1_000L },
) { ) {
var messages by remember { mutableStateOf<List<ChatMessage>?>(null) } 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) }
var draft by remember { mutableStateOf("") } var draft by remember { mutableStateOf("") }
var pending by remember { mutableStateOf<String?>(null) } var pending by remember { mutableStateOf<String?>(null) }
var error by remember { mutableStateOf<String?>(null) } var error by remember { mutableStateOf<String?>(null) }
@ -63,11 +76,18 @@ fun ChatScreen(
// Poll: the node appends inbound messages in the background and the retry // 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 // 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. // 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) { LaunchedEffect(Unit) {
runCatching { loadMaxAttempts() }.onSuccess { maxAttempts = it }
while (true) { while (true) {
runCatching { loadMessages() } runCatching { loadMessages() }
.onSuccess { messages = it } .onSuccess { messages = it }
.onFailure { error = it.message ?: it.toString() } .onFailure { error = it.message ?: it.toString() }
runCatching { loadOutbox() }
.onSuccess { outbox = it }
.onFailure { error = it.message ?: it.toString() }
delay(2_000) delay(2_000)
} }
} }
@ -156,13 +176,36 @@ fun ChatScreen(
} }
else -> { else -> {
// The outbox rows behind the pending sends: `queued (try
// 3/8, retry 45s)` needs the store's own counters and the
// core's retry budget. With either missing, or with a join
// that cannot prove itself, the rows keep the flat state
// marker — wrong numbers would be worse than none.
val max = maxAttempts
val details = if (max == null) {
List(list.size) { null }
} else {
outboxDetails(
rows = list.map { ChatRowInput(it.direction, it.delivery) },
outbox = outbox.map {
OutboxRowInput(
messageId = it.messageId,
status = it.status,
attempts = it.attempts,
nextAttemptAt = it.nextAttemptAt,
)
},
maxAttempts = max,
now = nowSeconds(),
)
}
LazyColumn( LazyColumn(
state = listState, state = listState,
modifier = Modifier.weight(1f).fillMaxWidth(), modifier = Modifier.weight(1f).fillMaxWidth(),
contentPadding = PaddingValues(12.dp), contentPadding = PaddingValues(12.dp),
verticalArrangement = Arrangement.spacedBy(6.dp), verticalArrangement = Arrangement.spacedBy(6.dp),
) { ) {
items(list) { m -> itemsIndexed(list) { i, m ->
val mine = m.direction == "out" val mine = m.direction == "out"
Row( Row(
Modifier.fillMaxWidth(), Modifier.fillMaxWidth(),
@ -187,7 +230,7 @@ fun ChatScreen(
.padding(horizontal = 10.dp, vertical = 8.dp), .padding(horizontal = 10.dp, vertical = 8.dp),
) )
parseDelivery(m.direction, m.delivery)?.let { d -> parseDelivery(m.direction, m.delivery)?.let { d ->
DeliveryMarker(d) DeliveryMarker(d, details.getOrNull(i))
} }
} }
} }
@ -262,14 +305,16 @@ fun ChatScreen(
/** /**
* One message's delivery marker, straight from the core's outbox state. * One message's delivery marker, straight from the core's outbox state.
* *
* The row carries an explicit [Delivery.contentDescription] so a screen reader * The row carries an explicit announcement so a screen reader says
* announces "Queued, not delivered yet" instead of reading a clock glyph, and a * "Queued, not delivered yet: retrying their onion (try 3/8, retry 45s)"
* [Delivery.testTag] so a UI test can find the state without depending on the * instead of reading a clock glyph, and a [Delivery.testTag] so a UI test can
* glyph. `send` shows a small indeterminate spinner while the worker has an * find the state without depending on the glyph. [detail] is the outbox row's
* own counters when the join landed; when it is `null` the row keeps the flat
* marker. `send` shows a small indeterminate spinner while the worker has an
* attempt in flight. * attempt in flight.
*/ */
@Composable @Composable
private fun DeliveryMarker(d: Delivery) { private fun DeliveryMarker(d: Delivery, detail: QueuedRowDetail?) {
val tint = when (d) { val tint = when (d) {
is Delivery.Failed -> MaterialTheme.colorScheme.error is Delivery.Failed -> MaterialTheme.colorScheme.error
Delivery.Sent -> MaterialTheme.colorScheme.onSurfaceVariant Delivery.Sent -> MaterialTheme.colorScheme.onSurfaceVariant
@ -281,7 +326,7 @@ private fun DeliveryMarker(d: Delivery) {
.padding(horizontal = 4.dp, vertical = 1.dp) .padding(horizontal = 4.dp, vertical = 1.dp)
.testTag(d.testTag) .testTag(d.testTag)
.semantics(mergeDescendants = true) { .semantics(mergeDescendants = true) {
contentDescription = d.contentDescription contentDescription = deliveryAnnouncement(d, detail)
}, },
) { ) {
if (d is Delivery.Sending) { if (d is Delivery.Sending) {
@ -293,7 +338,7 @@ private fun DeliveryMarker(d: Delivery) {
Spacer(Modifier.width(4.dp)) Spacer(Modifier.width(4.dp))
} }
Text( Text(
d.marker, deliveryMarkerText(d, detail),
style = MaterialTheme.typography.labelSmall, style = MaterialTheme.typography.labelSmall,
color = tint, color = tint,
) )

View file

@ -0,0 +1,141 @@
package com.siriusdevops.onionwire.ui
/**
* Why a chat row is still queued, read from the SDK's outbox rows
* (`Wire.outbox(pubkeyHex)` → `OutboxRow { messageId, status, attempts,
* nextAttemptAt, lastError }`).
*
* [Delivery] answers *what* state a row is in; this file answers *how far along*
* it is — `queued (try 3/8, retry 45s)` — from the store's own counters, never
* from a time the app invented. Mirrors `src/tui.rs::retry_in_text` /
* `delivery_tag` so both clients word the same state the same way.
*
* Nothing here is Android-specific: the join and the wording are pure functions
* so `OutboxDetailTest` can assert them on the JVM without a device or the
* native binding.
*/
/**
* Next-attempt age for a queued row, from the absolute `next_attempt_at` the
* store holds. Mirrors `src/tui.rs::retry_in_text`:
* `<= 0` → `retry now`; `< 60` → `retry {n}s`; else → `retry {ceil-minutes}m`.
*/
fun retryInText(nextInSecs: Long): String = when {
nextInSecs <= 0L -> "retry now"
nextInSecs < 60L -> "retry ${nextInSecs}s"
else -> "retry ${(nextInSecs + 59L) / 60L}m"
}
/**
* The outbox row's own numbers for one queued chat row.
*
* Only `"queued"` rows produce one: a terminal `"failed"` row keeps the last
* time it was *scheduled* for, so rendering it as a countdown would be a lie —
* a failed row is rendered from [Delivery.Failed] alone. `"sending"` has an
* attempt in flight and no next-attempt time worth showing, matching the TUI's
* bare `sending` tag.
*/
data class QueuedRowDetail(
val attempts: UInt,
val maxAttempts: UInt,
val nextInSecs: Long,
) {
/** `queued (try 3/8, retry 45s)` — the row text, mirroring the TUI. */
val text: String = "queued (try $attempts/$maxAttempts, ${retryInText(nextInSecs)})"
/**
* `try 3/8, retry 45s` — the same numbers without the state word, for a
* screen reader that has already heard "Queued, not delivered yet".
*/
val announcement: String = "try $attempts/$maxAttempts, ${retryInText(nextInSecs)}"
}
/** One SDK `ChatMessage`, narrowed to the fields the join reads. */
data class ChatRowInput(val direction: String, val delivery: String?)
/** One SDK `OutboxRow`, narrowed to the fields the join reads. */
data class OutboxRowInput(
val messageId: Long,
val status: String,
val attempts: UInt,
val nextAttemptAt: Long,
)
/** The store's own three pending encodings, trimmed and lowercased. */
private fun outboxKind(status: String): String? = when (val s = status.trim().lowercase()) {
"queued", "sending", "failed" -> s
else -> null
}
/** The same kind, read off the status the SDK already resolved for the message. */
private fun deliveryKind(d: Delivery?): String? = when (d) {
Delivery.Queued -> "queued"
Delivery.Sending -> "sending"
is Delivery.Failed -> "failed"
Delivery.Sent, null -> null
}
/**
* The SDK's `OutboxRow.message_id` is `messages.id` — the key the chat list is
* ordered by. The SDK's `ChatMessage` does not carry that id yet, so this join
* is positional: `messages()` is `ORDER BY m.id` and the outbox rows are one
* per pending send, so the *n*th pending chat row owns the *n*th outbox row
* (rows are sorted by `messageId` to make that explicit rather than trusting the
* core's row order).
*
* A positional join is only allowed to speak when it can prove itself: if the
* counts disagree, if a row carries a status this build does not know, or if a
* row's status does not match the status the SDK already resolved for the
* message in that slot, *every* detail is dropped and the rows fall back to the
* flat `queued` / `sending` / `failed` markers. Wrong numbers are worse than
* none. (`ChatMessage.id` would remove the positional part entirely; tracked
* as follow-up work.)
*
* Returns one entry per input row, `null` wherever there is nothing to add.
*/
fun outboxDetails(
rows: List<ChatRowInput>,
outbox: List<OutboxRowInput>,
maxAttempts: UInt,
now: Long,
): List<QueuedRowDetail?> {
val none: List<QueuedRowDetail?> = List(rows.size) { null }
val pending = rows.indices.filter {
deliveryKind(parseDelivery(rows[it].direction, rows[it].delivery)) != null
}
val ordered = outbox.sortedBy { it.messageId }
if (pending.size != ordered.size) return none
val details = arrayOfNulls<QueuedRowDetail>(rows.size)
for ((slot, index) in pending.withIndex()) {
val row = ordered[slot]
val kind = outboxKind(row.status) ?: return none
if (kind != deliveryKind(parseDelivery(rows[index].direction, rows[index].delivery))) {
return none
}
if (kind == "queued") {
details[index] = QueuedRowDetail(
attempts = row.attempts,
maxAttempts = maxAttempts,
nextInSecs = row.nextAttemptAt - now,
)
}
}
return details.toList()
}
/**
* Marker text for one row: the outbox row's own numbers when the join landed,
* otherwise the flat state marker `MessageDelivery` already produced.
*/
fun deliveryMarkerText(d: Delivery, detail: QueuedRowDetail?): String =
if (detail == null) d.marker else "${d.glyph} ${detail.text}"
/**
* What a screen reader announces for one row. The detail is appended to the
* sentence [Delivery] carries, never replaces it: a bare `try 3/8` is not a
* sentence.
*/
fun deliveryAnnouncement(d: Delivery, detail: QueuedRowDetail?): String =
if (detail == null) d.contentDescription else "${d.contentDescription} (${detail.announcement})"

View file

@ -0,0 +1,278 @@
package com.siriusdevops.onionwire.ui
import org.junit.Assert.assertEquals
import org.junit.Assert.assertNull
import org.junit.Assert.assertTrue
import org.junit.Test
/**
* The SDK's outbox rows turned into chat-row wording: `queued (try 3/8, retry
* 45s)`.
*
* These assert the pure model `ChatScreen` renders from — the same shape as
* `MessageDeliveryTest` — so the retry wording, the fail-closed join and the
* "a failed row never shows a countdown" rule are all covered on the JVM
* without a device.
*/
class OutboxDetailTest {
private fun out(delivery: String?) = ChatRowInput("out", delivery)
private fun row(
messageId: Long,
status: String,
attempts: UInt = 0u,
nextAttemptAt: Long = 0L,
) = OutboxRowInput(messageId, status, attempts, nextAttemptAt)
// --- retry_in_text: the three buckets, mirroring src/tui.rs -------------
@Test
fun retry_in_text_is_now_at_or_before_the_next_attempt_time() {
assertEquals("retry now", retryInText(0L))
assertEquals("retry now", retryInText(-45L))
}
@Test
fun retry_in_text_counts_seconds_below_a_minute() {
assertEquals("retry 1s", retryInText(1L))
assertEquals("retry 45s", retryInText(45L))
assertEquals("retry 59s", retryInText(59L))
}
@Test
fun retry_in_text_rounds_minutes_up_from_the_first_minute() {
// 60s is one minute, not "retry 1s" and not "retry 0m".
assertEquals("retry 1m", retryInText(60L))
// Anything over the boundary rounds up, so the app never promises an
// attempt sooner than the store will make one.
assertEquals("retry 2m", retryInText(61L))
assertEquals("retry 10m", retryInText(600L))
assertEquals("retry 25m", retryInText(1500L))
// The core's backoff caps at 30 minutes.
assertEquals("retry 30m", retryInText(1800L))
}
// --- the queued row's own numbers ---------------------------------------
@Test
fun a_queued_row_renders_the_tui_wording() {
val details = outboxDetails(
rows = listOf(out("queued")),
outbox = listOf(row(7L, "queued", attempts = 3u, nextAttemptAt = 1_000L + 45L)),
maxAttempts = 8u,
now = 1_000L,
)
val detail = requireNotNull(details.single())
assertEquals("queued (try 3/8, retry 45s)", detail.text)
assertEquals("◷ queued (try 3/8, retry 45s)", deliveryMarkerText(Delivery.Queued, detail))
}
@Test
fun the_denominator_comes_from_the_core_not_a_constant_here() {
val detail = requireNotNull(
outboxDetails(
rows = listOf(out("queued")),
outbox = listOf(row(1L, "queued", attempts = 3u, nextAttemptAt = 0L)),
maxAttempts = 12u,
now = 0L,
).single(),
)
assertEquals("queued (try 3/12, retry now)", detail.text)
}
@Test
fun an_overdue_attempt_reads_retry_now() {
val detail = requireNotNull(
outboxDetails(
rows = listOf(out("queued")),
outbox = listOf(row(1L, "queued", attempts = 1u, nextAttemptAt = 900L)),
maxAttempts = 8u,
now = 1_000L,
).single(),
)
assertEquals("queued (try 1/8, retry now)", detail.text)
}
@Test
fun the_countdown_is_computed_from_the_absolute_time_the_store_holds() {
val first = requireNotNull(
outboxDetails(
rows = listOf(out("queued")),
outbox = listOf(row(1L, "queued", attempts = 2u, nextAttemptAt = 1_000L + 600L)),
maxAttempts = 8u,
now = 1_000L,
).single(),
)
assertEquals("queued (try 2/8, retry 10m)", first.text)
// Same row, one minute later: the wording moves with `now`.
val later = requireNotNull(
outboxDetails(
rows = listOf(out("queued")),
outbox = listOf(row(1L, "queued", attempts = 2u, nextAttemptAt = 1_000L + 600L)),
maxAttempts = 8u,
now = 1_060L,
).single(),
)
assertEquals("queued (try 2/8, retry 9m)", later.text)
}
// --- the states that must not show a countdown --------------------------
@Test
fun a_failed_row_shows_no_countdown() {
// A terminal row keeps the last time it was scheduled for. Rendering
// that as "retry 15m" would promise an attempt that will never happen.
val details = outboxDetails(
rows = listOf(out("failed: connection timed out")),
outbox = listOf(row(4L, "failed", attempts = 8u, nextAttemptAt = 1_900L)),
maxAttempts = 8u,
now = 1_000L,
)
assertNull(details.single())
val d = requireNotNull(parseDelivery("out", "failed: connection timed out"))
assertEquals("✗ failed: connection timed out", deliveryMarkerText(d, details.single()))
assertEquals("Failed: connection timed out", deliveryAnnouncement(d, details.single()))
}
@Test
fun a_sending_row_shows_no_countdown() {
val details = outboxDetails(
rows = listOf(out("sending")),
outbox = listOf(row(4L, "sending", attempts = 2u, nextAttemptAt = 1_900L)),
maxAttempts = 8u,
now = 1_000L,
)
assertNull(details.single())
val d = requireNotNull(parseDelivery("out", "sending"))
assertEquals("» sending", deliveryMarkerText(d, details.single()))
}
@Test
fun delivered_and_inbound_rows_never_take_an_outbox_row() {
// No outbox rows at all: an accepted send and an inbound row are quiet.
val details = outboxDetails(
rows = listOf(ChatRowInput("in", null), out("sent")),
outbox = emptyList(),
maxAttempts = 8u,
now = 1_000L,
)
assertEquals(listOf(null, null), details)
}
// --- the join is positional, so it has to prove itself ------------------
@Test
fun details_are_attached_to_the_pending_row_in_order() {
val rows = listOf(out("sent"), ChatRowInput("in", null), out("queued"), out("failed: no route"))
val details = outboxDetails(
rows = rows,
outbox = listOf(
row(12L, "queued", attempts = 1u, nextAttemptAt = 1_030L),
row(15L, "failed", attempts = 8u, nextAttemptAt = 1_500L),
),
maxAttempts = 8u,
now = 1_000L,
)
assertNull(details[0])
assertNull(details[1])
assertEquals("queued (try 1/8, retry 30s)", requireNotNull(details[2]).text)
assertNull(details[3])
}
@Test
fun the_join_ignores_the_row_order_the_core_returned() {
val details = outboxDetails(
rows = listOf(out("queued"), out("queued")),
outbox = listOf(
row(20L, "queued", attempts = 1u, nextAttemptAt = 1_010L),
row(10L, "queued", attempts = 2u, nextAttemptAt = 1_020L),
),
maxAttempts = 8u,
now = 1_000L,
)
// Sorted by messageId, so the older message owns the 20s row.
assertEquals("queued (try 2/8, retry 20s)", requireNotNull(details[0]).text)
assertEquals("queued (try 1/8, retry 10s)", requireNotNull(details[1]).text)
}
@Test
fun a_row_count_that_does_not_match_the_pending_sends_drops_every_detail() {
// The app cannot prove which message owns which row, so it says nothing
// rather than showing the wrong attempt count.
val details = outboxDetails(
rows = listOf(out("queued"), out("queued")),
outbox = listOf(row(1L, "queued", attempts = 3u, nextAttemptAt = 1_010L)),
maxAttempts = 8u,
now = 1_000L,
)
assertEquals(listOf(null, null), details)
}
@Test
fun a_status_that_contradicts_the_message_drops_every_detail() {
// Positional join + the SDK's own per-message status is the check: the
// first message is queued, the row in its slot says failed.
val details = outboxDetails(
rows = listOf(out("queued"), out("queued")),
outbox = listOf(
row(1L, "failed", attempts = 8u, nextAttemptAt = 1_010L),
row(2L, "queued", attempts = 1u, nextAttemptAt = 1_010L),
),
maxAttempts = 8u,
now = 1_000L,
)
assertEquals(listOf(null, null), details)
}
@Test
fun a_status_this_build_does_not_know_drops_every_detail() {
val details = outboxDetails(
rows = listOf(out("queued")),
outbox = listOf(row(1L, "spooling", attempts = 1u, nextAttemptAt = 1_010L)),
maxAttempts = 8u,
now = 1_000L,
)
assertEquals(listOf(null), details)
}
@Test
fun an_unknown_delivery_on_a_pending_row_is_treated_as_pending() {
// parseDelivery maps an unrecognised outgoing status to Queued (never
// delivered), so the row still wants its outbox row.
val detail = requireNotNull(
outboxDetails(
rows = listOf(out("spooling")),
outbox = listOf(row(1L, "queued", attempts = 1u, nextAttemptAt = 1_000L)),
maxAttempts = 8u,
now = 1_000L,
).single(),
)
assertEquals("queued (try 1/8, retry now)", detail.text)
}
// --- a11y ---------------------------------------------------------------
@Test
fun the_announcement_keeps_the_sentence_and_adds_the_numbers() {
val detail = requireNotNull(
outboxDetails(
rows = listOf(out("queued")),
outbox = listOf(row(1L, "queued", attempts = 3u, nextAttemptAt = 1_045L)),
maxAttempts = 8u,
now = 1_000L,
).single(),
)
val said = deliveryAnnouncement(Delivery.Queued, detail)
assertEquals(
"Queued, not delivered yet: retrying their onion (try 3/8, retry 45s)",
said,
)
// Never a bare glyph, and never only numbers.
assertTrue(said.any { it.isLetter() })
assertTrue(!said.contains("◷"))
}
}

View file

@ -28,9 +28,11 @@
use std::path::PathBuf; use std::path::PathBuf;
use std::sync::{Arc, Mutex, OnceLock}; use std::sync::{Arc, Mutex, OnceLock};
use onionwire::Message;
use onionwire::hs::TorState as CoreTorState; use onionwire::hs::TorState as CoreTorState;
use onionwire::node::{FlushOutcome as CoreFlushOutcome, Node}; use onionwire::node::{FlushOutcome as CoreFlushOutcome, Node};
use onionwire::outbox::OutboxStatus;use onionwire::qr; use onionwire::outbox::{DEFAULT_MAX_ATTEMPTS, OutboxEntry, OutboxStatus};
use onionwire::qr;
uniffi::setup_scaffolding!(); uniffi::setup_scaffolding!();
@ -120,6 +122,11 @@ pub enum SendState {
#[derive(Debug, Clone, uniffi::Record)] #[derive(Debug, Clone, uniffi::Record)]
pub struct ChatMessage { pub struct ChatMessage {
/// `messages.id` of the stored row. This is the join key an
/// [`OutboxRow::message_id`] refers to, so a client matches an outbox row to
/// this message by id instead of matching bodies or counting rows. Stable
/// for the life of the row; never `0`.
pub id: i64,
/// "in" or "out". /// "in" or "out".
pub direction: String, pub direction: String,
pub body: String, pub body: String,
@ -131,6 +138,46 @@ pub struct ChatMessage {
pub delivery: Option<String>, pub delivery: Option<String>,
} }
/// One row of the local outbox for a friend: a chat send the core has not
/// finished delivering.
///
/// The join key is `message_id` — the `messages.id` a [`ChatMessage`] belongs
/// to — so a client matches these against its own list instead of matching
/// bodies. Delivered rows are deleted, which is why a message with no row here
/// was accepted by the peer and never needed a retry.
#[derive(Debug, Clone, PartialEq, Eq, uniffi::Record)]
pub struct OutboxRow {
/// `messages.id` of the chat row this outbox row belongs to.
pub message_id: i64,
/// `"queued"`, `"sending"` or `"failed"` — the store's own encoding of
/// `OutboxStatus`, the same string [`ChatMessage::delivery`] uses.
/// `"sent"` does not occur: a delivered row is deleted before this is read.
pub status: String,
/// Attempts already spent on this row. Compare against
/// [`outbox_max_attempts`] to render `try n/8`.
pub attempts: u32,
/// Absolute unix seconds of the next attempt, so the client renders its own
/// countdown from `now` instead of a stale number baked into a record.
/// Only meaningful while `status == "queued"`: a `"failed"` row is terminal
/// and keeps the last time it was scheduled for, which must not be shown as
/// a countdown.
pub next_attempt_at: i64,
/// Why the last attempt failed, as the core reported it. `None` until the
/// row has been attempted once.
pub last_error: Option<String>,
}
/// Retry budget after which a queued message turns terminally `"failed"` — the
/// denominator in `try n/8`.
///
/// A constant of the core's outbox, not per-node state, so it is a free
/// function: fetch it once and render `attempts` against it. It is exposed at
/// all because the client cannot read the Rust constant.
#[uniffi::export]
pub fn outbox_max_attempts() -> u32 {
DEFAULT_MAX_ATTEMPTS
}
#[derive(Debug, Clone, uniffi::Record)] #[derive(Debug, Clone, uniffi::Record)]
pub struct RotateOutcome { pub struct RotateOutcome {
pub notified: u32, pub notified: u32,
@ -205,7 +252,10 @@ impl Wire {
let guard = self.node.lock().map_err(|_| WireError::Stopped { let guard = self.node.lock().map_err(|_| WireError::Stopped {
message: "node handle lock poisoned by a panic; reopen the identity".to_string(), message: "node handle lock poisoned by a panic; reopen the identity".to_string(),
})?; })?;
guard.as_ref().cloned().ok_or_else(|| WireError::stopped("this call")) guard
.as_ref()
.cloned()
.ok_or_else(|| WireError::stopped("this call"))
} }
} }
@ -376,7 +426,8 @@ impl Wire {
.send(&pk, body.as_bytes()) .send(&pk, body.as_bytes())
.await .await
.map_err(WireError::new)?; .map_err(WireError::new)?;
Ok(send_state(status)) } Ok(send_state(status))
}
/// Chat history for a friend, oldest first. Bodies are decrypted here; /// Chat history for a friend, oldest first. Bodies are decrypted here;
/// they are stored encrypted at rest. Outgoing rows carry their delivery /// they are stored encrypted at rest. Outgoing rows carry their delivery
@ -390,14 +441,26 @@ impl Wire {
.node()? .node()?
.outbox_status_of_message(m.id) .outbox_status_of_message(m.id)
.map_err(WireError::new)?; .map_err(WireError::new)?;
out.push(ChatMessage { body: String::from_utf8_lossy(&m.plaintext).into_owned(), out.push(chat_message(m, status));
delivery: delivery_of(&m.dir, status),
direction: m.dir,
});
} }
Ok(out) Ok(out)
} }
/// Outbox rows for one friend that the core has not delivered yet: the
/// `"queued"` / `"sending"` / `"failed"` rows behind
/// [`ChatMessage::delivery`], with the core's own attempt counter and next
/// attempt time attached.
///
/// This is what lets a chat row say *why* it is still queued — `try 3/8,
/// retry 45s` — instead of a flat `"queued"`: [`OutboxRow::attempts`] and
/// [`OutboxRow::next_attempt_at`] are read from the store, never guessed by
/// the client. An empty result means nothing is outstanding for that friend.
pub async fn outbox(&self, pubkey_hex: String) -> WResult<Vec<OutboxRow>> {
let pk = unhex(&pubkey_hex)?;
let rows = self.node()?.outbox_pending(&pk).map_err(WireError::new)?;
Ok(rows.iter().map(outbox_row).collect())
}
/// Delete every message body. Identity and friends survive. /// Delete every message body. Identity and friends survive.
pub async fn wipe_messages(&self) -> WResult<()> { pub async fn wipe_messages(&self) -> WResult<()> {
self.node()?.wipe_messages().map_err(WireError::new) self.node()?.wipe_messages().map_err(WireError::new)
@ -462,6 +525,17 @@ fn send_state(status: OutboxStatus) -> SendState {
} }
} }
/// One stored chat row as the record a client renders. `id` is copied through
/// untouched: it is the `messages.id` an [`OutboxRow::message_id`] joins to.
fn chat_message(m: Message, status: Option<OutboxStatus>) -> ChatMessage {
ChatMessage {
id: m.id,
direction: m.dir.clone(),
body: String::from_utf8_lossy(&m.plaintext).into_owned(),
delivery: delivery_of(&m.dir, status),
}
}
/// Delivery string for one stored chat row. `None` for incoming rows. An /// Delivery string for one stored chat row. `None` for incoming rows. An
/// outgoing row with no outbox row was accepted on the first attempt, so it is /// outgoing row with no outbox row was accepted on the first attempt, so it is
/// reported as `"sent"` rather than left blank. /// reported as `"sent"` rather than left blank.
@ -475,14 +549,32 @@ fn delivery_of(dir: &str, status: Option<OutboxStatus>) -> Option<String> {
}) })
} }
/// One core outbox row as the record a client renders.
///
/// Field-for-field, so the client shows the store's numbers instead of a
/// timeout it invented: the row is keyed by `message_id` (the chat row to
/// patch), carries the store's own status string, and next-attempt as an
/// absolute unix second for the client to count down from.
fn outbox_row(entry: &OutboxEntry) -> OutboxRow {
OutboxRow {
message_id: entry.message_id,
status: entry.status.as_db_str().to_string(),
attempts: entry.attempts,
next_attempt_at: entry.next_attempt_at,
last_error: entry.last_error.clone(),
}
}
#[cfg(test)] #[cfg(test)]
mod tests { mod tests {
//! No Tor here on purpose: these exercise the *lifecycle* contract of the //! No Tor here on purpose: these exercise the *lifecycle* contract of the
//! handle, which is what a shut-down node must guarantee. A `Wire` with no //! handle, which is what a shut-down node must guarantee. A `Wire` with no
//! node is exactly the state `shutdown()` leaves behind. //! node is exactly the state `shutdown()` leaves behind.
use super::*; use super::*;
use onionwire::Store;
use onionwire::outbox::OutboxStatus; use onionwire::outbox::OutboxStatus;
use std::path::PathBuf;
use std::sync::atomic::{AtomicUsize, Ordering};
fn stopped_wire() -> Wire { fn stopped_wire() -> Wire {
Wire { Wire {
@ -544,7 +636,7 @@ mod tests {
assert_eq!(TorState::from(CoreTorState::Stopped), TorState::Stopped); assert_eq!(TorState::from(CoreTorState::Stopped), TorState::Stopped);
} }
#[test] #[test]
fn sent_is_sent_everything_else_is_queued() { fn sent_is_sent_everything_else_is_queued() {
assert_eq!(send_state(OutboxStatus::Sent), SendState::Sent); assert_eq!(send_state(OutboxStatus::Sent), SendState::Sent);
assert_eq!(send_state(OutboxStatus::Queued), SendState::Queued); assert_eq!(send_state(OutboxStatus::Queued), SendState::Queued);
@ -580,5 +672,134 @@ mod tests {
Some("failed: no route") Some("failed: no route")
); );
} }
}
/// One core outbox row with only the fields a record carries filled in
/// interestingly. `id`, `friend_pk`, `body` and `created_at` do not cross
/// UniFFI, so their values are irrelevant.
fn entry(status: OutboxStatus, attempts: u32, last_error: Option<&str>) -> OutboxEntry {
OutboxEntry {
id: 3,
friend_pk: vec![0xaa; 32],
message_id: 42,
body: b"hello".to_vec(),
attempts,
next_attempt_at: 1_700_000_045,
created_at: 1_700_000_000,
status,
last_error: last_error.map(str::to_string),
}
}
#[test]
fn outbox_row_carries_the_join_key_the_attempt_count_and_the_next_attempt_time() {
let row = outbox_row(&entry(
OutboxStatus::Queued,
3,
Some("peer onion unreachable"),
));
assert_eq!(row.message_id, 42);
assert_eq!(row.status, "queued");
assert_eq!(row.attempts, 3);
assert_eq!(row.next_attempt_at, 1_700_000_045);
assert_eq!(row.last_error.as_deref(), Some("peer onion unreachable"));
}
#[test]
fn outbox_row_keeps_the_stores_own_status_encoding() {
// These four strings are the `outbox.status` CHECK constraint in
// `src/store.rs`; a client switches on them verbatim.
for (status, want) in [
(OutboxStatus::Queued, "queued"),
(OutboxStatus::Sending, "sending"),
(OutboxStatus::Sent, "sent"),
(
OutboxStatus::Failed("peer onion unreachable".into()),
"failed",
),
] {
assert_eq!(outbox_row(&entry(status, 0, None)).status, want);
}
}
#[test]
fn a_failed_outbox_row_carries_the_cores_reason_verbatim() {
let row = outbox_row(&entry(
OutboxStatus::Failed("peer onion unreachable".into()),
8,
Some("peer onion unreachable"),
));
assert_eq!(row.status, "failed");
assert_eq!(row.attempts, 8);
assert_eq!(row.last_error.as_deref(), Some("peer onion unreachable"));
}
#[test]
fn outbox_max_attempts_is_the_denominator_a_client_renders_against() {
// The Android chat row renders `try n/8`. Pin the number so the SDK and
// the core's retry budget cannot drift apart silently.
assert_eq!(outbox_max_attempts(), 8);
}
/// An empty dir for a store-backed test. `tempfile` is not a dependency of
/// this crate and a store only needs somewhere private to live.
fn temp_home() -> PathBuf {
static NEXT: AtomicUsize = AtomicUsize::new(0);
let dir = std::env::temp_dir().join(format!(
"onionwire-sdk-join-{}-{}",
std::process::id(),
NEXT.fetch_add(1, Ordering::Relaxed)
));
let _ = std::fs::remove_dir_all(&dir);
dir
}
/// The property the Android client joins on: a chat row and the outbox row
/// behind it report the same `messages.id`. Reads both sides out of a real
/// store through the same helpers `Wire::messages` / `Wire::outbox` use, so
/// a client can match on the id instead of counting rows.
#[test]
fn a_chat_row_joins_to_its_outbox_row_by_message_id() {
let home = temp_home();
let store = Store::open_at_with_passphrase(&home, "join-key-pass").unwrap();
let friend = [0x11u8; 32];
store.upsert_friend(&friend, "peer.onion", None).unwrap();
let row_id = store
.append_message_id(&friend, "out", b"still queued")
.unwrap();
store
.enqueue_outbox(
&friend,
row_id,
3,
1_700_000_045,
"peer onion unreachable",
1_700_000_000,
)
.unwrap();
// Same two reads `Wire::messages` / `Wire::outbox` do.
let mut messages = Vec::new();
for m in store.list_messages(&friend).unwrap() {
let status = store.outbox_status_of_message(m.id).unwrap();
messages.push(chat_message(m, status));
}
let rows: Vec<OutboxRow> = store
.pending_outbox(&friend)
.unwrap()
.iter()
.map(outbox_row)
.collect();
assert_eq!(messages.len(), 1);
assert_eq!(rows.len(), 1);
// The outbox side really is the stored row (not a defaulted id) …
assert_eq!(rows[0].message_id, row_id);
// … and the id the client gets on the message is that same row id.
assert_eq!(messages[0].id, rows[0].message_id);
// Both sides describe the same row, queued with its attempt count.
assert_eq!(messages[0].delivery.as_deref(), Some("queued"));
assert_eq!(rows[0].attempts, 3);
std::fs::remove_dir_all(&home).ok();
}
}