Compare commits

...
Author SHA1 Message Date
agent
6796f861e0
docs(readme): keep manual-release bullet; do not resurrect auto-release on main paths
All checks were successful
ci / test (pull_request) Successful in 3m55s
ci / sdk (pull_request) Successful in 58s
2026-09-12 19:15:34 -04:00
Hermes apk-dev
2e738e2e99
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 19:15:14 -04:00
agent
e30c9f1699
fix(sdk): surface Sent/Queued on send(), and build the SDK in CI
Node::send() became Result<OutboxStatus, String> in the local-outbox work,
which broke crates/onionwire-sdk — and nothing noticed, because the SDK is a
separate cargo workspace that root CI never compiles.

- Wire::send() returns WResult<SendState> (Sent | Queued)
- ChatMessage.delivery for outgoing rows
- New sdk job in ci.yml (own target volume; rustls workspace)
- Refresh SDK Cargo.lock + README (SQLCipher / outbox facts)

Rebased onto main after #50/#54: no src/node.rs changes (WAL checkpoint lives
in Store now). README at-rest claims kept from #55.
2026-09-12 19:15:14 -04:00
9 changed files with 478 additions and 46 deletions

View file

@ -39,6 +39,11 @@ env:
CARGO_REGISTRY_VOLUME: onionwire-cargo-registry CARGO_REGISTRY_VOLUME: onionwire-cargo-registry
CARGO_TARGET_VOLUME: onionwire-target-ci CARGO_TARGET_VOLUME: onionwire-target-ci
BUILD_CONTAINER: onionwire-ci-${{ github.run_id }} 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: jobs:
test: test:
@ -73,3 +78,44 @@ jobs:
tar czf - --exclude=./target --exclude=./.git --exclude=./.worktrees . \ tar czf - --exclude=./target --exclude=./.git --exclude=./.worktrees . \
| docker start -a -i "$BUILD_CONTAINER" | docker start -a -i "$BUILD_CONTAINER"
docker rm -f "$BUILD_CONTAINER" > /dev/null 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

