Compare commits

...
Author SHA1 Message Date
Hermes apk-dev
4bc0d6684d
fix(android): surface the outbox send state instead of denying it
The SDK has returned `SendState` and a per-row `ChatMessage.delivery` since
the local outbox landed, but the app still said "there is no outbox in v1"
and threw the state away.

- `WireViewModel.send()` returns `SendState`; `ChatScreen` no longer discards
  it. A `QUEUED` send raises a "local-only until the retry worker gets a
  circuit through" hint instead of pretending success.
- Outgoing rows render the TUI's delivery markers from `ChatMessage.delivery`
  (`✓` / `◷ queued` / `» sending` / `✗ failed: <reason>`), plus the TUI's
  `{n} queued` footer while the outbox still owns rows. Incoming rows stay
  unmarked; an unreadable state renders no marker rather than a tick.
- The empty-chat copy describes the outbox (8 attempts, backoff capped at
  30 min, local-only until it lands) instead of denying it exists.
- New pure `Delivery.kt` so the vocabulary is unit-testable without a device.

Verified: `./gradlew :app:assembleDebug :app:testDebugUnitTest` → BUILD
SUCCESSFUL, 15 tests / 0 failures (10 new), APK contains the new copy and no
longer the "There is no outbox" string. Stacked on the SDK fix (PR #51).
2026-09-12 17:13:45 -04:00
Hermes rust-dev
0de5f7b220
fix(sdk): surface Sent/Queued on send(), and build the SDK in CI
All checks were successful
ci / test (pull_request) Successful in 3m2s
ci / sdk (pull_request) Successful in 55s
`Node::send()` became `Result<OutboxStatus, String>` in the local-outbox work,
which broke `crates/onionwire-sdk` (E0308 at src/lib.rs:195) — and nothing
noticed, because the SDK is a separate cargo workspace that root CI never
compiles and android-release.yml only builds on a v*.*.* tag.

- `Wire::send()` now returns `WResult<SendState>` (`Sent` | `Queued`) instead
  of swallowing the outcome as `()`. A queued send is local-only until the
  retry worker gets a circuit through, so the Kotlin boundary must be able to
  tell it apart from a delivered one.
- `ChatMessage` gains `delivery: Option<String>` ("sent" | "queued" |
  "sending" | "failed: <reason>"), populated from the message's outbox row;
  `None` for incoming messages. An outgoing row with no outbox row was accepted
  on the first attempt, so it reads "sent".
- New `sdk` job in `.forgejo/workflows/ci.yml`: `cargo test --locked` +
  `cargo clippy --locked --all-targets -- -D warnings` in `crates/onionwire-sdk`
  in the same rust:1.91-bookworm container, with its own target volume (the SDK
  resolves the root crate with rustls, so sharing the root job's target dir
  would thrash feature-unified artifacts).
- Drift found while un-rotting it: the SDK `Cargo.lock` was stale (missing
  `sha2`, added to the root crate by the zeroize work), so `--locked` failed;
  and the SDK README still said "no outbox, no spool in v1" and "identity keys
  in sqlite are plaintext", both untrue since the outbox and SQLCipher landed.

Tests: crates/onionwire-sdk 4 passed (2 new unit tests over the status
mapping), clippy clean; root `cargo test --locked` clean. The CI job body was
smoke-run locally in the same container image before being committed.
2026-09-12 17:12:33 -04:00
rust-dev
afff5f8dff
feat(tui): join outbox rows to chat rows by message id
All checks were successful
ci / test (pull_request) Successful in 3m27s
`chat_with_delivery` matched pending outbox rows to chat rows by body
because `store::Message` carried no id, so an older send that was still
queued showed a delivered mark whenever a newer send of the same text had
already crossed the circuit.

`store::Message` now carries its `messages.id`, and the TUI joins
`OutboxEntry::message_id` == `Message::id`. The body match and its
newest-first fallback are gone.

`list_messages()` keeps its signature; callers that do not need the id
are untouched.
2026-09-12 14:34:43 -04:00
t
ebd3a306e8
feat(tui): per-message outbox delivery state + N queued footer
All checks were successful
ci / test (pull_request) Successful in 3m20s
Chat rows now carry the state the local outbox actually holds: `✓` delivered,
`◷ queued (try n/8, retry 45s)` while the retry worker still has it, `» sending`
mid-attempt and `✗ failed: <short reason>` once attempts are exhausted. The
footer replaces the flat `sent` / `send failed` copy with the live count
(`2 queued`), and keeps a fail-closed `send failed: …` statement as long as any
row is terminally failed.

States come from the outbox API (`Node::outbox_pending` → `Queued` / `Sending` /
`Failed`; a delivered row is deleted, so absence is `Sent`). No parallel state
model, no new wire prefix. Every new glyph has an ASCII fallback (`ok` plus the
state word) exercised by a test.

- `chat_with_delivery()` / `delivery_tag()` / `retry_in_text()` /
  `short_send_reason()` / `OutboxSummary::note()` are pure and unit-tested.
- `draw_chat()` is now the real chat-pane renderer (extracted from
  `App::draw_main`) so width/wrap is testable without a `Node`.
- docs/TUI.md: delivery markers, copy, and the 80x24 floor / 120x40 target.

Verified: cargo test 26/26 suites ok (tui_spec 20/20, incl. a real Store +
Outbox::send -> pending() -> render path); clippy --all-targets -D warnings clean.
2026-09-12 14:22:38 -04:00
t
7c6de696a1
Merge remote-tracking branch 'origin/feat/local-outbox' into feat/tui-outbox-state
All checks were successful
ci / test (pull_request) Successful in 3m16s
2026-09-12 14:11:28 -04:00
Sirius DevOps
068b655c19
feat(outbox): local retry queue for chat sends
All checks were successful
ci / test (pull_request) Successful in 3m22s
Queue a chat send locally when the peer's v3 onion is unreachable and retry
it with exponential backoff (30s doubling, capped at 30 min, 8 attempts then
terminal Failed). Still peer-to-peer: no server, no store-and-forward relay,
no new frame prefix — every attempt is a fresh Noise IK handshake.

- src/outbox.rs: Outbox + Deliverer + ArtiDeliverer, pure backoff_secs(),
  is_permanent_send_error(), background worker (15s scan).
- store: `outbox` table (no body column — the body is read from the joined
  messages row, under that row's existing AEAD + AAD), append_message_id(),
  queue/due/pending/mark_* helpers, reset_sending_outbox(), wipe.
- Node::send() returns Result<OutboxStatus, String> (Sent/Queued) instead of
  Err on transport failure; protocol errors still fail immediately and are
  never queued.
- Retry triggers: timer, unlock/foreground (spawn_flush_all), and "that peer
  was just seen" (handshake or connect_onion -> spawn_flush_friend).
- File transfer and payment/rcp frames stay fail-closed.
- docs/PROTOCOL.md + docs/THREAT_MODEL.md: replace the no-queue statements;
  add the seizure/cadence delta to the threat model.

src/tui.rs gets one forced arm change (Ok(()) -> Ok(_)); UI surfacing is
child card t_d9a5b065.
2026-09-12 13:55:07 -04:00
20 changed files with 2281 additions and 165 deletions

View file

@ -39,6 +39,11 @@ env:
CARGO_REGISTRY_VOLUME: onionwire-cargo-registry
CARGO_TARGET_VOLUME: onionwire-target-ci
BUILD_CONTAINER: onionwire-ci-${{ github.run_id }}
# The SDK job gets its own target volume: it resolves the root crate with
# `rustls` instead of `native-tls`, so sharing a target dir would thrash both
# jobs' feature-unified artifacts.
SDK_CARGO_TARGET_VOLUME: onionwire-target-ci-sdk
SDK_BUILD_CONTAINER: onionwire-ci-sdk-${{ github.run_id }}
jobs:
test:
@ -73,3 +78,44 @@ jobs:
tar czf - --exclude=./target --exclude=./.git --exclude=./.worktrees . \
| docker start -a -i "$BUILD_CONTAINER"
docker rm -f "$BUILD_CONTAINER" > /dev/null
# `crates/onionwire-sdk` is a SEPARATE cargo workspace: its own Cargo.lock and
# a path dependency on the root crate, resolved with `rustls` instead of
# `native-tls`. The `test` job above therefore never compiles it, so a
# root-crate signature change (`Node::send` gaining the outbox result, the
# SQLCipher passphrase entry points) breaks the Android SDK — and the tagged
# release AAR, since android-release.yml only builds on `v*.*.*` — while both
# the root suites and local `cargo test` stay green. Build it here.
sdk:
runs-on: docker
timeout-minutes: 120
steps:
- name: Checkout
uses: https://code.forgejo.org/actions/checkout@v4
- name: cargo test + clippy for crates/onionwire-sdk on aarch64
run: |
set -euo pipefail
cd "${GITHUB_WORKSPACE}"
echo "workspace: $GITHUB_WORKSPACE"
docker volume create "$CARGO_REGISTRY_VOLUME" > /dev/null
docker volume create "$SDK_CARGO_TARGET_VOLUME" > /dev/null
docker rm -f "$SDK_BUILD_CONTAINER" > /dev/null 2>&1 || true
docker create --name "$SDK_BUILD_CONTAINER" -i \
-e CARGO_TARGET_DIR=/target \
-e CARGO_BUILD_JOBS=2 \
-e CARGO_TERM_COLOR=never \
-v "$CARGO_REGISTRY_VOLUME":/usr/local/cargo/registry \
-v "$SDK_CARGO_TARGET_VOLUME":/target \
-w /src \
"$RUST_IMAGE" \
sh -euxc 'mkdir -p /src && tar xzf - -C /src && cd /src/crates/onionwire-sdk \
&& apt-get update \
&& apt-get install -y --no-install-recommends pkg-config libssl-dev \
&& rustup component add clippy \
&& cargo test --locked \
&& cargo clippy --locked --all-targets -- -D warnings'
tar czf - --exclude=./target --exclude=./.git --exclude=./.worktrees \
--exclude=./crates/onionwire-sdk/target . \
| docker start -a -i "$SDK_BUILD_CONTAINER"
docker rm -f "$SDK_BUILD_CONTAINER" > /dev/null

View file

@ -289,7 +289,7 @@ FORGEJO_TOKEN=<pat> scripts/build-release-local.sh vX.Y.Z
Workflows (Forgejo Actions, `.forgejo/workflows/`):
- [`.forgejo/workflows/ci.yml`](.forgejo/workflows/ci.yml) — `cargo test --locked` + `cargo clippy --all-targets -- -D warnings` on `main` and PRs when `src/`, `crates/`, `tests/`, `Cargo.toml`, `Cargo.lock`, or this workflow change (ignored Tor-live tests are not run). `workflow_dispatch` always runs the suite. Pi runner, `docker` label.
- [`.forgejo/workflows/ci.yml`](.forgejo/workflows/ci.yml) — two jobs, both on the Pi runner (`docker` label), serialized by the `onionwire-ci-pi` concurrency group. `test`: `cargo test --locked` + `cargo clippy --all-targets -- -D warnings` at the repo root. `sdk`: the same for `crates/onionwire-sdk`, which is a separate cargo workspace (own `Cargo.lock`, root crate by path, `rustls` instead of `native-tls`) and therefore never gets compiled by the root job — without it a root-crate signature change would silently break the Android SDK and the tagged release AAR. Both run on `main` and PRs when `src/`, `crates/`, `tests/`, `Cargo.toml`, `Cargo.lock`, or this workflow change (ignored Tor-live tests are not run). `workflow_dispatch` always runs the suite.
- [`.forgejo/workflows/release.yml`](.forgejo/workflows/release.yml) — on core paths to `main` (`src/`, `crates/`, `Cargo.toml`, `Cargo.lock`, `scripts/release-body.md`): next tag, aarch64 (`docker`) + x86_64 (`docker-amd64`), one release. `workflow_dispatch` rebuilds a tag or `dry_run`s. Concurrency group `onionwire-ci-pi` (same as `ci.yml`, `cancel-in-progress: false`) so cargo jobs do not overlap on the Pi. Amd64 dind is serialized by runner `capacity=1`.
Scripts:

View file

@ -11,6 +11,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 uniffi.onionwire_sdk.openWire
@ -105,7 +106,15 @@ class WireViewModel(app: Application) : AndroidViewModel(app) {
suspend fun messages(pubkeyHex: String): List<ChatMessage> =
requireWire().messages(pubkeyHex)
suspend fun send(pubkeyHex: String, body: String) =
/**
* Hands the body to the node and reports what happened to it.
*
* `SENT` means the peer's onion took the frame during this call. `QUEUED`
* means it did not: the message is in the local outbox, local-only until
* the retry worker gets a circuit through. The caller must not render
* `QUEUED` as delivered.
*/
suspend fun send(pubkeyHex: String, body: String): SendState =
requireWire().send(pubkeyHex, body)
suspend fun wipeMessages() {

View file

@ -37,6 +37,12 @@ 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
/** Shown after a `Queued` send — the TUI's composer keeps `{n} queued`. */
private const val QUEUED_HINT =
"Queued: their onion is unreachable. The message is local-only in this " +
"device's outbox until the retry worker gets a circuit through."
@OptIn(ExperimentalMaterial3Api::class)
@Composable
@ -45,13 +51,14 @@ 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 hint by remember { mutableStateOf<String?>(null) }
val listState = rememberLazyListState()
// Poll: the node appends inbound messages in the background; there is no
@ -65,16 +72,32 @@ 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.
// Fail closed — but not fail lost. `send` returns `Queued` when the peer's
// onion is unreachable: the body is in this device's local outbox and the
// retry worker keeps trying. It only surfaces as a hard error when the
// node itself refuses the write.
LaunchedEffect(pending) {
val body = pending ?: return@LaunchedEffect
error = null
hint = null
runCatching { onSend(body) }
.onSuccess { state ->
// Never dress a queued send up as delivered.
hint = if (state == SendState.QUEUED) QUEUED_HINT else null
}
.onFailure { error = it.message ?: it.toString() }
pending = null
}
// The hint is a toast, not a log line: the row marker and the `N queued`
// footer are what stay on screen.
LaunchedEffect(hint) {
if (hint != null) {
delay(6_000)
hint = null
}
}
LaunchedEffect(messages?.size) {
val n = messages?.size ?: 0
if (n > 0) listState.animateScrollToItem(n - 1)
@ -127,8 +150,13 @@ 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.",
"Sends fail closed — nothing goes to a third party. If their " +
"onion is unreachable the message is queued in this " +
"device's outbox instead of being dropped: it stays " +
"local-only until the retry worker gets a circuit " +
"through (8 attempts, backoff capped at 30 min), then it " +
"lands. \u2713 means delivered, \u25f7 queued, " +
"\u2717 failed.",
style = MaterialTheme.typography.bodySmall,
color = MaterialTheme.colorScheme.onSurfaceVariant,
)
@ -149,25 +177,77 @@ 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),
)
// Outgoing rows only: the SDK reports `null` for
// inbound, and an outgoing row with no outbox
// entry reads "sent".
if (mine) {
deliveryMarker(m.delivery)?.let { marker ->
Text(
marker.text,
style = MaterialTheme.typography.labelSmall,
fontFamily = FontFamily.Monospace,
color = when (marker.tone) {
DeliveryTone.SENT ->
MaterialTheme.colorScheme.onSurfaceVariant
DeliveryTone.PENDING ->
MaterialTheme.colorScheme.tertiary
DeliveryTone.FAILED ->
MaterialTheme.colorScheme.error
},
modifier = Modifier.padding(
top = 2.dp,
end = 2.dp,
),
)
}
}
}
}
}
}
}
}
// TUI footer: `{n} queued` while the outbox still owns rows.
val queued = list?.count { it.direction == "out" && isOutboxPending(it.delivery) } ?: 0
if (queued > 0) {
Text(
"$queued queued",
style = MaterialTheme.typography.labelSmall,
fontFamily = FontFamily.Monospace,
color = MaterialTheme.colorScheme.tertiary,
modifier = Modifier.padding(horizontal = 12.dp, vertical = 4.dp),
)
}
hint?.let {
Text(
it,
style = MaterialTheme.typography.bodySmall,
color = MaterialTheme.colorScheme.tertiary,
modifier = Modifier.padding(horizontal = 12.dp, vertical = 4.dp),
)
}
error?.let {
Text(
it,

View file

@ -0,0 +1,78 @@
package com.siriusdevops.onionwire.ui
/**
* Per-row delivery markers for outgoing chat messages.
*
* The vocabulary is the TUI's (`docs/TUI.md` → "Delivery state (outbox)"), so
* both clients read the same:
*
* ```
* ✓ delivered — the peer's onion took the frame
* ◷ queued in this device's local outbox, waiting for a circuit
* » sending the retry worker has it in flight
* ✗ failed: … terminally failed (8 attempts, backoff capped at 30 min)
* ```
*
* The string comes from `ChatMessage.delivery` and is produced by the store's
* own outbox status — `"sent"` / `"queued"` / `"sending"` /
* `"failed: <reason>"` for outgoing rows, `null` for incoming ones. An outgoing
* row with no outbox row was accepted on the first attempt and reads `"sent"`.
*
* Nothing here guesses: a delivery string this build does not recognise renders
* no marker rather than a tick, because a missing marker never claims delivery
* while a wrong tick does.
*/
/** Which colour the marker is drawn in. */
internal enum class DeliveryTone {
/** Delivered to the peer's onion. */
SENT,
/** Still local-only: queued, or being retried right now. */
PENDING,
/** Out of attempts — the message never left this device. */
FAILED,
}
internal data class DeliveryMarker(val text: String, val tone: DeliveryTone)
/**
* Longest `failed: <reason>` tail we render before eliding. The TUI caps the
* same reason at 24 cells for its 80-column row; a phone bubble wraps, so this
* only exists to stop a pathological Tor error from filling the screen.
*/
private const val MAX_REASON_CHARS = 48
/** Marker for one outgoing row, or `null` when there is nothing to say. */
internal fun deliveryMarker(delivery: String?): DeliveryMarker? {
val state = delivery?.trim().orEmpty()
if (state.isEmpty()) return null
return when {
state == "sent" -> DeliveryMarker("\u2713", DeliveryTone.SENT)
state == "queued" -> DeliveryMarker("\u25f7 queued", DeliveryTone.PENDING)
state == "sending" -> DeliveryMarker("\u00bb sending", DeliveryTone.PENDING)
state.startsWith("failed") -> {
val reason = shortReason(state.substringAfter(':', "").trim())
DeliveryMarker(
if (reason.isEmpty()) "\u2717 failed" else "\u2717 failed: $reason",
DeliveryTone.FAILED,
)
}
// Unknown state: never render a tick for something we cannot read.
else -> null
}
}
/** True while the outbox still owns the row — the TUI's `{n} queued` footer. */
internal fun isOutboxPending(delivery: String?): Boolean {
val state = delivery?.trim().orEmpty()
return state == "queued" || state == "sending"
}
private fun shortReason(reason: String): String =
if (reason.length <= MAX_REASON_CHARS) {
reason
} else {
reason.take(MAX_REASON_CHARS - 1).trimEnd() + "\u2026"
}

View file

@ -0,0 +1,85 @@
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
/**
* The delivery vocabulary is shared with the TUI (`docs/TUI.md` → "Delivery
* state (outbox)"). These strings are the SDK's contract
* (`crates/onionwire-sdk/src/lib.rs`), so a drift here is a client that lies
* about a message having landed.
*/
class DeliveryMarkerTest {
@Test
fun delivered_row_gets_a_tick() {
val m = deliveryMarker("sent")
assertEquals(DeliveryMarker("\u2713", DeliveryTone.SENT), m)
}
@Test
fun queued_row_says_queued_not_delivered() {
val m = deliveryMarker("queued")
assertEquals(DeliveryMarker("\u25f7 queued", DeliveryTone.PENDING), m)
}
@Test
fun sending_row_is_pending() {
val m = deliveryMarker("sending")
assertEquals(DeliveryMarker("\u00bb sending", DeliveryTone.PENDING), m)
}
@Test
fun failed_row_carries_the_reason() {
val m = deliveryMarker("failed: connection timed out")
assertEquals(DeliveryMarker("\u2717 failed: connection timed out", DeliveryTone.FAILED), m)
}
@Test
fun failed_row_without_a_reason_still_reads_failed() {
assertEquals(
DeliveryMarker("\u2717 failed", DeliveryTone.FAILED),
deliveryMarker("failed"),
)
}
@Test
fun a_long_reason_is_elided() {
val m = deliveryMarker("failed: " + "x".repeat(200))
val text = m?.text.orEmpty()
assertTrue(text.startsWith("\u2717 failed: xxx"))
assertTrue(text.endsWith("\u2026"))
assertTrue("marker grew to ${text.length} chars", text.length <= 48 + "\u2717 failed: ".length)
}
@Test
fun incoming_row_has_no_marker() {
assertNull(deliveryMarker(null))
assertNull(deliveryMarker(""))
assertNull(deliveryMarker(" "))
}
@Test
fun unknown_state_never_claims_delivery() {
// Fail-safe: an unreadable state renders nothing rather than a tick.
assertNull(deliveryMarker("scheduled"))
assertNull(deliveryMarker("SENT"))
}
@Test
fun surrounding_whitespace_is_tolerated() {
assertEquals(DeliveryTone.SENT, deliveryMarker(" sent ")?.tone)
}
@Test
fun pending_counts_only_queued_and_sending() {
assertTrue(isOutboxPending("queued"))
assertTrue(isOutboxPending("sending"))
assertFalse(isOutboxPending("sent"))
assertFalse(isOutboxPending("failed: no route"))
assertFalse(isOutboxPending(null))
}
}

View file

@ -2774,6 +2774,7 @@ dependencies = [
"rusqlite",
"safelog",
"serde_json",
"sha2",
"sha3 0.10.9",
"snow",
"tokio",

View file

@ -18,8 +18,8 @@ onions directly. There is no `tor` binary, no torrc, no Orbot as the pipe.
| Onion | A **locator**, not an identity. It rotates. |
| Invite | `onionwire:v1:k=…:o=…:spk=…:sig=…` |
| Crypto | Noise IK (`Noise_IK_25519_ChaChaPoly_BLAKE2s`). `spk` is x25519. |
| Fail closed | Peer onion down → the send fails. No outbox, no spool in v1. |
| At rest | Chat bodies encrypted (Argon2id wrap + ChaCha20-Poly1305). Identity keys in sqlite are plaintext — that is honest, not an oversight. |
| Chat send | Unreachable peer onion → the message goes to the **local outbox** and is retried with backoff. `send()` returns `SendState.Sent` or `SendState.Queued`. File transfer and payments stay fail-closed. |
| At rest | The whole sqlite file is SQLCipher (key = Argon2id of the store passphrase), and chat bodies carry a second per-row ChaCha20-Poly1305 layer with row-bound AAD. Identity keys live in that same encrypted file. |
### Invite string
@ -66,8 +66,10 @@ Requirements:
## Kotlin surface
Everything is a `suspend fun` — Arti bootstrap and onion publish take minutes,
and a send retries the peer for up to 3 minutes before failing.
Everything is a `suspend fun` — Arti bootstrap and onion publish take minutes.
A send that cannot reach the peer comes back immediately as `QUEUED` (it is not
a long retry inside the call): the message is stored locally and a background
worker in the core keeps retrying it.
```kotlin
import uniffi.onionwire_sdk.*
@ -88,8 +90,16 @@ val friend: FriendInfo = wire.addFriend(pasted)
// 4. Roster and chat.
val roster: List<FriendInfo> = wire.friends()
wire.setPetname(friend.pubkeyHex, "ada")
wire.send(friend.pubkeyHex, "hello wire")
when (wire.send(friend.pubkeyHex, "hello wire")) {
SendState.SENT -> { /* the peer's onion took the frame */ }
SendState.QUEUED -> { /* unreachable: stored in the local outbox and
retried in the background. Show it as pending —
it is local-only until a circuit takes it. */ }
}
val msgs: List<ChatMessage> = wire.messages(friend.pubkeyHex)
// msgs[i].direction == "out" -> msgs[i].delivery is "sent" | "queued" |
// "sending" | "failed: <reason>"; null for incoming messages. Render the
// queued and failed states distinctly from sent.
// 5. Locator rotation. Do NOT wire this to a single tap — the app that embeds
// the SDK owns the typed confirmation.

View file

@ -11,7 +11,10 @@
//! the friend.
//! * Transport is in-process Arti. There is no `tor` binary, no torrc, no
//! Orbot pipe. If the onion service cannot publish, this fails closed.
//! * Chat bodies are encrypted at rest. Identity keys in sqlite are not.
//! * Chat bodies are encrypted at rest, and the whole sqlite file is
//! SQLCipher on top of that (see the root crate).
//! * A chat send that cannot reach the peer's onion is queued in a local
//! outbox and retried — see [`SendState`]. Nothing leaves the device.
//!
//! The façade deliberately exposes only plain data (records + hex strings) so
//! no TUI/ratatui type leaks into the AAR.
@ -20,6 +23,7 @@ use std::path::PathBuf;
use std::sync::{Arc, OnceLock};
use onionwire::node::Node;
use onionwire::outbox::OutboxStatus;
use onionwire::qr;
uniffi::setup_scaffolding!();
@ -79,11 +83,34 @@ pub struct FriendInfo {
pub last_connect_ok: bool,
}
/// What `send()` did with the message.
///
/// The core has a local outbox: when a friend's onion is unreachable the
/// message is written to the local sqlite store and a background worker
/// retries it with backoff. Nothing is handed to a third party — every attempt
/// is a fresh handshake straight to that friend's onion — but until a circuit
/// takes it the message exists only on this device. A consumer must not render
/// `Queued` as delivered.
#[derive(Debug, Clone, Copy, PartialEq, Eq, uniffi::Enum)]
pub enum SendState {
/// The frame reached the peer's onion service during this call.
Sent,
/// The peer's onion was unreachable: the message is in the local outbox,
/// local-only until the retry worker delivers it (or it ends `Failed`).
Queued,
}
#[derive(Debug, Clone, uniffi::Record)]
pub struct ChatMessage {
/// "in" or "out".
pub direction: String,
pub body: String,
/// Outgoing messages only: `"sent"`, `"queued"`, `"sending"` or
/// `"failed: <reason>"`. `None` for incoming messages. An outgoing row with
/// no outbox row is one the peer accepted on the first attempt, so it reads
/// `"sent"` — never treat a missing value as "delivered" on the app side,
/// read this field.
pub delivery: Option<String>,
}
#[derive(Debug, Clone, uniffi::Record)]
@ -188,28 +215,46 @@ impl Wire {
.map_err(WireError::new)
}
/// Send one message. Fail closed: if the peer's onion is down, this errors
/// after retrying. There is no outbox in v1 — no silent spooling.
pub async fn send(&self, pubkey_hex: String, body: String) -> WResult<()> {
/// Send one chat message.
///
/// Returns [`SendState::Sent`] when the frame reached the peer's onion
/// service during this call, and [`SendState::Queued`] when it did not: the
/// message is then in the local outbox and a background worker retries it
/// with exponential backoff (30s doubling, capped at 30 min, 8 attempts)
/// until it lands or ends terminally failed. A queued send is local-only —
/// show it as pending, not delivered.
///
/// A protocol error (signature mismatch, malformed or oversize frame) is
/// not retryable and still fails here; nothing is queued in that case.
pub async fn send(&self, pubkey_hex: String, body: String) -> WResult<SendState> {
let pk = unhex(&pubkey_hex)?;
self.inner
let status = self
.inner
.send(&pk, body.as_bytes())
.await
.map_err(WireError::new)
.map_err(WireError::new)?;
Ok(send_state(status))
}
/// Chat history for a friend, oldest first. Bodies are decrypted here;
/// they are stored encrypted at rest.
/// they are stored encrypted at rest. Outgoing rows carry their delivery
/// state in [`ChatMessage::delivery`].
pub async fn messages(&self, pubkey_hex: String) -> WResult<Vec<ChatMessage>> {
let pk = unhex(&pubkey_hex)?;
let rows = self.inner.list_messages(&pk).map_err(WireError::new)?;
Ok(rows
.into_iter()
.map(|m| ChatMessage {
direction: m.dir,
let mut out = Vec::with_capacity(rows.len());
for m in rows {
let status = self
.inner
.outbox_status_of_message(m.id)
.map_err(WireError::new)?;
out.push(ChatMessage {
body: String::from_utf8_lossy(&m.plaintext).into_owned(),
})
.collect())
delivery: delivery_of(&m.dir, status),
direction: m.dir,
});
}
Ok(out)
}
/// Delete every message body. Identity and friends survive.
@ -256,3 +301,70 @@ fn unhex(s: &str) -> WResult<Vec<u8>> {
})
.collect()
}
/// `Node::send` only ever yields `Sent` or `Queued`; `Sending`/`Failed` exist
/// only on stored outbox rows. Everything that is not a completed send maps to
/// `Queued`, so a status this build does not know about is never reported as
/// delivered — the fail-safe direction for a caller that hides its retry UI.
fn send_state(status: OutboxStatus) -> SendState {
match status {
OutboxStatus::Sent => SendState::Sent,
_ => SendState::Queued,
}
}
/// 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
/// reported as `"sent"` rather than left blank.
fn delivery_of(dir: &str, status: Option<OutboxStatus>) -> Option<String> {
if dir != "out" {
return None;
}
Some(match status {
None | Some(OutboxStatus::Sent) => "sent".to_string(),
Some(other) => other.to_string(),
})
}
#[cfg(test)]
mod tests {
use super::*;
use onionwire::outbox::OutboxStatus;
#[test]
fn sent_is_sent_everything_else_is_queued() {
assert_eq!(send_state(OutboxStatus::Sent), SendState::Sent);
assert_eq!(send_state(OutboxStatus::Queued), SendState::Queued);
// `Node::send` never returns these today, but they exist on stored
// rows. Unknown states map to `Queued` — the safe direction: never
// report a send as delivered unless the core says `Sent`.
assert_eq!(send_state(OutboxStatus::Sending), SendState::Queued);
assert_eq!(
send_state(OutboxStatus::Failed("no route".into())),
SendState::Queued
);
}
#[test]
fn delivery_is_reported_for_outgoing_rows_only() {
assert_eq!(delivery_of("in", Some(OutboxStatus::Queued)), None);
// Outgoing row with no outbox row: delivered on the first attempt.
assert_eq!(delivery_of("out", None).as_deref(), Some("sent"));
assert_eq!(
delivery_of("out", Some(OutboxStatus::Sent)).as_deref(),
Some("sent")
);
assert_eq!(
delivery_of("out", Some(OutboxStatus::Queued)).as_deref(),
Some("queued")
);
assert_eq!(
delivery_of("out", Some(OutboxStatus::Sending)).as_deref(),
Some("sending")
);
assert_eq!(
delivery_of("out", Some(OutboxStatus::Failed("no route".into()))).as_deref(),
Some("failed: no route")
);
}
}

View file

@ -19,7 +19,7 @@ SOCKS proxy.”
| Discovery | DHT + bootstrap nodes | Out-of-band invite only |
| After lookup | Direct IP or TCP relay (SOCKS if you forced it) | v3 onion ↔ v3 onion |
| Address | Tox ID lives in the DHT | ed25519 pubkey is identity; onion is a locator |
| Offline send | Expected (relays / retry) | Fail closed — no outbox |
| Offline send | Expected (relays / retry) | Queued locally, retried peer-to-peer (no relay) |
| Mixed clearnet | ToT can still talk to non-Tor Tox | No clearnet peers |
There is no directory, no name server, no introduction point of our own, and no
@ -51,8 +51,18 @@ not on the wire.
4. File transfer is N independent sessions (one handshake per chunk). There is
no multiplexed long-lived stream in v1.
If the onion is down, send fails. No retry queue except the locator-push path,
which retries for 180 seconds and then gives up.
If the onion is down, a **chat** send is persisted to the local outbox and
retried by a background worker with exponential backoff (30s, doubling, capped
at 30 min; 8 attempts, then terminal `Failed`). There is no server and no
store-and-forward relay: each attempt is a fresh handshake straight to
`(friend.onion, 80)`, exactly as above. Retries fire on a timer, on
unlock/foreground, and whenever that peer is heard from (successful handshake or
`connect_onion()`). A protocol failure — signature mismatch, unknown frame,
oversize — is not a transport failure and is never queued.
File transfer and payment frames stay fail-closed: they are one-shot and are
**not** queued. The locator-push path still retries for 180 seconds and then
gives up.
Incoming rendezvous accepts are token-bucket limited: 30 per 60s, burst 10.
Excess is dropped before handshake. That is availability, not anonymity.

View file

@ -24,7 +24,16 @@ Identity secret key, friend public keys, and locators remain plaintext in the sa
## Fail closed
Peer onion down → send fails. Fingerprint mismatch vs the pinned key → hard fail, no send. Arti HS experimental: if it cannot publish, OnionWire stops; it does not fall back to C-tor.
Peer onion down → a **chat** send is queued locally and retried (see “Local outbox (chat retry queue)”); file transfer and payment frames still fail immediately. Fingerprint mismatch vs the pinned key → hard fail, no send, never queued. Arti HS experimental: if it cannot publish, OnionWire stops; it does not fall back to C-tor.
## Local outbox (chat retry queue) is local, and it re-dials on a schedule
A chat send to an unreachable onion is written to an `outbox` row next to its `messages` row and retried in the background. There is no server-side queue: a queued message is never handed to a third party, and it dies with the device. Two consequences are real and are accepted:
- **Device seizure.** A pending (never-delivered) message sits in the same db as the rest of the history, under the same per-row AEAD and the same passphrase-derived key — no weaker, but also no shorter-lived. Seizure with the passphrase reveals messages that were never actually sent, including ones the sender may have moved on from. `/wipe` clears outbox rows with the rest of chat history; `/wipe-all` removes them with the data dir. Neither is a forensic erase.
- **Retry cadence is a local traffic-analysis surface.** A queued send re-dials the peer's onion on a backoff schedule while the app runs. An observer of your Tor client (or the network in front of it) sees a repeating connection attempt to one onion on a predictable cadence — it does not learn the plaintext or the recipient identity, but it can infer that you have an undelivered message for someone, and roughly when you composed it. The backoff is per-row, capped at one attempt per 30 min per message, and stops after 8 attempts or on a terminal failure.
The queue is bounded in scope: chat only. File transfer and `rcp` frames are one-shot, so a failed payment claim does not sit in the store being retried forever.
## Profile is friend-visible, not a directory
@ -65,5 +74,7 @@ the peer already knows the plaintext they sent.
## Out of v1
Prosody, XMPP, s2s, MAM, carbons, outbox, multi-device, DHT / name server,
sqlcipher, A/V.
Prosody, XMPP, s2s, MAM, carbons, a **server-side** outbox / store-and-forward
relay, multi-device, DHT / name server, sqlcipher, A/V. The local retry queue of
the previous section is not an outbox in the XMPP sense: it never leaves the
device.

View file

@ -351,6 +351,16 @@ Else RGB as today.
| box | ratatui `Borders::ALL` (light) | `+` `-` `\|` via `border::Set` |
| alert prefix | `! ` | `! ` |
| stale | word `stale` | `stale` |
| delivery: delivered | `✓` | `ok` |
| delivery: queued | `◷` | (word) `queued` |
| delivery: sending | `»` | (word) `sending` |
| delivery: failed | `✗` | (word) `failed` |
`queued` / `sending` / `failed` always carry their state word, so the ASCII
fallback drops the glyph instead of inventing one. Only `✓` is wordless, so it
falls back to `ok`. `delivery_glyph()` /
`tests/tui_spec.rs::delivery_markers_have_exercised_ascii_fallbacks` exercise the
fallback path.
No emoji. `onion_glyph()` stays for callers that already use it; do not put it
on the main header.
@ -401,6 +411,9 @@ Do not soften fail-closed into a loader.
| sending | `sending` (keep, no spinner) |
| sent | `sent` |
| peer down / send err | `send failed: {e}` (visible) |
| queued (outbox) | `{n} queued` — replaces the flat `sent`/`send failed` while rows are outstanding |
| queued + terminal failure | `{n} queued, send failed: {short}` |
| terminal failure | `send failed: {short}` (`{f} failed` when more than one) |
| already sending | `already sending` (keep) |
| stale friend | `stale` suffix (keep) |
| empty composer | `message` as dim placeholder (not the slash list). Slash list stays in `?` |
@ -570,3 +583,41 @@ cargo test --locked --test tui_spec -- --nocapture dump_spec_frames
Copy wired in `src/tui.rs` (not in the reconstructed standin): empty thread is
`no messages` / `type below, Enter sends`; paste error is `{err}` then
`Enter resubmits Esc back`; alerts truncate to the frame width.
## Delivery state (outbox) — implemented
Per-message state, read from the local outbox. The states are the store's own
(`Queued` / `Sending` / `Sent` / `Failed`) — no parallel model, no new wire
prefix, no server.
| Row | Marker |
|---|---|
| delivered | `you: ping ✓` |
| queued (2nd attempt, 45s out) | `you: pong ◷ queued (try 2/8, retry 45s)` |
| sending | `you: pong » sending` |
| failed | `you: pong ✗ failed: connection timed out` |
| inbound | `them: pong` (no marker) |
- `try {n}/{8}` is the outbox attempt count; `retry {s}s` / `retry {m}m` /
`retry now` comes from the stored absolute `next_attempt_at`.
- Failed reasons are sanitized, cut to the tail of the `a: b: c` chain and
capped at 24 cells (`short_send_reason`).
- Footer while rows are outstanding: `{n} queued`; any terminal failure keeps a
fail-closed `send failed: {short}` statement (with `! ` when colour is off).
- The tag trails the body and wraps with it, so it is never clipped away.
Correlation: a delivered row is deleted from the outbox, so an outbound message
with no row is `Sent`; pending rows are joined to messages on the row id —
`store::Message::id` equals `OutboxEntry::message_id` (`chat_with_delivery`).
Two identical bodies are distinct rows with distinct ids, so the marker always
lands on the row that actually owns the outbox entry.
### Size floor / target
- **Floor: 80x24.** Everything above must render there.
- **Target: 120x40.**
- `tests/tui_spec.rs::chat_and_footer_rows_fit_80x24_and_wrap_instead_of_clipping`
draws the real `draw_chat` + `status_footer` at 80x24 and asserts every chat
and footer row is `<=` the terminal width, that the markers render, and that
an over-long message wraps instead of being clipped.
- Dump frames: `cargo test --locked --test tui_spec -- --nocapture dump_spec_frames`.

View file

@ -5,6 +5,7 @@ pub mod frame;
pub mod hs;
pub mod loc;
pub mod node;
pub mod outbox;
pub mod pay;
pub mod profile;
pub mod qr;

View file

@ -14,6 +14,7 @@ use crate::file;
use crate::frame;
use crate::hs::{self, Client, HS_PORT};
use crate::loc;
use crate::outbox::{ArtiDeliverer, Outbox, OutboxStatus};
use crate::pay;
use crate::profile;
use crate::qr;
@ -39,9 +40,18 @@ impl Drop for HsHandle {
}
}
/// Abort the outbox worker when the node goes away.
struct WorkerHandle(tokio::task::JoinHandle<()>);
impl Drop for WorkerHandle {
fn drop(&mut self) {
self.0.abort();
}
}
pub struct Node {
home: PathBuf,
store: Mutex<Store>,
store: Arc<Mutex<Store>>,
client: Client,
hs: Mutex<Option<HsHandle>>,
onion: Mutex<String>,
@ -49,6 +59,8 @@ pub struct Node {
wallet: Wallet,
incoming_limit: Mutex<TokenBucket>,
inbox: Mutex<file::Inbox>,
outbox: Arc<Outbox>,
_outbox_worker: WorkerHandle,
}
impl Node {
@ -79,9 +91,17 @@ impl Node {
let (svc, rend) = launched;
let onion = hs::onion_string(&svc)?;
let inbox = file::Inbox::new(home.join("inbox"));
let store = Arc::new(Mutex::new(store));
let outbox = Arc::new(Outbox::new(
Arc::clone(&store),
Arc::new(ArtiDeliverer::new(client.clone(), keys.clone())),
));
if let Err(e) = outbox.reset_stale() {
eprintln!("outbox: {e}");
}
let node = Arc::new(Self {
home,
store: Mutex::new(store),
store,
client,
hs: Mutex::new(None),
onion: Mutex::new(onion.clone()),
@ -89,7 +109,12 @@ impl Node {
wallet: Wallet::from_env(),
incoming_limit: Mutex::new(TokenBucket::default()),
inbox: Mutex::new(inbox),
outbox: Arc::clone(&outbox),
_outbox_worker: WorkerHandle(outbox.spawn_worker()),
});
// Unlock trigger: flush anything queued by a previous run now, in the
// background, rather than waiting out its backoff.
spawn_flush_all(Arc::clone(&node.outbox));
// Accept rens before waiting so a reachability probe can succeed
// while combined status is still Bootstrapping.
let rend = spawn_rend(Arc::clone(&node), rend);
@ -416,6 +441,8 @@ impl Node {
self.try_send(&onion, friend_pk, &prekey, plaintext).await
}
/// Dial a peer's onion. Success is evidence the peer is up, which is one of
/// the outbox retry triggers.
pub async fn connect_onion(&self, onion: &str) -> Result<(), String> {
tokio::time::timeout(
Duration::from_secs(20),
@ -424,6 +451,14 @@ impl Node {
.await
.map_err(|_| format!("connect {onion}:{HS_PORT} timed out"))?
.map_err(|e| format!("connect {onion}:{HS_PORT}: {e}"))?;
if let Ok(Some(friend)) = self
.store
.lock()
.map_err(|e| e.to_string())
.and_then(|s| s.friend_by_onion(onion).map_err(|e| e.to_string()))
{
spawn_flush_friend(Arc::clone(&self.outbox), friend.pubkey);
}
Ok(())
}
@ -506,36 +541,30 @@ impl Node {
Ok(name)
}
pub async fn send(&self, friend_pk: &[u8], plaintext: &[u8]) -> Result<(), String> {
let (onion, prekey) = {
let store = self.store.lock().map_err(|e| e.to_string())?;
let f = store
.get_friend(friend_pk)
.map_err(|e| e.to_string())?
.ok_or_else(|| "unknown friend".to_string())?;
if f.prekey.len() != 32 {
return Err("friend missing prekey".into());
}
(f.onion, f.prekey)
};
let deadline = Instant::now() + Duration::from_secs(180);
let mut last = None::<String>;
while Instant::now() < deadline {
match self.try_send(&onion, friend_pk, &prekey, plaintext).await {
Ok(()) => {
self.store
.lock()
.map_err(|e| e.to_string())?
.append_message(friend_pk, "out", plaintext)
.map_err(|e| e.to_string())?;
return Ok(());
}
Err(e) if e.contains("fingerprint mismatch") => return Err(e),
Err(e) => last = Some(e),
}
tokio::time::sleep(Duration::from_secs(3)).await;
}
Err(last.unwrap_or_else(|| "send timed out".into()))
/// Send one chat message. Returns `Sent` when it went out now and `Queued`
/// when the peer's onion is unreachable — the outbox worker then retries with
/// backoff. A real protocol error (signature mismatch, unknown/short/oversize
/// frame) still fails immediately and is never retried.
pub async fn send(&self, friend_pk: &[u8], plaintext: &[u8]) -> Result<OutboxStatus, String> {
self.outbox.send(friend_pk, plaintext).await
}
/// Pending and failed outbox rows for a friend, for UI surfacing.
/// Delivered rows are dropped, so a message absent here was sent.
pub fn outbox_pending(&self, friend_pk: &[u8]) -> Result<Vec<crate::store::OutboxEntry>, String> {
self.outbox.pending(friend_pk)
}
pub fn outbox_status_of_message(
&self,
message_id: i64,
) -> Result<Option<OutboxStatus>, String> {
self.outbox.status_of_message(message_id)
}
/// Foreground/unlock trigger: try every outstanding queued send now.
pub fn flush_outbox(&self) {
spawn_flush_all(Arc::clone(&self.outbox));
}
async fn push_loc(
@ -568,20 +597,10 @@ impl Node {
remote_prekey: &[u8],
plaintext: &[u8],
) -> Result<(), String> {
let mut stream = self
.client
.connect((onion, HS_PORT))
self.outbox
.deliverer()
.deliver(onion, pinned_id, remote_prekey, plaintext)
.await
.map_err(|e| format!("connect {onion}:{HS_PORT}: {e}"))?;
let keys = self.keys()?;
let mut sess = session::handshake_initiator(&mut stream, &keys, pinned_id, remote_prekey)
.await
.map_err(session_err)?;
let ct = sess.encrypt(plaintext).map_err(session_err)?;
frame::write_frame(&mut stream, &ct)
.await
.map_err(|e| e.to_string())?;
Ok(())
}
async fn handle_incoming<S>(&self, stream: &mut S) -> Result<(), String>
@ -598,6 +617,9 @@ impl Node {
})
.await
.map_err(session_err)?;
// Trigger (c): the peer just proved they are online. Try their queued
// sends now instead of waiting out the backoff, off this stream's path.
spawn_flush_friend(Arc::clone(&self.outbox), sess.peer_identity.clone());
let ct = frame::read_frame(stream).await.map_err(|e| e.to_string())?;
let pt = sess.decrypt(&ct).map_err(session_err)?;
match dispatch::classify(&pt) {
@ -814,6 +836,24 @@ fn spawn_rend(
})
}
/// Foreground/unlock flush: every outstanding queued send gets one attempt now.
fn spawn_flush_all(outbox: Arc<Outbox>) {
tokio::spawn(async move {
if let Err(e) = outbox.flush_all(unix_now()).await {
eprintln!("outbox: {e}");
}
});
}
/// We just saw this peer (handshake or successful dial): try their queue now.
fn spawn_flush_friend(outbox: Arc<Outbox>, friend_pk: Vec<u8>) {
tokio::spawn(async move {
if let Err(e) = outbox.flush_friend(&friend_pk, unix_now()).await {
eprintln!("outbox: {e}");
}
});
}
fn next_hs_nickname(cur: &str) -> String {
let n = cur
.strip_prefix("ow")

308
src/outbox.rs Normal file
View file

@ -0,0 +1,308 @@
//! Local-only outbox.
//!
//! When a peer's v3 onion cannot be dialed, a chat send is persisted locally and
//! retried by a background worker with exponential backoff. There is no server
//! and no store-and-forward relay: every attempt is a fresh Noise IK handshake
//! straight to the friend's onion, so a queued message is never handed to a
//! third party. File transfer and payment frames stay fail-closed — only chat
//! goes through here.
use std::future::Future;
use std::pin::Pin;
use std::sync::{Arc, Mutex, MutexGuard};
use std::time::{Duration, SystemTime, UNIX_EPOCH};
use tokio::sync::Notify;
use crate::frame;
use crate::hs::{Client, HS_PORT};
use crate::session::{self, Keys};
use crate::store::Store;
pub use crate::store::{OutboxEntry, OutboxStatus};
/// First retry waits this long.
pub const BACKOFF_START_SECS: i64 = 30;
/// Backoff never sleeps longer than this.
pub const BACKOFF_CAP_SECS: i64 = 1_800;
/// Attempts after which a queued message is terminally `Failed`.
pub const DEFAULT_MAX_ATTEMPTS: u32 = 8;
/// Worker scan period. The shortest backoff is 30s, so a slower scan still
/// lands each retry close to its schedule without busy-waiting.
pub const WORKER_TICK: Duration = Duration::from_secs(15);
/// Cap on rows attempted in one pass, so a big backlog cannot monopolize the
/// worker.
const MAX_PER_PASS: i64 = 32;
pub type BoxFut<'a, T> = Pin<Box<dyn Future<Output = T> + Send + 'a>>;
/// Pure backoff schedule, asserted numerically by a unit test: 30s, 60s, 120s…
/// capped at 30 min. `attempt` is the number of retries already made.
pub fn backoff_secs(attempt: u32) -> i64 {
// 30 << 16 is the largest shift we ever need to reach the cap, so this
// cannot overflow even for a silly attempt count.
(BACKOFF_START_SECS << attempt.min(16)).min(BACKOFF_CAP_SECS)
}
/// Protocol failures: another attempt cannot fix a bad signature, a bad frame
/// header, or an oversize payload, so they must fail loudly and never queue.
const PERMANENT_ERRORS: &[&str] = &[
"fingerprint mismatch",
"bad identity proof",
"unexpected handshake payload",
"frame too large",
"bad version",
"length mismatch",
"short frame",
];
pub fn is_permanent_send_error(err: &str) -> bool {
PERMANENT_ERRORS.iter().any(|p| err.contains(p))
}
/// One delivery attempt. Implemented by Arti for real sends and by tests for a
/// fake or flaky peer.
pub trait Deliverer: Send + Sync {
fn deliver<'a>(
&'a self,
onion: &'a str,
pinned_id: &'a [u8],
prekey: &'a [u8],
plaintext: &'a [u8],
) -> BoxFut<'a, Result<(), String>>;
}
/// Real transport: dial the v3 onion, Noise IK handshake pinned to the friend's
/// identity key, send exactly one application frame, drop the circuit.
pub struct ArtiDeliverer {
client: Client,
keys: Keys,
}
impl ArtiDeliverer {
pub fn new(client: Client, keys: Keys) -> Self {
Self { client, keys }
}
}
impl Deliverer for ArtiDeliverer {
fn deliver<'a>(
&'a self,
onion: &'a str,
pinned_id: &'a [u8],
prekey: &'a [u8],
plaintext: &'a [u8],
) -> BoxFut<'a, Result<(), String>> {
Box::pin(async move {
let mut stream = self
.client
.connect((onion, HS_PORT))
.await
.map_err(|e| format!("connect {onion}:{HS_PORT}: {e}"))?;
let mut sess =
session::handshake_initiator(&mut stream, &self.keys, pinned_id, prekey)
.await
.map_err(|e| e.into_message())?;
let ct = sess.encrypt(plaintext).map_err(|e| e.into_message())?;
frame::write_frame(&mut stream, &ct)
.await
.map_err(|e| e.to_string())?;
Ok(())
})
}
}
pub struct Outbox {
store: Arc<Mutex<Store>>,
deliverer: Arc<dyn Deliverer>,
max_attempts: u32,
wake: Notify,
}
impl Outbox {
pub fn new(store: Arc<Mutex<Store>>, deliverer: Arc<dyn Deliverer>) -> Self {
Self {
store,
deliverer,
max_attempts: DEFAULT_MAX_ATTEMPTS,
wake: Notify::new(),
}
}
pub fn with_max_attempts(mut self, max: u32) -> Self {
self.max_attempts = max.max(1);
self
}
/// The transport, for callers (locator/profile pushes) that stay fail-closed
/// and must not queue.
pub fn deliverer(&self) -> &dyn Deliverer {
self.deliverer.as_ref()
}
/// Try once. `Ok(Sent)` — delivered now. `Ok(Queued)` — the peer's onion is
/// unreachable, the message is persisted and will be retried. `Err` — a
/// protocol error or a bad local state, never retried.
pub async fn send(&self, friend_pk: &[u8], plaintext: &[u8]) -> Result<OutboxStatus, String> {
let (onion, prekey) = self.target(friend_pk)?;
match self.deliverer.deliver(&onion, friend_pk, &prekey, plaintext).await {
Ok(()) => {
self.store()?.append_message(friend_pk, "out", plaintext)?;
Ok(OutboxStatus::Sent)
}
Err(e) if is_permanent_send_error(&e) => Err(e),
Err(e) => {
let now = unix_now();
let store = self.store()?;
let message_id = store.append_message_id(friend_pk, "out", plaintext)?;
store.enqueue_outbox(
friend_pk,
message_id,
1,
now + backoff_secs(0),
&e,
now,
)?;
Ok(OutboxStatus::Queued)
}
}
}
/// Timer trigger: every row whose backoff has elapsed gets one attempt.
pub async fn tick(&self, now: i64) -> Result<Vec<(i64, OutboxStatus)>, String> {
let due = self.store()?.due_outbox(now, MAX_PER_PASS)?;
self.attempt(due, now).await
}
/// Unlock / foreground trigger: every outstanding row gets one attempt now,
/// regardless of where it sits in the backoff.
pub async fn flush_all(&self, now: i64) -> Result<Vec<(i64, OutboxStatus)>, String> {
let rows = self.store()?.all_pending_outbox(MAX_PER_PASS)?;
self.attempt(rows, now).await
}
/// Trigger (c): we just heard from this peer, so try their rows immediately.
pub async fn flush_friend(
&self,
friend_pk: &[u8],
now: i64,
) -> Result<Vec<(i64, OutboxStatus)>, String> {
let rows = self.store()?.outbox_for_friend(friend_pk)?;
self.attempt(rows, now).await
}
/// Pending and failed rows for one friend. Delivered rows are deleted, so a
/// message that is not here was either sent first try or flushed since.
pub fn pending(&self, friend_pk: &[u8]) -> Result<Vec<OutboxEntry>, String> {
self.store()?.pending_outbox(friend_pk).map_err(store_err)
}
pub fn status_of_message(&self, message_id: i64) -> Result<Option<OutboxStatus>, String> {
self.store()?
.outbox_status_of_message(message_id)
.map_err(store_err)
}
/// A process that died mid-attempt leaves `sending` rows behind; requeue
/// them on unlock so they are retried instead of stranded.
pub fn reset_stale(&self) -> Result<usize, String> {
self.store()?.reset_sending_outbox().map_err(store_err)
}
/// Wake the worker (e.g. after `flush_all` was queued from a UI thread).
pub fn kick(&self) {
self.wake.notify_one();
}
/// Background retry worker. Aborted by dropping the returned handle.
pub fn spawn_worker(self: &Arc<Self>) -> tokio::task::JoinHandle<()> {
let me = Arc::clone(self);
tokio::spawn(async move {
loop {
if let Err(e) = me.tick(unix_now()).await {
eprintln!("outbox: {e}");
}
tokio::select! {
_ = tokio::time::sleep(WORKER_TICK) => {}
_ = me.wake.notified() => {}
}
}
})
}
async fn attempt(
&self,
rows: Vec<OutboxEntry>,
now: i64,
) -> Result<Vec<(i64, OutboxStatus)>, String> {
let mut out = Vec::with_capacity(rows.len());
for entry in rows {
self.store()?.mark_outbox_sending(entry.id, now)?;
let (onion, prekey) = match self.target(&entry.friend_pk) {
Ok(t) => t,
Err(e) => {
self.store()?.mark_outbox_failed(entry.id, now, &e)?;
out.push((entry.id, OutboxStatus::Failed(e)));
continue;
}
};
let result = self
.deliverer
.deliver(&onion, &entry.friend_pk, &prekey, &entry.body)
.await;
let status = match result {
Ok(()) => {
self.store()?.mark_outbox_sent(entry.id)?;
OutboxStatus::Sent
}
Err(e) if is_permanent_send_error(&e) => {
self.store()?.mark_outbox_failed(entry.id, now, &e)?;
OutboxStatus::Failed(e)
}
Err(e) => {
let attempts = entry.attempts.saturating_add(1);
if attempts >= self.max_attempts {
self.store()?.mark_outbox_failed(entry.id, now, &e)?;
OutboxStatus::Failed(e)
} else {
let next = now + backoff_secs(attempts - 1);
self.store()?
.mark_outbox_retry(entry.id, attempts, next, now, &e)?;
OutboxStatus::Queued
}
}
};
out.push((entry.id, status));
}
Ok(out)
}
/// Friend's current locator + Noise static. Missing prekey means the invite
/// was never completed — retrying cannot fix that, so it is fatal.
fn target(&self, friend_pk: &[u8]) -> Result<(String, Vec<u8>), String> {
let store = self.store()?;
let f = store
.get_friend(friend_pk)
.map_err(store_err)?
.ok_or_else(|| "unknown friend".to_string())?;
if f.prekey.len() != 32 {
return Err("friend missing prekey".into());
}
Ok((f.onion, f.prekey))
}
fn store(&self) -> Result<MutexGuard<'_, Store>, String> {
self.store.lock().map_err(|e| e.to_string())
}
}
fn store_err(e: crate::store::Error) -> String {
e.to_string()
}
fn unix_now() -> i64 {
SystemTime::now()
.duration_since(UNIX_EPOCH)
.map(|d| d.as_secs() as i64)
.unwrap_or(0)
}

View file

@ -35,6 +35,16 @@ impl Error {
pub fn is_fingerprint_mismatch(&self) -> bool {
self.mismatch
}
/// String for the UI: a pinned-identity mismatch gets the documented banner,
/// everything else is the underlying snow/framing message.
pub fn into_message(self) -> String {
if self.mismatch {
crate::tui::fingerprint_mismatch_banner().to_string()
} else {
self.msg
}
}
}
impl std::fmt::Display for Error {

View file

@ -40,6 +40,15 @@ impl From<String> for Error {
}
}
/// The store error is a message and nothing else, and the rest of the crate
/// (transport, UI) already speaks `String`. Lossless, so `?` is enough at the
/// outbox boundary — no per-call `map_err`.
impl From<Error> for String {
fn from(e: Error) -> Self {
e.0
}
}
pub struct Store {
conn: Connection,
msg_key: [u8; 32],
@ -71,6 +80,9 @@ pub struct FriendProfile {
#[derive(Debug)]
pub struct Message {
/// `messages.id` row id. The outbox row for a send carries the same
/// `message_id`, so the UI can join exactly instead of matching bodies.
pub id: i64,
pub dir: String,
pub plaintext: Vec<u8>,
}
@ -88,6 +100,64 @@ pub struct Payment {
pub created_at: i64,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum OutboxStatus {
Queued,
Sending,
Sent,
/// Terminal: transport or protocol failure that will not be retried.
Failed(String),
}
impl OutboxStatus {
pub fn is_terminal(&self) -> bool {
matches!(self, OutboxStatus::Sent | OutboxStatus::Failed(_))
}
/// Column encoding for the `outbox.status` CHECK constraint.
pub fn as_db_str(&self) -> &'static str {
match self {
OutboxStatus::Queued => "queued",
OutboxStatus::Sending => "sending",
OutboxStatus::Sent => "sent",
OutboxStatus::Failed(_) => "failed",
}
}
pub fn from_db(status: &str, last_error: Option<&str>) -> Self {
match status {
"sending" => OutboxStatus::Sending,
"sent" => OutboxStatus::Sent,
"failed" => OutboxStatus::Failed(last_error.unwrap_or("failed").to_string()),
_ => OutboxStatus::Queued,
}
}
}
impl std::fmt::Display for OutboxStatus {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
OutboxStatus::Failed(why) => write!(f, "failed: {why}"),
other => f.write_str(other.as_db_str()),
}
}
}
/// One queued chat send. The body is not copied: it lives in the `messages`
/// row the outbox row points at, under that row's own AEAD.
#[derive(Debug, Clone)]
pub struct OutboxEntry {
pub id: i64,
pub friend_pk: Vec<u8>,
pub message_id: i64,
pub body: Vec<u8>,
pub attempts: u32,
pub next_attempt_at: i64,
pub created_at: i64,
pub status: OutboxStatus,
pub last_error: Option<String>,
}
pub struct PaymentWrite<'a> {
pub dir: &'a str,
pub kind: &'a str,
@ -189,6 +259,18 @@ impl Store {
verified INTEGER NOT NULL DEFAULT 0,
created_at INTEGER NOT NULL
);
CREATE TABLE IF NOT EXISTS outbox (
id INTEGER PRIMARY KEY,
friend_id INTEGER NOT NULL REFERENCES friends(id),
message_id INTEGER NOT NULL,
attempts INTEGER NOT NULL DEFAULT 0,
next_attempt_at INTEGER NOT NULL,
status TEXT NOT NULL CHECK(status IN ('queued','sending','sent','failed')),
last_error TEXT,
created_at INTEGER NOT NULL,
updated_at INTEGER NOT NULL
);
CREATE INDEX IF NOT EXISTS outbox_due ON outbox (status, next_attempt_at);
INSERT OR IGNORE INTO self_profile (id) VALUES (1);
",
)?;
@ -475,6 +557,20 @@ impl Store {
.map_err(Into::into)
}
/// Locator → friend. Onions are not unique in the schema (a stale row can
/// hold a rotated address), so the first match wins; the outbox uses this
/// only to pick which queue to flush early.
pub fn friend_by_onion(&self, onion: &str) -> Result<Option<Friend>> {
self.conn
.query_row(
"SELECT pubkey, fingerprint, petname, onion, last_connect_ok, prekey FROM friends WHERE onion = ?1 ORDER BY id LIMIT 1",
params![onion],
friend_from_row,
)
.optional()
.map_err(Into::into)
}
pub fn list_friends(&self) -> Result<Vec<Friend>> {
let mut stmt = self.conn.prepare(
"SELECT pubkey, fingerprint, petname, onion, last_connect_ok, prekey FROM friends
@ -699,6 +795,17 @@ impl Store {
}
pub fn append_message(&self, friend_pk: &[u8], dir: &str, plaintext: &[u8]) -> Result<()> {
self.append_message_id(friend_pk, dir, plaintext).map(|_| ())
}
/// Same as `append_message`, returning the row id so an outbox row can
/// point at the body instead of storing a second copy.
pub fn append_message_id(
&self,
friend_pk: &[u8],
dir: &str,
plaintext: &[u8],
) -> Result<i64> {
if dir != "in" && dir != "out" {
return Err(Error("dir must be in or out".into()));
}
@ -723,7 +830,7 @@ impl Store {
params![blob, row_id],
)?;
tx.commit()?;
Ok(())
Ok(row_id)
}
pub fn list_messages(&self, friend_pk: &[u8]) -> Result<Vec<Message>> {
@ -747,7 +854,195 @@ impl Store {
let aad = message_aad(friend_id, &dir, id);
let plaintext = crate::backup::aead_decrypt(&self.msg_key, &blob, &aad)
.map_err(|_| Error("message decrypt failed".into()))?;
out.push(Message { dir, plaintext });
out.push(Message {
id,
dir,
plaintext,
});
}
Ok(out)
}
/// Queue one already-stored chat message for retry. `next_attempt_at` is an
/// absolute unix second; `now` is used for created_at/updated_at so the
/// caller and the row agree on the clock.
pub fn enqueue_outbox(
&self,
friend_pk: &[u8],
message_id: i64,
attempts: u32,
next_attempt_at: i64,
last_error: &str,
now: i64,
) -> Result<i64> {
let friend_id: i64 = self
.conn
.query_row(
"SELECT id FROM friends WHERE pubkey = ?1",
params![friend_pk],
|row| row.get(0),
)
.map_err(|_| Error("friend not found".into()))?;
self.conn.execute(
"INSERT INTO outbox (friend_id, message_id, attempts, next_attempt_at, status, last_error, created_at, updated_at)
VALUES (?1, ?2, ?3, ?4, 'queued', ?5, ?6, ?6)",
params![friend_id, message_id, attempts, next_attempt_at, last_error, now],
)?;
Ok(self.conn.last_insert_rowid())
}
/// Rows whose backoff has elapsed: the timer trigger for the worker.
pub fn due_outbox(&self, now: i64, limit: i64) -> Result<Vec<OutboxEntry>> {
self.outbox_query(
&format!(
"{OUTBOX_SELECT} WHERE o.status = 'queued' AND o.next_attempt_at <= ?1
ORDER BY o.next_attempt_at, o.id LIMIT ?2"
),
params![now, limit],
)
}
/// Unscheduleable rows for one friend (queued or mid-attempt): the
/// "we just heard from this peer" trigger, which ignores the backoff.
pub fn outbox_for_friend(&self, friend_pk: &[u8]) -> Result<Vec<OutboxEntry>> {
self.outbox_query(
&format!(
"{OUTBOX_SELECT} WHERE f.pubkey = ?1 AND o.status IN ('queued','sending')
ORDER BY o.id"
),
params![friend_pk],
)
}
/// Every row the worker may still try: the unlock/foreground trigger.
pub fn all_pending_outbox(&self, limit: i64) -> Result<Vec<OutboxEntry>> {
self.outbox_query(
&format!(
"{OUTBOX_SELECT} WHERE o.status IN ('queued','sending')
ORDER BY o.next_attempt_at, o.id LIMIT ?1"
),
params![limit],
)
}
/// Pending and failed rows for one friend — what a UI shows as not-yet-sent.
/// Delivered rows are deleted, so absence means "sent".
pub fn pending_outbox(&self, friend_pk: &[u8]) -> Result<Vec<OutboxEntry>> {
self.outbox_query(
&format!(
"{OUTBOX_SELECT} WHERE f.pubkey = ?1 AND o.status IN ('queued','sending','failed')
ORDER BY o.id"
),
params![friend_pk],
)
}
pub fn outbox_status_of_message(&self, message_id: i64) -> Result<Option<OutboxStatus>> {
let row: Option<(String, Option<String>)> = self
.conn
.query_row(
"SELECT status, last_error FROM outbox WHERE message_id = ?1 ORDER BY id DESC LIMIT 1",
params![message_id],
|r| Ok((r.get(0)?, r.get(1)?)),
)
.optional()?;
Ok(row.map(|(s, e)| OutboxStatus::from_db(&s, e.as_deref())))
}
pub fn mark_outbox_sending(&self, id: i64, now: i64) -> Result<()> {
self.conn.execute(
"UPDATE outbox SET status = 'sending', updated_at = ?1 WHERE id = ?2",
params![now, id],
)?;
Ok(())
}
/// Delivered. The row is dropped — the chat history is the record, and a
/// per-message status table would grow without bound.
pub fn mark_outbox_sent(&self, id: i64) -> Result<()> {
self.conn
.execute("DELETE FROM outbox WHERE id = ?1", params![id])?;
Ok(())
}
pub fn mark_outbox_failed(&self, id: i64, now: i64, why: &str) -> Result<()> {
self.conn.execute(
"UPDATE outbox SET status = 'failed', last_error = ?1, updated_at = ?2 WHERE id = ?3",
params![why, now, id],
)?;
Ok(())
}
pub fn mark_outbox_retry(
&self,
id: i64,
attempts: u32,
next_attempt_at: i64,
now: i64,
why: &str,
) -> Result<()> {
self.conn.execute(
"UPDATE outbox SET status = 'queued', attempts = ?1, next_attempt_at = ?2, last_error = ?3, updated_at = ?4 WHERE id = ?5",
params![attempts, next_attempt_at, why, now, id],
)?;
Ok(())
}
/// A row left in 'sending' means we died mid-attempt. Requeue on unlock.
pub fn reset_sending_outbox(&self) -> Result<usize> {
let n = self.conn.execute(
"UPDATE outbox SET status = 'queued' WHERE status = 'sending'",
[],
)?;
Ok(n)
}
fn outbox_query(&self, sql: &str, args: &[&dyn rusqlite::ToSql]) -> Result<Vec<OutboxEntry>> {
let mut stmt = self.conn.prepare(sql)?;
let rows = stmt.query_map(args, |row| {
Ok((
row.get::<_, i64>(0)?,
row.get::<_, Vec<u8>>(1)?,
row.get::<_, i64>(2)?,
row.get::<_, i64>(3)?,
row.get::<_, i64>(4)?,
row.get::<_, String>(5)?,
row.get::<_, Option<String>>(6)?,
row.get::<_, i64>(7)?,
row.get::<_, i64>(8)?,
row.get::<_, String>(9)?,
row.get::<_, Vec<u8>>(10)?,
))
})?;
let mut out = Vec::new();
for row in rows {
let (
id,
friend_pk,
message_id,
attempts,
next_attempt_at,
status,
last_error,
created_at,
m_friend_id,
dir,
blob,
) = row?;
let aad = message_aad(m_friend_id, &dir, message_id);
let body = crate::backup::aead_decrypt(&self.msg_key, &blob, &aad)
.map_err(|_| Error("outbox body decrypt failed".into()))?;
out.push(OutboxEntry {
id,
friend_pk,
message_id,
body,
attempts: attempts as u32,
next_attempt_at,
created_at,
status: OutboxStatus::from_db(&status, last_error.as_deref()),
last_error,
});
}
Ok(out)
}
@ -755,6 +1050,7 @@ impl Store {
/// Drop chat + payments history. Identity + friends stay.
/// Not a forensic erase: SSD wear-leveling can keep copies.
pub fn wipe_messages(&self) -> Result<()> {
self.conn.execute("DELETE FROM outbox", [])?;
self.conn.execute(
"UPDATE messages SET plaintext = zeroblob(length(plaintext))",
[],
@ -859,6 +1155,12 @@ fn mkdir_700(path: &Path) -> Result<()> {
Ok(())
}
/// Base projection for outbox rows: the body comes from the `messages` row the
/// outbox row points at, so it stays under that row's AEAD + AAD.
const OUTBOX_SELECT: &str = "SELECT o.id, f.pubkey, o.message_id, o.attempts, o.next_attempt_at, \
o.status, o.last_error, o.created_at, m.friend_id, m.dir, m.plaintext \
FROM outbox o JOIN friends f ON f.id = o.friend_id JOIN messages m ON m.id = o.message_id";
/// AAD: `owmsg1` || friend_id_le64 || dir || 0x00 || row_id_le64
fn message_aad(friend_id: i64, dir: &str, row_id: i64) -> Vec<u8> {
let mut aad = Vec::with_capacity(6 + 8 + dir.len() + 1 + 8);

View file

@ -1,6 +1,7 @@
use std::collections::HashMap;
use std::io::{self, IsTerminal};
use std::sync::{Arc, mpsc};
use std::time::Duration;
use std::time::{Duration, SystemTime, UNIX_EPOCH};
use ratatui::crossterm::event::{self, Event, KeyCode, KeyEvent, KeyEventKind, KeyModifiers};
use ratatui::layout::{Constraint, Layout, Rect};
@ -10,9 +11,10 @@ use ratatui::widgets::{Block, Borders, Clear, List, ListItem, ListState, Paragra
use ratatui::{DefaultTerminal, Frame};
use crate::node::Node;
use crate::outbox::DEFAULT_MAX_ATTEMPTS;
use crate::qr::{self, QrPayload};
use crate::sanitize;
use crate::store::{Friend, FriendProfile};
use crate::store::{Friend, FriendProfile, Message, OutboxEntry, OutboxStatus};
const C_ACCENT: Color = Color::Rgb(232, 165, 75);
const C_TEXT: Color = Color::Rgb(196, 214, 176);
@ -116,6 +118,200 @@ pub fn empty_friend_chat_text() -> &'static str {
"no messages\ntype below, Enter sends"
}
// ---------------------------------------------------------------------------
// Delivery state (outbox)
//
// The outbox is the only source of per-message state: `Queued` / `Sending` /
// `Failed` rows are what `Node::outbox_pending` still holds, and a row is
// deleted the moment the send crosses the circuit — so an outbound message with
// no row is `Sent`. No parallel state model, no new wire prefix.
// ---------------------------------------------------------------------------
/// Longest short-form failure reason shown in a chat row.
pub const FAIL_REASON_BUDGET: usize = 24;
/// Marker glyph for one delivery state. ASCII chrome falls back to `ok` for the
/// wordless delivered state; `queued` / `sending` / `failed` already carry their
/// word, so their glyph is dropped rather than invented.
pub fn delivery_glyph(status: &OutboxStatus) -> &'static str {
let ascii = ascii_chrome();
match status {
OutboxStatus::Sent => {
if ascii {
"ok"
} else {
"✓"
}
}
OutboxStatus::Queued => {
if ascii {
""
} else {
"◷"
}
}
OutboxStatus::Sending => {
if ascii {
""
} else {
"»"
}
}
OutboxStatus::Failed(_) => {
if ascii {
""
} else {
"✗"
}
}
}
}
/// Next-attempt age for a queued row, from the absolute `next_attempt_at` the
/// outbox stores.
pub fn retry_in_text(next_in_secs: i64) -> String {
if next_in_secs <= 0 {
"retry now".to_string()
} else if next_in_secs < 60 {
format!("retry {next_in_secs}s")
} else {
format!("retry {}m", (next_in_secs + 59) / 60)
}
}
/// 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.
pub fn short_send_reason(why: &str, budget: usize) -> String {
let clean = sanitize::display_text(why.as_bytes());
let tail = clean.rsplit(": ").next().unwrap_or("").trim();
let text = if tail.is_empty() { clean.trim() } else { tail };
truncate_chars(text, budget)
}
/// One row's delivery marker, straight from the outbox state.
pub fn delivery_tag(status: &OutboxStatus, attempts: u32, next_in_secs: i64) -> String {
let glyph = delivery_glyph(status);
let body = match status {
OutboxStatus::Sent => String::new(),
OutboxStatus::Queued => format!(
"queued (try {attempts}/{DEFAULT_MAX_ATTEMPTS}, {})",
retry_in_text(next_in_secs)
),
OutboxStatus::Sending => "sending".to_string(),
OutboxStatus::Failed(why) => {
format!("failed: {}", short_send_reason(why, FAIL_REASON_BUDGET))
}
};
match (glyph.is_empty(), body.is_empty()) {
(_, true) => glyph.to_string(),
(true, false) => body,
(false, false) => format!("{glyph} {body}"),
}
}
/// Footer summary derived from the outbox rows of the selected friend.
#[derive(Debug, Default, Clone, PartialEq, Eq)]
pub struct OutboxSummary {
/// `Queued` + `Sending`: rows the worker may still deliver.
pub queued: usize,
/// Terminal failures — these never retry.
pub failed: usize,
/// First terminal failure, for the fail-closed footer copy.
pub first_error: Option<String>,
}
impl OutboxSummary {
/// Footer note, or `None` when nothing is outstanding. Any terminal failure
/// keeps a `send failed` statement so the fail-closed copy stays visible.
pub fn note(&self) -> Option<String> {
let reason = || {
short_send_reason(
self.first_error.as_deref().unwrap_or("unknown"),
FAIL_REASON_BUDGET,
)
};
match (self.queued, self.failed) {
(0, 0) => None,
(queued, 0) => Some(format!("{queued} queued")),
(0, 1) => Some(format!("send failed: {}", reason())),
(0, failed) => Some(format!("send failed: {} ({failed} failed)", reason())),
(queued, _) => Some(format!("{queued} queued, send failed: {}", reason())),
}
}
}
/// Chat transcript with per-message delivery state, plus the footer summary.
///
/// Pending rows are joined to messages on `Message::id` /
/// `OutboxEntry::message_id` — never on the body. Two identical bodies are
/// distinct rows with distinct ids, so the marker always lands on the row that
/// actually owns the outbox entry.
pub fn chat_with_delivery(
msgs: &[Message],
pending: &[OutboxEntry],
now: i64,
) -> (Vec<String>, OutboxSummary) {
let mut summary = OutboxSummary::default();
for entry in pending {
match &entry.status {
OutboxStatus::Failed(why) => {
summary.failed += 1;
summary.first_error.get_or_insert_with(|| why.clone());
}
_ => summary.queued += 1,
}
}
if msgs.is_empty() {
return (
empty_friend_chat_text()
.lines()
.map(str::to_string)
.collect(),
summary,
);
}
// One row per message in practice (a retry updates its row, not inserts a
// second), and `pending` is ordered by row id, so a hypothetical duplicate
// resolves to the newest — the same rule the store's own
// `outbox_status_of_message` uses.
let by_id: HashMap<i64, &OutboxEntry> =
pending.iter().map(|entry| (entry.message_id, entry)).collect();
let mut tags: Vec<Option<String>> = vec![None; msgs.len()];
for (i, msg) in msgs.iter().enumerate() {
if msg.dir != "out" {
continue;
}
if let Some(entry) = by_id.get(&msg.id) {
tags[i] = Some(delivery_tag(
&entry.status,
entry.attempts,
entry.next_attempt_at - now,
));
}
}
let lines = msgs
.iter()
.enumerate()
.map(|(i, msg)| {
let side = if msg.dir == "out" { "you" } else { "them" };
let body = sanitize::display_text(&msg.plaintext);
let tag = match tags[i].clone() {
Some(tag) => tag,
None if msg.dir == "out" => delivery_tag(&OutboxStatus::Sent, 0, 0),
None => String::new(),
};
if tag.is_empty() {
format!("{side}: {body}")
} else {
format!("{side}: {body} {tag}")
}
})
.collect();
(lines, summary)
}
/// Paste overlay copy. Error keeps the resubmit hint.
pub fn paste_screen_text(buf: &str, err: Option<&str>) -> String {
let hint = match err {
@ -1449,9 +1645,13 @@ impl App {
let (tx, rx) = mpsc::channel();
self.status_note = Some("sending".into());
std::mem::drop(self.rt.spawn(async move {
// `send()` reports `Sent` when the circuit took it and `Queued` when
// the peer's onion is unreachable. The footer then reads the real
// row count from the outbox, so this note is only the first word.
let note = match node.send(&pk, &body).await {
Ok(()) => "sent".to_string(),
Err(e) => format!("send failed: {e}"),
Ok(OutboxStatus::Sent) => "sent".to_string(),
Ok(_) => "queued".to_string(),
Err(e) => format!("send failed: {}", short_send_reason(&e, FAIL_REASON_BUDGET)),
};
let _ = tx.send(note);
}));
@ -1561,38 +1761,22 @@ impl App {
}
f.render_stateful_widget(roster, panes[0], &mut roster_state);
let chat_lines = self.chat_lines();
let inner_h = panes[1].height.saturating_sub(2);
let nlines = chat_lines.len();
let max_scroll = nlines.saturating_sub(inner_h as usize) as u16;
let scroll = self.chat_scroll.min(max_scroll);
let overflow = nlines > inner_h as usize && inner_h > 0;
let chat_title = {
let name = self.friends.get(self.selected).map(|friend| {
friend
.petname
.as_deref()
.unwrap_or(&friend.fingerprint)
.to_string()
});
let mut t = match name {
Some(n) => format!("chat {n}"),
None => "chat".to_string(),
};
if overflow {
let end = (scroll as usize + inner_h as usize).min(nlines);
t.push_str(&format!(" {}-{end}/{nlines}", scroll as usize + 1));
}
let mark = if self.focus == Pane::Chat { "> " } else { " " };
format!("{mark}{t}")
};
let chat_text = chat_lines.join("\n");
let chat = Paragraph::new(chat_text)
.style(style_text())
.wrap(Wrap { trim: false })
.scroll((scroll, 0))
.block(self.pane_block(&chat_title, Pane::Chat));
f.render_widget(chat, panes[1]);
let (chat_lines, summary) = self.chat_view();
let chat_name = self.friends.get(self.selected).map(|friend| {
friend
.petname
.as_deref()
.unwrap_or(&friend.fingerprint)
.to_string()
});
draw_chat(
f,
panes[1],
&chat_lines,
chat_name.as_deref(),
self.focus == Pane::Chat,
self.chat_scroll,
);
let mark = if self.focus == Pane::Composer {
"> "
@ -1616,62 +1800,108 @@ impl App {
cols[3],
);
let footer = self.footer_line(area.width);
let footer = self.footer_line(area.width, &summary);
f.render_widget(Paragraph::new(footer).style(style_dim()), cols[4]);
}
fn footer_line(&self, width: u16) -> String {
fn footer_line(&self, width: u16, summary: &OutboxSummary) -> String {
// The outbox is the source of truth while anything is outstanding; the
// transient note still covers "sending", "sent file x", "invoice sent".
let note = summary.note().or_else(|| self.status_note.clone());
status_footer(
width,
&self.me_fp,
&self.me_onion,
self.status_note.as_deref(),
note.as_deref(),
footer_hints(&self.screen),
)
}
fn chat_lines(&self) -> Vec<String> {
fn chat_view(&self) -> (Vec<String>, OutboxSummary) {
let Some(friend) = self.friends.get(self.selected) else {
return vec![
"no friends yet".into(),
"F3 paste an invite to add one".into(),
];
return (
vec![
"no friends yet".into(),
"F3 paste an invite to add one".into(),
],
OutboxSummary::default(),
);
};
match self.node.list_messages(&friend.pubkey) {
Ok(msgs) if msgs.is_empty() => empty_friend_chat_text()
.lines()
.map(str::to_string)
.collect(),
Ok(msgs) => msgs
.iter()
.map(|m| {
let side = if m.dir == "out" { "you" } else { "them" };
format!("{side}: {}", sanitize::display_text(&m.plaintext))
})
.collect(),
Err(e) => vec![e],
Ok(msgs) => {
let pending = self.node.outbox_pending(&friend.pubkey).unwrap_or_default();
chat_with_delivery(&msgs, &pending, unix_now_secs())
}
Err(e) => (vec![e], OutboxSummary::default()),
}
}
fn pane_block<'a>(&self, title: &'a str, pane: Pane) -> Block<'a> {
let focused = self.focus == pane;
let border = if focused {
style_accent()
} else {
style_border()
};
let title_style = if focused {
style_accent().add_modifier(Modifier::BOLD)
} else {
style_dim()
};
apply_chrome_borders(Block::default())
.border_style(border)
.title(title)
.title_style(title_style)
pane_block_for(title, self.focus == pane)
}
}
/// Pane chrome without an `App`: focus is accent border + bold title, never
/// color alone (the `> ` marks come from the callers).
fn pane_block_for(title: &str, focused: bool) -> Block<'_> {
let border = if focused {
style_accent()
} else {
style_border()
};
let title_style = if focused {
style_accent().add_modifier(Modifier::BOLD)
} else {
style_dim()
};
apply_chrome_borders(Block::default())
.border_style(border)
.title(title)
.title_style(title_style)
}
fn unix_now_secs() -> i64 {
SystemTime::now()
.duration_since(UNIX_EPOCH)
.map(|d| d.as_secs() as i64)
.unwrap_or(0)
}
/// Real chat-pane renderer: `App::draw_main` calls this, so width, wrap and
/// delivery-marker behaviour are testable without constructing a `Node`.
pub fn draw_chat(
f: &mut Frame,
area: Rect,
lines: &[String],
name: Option<&str>,
focused: bool,
scroll: u16,
) {
let inner_h = area.height.saturating_sub(2);
let nlines = lines.len();
let max_scroll = nlines.saturating_sub(inner_h as usize) as u16;
let scroll = scroll.min(max_scroll);
let overflow = nlines > inner_h as usize && inner_h > 0;
let mut title = match name {
Some(n) => format!("chat {n}"),
None => "chat".to_string(),
};
if overflow {
let end = (scroll as usize + inner_h as usize).min(nlines);
title.push_str(&format!(" {}-{end}/{nlines}", scroll as usize + 1));
}
let mark = if focused { "> " } else { " " };
let title = format!("{mark}{title}");
f.render_widget(
Paragraph::new(lines.join("\n"))
.style(style_text())
.wrap(Wrap { trim: false })
.scroll((scroll, 0))
.block(pane_block_for(&title, focused)),
area,
);
}
/// Status bar: never drop a non-empty `status_note`. Always keep `TOR`, `me:`, `? help`.
pub fn status_footer(
width: u16,
@ -1687,7 +1917,7 @@ pub fn status_footer(
let mut note = status_note.unwrap_or("").trim().to_string();
if !note.is_empty()
&& color_mode() == ColorMode::None
&& (note.starts_with("send failed") || note == "fingerprint mismatch")
&& (note.contains("send failed") || note == "fingerprint mismatch")
&& !note.starts_with("! ")
{
note = format!("! {note}");

312
tests/outbox.rs Normal file
View file

@ -0,0 +1,312 @@
//! Local outbox: queue a chat send when the peer's onion is unreachable, retry
//! with exponential backoff, expose a terminal status. All offline — the
//! transport is a fake deliverer, so these run without Tor.
use std::sync::atomic::{AtomicUsize, Ordering};
use std::sync::{Arc, Mutex};
use onionwire::outbox::{
BACKOFF_CAP_SECS, BACKOFF_START_SECS, BoxFut, Deliverer, Outbox, OutboxStatus, backoff_secs,
is_permanent_send_error,
};
use onionwire::Store;
const PASS: &str = "outbox-pass";
fn pk(tag: u8) -> [u8; 32] {
let mut k = [0u8; 32];
k[0] = tag;
k
}
/// Fails `fail_times` dials with `err`, then succeeds and records the plaintext.
struct Flaky {
fail_times: AtomicUsize,
err: String,
calls: AtomicUsize,
delivered: Mutex<Vec<Vec<u8>>>,
}
impl Flaky {
fn new(fail_times: usize, err: &str) -> Arc<Self> {
Arc::new(Self {
fail_times: AtomicUsize::new(fail_times),
err: err.into(),
calls: AtomicUsize::new(0),
delivered: Mutex::new(Vec::new()),
})
}
fn calls(&self) -> usize {
self.calls.load(Ordering::SeqCst)
}
fn delivered(&self) -> Vec<Vec<u8>> {
self.delivered.lock().unwrap().clone()
}
}
impl Deliverer for Flaky {
fn deliver<'a>(
&'a self,
_onion: &'a str,
_pinned_id: &'a [u8],
_prekey: &'a [u8],
plaintext: &'a [u8],
) -> BoxFut<'a, Result<(), String>> {
self.calls.fetch_add(1, Ordering::SeqCst);
let left = self.fail_times.load(Ordering::SeqCst);
if left > 0 {
self.fail_times.fetch_sub(1, Ordering::SeqCst);
let err = self.err.clone();
return Box::pin(async move { Err(err) });
}
self.delivered.lock().unwrap().push(plaintext.to_vec());
Box::pin(async move { Ok(()) })
}
}
fn store_and_friend(dir: &std::path::Path, onion: &str) -> Arc<Mutex<Store>> {
let store = Store::open_at_with_passphrase(dir, PASS).expect("open store");
store.upsert_friend(&pk(1), onion, None).unwrap();
store.set_friend_prekey(&pk(1), &[7u8; 32]).unwrap();
Arc::new(Mutex::new(store))
}
fn outbox(store: Arc<Mutex<Store>>, deliverer: Arc<dyn Deliverer>, max_attempts: u32) -> Outbox {
Outbox::new(store, deliverer).with_max_attempts(max_attempts)
}
#[test]
fn backoff_schedule_doubles_from_30s_and_caps_at_30m() {
assert_eq!(BACKOFF_START_SECS, 30);
assert_eq!(BACKOFF_CAP_SECS, 1800);
let got: Vec<i64> = (0..9).map(backoff_secs).collect();
assert_eq!(
got,
vec![30, 60, 120, 240, 480, 960, 1800, 1800, 1800],
"exponential backoff, capped"
);
assert_eq!(
backoff_secs(u32::MAX),
BACKOFF_CAP_SECS,
"no overflow at silly attempt counts"
);
}
#[test]
fn transport_errors_are_retryable_protocol_errors_are_not() {
assert!(!is_permanent_send_error(
"connect abc.onion:80: timed out"
));
assert!(!is_permanent_send_error("connect abc.onion:80: refused"));
assert!(is_permanent_send_error("fingerprint mismatch"));
assert!(is_permanent_send_error("frame too large"));
assert!(is_permanent_send_error("bad version"));
assert!(is_permanent_send_error("bad identity proof"));
}
#[tokio::test]
async fn send_to_dead_onion_is_queued_and_row_persists() {
let dir = tempfile::tempdir().unwrap();
let store = store_and_friend(dir.path(), "dead.onion");
let dead = Flaky::new(usize::MAX, "connect dead.onion:80: timed out");
let ob = outbox(Arc::clone(&store), dead, 8);
let status = ob.send(&pk(1), b"hello dead peer").await.unwrap();
assert_eq!(status, OutboxStatus::Queued, "dead onion must queue, not Err");
assert!(!status.is_terminal());
let pending = ob.pending(&pk(1)).unwrap();
assert_eq!(pending.len(), 1, "one outbox row");
assert_eq!(pending[0].status, OutboxStatus::Queued);
assert_eq!(pending[0].attempts, 1, "the immediate attempt counted");
assert!(
ob.status_of_message(pending[0].message_id).unwrap().is_some(),
"status is addressable by chat row id"
);
// The chat line is already in local history while it waits.
let msgs = store.lock().unwrap().list_messages(&pk(1)).unwrap();
assert_eq!(msgs.len(), 1);
assert_eq!(msgs[0].dir, "out");
assert_eq!(msgs[0].plaintext, b"hello dead peer");
}
#[tokio::test]
async fn flaky_peer_is_flushed_by_the_worker_on_schedule() {
let dir = tempfile::tempdir().unwrap();
let store = store_and_friend(dir.path(), "flaky.onion");
// First dial fails (the immediate one), the rest succeed: "peer came up".
let flaky = Flaky::new(1, "connect flaky.onion:80: timed out");
let ob = outbox(Arc::clone(&store), flaky.clone(), 8);
let status = ob.send(&pk(1), b"late hello").await.unwrap();
assert_eq!(status, OutboxStatus::Queued);
let next = ob.pending(&pk(1)).unwrap()[0].next_attempt_at;
assert_eq!(
next - ob.pending(&pk(1)).unwrap()[0].created_at,
BACKOFF_START_SECS,
"first retry waits the start of the schedule"
);
// Too early: the worker must not dial out of schedule.
let t0 = next - BACKOFF_START_SECS;
let fired = ob.tick(t0 + BACKOFF_START_SECS - 1).await.unwrap();
assert!(fired.is_empty(), "not due yet");
let fired = ob.tick(t0 + BACKOFF_START_SECS).await.unwrap();
assert_eq!(fired.len(), 1);
assert_eq!(fired[0].1, OutboxStatus::Sent);
assert_eq!(flaky.delivered(), vec![b"late hello".to_vec()]);
assert!(
ob.pending(&pk(1)).unwrap().is_empty(),
"delivered rows leave the pending set"
);
}
#[tokio::test]
async fn max_attempts_reaches_failed_and_stops_retrying() {
let dir = tempfile::tempdir().unwrap();
let store = store_and_friend(dir.path(), "gone.onion");
let dead = Flaky::new(usize::MAX, "connect gone.onion:80: timed out");
let ob = outbox(Arc::clone(&store), dead.clone(), 3);
assert_eq!(
ob.send(&pk(1), b"never lands").await.unwrap(),
OutboxStatus::Queued
);
assert_eq!(dead.calls(), 1, "immediate attempt");
// Walk the schedule forward; each tick is one more attempt.
let mut now = ob.pending(&pk(1)).unwrap()[0].next_attempt_at;
let mut last = OutboxStatus::Queued;
for _ in 0..6 {
let fired = ob.tick(now).await.unwrap();
if let Some((_, st)) = fired.first() {
last = st.clone();
}
if last == OutboxStatus::Failed("connect gone.onion:80: timed out".into()) {
break;
}
now += BACKOFF_CAP_SECS;
}
assert_eq!(
last,
OutboxStatus::Failed("connect gone.onion:80: timed out".into()),
"gives up after max_attempts"
);
assert_eq!(dead.calls(), 3, "attempts stop at the cap");
let calls_at_cap = dead.calls();
for _ in 0..3 {
now += BACKOFF_CAP_SECS;
assert!(ob.tick(now).await.unwrap().is_empty(), "no more retries");
}
assert_eq!(dead.calls(), calls_at_cap);
let pending = ob.pending(&pk(1)).unwrap();
assert_eq!(pending.len(), 1);
assert!(matches!(pending[0].status, OutboxStatus::Failed(_)));
assert!(pending[0].status.is_terminal());
}
#[tokio::test]
async fn queued_message_survives_reopen_and_flushes_after_unlock() {
let dir = tempfile::tempdir().unwrap();
let pk1 = pk(1);
let next_attempt_at = {
let store = store_and_friend(dir.path(), "later.onion");
let dead = Flaky::new(usize::MAX, "connect later.onion:80: timed out");
let ob = outbox(Arc::clone(&store), dead, 8);
assert_eq!(
ob.send(&pk1, b"survives restart").await.unwrap(),
OutboxStatus::Queued
);
ob.pending(&pk1).unwrap()[0].next_attempt_at
};
// Process exit: everything above is dropped and the store is reopened.
let store = Arc::new(Mutex::new(
Store::open_at_with_passphrase(dir.path(), PASS).unwrap(),
));
let up = Flaky::new(0, "");
let ob = outbox(Arc::clone(&store), up.clone(), 8);
let fired = ob.flush_all(next_attempt_at).await.unwrap();
assert_eq!(fired.len(), 1);
assert_eq!(fired[0].1, OutboxStatus::Sent);
assert_eq!(up.delivered(), vec![b"survives restart".to_vec()]);
assert!(ob.pending(&pk1).unwrap().is_empty());
}
#[tokio::test]
async fn protocol_error_fails_immediately_and_is_not_queued() {
let dir = tempfile::tempdir().unwrap();
let store = store_and_friend(dir.path(), "liar.onion");
let liar = Flaky::new(usize::MAX, "fingerprint mismatch");
let ob = outbox(Arc::clone(&store), liar, 8);
let err = ob.send(&pk(1), b"hello liar").await.unwrap_err();
assert!(err.contains("fingerprint mismatch"), "got {err}");
assert!(
ob.pending(&pk(1)).unwrap().is_empty(),
"protocol errors are never queued"
);
assert!(
store.lock().unwrap().list_messages(&pk(1)).unwrap().is_empty(),
"a failed protocol send is not written to history"
);
}
#[tokio::test]
async fn flush_friend_ignores_the_schedule_when_that_peer_was_seen() {
let dir = tempfile::tempdir().unwrap();
let store = store_and_friend(dir.path(), "seen.onion");
let flaky = Flaky::new(1, "connect seen.onion:80: timed out");
let ob = outbox(Arc::clone(&store), flaky.clone(), 8);
assert_eq!(
ob.send(&pk(1), b"you are back").await.unwrap(),
OutboxStatus::Queued
);
let now = ob.pending(&pk(1)).unwrap()[0].created_at;
let fired = ob.flush_friend(&pk(1), now).await.unwrap();
assert_eq!(fired.len(), 1, "a live handshake flushes without waiting");
assert_eq!(fired[0].1, OutboxStatus::Sent);
}
#[tokio::test]
async fn wipe_clears_outbox_rows() {
let dir = tempfile::tempdir().unwrap();
let store = store_and_friend(dir.path(), "dead.onion");
let dead = Flaky::new(usize::MAX, "connect dead.onion:80: timed out");
let ob = outbox(Arc::clone(&store), dead, 8);
assert_eq!(
ob.send(&pk(1), b"wipe me").await.unwrap(),
OutboxStatus::Queued
);
assert_eq!(ob.pending(&pk(1)).unwrap().len(), 1);
store.lock().unwrap().wipe_messages().unwrap();
assert!(
ob.pending(&pk(1)).unwrap().is_empty(),
"wipe must drop queued sends, not only chat"
);
}
#[tokio::test]
async fn missing_prekey_is_fatal_not_queued() {
let dir = tempfile::tempdir().unwrap();
let store = Arc::new(Mutex::new(
Store::open_at_with_passphrase(dir.path(), PASS).unwrap(),
));
{
let s = store.lock().unwrap();
s.upsert_friend(&pk(2), "noprekey.onion", None).unwrap();
}
let ob = outbox(Arc::clone(&store), Flaky::new(0, ""), 8);
let err = ob.send(&pk(2), b"hi").await.unwrap_err();
assert!(err.contains("prekey"), "got {err}");
assert!(ob.pending(&pk(2)).unwrap().is_empty());
}

View file

@ -1,10 +1,13 @@
//! Spec implementation tests for docs/TUI.md (this card).
//! Does not own `tests/tui_frames.rs` (PR #23).
use onionwire::Message;
use onionwire::outbox::{OutboxEntry, OutboxStatus};
use onionwire::qr;
use onionwire::tui::{
alert_line, ascii_chrome, draw_share, draw_text_overlay, empty_friend_chat_text,
help_overlay_text, main_footer_hints, main_header_line, paste_screen_text, roster_col_width,
OutboxSummary, alert_line, ascii_chrome, chat_with_delivery, delivery_tag, draw_chat,
draw_share, draw_text_overlay, empty_friend_chat_text, help_overlay_text, main_footer_hints,
main_header_line, paste_screen_text, retry_in_text, roster_col_width, short_send_reason,
status_footer, wrap_invite,
};
use ratatui::Frame;
@ -376,3 +379,420 @@ fn ascii_switch_80x24_frame_is_pure_ascii() {
println!("===== AFTER ascii share 80x24 =====\n{screen}");
unsafe { std::env::remove_var("ONIONWIRE_ASCII") };
}
// ---------------------------------------------------------------------------
// Outbox delivery state (card t_d9a5b065)
//
// States come from the outbox API (`Outbox::pending` → `Queued` / `Sending` /
// `Failed`; delivered rows are deleted, so absence means `Sent`). No new wire
// prefix, no parallel state model.
// ---------------------------------------------------------------------------
fn out_msg(id: i64, body: &str) -> Message {
Message {
id,
dir: "out".into(),
plaintext: body.as_bytes().to_vec(),
}
}
fn in_msg(id: i64, body: &str) -> Message {
Message {
id,
dir: "in".into(),
plaintext: body.as_bytes().to_vec(),
}
}
fn pending_row(
message_id: i64,
body: &str,
status: OutboxStatus,
attempts: u32,
next_in: i64,
now: i64,
) -> OutboxEntry {
OutboxEntry {
id: 1,
friend_pk: vec![9u8; 32],
message_id,
body: body.as_bytes().to_vec(),
attempts,
next_attempt_at: now + next_in,
created_at: now,
status,
last_error: None,
}
}
fn queued_row(message_id: i64, body: &str, attempts: u32, next_in: i64, now: i64) -> OutboxEntry {
pending_row(message_id, body, OutboxStatus::Queued, attempts, next_in, now)
}
fn sending_row(message_id: i64, body: &str, now: i64) -> OutboxEntry {
pending_row(message_id, body, OutboxStatus::Sending, 1, 0, now)
}
fn failed_row(message_id: i64, body: &str, why: &str, now: i64) -> OutboxEntry {
pending_row(
message_id,
body,
OutboxStatus::Failed(why.into()),
8,
0,
now,
)
}
/// Marker is everything after the two-space separator the render helper uses.
fn marker_of(line: &str) -> &str {
line.rsplit(" ").next().unwrap_or("")
}
/// Force the non-ASCII (unicode glyph) path. Caller holds `ASCII_ENV`.
fn force_unicode_mode() {
unsafe {
std::env::remove_var("ONIONWIRE_ASCII");
std::env::remove_var("NO_COLOR");
}
}
#[test]
fn queued_and_delivered_messages_render_different_markers() {
let guard = ASCII_ENV.lock().expect("ascii env lock");
force_unicode_mode();
let _guard = guard;
let now = 1_700_000_000;
let msgs = vec![out_msg(1, "ping"), out_msg(2, "pong")];
let pending = vec![queued_row(2, "pong", 2, 45, now)];
let (lines, summary) = chat_with_delivery(&msgs, &pending, now);
assert!(
lines[0].contains('✓'),
"delivered row lost its mark: {:?}",
lines[0]
);
assert!(!lines[0].contains("queued"), "{:?}", lines[0]);
assert!(
lines[1].contains('◷'),
"queued row lost its glyph: {:?}",
lines[1]
);
assert!(lines[1].contains("queued"), "{:?}", lines[1]);
assert!(
lines[1].contains("try 2/8"),
"attempt count missing: {:?}",
lines[1]
);
assert!(
lines[1].contains("retry 45s"),
"retry age missing: {:?}",
lines[1]
);
assert_ne!(
marker_of(&lines[0]),
marker_of(&lines[1]),
"queued and delivered must not share a marker"
);
assert_eq!(summary.queued, 1);
assert_eq!(summary.failed, 0);
}
/// The case the body match got wrong: the same text sent twice, only the
/// *older* send still queued. Joined by body, the (single) pending row lands on
/// the newest send and the actually-queued row shows `✓` — which is exactly
/// false delivery. The join is on `Message::id` / `OutboxEntry::message_id`.
#[test]
fn identical_bodies_join_by_message_id_not_body() {
let guard = ASCII_ENV.lock().expect("ascii env lock");
force_unicode_mode();
let _guard = guard;
let now = 1_700_000_000;
let msgs = vec![out_msg(7, "same text"), out_msg(8, "same text")];
let pending = vec![queued_row(7, "same text", 1, 30, now)];
let (lines, summary) = chat_with_delivery(&msgs, &pending, now);
assert!(
lines[0].contains('◷') && lines[0].contains("queued"),
"queued marker must land on the queued row (id 7): {:?}",
lines[0]
);
assert!(
!lines[0].contains('✓'),
"queued row must not claim delivery: {:?}",
lines[0]
);
assert_eq!(
marker_of(&lines[1]),
"✓",
"delivered row (id 8) must keep its mark: {:?}",
lines[1]
);
assert_eq!(summary.note().as_deref(), Some("1 queued"));
}
#[test]
fn delivery_markers_have_exercised_ascii_fallbacks() {
let _guard = ASCII_ENV.lock().expect("ascii env lock");
unsafe {
std::env::set_var("ONIONWIRE_ASCII", "1");
std::env::remove_var("NO_COLOR");
}
let now = 500;
let msgs = vec![
out_msg(1, "alpha"),
out_msg(2, "beta"),
out_msg(3, "gamma"),
out_msg(4, "delta"),
in_msg(5, "epsilon"),
];
let pending = vec![
failed_row(1, "alpha", "connect peer.onion:80: connection timed out", now),
queued_row(2, "beta", 1, 30, now),
sending_row(3, "gamma", now),
];
let (lines, summary) = chat_with_delivery(&msgs, &pending, now);
for line in &lines {
assert!(
line.is_ascii(),
"ASCII fallback missing, non-ASCII in {line:?}"
);
}
assert_eq!(marker_of(&lines[0]), "failed: connection timed out");
assert_eq!(marker_of(&lines[1]), "queued (try 1/8, retry 30s)");
assert_eq!(marker_of(&lines[2]), "sending");
assert_eq!(marker_of(&lines[3]), "ok", "delivered fallback is `ok`");
assert_eq!(lines[4], "them: epsilon", "inbound rows carry no state");
assert_eq!(summary.queued, 2, "queued + sending are both outstanding");
assert_eq!(summary.failed, 1);
unsafe { std::env::remove_var("ONIONWIRE_ASCII") };
}
#[test]
fn retry_age_and_failure_reason_are_short_forms() {
assert_eq!(retry_in_text(45), "retry 45s");
assert_eq!(retry_in_text(59), "retry 59s");
assert_eq!(retry_in_text(60), "retry 1m");
assert_eq!(retry_in_text(720), "retry 12m");
assert_eq!(retry_in_text(0), "retry now");
assert_eq!(retry_in_text(-30), "retry now");
assert_eq!(
short_send_reason("connect abcdef.onion:80: connection timed out", 24),
"connection timed out"
);
let long = short_send_reason("a-really-long-failure-description-here", 12);
assert!(long.chars().count() <= 12, "{long:?}");
assert!(
long.contains('…') || long.contains("..."),
"truncation marker missing: {long:?}"
);
assert_eq!(short_send_reason("nope", 24), "nope");
}
#[test]
fn delivery_tag_reads_the_outbox_status_enum() {
let guard = ASCII_ENV.lock().expect("ascii env lock");
force_unicode_mode();
let _guard = guard;
assert_eq!(delivery_tag(&OutboxStatus::Sent, 0, 0), "✓");
assert_eq!(
delivery_tag(&OutboxStatus::Queued, 3, 120),
"◷ queued (try 3/8, retry 2m)"
);
assert_eq!(delivery_tag(&OutboxStatus::Sending, 1, 0), "» sending");
assert_eq!(
delivery_tag(&OutboxStatus::Failed("connect x:80: nope".into()), 8, 0),
"✗ failed: nope"
);
}
#[test]
fn footer_summary_counts_queued_and_keeps_fail_closed() {
let none = OutboxSummary::default();
assert_eq!(none.note(), None);
let queued = OutboxSummary {
queued: 2,
failed: 0,
first_error: None,
};
assert_eq!(queued.note().as_deref(), Some("2 queued"));
let failed = OutboxSummary {
queued: 0,
failed: 1,
first_error: Some("connect peer.onion:80: connection timed out".into()),
};
let note = failed.note().expect("failed rows must produce a note");
assert!(note.starts_with("send failed:"), "{note:?}");
assert!(note.contains("connection timed out"), "{note:?}");
let mixed = OutboxSummary {
queued: 3,
failed: 1,
first_error: Some("connect peer.onion:80: connection timed out".into()),
};
let mixed_note = mixed.note().expect("mixed rows must produce a note");
assert!(mixed_note.contains("3 queued"), "{mixed_note:?}");
assert!(mixed_note.contains("send failed"), "{mixed_note:?}");
// Fail-closed copy stays visible in the real footer at the 80-col floor.
let line = status_footer(80, FP, ONION, Some(&note), main_footer_hints());
assert!(
line.chars().count() <= 80,
"{} {line:?}",
line.chars().count()
);
assert!(line.contains("send failed"), "footer dropped it: {line:?}");
assert!(line.contains("TOR") && line.contains("? help"), "{line:?}");
let queued_line = status_footer(80, FP, ONION, queued.note().as_deref(), main_footer_hints());
assert!(queued_line.contains("2 queued"), "{queued_line:?}");
assert!(queued_line.chars().count() <= 80);
// `! ` ornament (colour off) still lands on the derived failing note.
let _guard = ASCII_ENV.lock().expect("ascii env lock");
unsafe { std::env::set_var("NO_COLOR", "1") };
let no_color = status_footer(80, FP, ONION, Some(&note), main_footer_hints());
assert!(no_color.contains("! send failed"), "{no_color:?}");
unsafe { std::env::remove_var("NO_COLOR") };
}
/// The card's width criterion: draw the real helpers at the documented floor
/// (80x24) and prove nothing in the chat/footer region exceeds the width, and
/// that an over-long row wraps in the pane instead of being clipped.
#[test]
fn chat_and_footer_rows_fit_80x24_and_wrap_instead_of_clipping() {
let guard = ASCII_ENV.lock().expect("ascii env lock");
force_unicode_mode();
let _guard = guard;
let now = 1_700_000_000;
let long = "this is a very long chat line that should wrap inside the chat pane instead of running off the right edge of an 80-column terminal and colliding with the roster border";
let msgs = vec![out_msg(1, "ok"), in_msg(2, "pong"), out_msg(3, long)];
let pending = vec![queued_row(3, long, 3, 45, now)];
let (lines, summary) = chat_with_delivery(&msgs, &pending, now);
for line in lines.iter().take(2) {
assert!(
line.chars().count() <= 80,
"short row wider than 80: {} {line:?}",
line.chars().count()
);
}
let footer = status_footer(
80,
FP,
ONION,
summary.note().as_deref(),
main_footer_hints(),
);
assert!(footer.chars().count() <= 80, "{footer:?}");
let backend = TestBackend::new(80, 24);
let mut terminal = Terminal::new(backend).expect("terminal");
terminal
.draw(|f| {
let area = f.area();
let cols = Layout::vertical([Constraint::Min(3), Constraint::Length(1)]).split(area);
draw_chat(f, cols[0], &lines, Some("alice"), true, 0);
f.render_widget(Paragraph::new(footer.clone()), cols[1]);
})
.expect("draw");
let buf = terminal.backend().buffer();
let mut screen = String::new();
for y in 0..24u16 {
for x in 0..80u16 {
screen.push_str(buf[(x, y)].symbol());
}
screen.push('\n');
}
for (y, row) in screen.lines().enumerate() {
assert!(
row.chars().count() <= 80,
"80x24 chat/footer row {y} wider than the terminal: {} {row:?}",
row.chars().count()
);
}
assert!(
screen.contains('◷'),
"queued glyph missing from frame:\n{screen}"
);
assert!(screen.contains("queued"), "queued word missing:\n{screen}");
assert!(screen.contains('✓'), "delivered glyph missing:\n{screen}");
assert!(
screen.contains("with the roster border"),
"long row was clipped, not wrapped:\n{screen}"
);
assert!(
screen.contains("1 queued"),
"footer summary missing:\n{screen}"
);
println!("===== AFTER outbox 80x24 (real draw_chat + status_footer) =====\n{screen}");
}
/// The renderer consumes the real outbox API, not a hand-written fixture: a
/// genuine unreachable-onion send leaves a `Queued` row, and that row is what
/// the chat line and the footer note are built from.
#[tokio::test]
async fn renders_a_queued_row_from_a_real_outbox_send() {
use onionwire::Store;
use onionwire::outbox::{BoxFut, Deliverer, Outbox};
use std::sync::Arc;
struct Dead;
impl Deliverer for Dead {
fn deliver<'a>(
&'a self,
_onion: &'a str,
_pinned_id: &'a [u8],
_prekey: &'a [u8],
_plaintext: &'a [u8],
) -> BoxFut<'a, Result<(), String>> {
Box::pin(async { Err("connect dead.onion:80: timed out".to_string()) })
}
}
let dir = tempfile::tempdir().expect("tempdir");
let store = Store::open_at_with_passphrase(dir.path(), "tui-spec-pass").expect("open store");
let pk = [1u8; 32];
store
.upsert_friend(&pk, "dead.onion", None)
.expect("friend");
store.set_friend_prekey(&pk, &[7u8; 32]).expect("prekey");
let store = Arc::new(std::sync::Mutex::new(store));
let outbox = Outbox::new(Arc::clone(&store), Arc::new(Dead));
assert_eq!(
outbox.send(&pk, b"queued for a dead peer").await,
Ok(OutboxStatus::Queued)
);
let pending = outbox.pending(&pk).expect("pending rows");
assert_eq!(pending.len(), 1, "one queued row");
let msgs = store
.lock()
.expect("store lock")
.list_messages(&pk)
.expect("messages");
let now = pending[0].next_attempt_at - 45;
let (lines, summary) = chat_with_delivery(&msgs, &pending, now);
assert_eq!(lines.len(), 1);
assert!(
lines[0].contains("queued (try 1/8, retry 45s)"),
"real outbox row did not render: {:?}",
lines[0]
);
assert_eq!(summary.note().as_deref(), Some("1 queued"));
// And once a send crosses the circuit the row is gone, so the same message
// renders as delivered.
let (delivered, summary) = chat_with_delivery(&msgs, &[], now);
assert!(delivered[0].contains('✓'), "{:?}", delivered[0]);
assert_eq!(summary.note(), None);
}