android: profile screen — nickname + Monero receiving address
All checks were successful
android-ci / android (pull_request) Successful in 12m27s

The phone's half of the TUI's `/profile`. A `Profile` action on the roster's
app bar opens `ui/ProfileScreen.kt`: nickname, bio, and the Monero address
friends pay to, all three loaded from the store and written back through the
core's own validation.

- The address is checked with `uniffi.onionwire_sdk.checkAddress` *before* the
  write, so a typo is refused with the typed text still in the field instead of
  surfacing as a store error afterwards. An empty address is allowed and is
  labelled with its consequence: with no profile address and no running wallet
  child the core has nothing to hand a payer.
- The bio is carried, not owned: a save that did not touch the field writes
  back the value read from the store immediately before the write, so a bio set
  in the TUI cannot be blanked from the phone.
- On save the profile is pushed to **every** friend in the roster, one-shot and
  fail-closed per friend like the TUI's `save_profile`. A push failure is not a
  save failure: the status line always starts with `profile saved` and names the
  count, with each failure listed by petname (else shortened fingerprint).

Every decision the screen makes is a pure function in the new file, covered by
`ProfileDraftTest` (21 cases) on the JVM: the save-button rule (dead until the
read lands, dead while the form is unchanged), the address branch, the bio rule,
label selection and the status-line aggregation.

Verified on AVD ow35 (x86_64 slice, emulator-5560): the roster app bar carries
`Profile`; nickname/bio/address survive `am force-stop` + relaunch; an invalid
address is refused before the write; a save with an empty roster reports
`profile saved`; with one (self-)peer in the roster a save reports
`profile saved · sent to 1 friend`, and with the emulator's network cut the same
save reports `profile saved · sent to 0 of 1 friend · failed: <label>: <tor err>`.
This commit is contained in:
agent 2026-09-22 02:12:32 -04:00
commit 775f2e88be
No known key found for this signature in database
5 changed files with 736 additions and 0 deletions

View file