@ -304,7 +304,7 @@ FORGEJO_TOKEN=<pat> scripts/build-release-local.sh vX.Y.Z
Workflows (Forgejo Actions, `.forgejo/workflows/`): 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 on the Pi runner (`docker` label), serialized by `onionwire-ci-pi`. `test`: `cargo test --locked` + `cargo clippy --all-targets -- -D warnings` at the repo root. `sdk`: the same for `crates/onionwire-sdk` (separate cargo workspace — own `Cargo.lock`, root crate by path, `rustls` instead of `native-tls` — so a root signature change cannot silently break the Android SDK). 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) — manual, batched release (`workflow_dispatch` only: `dry_run`, `bump`, `version`, `tag`): next tag, aarch64 (`docker`) + x86_64 (`docker-amd64`), one release, fail-closed tag delete on failure. Dispatch [`android-release.yml`](.forgejo/workflows/android-release.yml) with that tag to add the APK + AAR (no automatic trigger fires on this Forgejo; it is `workflow_dispatch` only). 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`. - [`.forgejo/workflows/release.yml`](.forgejo/workflows/release.yml) — manual, batched release (`workflow_dispatch` only: `dry_run`, `bump`, `version`, `tag`): next tag, aarch64 (`docker`) + x86_64 (`docker-amd64`), one release, fail-closed tag delete on failure. Dispatch [`android-release.yml`](.forgejo/workflows/android-release.yml) with that tag to add the APK + AAR (no automatic trigger fires on this Forgejo; it is `workflow_dispatch` only). 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: Scripts:

View file

@ -21,6 +21,7 @@ import uniffi.onionwire_sdk.ChatMessage
import uniffi.onionwire_sdk.FriendInfo import uniffi.onionwire_sdk.FriendInfo
import uniffi.onionwire_sdk.InviteInfo import uniffi.onionwire_sdk.InviteInfo
import uniffi.onionwire_sdk.RotateOutcome import uniffi.onionwire_sdk.RotateOutcome
import uniffi.onionwire_sdk.SendState
import uniffi.onionwire_sdk.Wire import uniffi.onionwire_sdk.Wire
import uniffi.onionwire_sdk.decodeInvite import uniffi.onionwire_sdk.decodeInvite
import java.io.File import java.io.File
@ -361,7 +362,15 @@ class WireViewModel(app: Application) : AndroidViewModel(app) {
suspend fun messages(pubkeyHex: String): List<ChatMessage> = suspend fun messages(pubkeyHex: String): List<ChatMessage> =
requireWire().messages(pubkeyHex) requireWire().messages(pubkeyHex)
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) requireWire().send(pubkeyHex, body)
suspend fun wipeMessages() { suspend fun wipeMessages() {

View file

@ -37,6 +37,12 @@ import androidx.compose.ui.text.font.FontFamily
import androidx.compose.ui.unit.dp import androidx.compose.ui.unit.dp
import kotlinx.coroutines.delay import kotlinx.coroutines.delay
import uniffi.onionwire_sdk.ChatMessage import uniffi.onionwire_sdk.ChatMessage
import uniffi.onionwire_sdk.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) @OptIn(ExperimentalMaterial3Api::class)
@Composable @Composable
@ -45,13 +51,14 @@ fun ChatScreen(
fingerprint: String, fingerprint: String,
onion: String, onion: String,
loadMessages: suspend () -> List<ChatMessage>, loadMessages: suspend () -> List<ChatMessage>,
onSend: suspend (String) -> Unit, onSend: suspend (String) -> SendState,
onBack: () -> Unit, onBack: () -> Unit,
) { ) {
var messages by remember { mutableStateOf<List<ChatMessage>?>(null) } var messages by remember { mutableStateOf<List<ChatMessage>?>(null) }
var draft by remember { mutableStateOf("") } var draft by remember { mutableStateOf("") }
var pending by remember { mutableStateOf<String?>(null) } var pending by remember { mutableStateOf<String?>(null) }
var error by remember { mutableStateOf<String?>(null) } var error by remember { mutableStateOf<String?>(null) }
var hint by remember { mutableStateOf<String?>(null) }
val listState = rememberLazyListState() val listState = rememberLazyListState()
// Poll: the node appends inbound messages in the background; there is no // 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 // Fail closed — but not fail lost. `send` returns `Queued` when the peer's
// then errors — nothing is spooled, so a failure is a real failure. // 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) { LaunchedEffect(pending) {
val body = pending ?: return@LaunchedEffect val body = pending ?: return@LaunchedEffect
error = null error = null
hint = null
runCatching { onSend(body) } 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() } .onFailure { error = it.message ?: it.toString() }
pending = null 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) { LaunchedEffect(messages?.size) {
val n = messages?.size ?: 0 val n = messages?.size ?: 0
if (n > 0) listState.animateScrollToItem(n - 1) if (n > 0) listState.animateScrollToItem(n - 1)
@ -127,8 +150,13 @@ fun ChatScreen(
Text("No messages", style = MaterialTheme.typography.titleSmall) Text("No messages", style = MaterialTheme.typography.titleSmall)
Spacer(Modifier.height(6.dp)) Spacer(Modifier.height(6.dp))
Text( Text(
"Sends fail closed: if their onion is down the message is " + "Sends fail closed — nothing goes to a third party. If their " +
"not spooled anywhere. There is no outbox in v1.", "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, style = MaterialTheme.typography.bodySmall,
color = MaterialTheme.colorScheme.onSurfaceVariant, color = MaterialTheme.colorScheme.onSurfaceVariant,
) )
@ -148,6 +176,10 @@ fun ChatScreen(
Modifier.fillMaxWidth(), Modifier.fillMaxWidth(),
horizontalArrangement = horizontalArrangement =
if (mine) Arrangement.End else Arrangement.Start, if (mine) Arrangement.End else Arrangement.Start,
) {
Column(
horizontalAlignment =
if (mine) Alignment.End else Alignment.Start,
) { ) {
Text( Text(
m.body, m.body,
@ -162,11 +194,59 @@ fun ChatScreen(
) )
.padding(horizontal = 10.dp, vertical = 8.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 { error?.let {
Text( Text(

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

@ -2443,6 +2443,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "91632f3b4fb6bd1d72aa3d78f41ffecfcf2b1a6648d8c241dbe7dbfaf4875e15" checksum = "91632f3b4fb6bd1d72aa3d78f41ffecfcf2b1a6648d8c241dbe7dbfaf4875e15"
dependencies = [ dependencies = [
"cc", "cc",
"openssl-sys",
"pkg-config", "pkg-config",
"vcpkg", "vcpkg",
] ]
@ -2774,6 +2775,7 @@ dependencies = [
"rusqlite", "rusqlite",
"safelog", "safelog",
"serde_json", "serde_json",
"sha2",
"sha3 0.10.9", "sha3 0.10.9",
"snow", "snow",
"tokio", "tokio",
@ -2781,6 +2783,7 @@ dependencies = [
"tor-hsservice", "tor-hsservice",
"tor-rtcompat", "tor-rtcompat",
"x25519-dalek", "x25519-dalek",
"zeroize",
] ]
[[package]] [[package]]
@ -2801,6 +2804,28 @@ version = "0.3.1"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "c08d65885ee38876c4f86fa503fb49d7b507c2b62552df7c70b2fce627e06381" checksum = "c08d65885ee38876c4f86fa503fb49d7b507c2b62552df7c70b2fce627e06381"
[[package]]
name = "openssl-src"
version = "300.6.1+3.6.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "46eb8fb9fb3b61ce1c0f8a026c4c1a0714d3a9e138e7fbde78753ce2babc3846"
dependencies = [
"cc",
]
[[package]]
name = "openssl-sys"
version = "0.9.117"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b47e7e6bb2c38cd930d25a23b40fa52e068c10e85f3e03a7f5ba5aaca5713695"
dependencies = [
"cc",
"libc",
"openssl-src",
"pkg-config",
"vcpkg",
]
[[package]] [[package]]
name = "option-ext" name = "option-ext"
version = "0.2.0" version = "0.2.0"

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. | | Onion | A **locator**, not an identity. It rotates. |
| Invite | `onionwire:v1:k=…:o=…:spk=…:sig=…` | | Invite | `onionwire:v1:k=…:o=…:spk=…:sig=…` |
| Crypto | Noise IK (`Noise_IK_25519_ChaChaPoly_BLAKE2s`). `spk` is x25519. | | 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. | | 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 | Chat bodies encrypted (Argon2id wrap + ChaCha20-Poly1305). Identity keys in sqlite are plaintext — that is honest, not an oversight. | | 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 ### Invite string
@ -66,8 +66,10 @@ Requirements:
## Kotlin surface ## Kotlin surface
Everything is a `suspend fun` — Arti bootstrap and onion publish take minutes, 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. 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 ```kotlin
import uniffi.onionwire_sdk.* import uniffi.onionwire_sdk.*
@ -88,8 +90,16 @@ val friend: FriendInfo = wire.addFriend(pasted)
// 4. Roster and chat. // 4. Roster and chat.
val roster: List<FriendInfo> = wire.friends() val roster: List<FriendInfo> = wire.friends()
wire.setPetname(friend.pubkeyHex, "ada") 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) 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 // 5. Locator rotation. Do NOT wire this to a single tap — the app that embeds
// the SDK owns the typed confirmation. // the SDK owns the typed confirmation.

View file

@ -11,7 +11,10 @@
//! the friend. //! the friend.
//! * Transport is in-process Arti. There is no `tor` binary, no torrc, no //! * Transport is in-process Arti. There is no `tor` binary, no torrc, no
//! Orbot pipe. If the onion service cannot publish, this fails closed. //! 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.
//! //!
//! Lifecycle: a node is started by [`open_wire`] and stopped by //! Lifecycle: a node is started by [`open_wire`] and stopped by
//! [`Wire::shutdown`]. Between those, [`Wire::tor_state`] is the observable //! [`Wire::shutdown`]. Between those, [`Wire::tor_state`] is the observable
@ -27,7 +30,7 @@ use std::sync::{Arc, Mutex, OnceLock};
use onionwire::hs::TorState as CoreTorState; use onionwire::hs::TorState as CoreTorState;
use onionwire::node::{FlushOutcome as CoreFlushOutcome, Node}; use onionwire::node::{FlushOutcome as CoreFlushOutcome, Node};
use onionwire::qr; use onionwire::outbox::OutboxStatus;use onionwire::qr;
uniffi::setup_scaffolding!(); uniffi::setup_scaffolding!();
@ -98,11 +101,34 @@ pub struct FriendInfo {
pub last_connect_ok: bool, 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)] #[derive(Debug, Clone, uniffi::Record)]
pub struct ChatMessage { pub struct ChatMessage {
/// "in" or "out". /// "in" or "out".
pub direction: String, pub direction: String,
pub body: 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)] #[derive(Debug, Clone, uniffi::Record)]
@ -332,34 +358,44 @@ impl Wire {
.map_err(WireError::new) .map_err(WireError::new)
} }
/// Send one message. Returns once the outcome is known: delivered now, or /// Send one chat message.
/// queued for retry because the peer's onion is unreachable. A protocol ///
/// error (bad signature, bad frame) still fails immediately and is never /// Returns [`SendState::Sent`] when the frame reached the peer's onion
/// queued. Use [`flush`](Self::flush) to retry the queue on demand. /// service during this call, and [`SendState::Queued`] when it did not: the
pub async fn send(&self, pubkey_hex: String, body: String) -> WResult<()> { /// 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)?; let pk = unhex(&pubkey_hex)?;
self.node()? let status = self
.node()?
.send(&pk, body.as_bytes()) .send(&pk, body.as_bytes())
.await .await
.map_err(WireError::new)?; .map_err(WireError::new)?;
Ok(()) Ok(send_state(status)) }
}
/// Chat history for a friend, oldest first. Bodies are decrypted here; /// Chat history for a friend, oldest first. Bodies are decrypted here;
/// they are stored encrypted at rest. /// 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>> { pub async fn messages(&self, pubkey_hex: String) -> WResult<Vec<ChatMessage>> {
let pk = unhex(&pubkey_hex)?; let pk = unhex(&pubkey_hex)?;
let rows = self let rows = self.node()?.list_messages(&pk).map_err(WireError::new)?;
let mut out = Vec::with_capacity(rows.len());
for m in rows {
let status = self
.node()? .node()?
.list_messages(&pk) .outbox_status_of_message(m.id)
.map_err(WireError::new)?; .map_err(WireError::new)?;
Ok(rows out.push(ChatMessage { body: String::from_utf8_lossy(&m.plaintext).into_owned(),
.into_iter() delivery: delivery_of(&m.dir, status),
.map(|m| ChatMessage {
direction: m.dir, direction: m.dir,
body: String::from_utf8_lossy(&m.plaintext).into_owned(), });
}) }
.collect()) Ok(out)
} }
/// Delete every message body. Identity and friends survive. /// Delete every message body. Identity and friends survive.
@ -415,6 +451,30 @@ fn unhex(s: &str) -> WResult<Vec<u8>> {
.collect() .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)] #[cfg(test)]
mod tests { mod tests {
//! No Tor here on purpose: these exercise the *lifecycle* contract of the //! No Tor here on purpose: these exercise the *lifecycle* contract of the
@ -422,6 +482,7 @@ mod tests {
//! node is exactly the state `shutdown()` leaves behind. //! node is exactly the state `shutdown()` leaves behind.
use super::*; use super::*;
use onionwire::outbox::OutboxStatus;
fn stopped_wire() -> Wire { fn stopped_wire() -> Wire {
Wire { Wire {
@ -482,4 +543,42 @@ mod tests {
); );
assert_eq!(TorState::from(CoreTorState::Stopped), TorState::Stopped); assert_eq!(TorState::from(CoreTorState::Stopped), TorState::Stopped);
} }
#[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")
);
}
}