@ -25,6 +25,7 @@ import androidx.navigation.compose.rememberNavController
import androidx.navigation.navArgument
import com.siriusdevops.onionwire.ui.ChatScreen
import com.siriusdevops.onionwire.ui.PasteInviteScreen
import com.siriusdevops.onionwire.ui.ProfileScreen
import com.siriusdevops.onionwire.ui.RosterScreen
import com.siriusdevops.onionwire.ui.RotateScreen
import com.siriusdevops.onionwire.ui.ShareInviteScreen
@ -104,6 +105,7 @@ private fun ReadyGraph(vm: WireViewModel, ready: Phase.Ready, keepAliveNote: Str
onPaste = { nav.navigate("paste") },
onRotate = { nav.navigate("rotate") },
onWipe = { scope.launch { vm.wipeMessages() } },
onOpenProfile = { nav.navigate("profile") },
onLock = vm::lock,
onOpenWallet = { nav.navigate("wallet") },
)
@ -136,6 +138,10 @@ private fun ReadyGraph(vm: WireViewModel, ready: Phase.Ready, keepAliveNote: Str
WalletScreen(vm = vm, onBack = { nav.popBackStack() })
}
composable("profile") {
ProfileScreen(vm = vm, onBack = { nav.popBackStack() })
}
composable(
route = "chat/{pk}",
arguments = listOf(navArgument("pk") { type = NavType.StringType }),

View file

@ -38,6 +38,7 @@ import uniffi.onionwire_sdk.FriendInfo
import uniffi.onionwire_sdk.InviteInfo
import uniffi.onionwire_sdk.OutboxRow
import uniffi.onionwire_sdk.RotateOutcome
import uniffi.onionwire_sdk.SelfProfile
import uniffi.onionwire_sdk.SendState
import uniffi.onionwire_sdk.TransferRow
import uniffi.onionwire_sdk.WalletChildStatus
@ -570,6 +571,33 @@ class WireViewModel(app: Application) : AndroidViewModel(app) {
suspend fun decode(invite: String): InviteInfo = decodeInvite(invite)
// --- This identity's own profile ---------------------------------------
// The phone's half of the TUI's `/profile`. `setSelfProfile` only writes
// locally; friends keep showing the old profile until `pushSelfProfile`
// reaches each of them, which is why the screen reports the two separately.
/** The stored profile (nickname, bio, address). A store read; never dials. */
suspend fun selfProfile(): Result<SelfProfile> =
runCatching { requireWire().selfProfile() }
/**
* Replace the stored profile. Validated in the core before it is written:
* a rejected edit leaves the previous profile untouched.
*/
suspend fun setSelfProfile(
displayName: String,
bio: String,
xmrAddr: String,
): Result<Unit> = runCatching { requireWire().setSelfProfile(displayName, bio, xmrAddr) }
/**
* Send the signed profile to one friend so their view of this identity is
* current. One-shot and fail-closed: an unreachable peer is a failure for
* that peer, and nothing is queued for them.
*/
suspend fun pushSelfProfile(pubkeyHex: String): Result<Unit> =
runCatching { requireWire().pushSelfProfile(pubkeyHex) }
// --- Wallet & payments -------------------------------------------------
// These mirror the SDK surface added for the wallet screen. Payment sends
// are one-shot: if the peer's onion is unreachable, `send_*` fails now.

View file

@ -0,0 +1,448 @@
package com.siriusdevops.onionwire.ui
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.WindowInsets
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.rememberScrollState
import androidx.compose.foundation.verticalScroll
import androidx.compose.material3.Button
import androidx.compose.material3.Card
import androidx.compose.material3.CardDefaults
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.OutlinedTextField
import androidx.compose.material3.Scaffold
import androidx.compose.material3.Text
import androidx.compose.material3.TextButton
import androidx.compose.material3.TopAppBar
import androidx.compose.material3.TopAppBarDefaults
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.rememberCoroutineScope
import androidx.compose.runtime.setValue
import androidx.compose.ui.Modifier
import androidx.compose.ui.platform.testTag
import androidx.compose.ui.text.font.FontFamily
import androidx.compose.ui.unit.dp
import androidx.lifecycle.compose.collectAsStateWithLifecycle
import com.siriusdevops.onionwire.WireViewModel
import kotlinx.coroutines.launch
import uniffi.onionwire_sdk.checkAddress
/**
* This identity's own profile — nickname, bio, Monero receiving address — the
* phone's half of the TUI's `/profile`.
*
* The screen is a thin shell over three SDK calls (`self_profile`,
* `set_self_profile`, `push_self_profile`) and every decision it makes is a
* pure function at the bottom of this file, covered by `ProfileDraftTest` on
* the JVM. Nothing here invents policy the core does not have:
*
* - The write goes through the core's own validation (nickname ≤ 64 bytes,
* bio ≤ 512, no newlines, a non-empty address must pass `check_address`).
* The screen pre-checks the address so a typo is refused *before* the write,
* with the typed text still in the field, instead of being reported as a
* store error after it.
* - An **empty** address is a real, allowed value: it clears the profile
* address. It is labelled with its consequence, because with no profile
* address and no running wallet child the core has nothing to hand a payer
* (`Node::wallet_receive_address`) and the invoice path fails.
* - The bio is carried, not owned: a save that did not touch the bio field
* writes back the value read from the store immediately before the write, so
* a bio set in the TUI cannot be blanked from the phone.
* - The push is per friend and one-shot, exactly like the TUI's `save_profile`
* (which pushes to the selected friend): a peer whose onion is down fails
* and nothing is queued. A push failure is *not* a save failure — the local
* write already happened — so the two are reported separately.
*/
@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun ProfileScreen(
vm: WireViewModel,
onBack: () -> Unit,
) {
val friends by vm.friends.collectAsStateWithLifecycle()
val scope = rememberCoroutineScope()
// What the store held when this screen opened, and the live edits. Both
// null until the first read lands; the save button is dead until then.
var loaded by remember { mutableStateOf<ProfileDraft?>(null) }
var draft by remember { mutableStateOf<ProfileDraft?>(null) }
var loadError by remember { mutableStateOf<String?>(null) }
var addressError by remember { mutableStateOf<String?>(null) }
var saveError by remember { mutableStateOf<String?>(null) }
var status by remember { mutableStateOf<String?>(null) }
var busy by remember { mutableStateOf(false) }
LaunchedEffect(Unit) {
vm.selfProfile().fold(
onSuccess = { p ->
val d = ProfileDraft(p.displayName, p.bio, p.xmrAddr)
loaded = d
draft = d
},
onFailure = { loadError = it.message ?: it.toString() },
)
}
Scaffold(
contentWindowInsets = WindowInsets(0, 0, 0, 0),
topBar = {
TopAppBar(
title = { Text("Profile") },
navigationIcon = {
TextButton(onClick = onBack) { Text("Back") }
},
colors = TopAppBarDefaults.topAppBarColors(
containerColor = MaterialTheme.colorScheme.background,
),
)
},
) { pad ->
Column(
Modifier
.padding(pad)
.fillMaxSize()
.screenContentInsets()
.verticalScroll(rememberScrollState()),
) {
val form = draft
if (form == null) {
Text(
loadError ?: "loading…",
style = MaterialTheme.typography.bodySmall,
color = if (loadError != null) {
MaterialTheme.colorScheme.error
} else {
MaterialTheme.colorScheme.onSurfaceVariant
},
modifier = Modifier
.padding(12.dp)
.testTag("profile-load-error"),
)
return@Column
}
Card(
modifier = Modifier
.fillMaxWidth()
.padding(horizontal = 12.dp, vertical = 8.dp),
colors = CardDefaults.cardColors(
containerColor = MaterialTheme.colorScheme.surfaceVariant,
),
) {
Column(Modifier.padding(12.dp)) {
Text(
"Friends see this nickname and pay to this address.",
style = MaterialTheme.typography.bodySmall,
)
Spacer(Modifier.height(4.dp))
Text(
"Nothing is published anywhere: each friend gets it only when " +
"this is saved and sent to them.",
style = MaterialTheme.typography.labelSmall,
color = MaterialTheme.colorScheme.onSurfaceVariant,
)
}
}
OutlinedTextField(
value = form.nickname,
onValueChange = { draft = form.copy(nickname = it) },
singleLine = true,
label = { Text("nickname") },
supportingText = {
Text(
"What friends call you. Empty is allowed — they fall back to " +
"your fingerprint.",
style = MaterialTheme.typography.labelSmall,
)
},
modifier = Modifier
.fillMaxWidth()
.padding(horizontal = 12.dp)
.testTag("profile-nickname"),
)
Spacer(Modifier.height(8.dp))
OutlinedTextField(
value = form.bio,
onValueChange = { draft = form.copy(bio = it) },
singleLine = true,
label = { Text("bio") },
supportingText = {
Text(
"Kept when you save without touching it, including one set in " +
"the TUI.",
style = MaterialTheme.typography.labelSmall,
)
},
modifier = Modifier
.fillMaxWidth()
.padding(horizontal = 12.dp)
.testTag("profile-bio"),
)
Spacer(Modifier.height(8.dp))
OutlinedTextField(
value = form.address,
onValueChange = {
draft = form.copy(address = it)
addressError = null
},
singleLine = true,
isError = addressError != null,
label = { Text("Monero address") },
supportingText = {
Text(
// The consequence, on the screen, before a payment fails:
// `Node::wallet_receive_address` uses the wallet child's
// subaddress while it is up and this address otherwise,
// and with neither there is nothing to be paid to.
profileAddressNotice(form.address),
style = MaterialTheme.typography.labelSmall,
)
},
modifier = Modifier
.fillMaxWidth()
.padding(horizontal = 12.dp)
.testTag("profile-address"),
)
addressError?.let {
Text(
it,
style = MaterialTheme.typography.bodySmall,
color = MaterialTheme.colorScheme.error,
modifier = Modifier
.padding(horizontal = 12.dp, vertical = 4.dp)
.testTag("profile-address-error"),
)
}
Row(
modifier = Modifier
.fillMaxWidth()
.padding(12.dp),
horizontalArrangement = Arrangement.End,
) {
Button(
onClick = {
addressError = null
saveError = null
status = null
val clean = form.normalized()
// The address check first: a typo must be refused before
// the write, and the field keeps exactly what was typed.
val problem = profileAddressProblem(clean.address) { addr ->
runCatching { checkAddress(addr) }
}
if (problem != null) {
addressError = problem
return@Button
}
scope.launch {
busy = true
try {
// Read the stored profile again for the bio
// alone: a bio edited elsewhere since this
// screen loaded must not be blanked by a save
// that never touched the field.
val storedBio = vm.selfProfile().getOrNull()?.bio
val bio = bioToWrite(
draftBio = clean.bio,
loadedBio = loaded?.bio.orEmpty(),
storedBio = storedBio ?: clean.bio,
)
vm.setSelfProfile(clean.nickname, bio, clean.address).fold(
onSuccess = {
// Every friend in the roster, like the
// TUI pushes on save. One-shot each: a
// peer that is down is a failure for
// that peer, never a save failure.
val outcomes = friends.map { f ->
ProfilePushOutcome(
label = friendLabel(f.petname, f.fingerprint),
error = vm.pushSelfProfile(f.pubkeyHex)
.exceptionOrNull()
?.let { it.message ?: it.toString() },
)
}
status = profileStatusLine(outcomes)
// Re-read so the form matches the store
// and the save button goes back to dead.
vm.selfProfile().onSuccess { p ->
val d = ProfileDraft(p.displayName, p.bio, p.xmrAddr)
loaded = d
draft = d
}
},
onFailure = { saveError = it.message ?: it.toString() },
)
} finally {
busy = false
}
}
},
enabled = !busy && profileSaveEnabled(loaded, form),
modifier = Modifier.testTag("profile-save"),
) {
Text(if (busy) "Saving…" else "Save")
}
}
status?.let {
Text(
it,
style = MaterialTheme.typography.bodySmall,
color = MaterialTheme.colorScheme.primary,
modifier = Modifier
.padding(horizontal = 12.dp, vertical = 4.dp)
.testTag("profile-status"),
)
}
saveError?.let {
Text(
it,
style = MaterialTheme.typography.bodySmall,
color = MaterialTheme.colorScheme.error,
modifier = Modifier
.padding(horizontal = 12.dp, vertical = 4.dp)
.testTag("profile-save-error"),
)
}
Spacer(Modifier.height(12.dp))
}
}
}
// --- the whole decision surface, pure ---------------------------------------
/**
* The three fields this screen edits, as they sit on screen.
*
* A local mirror of the SDK's `SelfProfile`, deliberately: the rules below are
* JVM-testable without UniFFI, and a `data class` gives the dirty check an
* equality that is the fields themselves rather than an identity.
*/
internal data class ProfileDraft(
val nickname: String = "",
val bio: String = "",
val address: String = "",
)
/** One friend's push outcome: the label the roster shows, and the failure if any. */
internal data class ProfilePushOutcome(
val label: String,
val error: String? = null,
)
/**
* Edge whitespace out of every field.
*
* A paste from a clipboard or a soft keyboard's autocorrect habitually carries
* leading/trailing spaces, and none of the three fields can mean anything with
* them: the core refuses a nickname or address carrying a newline, and
* `check_address` is a base58 decode that fails on a stray space. Interior
* whitespace is untouched — the user may well want it in a bio.
*/
internal fun ProfileDraft.normalized(): ProfileDraft = copy(
nickname = nickname.trim(),
bio = bio.trim(),
address = address.trim(),
)
/**
* The save button's rule.
*
* Dead until the first read lands (`loaded == null`), dead while the form is
* byte-identical to what was loaded, live as soon as it differs. Comparison is
* on the normalised forms, so typing a trailing space into a field does not
* offer a save that would write the same value back.
*
* An **empty nickname is allowed**: the core accepts it (it only bounds the
* length and forbids newlines), the TUI's `/profile` accepts it, and the roster
* already renders a friend with no nickname as their fingerprint. Clearing a
* nickname is therefore a real edit that must be saveable.
*/
internal fun profileSaveEnabled(loaded: ProfileDraft?, draft: ProfileDraft): Boolean =
loaded != null && draft.normalized() != loaded.normalized()
/**
* Why the typed address cannot be saved, or `null` when it can.
*
* Empty is *allowed* and returns `null` without calling [check] at all — it
* clears the profile address, which the core permits. A non-empty address is
* handed to [check] (`uniffi.onionwire_sdk.checkAddress` in production) and its
* message is the reason shown, so the words match the core's own.
*/
internal fun profileAddressProblem(address: String, check: (String) -> Result<Unit>): String? {
val trimmed = address.trim()
if (trimmed.isEmpty()) return null
return check(trimmed).exceptionOrNull()?.let { it.message ?: it.toString() }
}
/**
* The bio that actually gets written.
*
* The field wins only when it differs from what was loaded — i.e. the user
* edited it. Otherwise the value read from the store immediately before the
* write is passed through unchanged, which is what keeps a bio set in the TUI
* alive through a phone save that only changed the nickname.
*/
internal fun bioToWrite(draftBio: String, loadedBio: String, storedBio: String): String =
if (draftBio.trim() != loadedBio.trim()) draftBio.trim() else storedBio
/** The label the roster would show for a friend: petname, else the short id. */
internal fun friendLabel(petname: String?, fingerprint: String): String =
petname?.takeIf { it.isNotBlank() } ?: shortId(fingerprint)
/**
* The one line under the Save button, in the TUI's shape.
*
* `src/tui.rs` `save_profile` reports `profile saved · sent` on a clean push
* and `profile saved` with no friends; here the count and the per-friend
* failures are spelled out, because the phone pushes to **every** friend and
* "some of them failed" has to name which.
*/
internal fun profileStatusLine(outcomes: List<ProfilePushOutcome>): String {
if (outcomes.isEmpty()) return PROFILE_SAVED
val failed = outcomes.filter { it.error != null }
if (failed.isEmpty()) {
return "$PROFILE_SAVED · sent to ${friendCount(outcomes.size)}"
}
val sent = outcomes.size - failed.size
val detail = failed.joinToString("; ") { "${it.label}: ${it.error}" }
return "$PROFILE_SAVED · sent to $sent of ${friendCount(outcomes.size)} · failed: $detail"
}
private fun friendCount(n: Int): String = if (n == 1) "1 friend" else "$n friends"
/** The TUI's word for a local write that reached nobody. */
internal const val PROFILE_SAVED: String = "profile saved"
/**
* What an empty address means, stated where the address is typed.
*
* `Node::wallet_receive_address` answers with the wallet child's own subaddress
* while it is up, and this address otherwise; with neither, the invoice path
* fails outright. The user should read that here, not after a friend's payment
* bounces.
*/
internal fun profileAddressNotice(address: String): String =
if (address.trim().isEmpty()) {
"Empty is allowed, and it clears the profile address. Your receive address " +
"then comes from the wallet child while it is running — with no address " +
"here and no wallet running, nobody can send you an invoice."
} else {
"What friends pay to. Validated before it is saved; an invalid address is " +
"refused and nothing is written."
}

View file

@ -49,6 +49,7 @@ fun RosterScreen(
onPaste: () -> Unit,
onRotate: () -> Unit,
onWipe: () -> Unit,
onOpenProfile: () -> Unit,
onLock: () -> Unit,
onOpenWallet: () -> Unit,
) {
@ -68,6 +69,7 @@ fun RosterScreen(
TopAppBar(
title = { Text("OnionWire") },
actions = {
TextButton(onClick = onOpenProfile) { Text("Profile") }
TextButton(onClick = onLock) { Text("Lock") }
},
colors = TopAppBarDefaults.topAppBarColors(