From b8c52ca97ddc184b45d5806bafe738b66e211000 Mon Sep 17 00:00:00 2001 From: rust-dev Date: Thu, 22 Oct 2026 22:23:44 -0400 Subject: [PATCH 01/19] pay: domain-separate tip and gate legacy signature acceptance MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit `tip` was the one payment frame with no domain tag: sign_tip signed the LF-joined fields, so its signature could be confused with any other newline-joined preimage. Mirror inv/rcp: sign_tip now emits "onionwire-tip-v1" || 0x00-separated txid/amount/address/memo/ts, and verify_tip tries that form then the historical layout. Legacy acceptance is now one switch instead of nine call sites: `pay::LEGACY_SIGS` (default true) plus `pay::legacy_sigs()`. Every v1 / concat fallback reads it — the `onionwire:v1` invite string and its two historical signature forms, `loc`, `inv`, `rcp`, and `tip`. `prf` is not gated here because src/profile.rs is outside this card's file scope; the spec says so. Tests: legacy-on keeps every untagged form verifying (incl. a new tip case); legacy-off rejects each untagged form while the tagged form still verifies (loc, inv, rcp, tip, invite); sign_tip is pinned to the tagged layout. docs/PROTOCOL.md gains the emitted/accepted table per signed frame and the mixed-fleet consequence. --- docs/PROTOCOL.md | 64 +++++++++++----- src/loc.rs | 7 +- src/pay.rs | 100 +++++++++++++++++++++---- src/qr.rs | 5 ++ tests/app_sig.rs | 185 +++++++++++++++++++++++++++++++++++++++++++++++ tests/qr.rs | 22 ++++++ 6 files changed, 350 insertions(+), 33 deletions(-) diff --git a/docs/PROTOCOL.md b/docs/PROTOCOL.md index 72ffd93..bec89a8 100644 --- a/docs/PROTOCOL.md +++ b/docs/PROTOCOL.md @@ -312,20 +312,42 @@ prefix. ### Application-frame signatures -`loc`, `prf`, `inv`, and `rcp` each carry an ed25519 signature over the +`loc`, `prf`, `inv`, `rcp`, and `tip` each carry an ed25519 signature over the **fields**, not the 4-byte typed prefix. Encode MUST sign the domain-separated form (type tag, then each field, `0x00` separators). Verify MUST accept that form and, for mixed-version peers, the legacy untagged LF-joined layout. Anything else fails closed. Do not emit the legacy layout. -`tip` is signed over the LF-joined fields only (no domain tag on encode today). -The `tip ` prefix is not signed. +The invite string is separate and uses `onionwire-invite-v2` (see Invite). -The invite string is separate and keeps `onionwire-invite-v1` (see Invite). +Legacy acceptance is one switch, `LEGACY_SIGS`, default **on**. Every fallback +listed below reads it; with it off, verification accepts only the emitted +(tagged) form. It is a local capability constant, not a wire field: it is never +sent, and a peer cannot negotiate it. -Older builds verify only the untagged bytes, so they reject tagged signatures -(fail closed, no downgrade). Mixed-version fleets break outbound application -frames from a new sender to an old receiver until both sides are updated. +| frame | emitted | accepted inbound | +| --- | --- | --- | +| invite | `onionwire-invite-v2`, `0x00`-separated over `k`, `o`, `spk`, `kem` | same; `onionwire:v1` over `onionwire-invite-v1` `0x00`-separated `k`,`o`,`spk`, or over `k \|\| o \|\| spk` (legacy only) | +| `loc ` | `"onionwire-loc-v1"` `0x00` `onion` `0x00` `ts` | same; `onion \|\| LF \|\| ts` (legacy only) | +| `prf ` | `"onionwire-prf-v1"` `0x00` `name` `0x00` `bio` `0x00` `xmr_addr` `0x00` `ts` | same; the four fields joined by LF (not yet gated — see below) | +| `inv ` | `"onionwire-inv-v1"` `0x00` `amount_atomic` `0x00` `address` `0x00` `memo` `0x00` `ts` | same; the four fields joined by LF (legacy only) | +| `rcp ` | `"onionwire-rcp-v1"` `0x00` `txid` `0x00` `amount_atomic` `0x00` `address` `0x00` `ts` | same; the four fields joined by LF (legacy only) | +| `tip ` | `"onionwire-tip-v1"` `0x00` `txid` `0x00` `amount_atomic` `0x00` `address` `0x00` `memo` `0x00` `ts` | same; the five fields joined by LF (legacy only) | + +The tag suffixes do say `-v1`; that is the tag's own version, not the invite +string version. + +`prf ` is the one frame whose legacy fallback is not yet gated: it is accepted +unconditionally in this revision and moving it under `LEGACY_SIGS` is a +separate change. + +**Mixed-fleet consequence.** Older builds verify only the untagged bytes, so +they reject every tagged signature from a new sender — including `tip `, which +older builds emitted and verified untagged. That direction needs the peer +updated before tips flow. The reverse works while `LEGACY_SIGS` is on: a new +build verifies an old sender's untagged `loc`/`prf`/`inv`/`rcp`/`tip` and an +`onionwire:v1` invite. Turning the switch off is a fleet-wide cutover, not a +per-peer choice. ### `loc ` — locator update @@ -348,8 +370,8 @@ ed25519_sign(identity_sk, ``` **Legacy accept:** a signature over `onion || LF || ascii(ts)` is still -accepted on verify so old loc frames verify. New loc frames MUST use the -domain-separated form. Do not emit legacy. +accepted on verify while `LEGACY_SIGS` is on, so old loc frames verify. New loc +frames MUST use the domain-separated form. Do not emit legacy. Apply only if **all** of: @@ -380,7 +402,7 @@ ed25519_sign(identity_sk, **Legacy accept:** a signature over the four fields joined by LF is still accepted on verify. New profile frames MUST use the domain-separated form. -Do not emit legacy. +Do not emit legacy. This fallback is not yet read through `LEGACY_SIGS`. Apply only for an existing friend, valid signature, newer `ts`. Not a public profile. Not a directory. @@ -403,8 +425,8 @@ ed25519_sign(identity_sk, ``` **Legacy accept:** a signature over the four fields joined by LF is still -accepted on verify. New invoices MUST use the domain-separated form. Do not -emit legacy. +accepted on verify while `LEGACY_SIGS` is on. New invoices MUST use the +domain-separated form. Do not emit legacy. The frame is a signed claim, not a payment. It is one-shot: if the peer onion is down, the send fails. There is no queued invoice. @@ -425,8 +447,8 @@ ed25519_sign(identity_sk, ``` **Legacy accept:** a signature over the four fields joined by LF is still -accepted on verify. New receipts MUST use the domain-separated form. Do not -emit legacy. +accepted on verify while `LEGACY_SIGS` is on. New receipts MUST use the +domain-separated form. Do not emit legacy. Signature proves which friend sent the claim. It does **not** prove money moved. Local `verified=1` only if a user-hosted `monero-wallet-rpc` returns @@ -442,13 +464,20 @@ Sent after a chain transfer, together with `rcp `. One-shot. tip \n\n
\n\n\n ``` -The `tip ` prefix is **not** signed. Encode signs the LF-joined fields: +The `tip ` prefix is **not** signed. + +**Current signature (encode this):** ``` ed25519_sign(identity_sk, - txid || LF || amount_atomic || LF || address || LF || memo || LF || ascii(ts)) + "onionwire-tip-v1" || 0x00 || txid || 0x00 || amount_atomic || 0x00 || + address || 0x00 || memo || 0x00 || ascii(ts)) ``` +**Legacy accept:** a signature over the five fields joined by LF is still +accepted on verify while `LEGACY_SIGS` is on. New tips MUST use the +domain-separated form. Do not emit legacy. + `memo` MUST NOT contain newlines. Same address and amount rules as invoices. A peer that does not implement `tip ` MUST drop it as an unknown typed prefix, not render it as chat. @@ -880,7 +909,8 @@ signature covers `kem_ascii`, removing the field or substituting a different key fails verification — that is the anti-strip/anti-substitution property. **Legacy accept (`onionwire:v1`):** a v1 invite has no `kem` field. Decode -accepts it and yields a friend with no `kem_pk`, i.e. a classical peer. A v1 +accepts it while `LEGACY_SIGS` is on and yields a friend with no `kem_pk`, i.e. +a classical peer; with the switch off a v1 invite fails closed. A v1 signature is accepted in either historical form: the tagged `"onionwire-invite-v1" || 0x00 || k || 0x00 || o || 0x00 || spk` or the raw concatenation `k || o || spk` (no tag, no separators), so old invites keep diff --git a/src/loc.rs b/src/loc.rs index 9803f77..16d4f25 100644 --- a/src/loc.rs +++ b/src/loc.rs @@ -54,9 +54,10 @@ pub fn verify(identity_pk: &[u8], loc: &Loc) -> bool { let signature = Signature::from_bytes(&sig); vk.verify(&sign_msg_v2(&loc.onion, loc.ts), &signature) .is_ok() - || vk - .verify(&sign_msg_v1(&loc.onion, loc.ts), &signature) - .is_ok() + || (crate::pay::legacy_sigs() + && vk + .verify(&sign_msg_v1(&loc.onion, loc.ts), &signature) + .is_ok()) } pub fn encode(loc: &Loc) -> Vec { diff --git a/src/pay.rs b/src/pay.rs index 681f106..c15b670 100644 --- a/src/pay.rs +++ b/src/pay.rs @@ -1,9 +1,47 @@ use ed25519_dalek::{Signature, Signer, SigningKey, Verifier, VerifyingKey}; use sha3::{Digest, Keccak256}; +use std::cell::Cell; use zeroize::Zeroizing; pub type Result = std::result::Result; +/// Legacy signature acceptance. +/// +/// Every signed frame is **emitted** in its domain-tagged form. Inbound, the +/// historical untagged / LF-joined layout (and the `onionwire:v1` invite +/// string) is still accepted so a mixed-version fleet keeps working; that +/// fallback is gated on this one switch. Set it to `false` to fail closed on +/// legacy signatures for every frame that reads it — `loc`, the invite string, +/// `inv`, `rcp`, and `tip`. (`prf` is not yet gated; see `docs/PROTOCOL.md`.) +pub const LEGACY_SIGS: bool = true; + +thread_local! { + /// Per-thread override for tests. `None` follows [`LEGACY_SIGS`]. + static LEGACY_SIGS_OVERRIDE: Cell> = const { Cell::new(None) }; +} + +/// Whether legacy (pre-domain-tag) signatures are accepted inbound. +pub fn legacy_sigs() -> bool { + LEGACY_SIGS_OVERRIDE + .with(|o| o.get()) + .unwrap_or(LEGACY_SIGS) +} + +/// Run `f` with legacy acceptance forced to `on`, then restore the previous +/// thread state. A test hook, not a runtime setting: production code reads the +/// switch through [`legacy_sigs`] only. +#[doc(hidden)] +pub fn with_legacy_sigs(on: bool, f: impl FnOnce() -> R) -> R { + struct Restore(Option); + impl Drop for Restore { + fn drop(&mut self) { + LEGACY_SIGS_OVERRIDE.with(|o| o.set(self.0)); + } + } + let _restore = Restore(LEGACY_SIGS_OVERRIDE.with(|o| o.replace(Some(on)))); + f() +} + #[derive(Debug)] pub struct Error(String); @@ -202,11 +240,12 @@ pub fn verify_invoice(identity_pk: &[u8], inv: &Invoice) -> bool { identity_pk, &inv_sign_msg_v2(&inv.amount_atomic, &inv.address, &inv.memo, inv.ts), &inv.sig, - ) || verify_bytes( - identity_pk, - &inv_sign_msg_v1(&inv.amount_atomic, &inv.address, &inv.memo, inv.ts), - &inv.sig, - ) + ) || (legacy_sigs() + && verify_bytes( + identity_pk, + &inv_sign_msg_v1(&inv.amount_atomic, &inv.address, &inv.memo, inv.ts), + &inv.sig, + )) } pub fn encode_invoice(inv: &Invoice) -> Vec { @@ -273,11 +312,12 @@ pub fn verify_receipt(identity_pk: &[u8], rcp: &Receipt) -> bool { identity_pk, &rcp_sign_msg_v2(&rcp.txid, &rcp.amount_atomic, &rcp.address, rcp.ts), &rcp.sig, - ) || verify_bytes( - identity_pk, - &rcp_sign_msg_v1(&rcp.txid, &rcp.amount_atomic, &rcp.address, rcp.ts), - &rcp.sig, - ) + ) || (legacy_sigs() + && verify_bytes( + identity_pk, + &rcp_sign_msg_v1(&rcp.txid, &rcp.amount_atomic, &rcp.address, rcp.ts), + &rcp.sig, + )) } pub fn encode_receipt(rcp: &Receipt) -> Vec { @@ -339,6 +379,20 @@ fn check_tip_fields(txid: &str, amount_atomic: &str, address: &str, memo: &str) Ok(()) } +fn tip_sign_msg_v2(txid: &str, amount_atomic: &str, address: &str, memo: &str, ts: i64) -> Vec { + tagged( + b"onionwire-tip-v1", + &[ + txid.as_bytes(), + amount_atomic.as_bytes(), + address.as_bytes(), + memo.as_bytes(), + ts.to_string().as_bytes(), + ], + ) +} + +/// Historical untagged form. Accept-only, and only while [`LEGACY_SIGS`] is on. fn tip_sign_msg_v1(txid: &str, amount_atomic: &str, address: &str, memo: &str, ts: i64) -> Vec { let mut msg = Vec::from(txid.as_bytes()); msg.push(b'\n'); @@ -361,7 +415,10 @@ pub fn sign_tip( ts: i64, ) -> Result { check_tip_fields(txid, amount_atomic, address, memo)?; - let sig = sign_bytes(identity_sk, &tip_sign_msg_v1(txid, amount_atomic, address, memo, ts))?; + let sig = sign_bytes( + identity_sk, + &tip_sign_msg_v2(txid, amount_atomic, address, memo, ts), + )?; Ok(Tip { txid: txid.to_string(), amount_atomic: amount_atomic.to_string(), @@ -378,9 +435,26 @@ pub fn verify_tip(identity_pk: &[u8], tip: &Tip) -> bool { } verify_bytes( identity_pk, - &tip_sign_msg_v1(&tip.txid, &tip.amount_atomic, &tip.address, &tip.memo, tip.ts), + &tip_sign_msg_v2( + &tip.txid, + &tip.amount_atomic, + &tip.address, + &tip.memo, + tip.ts, + ), &tip.sig, - ) + ) || (legacy_sigs() + && verify_bytes( + identity_pk, + &tip_sign_msg_v1( + &tip.txid, + &tip.amount_atomic, + &tip.address, + &tip.memo, + tip.ts, + ), + &tip.sig, + )) } pub fn encode_tip(tip: &Tip) -> Vec { diff --git a/src/qr.rs b/src/qr.rs index cc8504d..dca9262 100644 --- a/src/qr.rs +++ b/src/qr.rs @@ -101,6 +101,11 @@ pub fn decode(raw: &str) -> Result { if kem_ascii.is_some() { return Err(Error("unknown field".into())); } + // A v1 invite only ever carries a legacy signature: with legacy + // acceptance off it fails closed here, before any verify. + if !crate::pay::legacy_sigs() { + return Err(Error("legacy invite signatures disabled".into())); + } let ok_tagged = vk .verify(&sign_msg_v1_tagged(&k, &onion, &spk), &signature) .is_ok(); diff --git a/tests/app_sig.rs b/tests/app_sig.rs index a3aaac1..523ddea 100644 --- a/tests/app_sig.rs +++ b/tests/app_sig.rs @@ -198,3 +198,188 @@ fn inv_signature_does_not_verify_as_rcp() { "inv-shaped payload must not verify as rcp" ); } + +// ---- legacy acceptance is one switch (`pay::LEGACY_SIGS`) ---- + +fn untagged_loc(sk: &SigningKey, onion: &str, ts: i64) -> Loc { + let mut msg = Vec::from(onion.as_bytes()); + msg.push(b'\n'); + msg.extend_from_slice(ts.to_string().as_bytes()); + Loc { + onion: onion.into(), + ts, + sig: sk.sign(&msg).to_bytes().to_vec(), + } +} + +fn untagged_inv(sk: &SigningKey, amount: &str, address: &str, memo: &str, ts: i64) -> Invoice { + let mut msg = Vec::from(amount.as_bytes()); + msg.push(b'\n'); + msg.extend_from_slice(address.as_bytes()); + msg.push(b'\n'); + msg.extend_from_slice(memo.as_bytes()); + msg.push(b'\n'); + msg.extend_from_slice(ts.to_string().as_bytes()); + Invoice { + amount_atomic: amount.into(), + address: address.into(), + memo: memo.into(), + ts, + sig: sk.sign(&msg).to_bytes().to_vec(), + } +} + +fn untagged_rcp(sk: &SigningKey, txid: &str, amount: &str, address: &str, ts: i64) -> Receipt { + let mut msg = Vec::from(txid.as_bytes()); + msg.push(b'\n'); + msg.extend_from_slice(amount.as_bytes()); + msg.push(b'\n'); + msg.extend_from_slice(address.as_bytes()); + msg.push(b'\n'); + msg.extend_from_slice(ts.to_string().as_bytes()); + Receipt { + txid: txid.into(), + amount_atomic: amount.into(), + address: address.into(), + ts, + sig: sk.sign(&msg).to_bytes().to_vec(), + } +} + +fn untagged_tip( + sk: &SigningKey, + txid: &str, + amount: &str, + address: &str, + memo: &str, + ts: i64, +) -> onionwire::pay::Tip { + let mut msg = Vec::from(txid.as_bytes()); + for f in [amount, address, memo] { + msg.push(b'\n'); + msg.extend_from_slice(f.as_bytes()); + } + msg.push(b'\n'); + msg.extend_from_slice(ts.to_string().as_bytes()); + onionwire::pay::Tip { + txid: txid.into(), + amount_atomic: amount.into(), + address: address.into(), + memo: memo.into(), + ts, + sig: sk.sign(&msg).to_bytes().to_vec(), + } +} + +#[test] +fn legacy_untagged_tip_still_verifies() { + let (sk, pk) = keypair(); + let tip = untagged_tip(&sk, "abc123", "1", MAINNET_STD, "coffee", 42); + assert!( + pay::verify_tip(&pk, &tip), + "legacy tip LF layout must still verify while LEGACY_SIGS is on" + ); +} + +#[test] +fn legacy_off_rejects_untagged_loc() { + let (sk, pk) = keypair(); + let legacy = untagged_loc(&sk, "abc.onion", 42); + let tagged = loc::sign(&sk.to_bytes(), "abc.onion", 42).unwrap(); + pay::with_legacy_sigs(false, || { + assert!( + !loc::verify(&pk, &legacy), + "untagged loc must be rejected with legacy off" + ); + assert!( + loc::verify(&pk, &tagged), + "tagged loc must still verify with legacy off" + ); + }); + assert!( + loc::verify(&pk, &legacy), + "the switch restores acceptance after the scoped override" + ); +} + +#[test] +fn legacy_off_rejects_untagged_inv() { + let (sk, pk) = keypair(); + let legacy = untagged_inv(&sk, "1", MAINNET_STD, "coffee", 42); + let tagged = pay::sign_invoice(&sk.to_bytes(), "1", MAINNET_STD, "coffee", 42).unwrap(); + pay::with_legacy_sigs(false, || { + assert!( + !pay::verify_invoice(&pk, &legacy), + "untagged inv must be rejected with legacy off" + ); + assert!( + pay::verify_invoice(&pk, &tagged), + "tagged inv must still verify with legacy off" + ); + }); + assert!(pay::verify_invoice(&pk, &legacy)); +} + +#[test] +fn legacy_off_rejects_untagged_rcp() { + let (sk, pk) = keypair(); + let legacy = untagged_rcp(&sk, "deadbeef", "1", MAINNET_STD, 99); + let tagged = pay::sign_receipt(&sk.to_bytes(), "deadbeef", "1", MAINNET_STD, 99).unwrap(); + pay::with_legacy_sigs(false, || { + assert!( + !pay::verify_receipt(&pk, &legacy), + "untagged rcp must be rejected with legacy off" + ); + assert!( + pay::verify_receipt(&pk, &tagged), + "tagged rcp must still verify with legacy off" + ); + }); + assert!(pay::verify_receipt(&pk, &legacy)); +} + +#[test] +fn legacy_off_rejects_untagged_tip() { + let (sk, pk) = keypair(); + let legacy = untagged_tip(&sk, "abc123", "1", MAINNET_STD, "coffee", 42); + let tagged = pay::sign_tip(&sk.to_bytes(), "abc123", "1", MAINNET_STD, "coffee", 42).unwrap(); + pay::with_legacy_sigs(false, || { + assert!( + !pay::verify_tip(&pk, &legacy), + "untagged tip must be rejected with legacy off" + ); + assert!( + pay::verify_tip(&pk, &tagged), + "tagged tip must still verify with legacy off" + ); + }); + assert!(pay::verify_tip(&pk, &legacy)); +} + +/// `sign_tip` emits the tagged form only: its signature must not verify over +/// the untagged LF layout. +#[test] +fn tip_emits_tagged_form_only() { + use ed25519_dalek::{Signature, Verifier}; + let (sk, pk) = keypair(); + let tip = pay::sign_tip(&sk.to_bytes(), "abc123", "1", MAINNET_STD, "coffee", 42).unwrap(); + assert!(pay::verify_tip(&pk, &tip)); + let sig: [u8; 64] = tip.sig.as_slice().try_into().expect("64-byte sig"); + let mut msg = Vec::from(b"abc123".as_slice()); + for f in ["1", MAINNET_STD, "coffee"] { + msg.push(b'\n'); + msg.extend_from_slice(f.as_bytes()); + } + msg.push(b'\n'); + msg.extend_from_slice(b"42"); + assert!( + sk.verifying_key() + .verify(&msg, &Signature::from_bytes(&sig)) + .is_err(), + "sign_tip must not sign the untagged layout" + ); + // And the tagged signature covers the memo: changing it fails. + let mut tampered = tip.clone(); + tampered.memo = String::new(); + assert!(!pay::verify_tip(&pk, &tampered)); +} diff --git a/tests/qr.rs b/tests/qr.rs index 3e38e0d..985b9c6 100644 --- a/tests/qr.rs +++ b/tests/qr.rs @@ -312,3 +312,25 @@ fn huge_hex_is_err_quickly() { "decode must fail closed before a multi-MB alloc" ); } + +#[test] +fn legacy_off_rejects_v1_invite_but_v2_still_decodes() { + let _home = TempHome::new(); + let store = Store::open().expect("open"); + let me = store.self_identity().expect("self"); + let sk: [u8; 32] = me.identity_sk.as_slice().try_into().expect("32-byte sk"); + let onion = v3onion("switch"); + let raw_v1 = legacy_v1(&sk, &onion, &[8u8; 32]); + let raw_v2 = qr::encode(&me.identity_sk, &onion, &[8u8; 32], &me.kem_pk).expect("encode v2"); + + onionwire::pay::with_legacy_sigs(false, || { + assert!( + qr::decode(&raw_v1).is_err(), + "a v1 invite must be rejected with legacy off" + ); + let p = qr::decode(&raw_v2).expect("v2 invite still decodes with legacy off"); + assert!(p.kem_pk.is_some(), "v2 invite keeps its PQ key"); + }); + // Legacy acceptance returns with the default switch state. + assert!(qr::decode(&raw_v1).is_ok()); +} From 8f959e937f844ee31938233fd359b16b4fe89fcd Mon Sep 17 00:00:00 2001 From: rust-dev Date: Thu, 22 Oct 2026 22:29:28 -0400 Subject: [PATCH 02/19] kdf: version Argon2id profiles and raise the default to 64 MiB / t=3 The store and identity backup shared one hard-coded Argon2id profile (m=19456 KiB, t=2, p=1) with nothing recorded on disk, so changing it would have bricked every existing store and backup. Record the profile with the data and raise the default: - KdfProfile { Legacy = 0, Current = 1 }; Current is m=65536 KiB, t=3, p=1, out=32. - Backups: seal() writes a profile byte after owbak1. Legacy blobs (exactly SEALED_BODY_LEN after MAGIC) still open; an unknown id is an error, never a fallback. - Stores: store_meta gains kdf_profile (additive, default 0). The SQLCipher file key has no place to record a profile before the db opens, so a legacy file is detected by trial-opening with the legacy profile, then rekeyed to Current in one SQLCipher transaction; store_meta is re-wrapped (salt + ciphertext + profile) in a single transaction on the first successful unlock. Both are one-shot: the next start takes the current path. - docs/THREAT_MODEL.md states the new params and the versioning. Measured in release on this host: kdf legacy 0.018s / current 0.095s; Store reopen current 0.354s, legacy upgrade path 0.528s. --- docs/THREAT_MODEL.md | 15 ++- src/backup.rs | 165 +++++++++++++++++++++-- src/store.rs | 312 ++++++++++++++++++++++++++++++++++++++++--- 3 files changed, 460 insertions(+), 32 deletions(-) diff --git a/docs/THREAT_MODEL.md b/docs/THREAT_MODEL.md index b618876..a212015 100644 --- a/docs/THREAT_MODEL.md +++ b/docs/THREAT_MODEL.md @@ -59,9 +59,18 @@ What this does **not** buy: ## Your store is encrypted The sqlite store is SQLCipher (`rusqlite` feature `bundled-sqlcipher-vendored-openssl`). -A 32-byte key is derived from the store passphrase with Argon2id (same params as -identity backup) over a per-install 16-byte salt in `store_salt`, and handed to -SQLCipher as a **raw** key (`PRAGMA key = "x'…'"`) — no second KDF pass over it. +A 32-byte key is derived from the store passphrase with Argon2id — m = +65_536 KiB (64 MiB), t = 3, p = 1, out = 32 — over a per-install 16-byte salt +in `store_salt`, and handed to SQLCipher as a **raw** key (`PRAGMA key = +"x'…'"`) — no second KDF pass over it. The identity backup and the +message-key wrap in `store_meta` use the same profile. Parameters are +versioned with the data: a backup blob names its profile in the header and +`store_meta.kdf_profile` names the store's, and an unknown profile id is a +clear error, never a silent fallback. Data written with the earlier +19_456 KiB / t=2 / p=1 profile still opens: a legacy store is rekeyed and its +message key re-wrapped with the current profile on the first successful +unlock, and a legacy backup file opens as-is (re-exporting it writes the +current profile). The key is the first statement after open, so the file header, schema, identity secret key, friend public keys, locators, profiles, payment rows and the per-friend ratchet session blobs (`ratchet_sessions`) are all ciphertext on diff --git a/src/backup.rs b/src/backup.rs index 5e6a775..7a4d000 100644 --- a/src/backup.rs +++ b/src/backup.rs @@ -1,4 +1,9 @@ //! Encrypted identity backup. Onion (locator) is not included. +//! +//! `seal()` writes `owbak1 || profile(1) || salt(16) || nonce(12) || ct`. +//! The pre-profile `owbak1 || salt(16) || nonce(12) || ct` layout is still +//! accepted as [`KdfProfile::Legacy`]; the two are unambiguous because the +//! plaintext is a fixed [`PLAIN_LEN`], so only two total lengths are legal. use argon2::{Algorithm, Argon2, Params, Version}; use chacha20poly1305::aead::{Aead, AeadCore, KeyInit, OsRng, Payload}; @@ -11,6 +16,52 @@ const SALT_LEN: usize = 16; const NONCE_LEN: usize = 12; const KEY_LEN: usize = 32; const PLAIN_LEN: usize = KEY_LEN * 4; +/// Salt + nonce + ciphertext + Poly1305 tag, i.e. everything after `MAGIC`. +const SEALED_BODY_LEN: usize = SALT_LEN + NONCE_LEN + PLAIN_LEN + 16; + +/// Which Argon2id parameters a stored blob was written with. +/// +/// The id is recorded with the data (a byte in the backup header, a +/// `store_meta.kdf_profile` column in the store). `Legacy` is id `0` and also +/// covers every blob written before profiles existed — those have no recorded +/// id at all. Never change an existing profile's parameters: a new cost means +/// a new id. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum KdfProfile { + /// m = 19_456 KiB, t = 2, p = 1. + Legacy, + /// m = 65_536 KiB (64 MiB), t = 3, p = 1. + Current, +} + +impl KdfProfile { + pub(crate) const LEGACY_ID: u8 = 0; + pub(crate) const CURRENT_ID: u8 = 1; + + pub(crate) fn id(self) -> u8 { + match self { + Self::Legacy => Self::LEGACY_ID, + Self::Current => Self::CURRENT_ID, + } + } + + /// Strict: an id this build does not know is an error, never a fallback. + pub(crate) fn from_id(id: u8) -> Result { + match id { + Self::LEGACY_ID => Ok(Self::Legacy), + Self::CURRENT_ID => Ok(Self::Current), + other => Err(format!("unknown kdf profile {other}")), + } + } + + fn params(self) -> Result { + let (m_cost, t_cost, p_cost) = match self { + Self::Legacy => (19_456, 2, 1), + Self::Current => (65_536, 3, 1), + }; + Params::new(m_cost, t_cost, p_cost, Some(KEY_LEN)).map_err(|e| e.to_string()) + } +} /// The identity bundle. Secret halves wipe on drop; `Debug` never prints them. #[derive(Clone, PartialEq, Eq, Zeroize, ZeroizeOnDrop)] @@ -58,14 +109,21 @@ impl BackupKeys { } pub(crate) fn kdf(passphrase: &str, salt: &[u8]) -> Result, String> { + kdf_with(KdfProfile::Current, passphrase, salt) +} + +pub(crate) fn kdf_with( + profile: KdfProfile, + passphrase: &str, + salt: &[u8], +) -> Result, String> { if passphrase.is_empty() { return Err("empty passphrase".into()); } if salt.len() != SALT_LEN { return Err("salt length".into()); } - let params = Params::new(19_456, 2, 1, Some(32)).map_err(|e| e.to_string())?; - let argon = Argon2::new(Algorithm::Argon2id, Version::V0x13, params); + let argon = Argon2::new(Algorithm::Argon2id, Version::V0x13, profile.params()?); let mut key = Zeroizing::new([0u8; 32]); argon .hash_password_into(passphrase.as_bytes(), salt, &mut key[..]) @@ -85,8 +143,9 @@ pub fn seal(passphrase: &str, keys: &BackupKeys) -> Result, String> { let ct = cipher .encrypt(&nonce, &keys.to_bytes()[..]) .map_err(|_| "encrypt failed".to_string())?; - let mut out = Vec::with_capacity(MAGIC.len() + SALT_LEN + NONCE_LEN + ct.len()); + let mut out = Vec::with_capacity(MAGIC.len() + 1 + SEALED_BODY_LEN); out.extend_from_slice(MAGIC); + out.push(KdfProfile::Current.id()); out.extend_from_slice(&salt); out.extend_from_slice(&nonce); out.extend_from_slice(&ct); @@ -94,15 +153,25 @@ pub fn seal(passphrase: &str, keys: &BackupKeys) -> Result, String> { } pub fn open(passphrase: &str, blob: &[u8]) -> Result { - let min = MAGIC.len() + SALT_LEN + NONCE_LEN + 16; - if blob.len() < min || !blob.starts_with(MAGIC) { + if !blob.starts_with(MAGIC) { return Err("not an onionwire backup".into()); } - let salt = &blob[MAGIC.len()..MAGIC.len() + SALT_LEN]; - let nonce_off = MAGIC.len() + SALT_LEN; - let nonce = Nonce::from_slice(&blob[nonce_off..nonce_off + NONCE_LEN]); - let ct = &blob[nonce_off + NONCE_LEN..]; - let key = kdf(passphrase, salt)?; + let rest = &blob[MAGIC.len()..]; + // The sealed plaintext is a fixed size, so a legacy blob is exactly + // SEALED_BODY_LEN bytes after MAGIC and a versioned one is one byte longer. + let (profile, body) = match rest.len() { + SEALED_BODY_LEN => (KdfProfile::Legacy, rest), + n if n == SEALED_BODY_LEN + 1 => { + let profile = KdfProfile::from_id(rest[0])?; + (profile, &rest[1..]) + } + _ => return Err("not an onionwire backup".into()), + }; + let salt = &body[..SALT_LEN]; + let nonce_off = SALT_LEN; + let nonce = Nonce::from_slice(&body[nonce_off..nonce_off + NONCE_LEN]); + let ct = &body[nonce_off + NONCE_LEN..]; + let key = kdf_with(profile, passphrase, salt)?; let cipher = ChaCha20Poly1305::new(Key::from_slice(&key[..])); let pt = Zeroizing::new( cipher @@ -191,4 +260,80 @@ mod tests { assert!(dbg.contains(""), "{dbg}"); assert!(dbg.contains("174"), "public half should stay: {dbg}"); } + + /// The pre-profile layout: `MAGIC || salt || nonce || ct`, no id byte. + fn legacy_blob(passphrase: &str, keys: &BackupKeys) -> Vec { + let salt = [0x5Au8; SALT_LEN]; + let key = kdf_with(KdfProfile::Legacy, passphrase, &salt).expect("legacy kdf"); + let cipher = ChaCha20Poly1305::new(Key::from_slice(&key[..])); + let nonce = ChaCha20Poly1305::generate_nonce(&mut OsRng); + let ct = cipher.encrypt(&nonce, &keys.to_bytes()[..]).expect("seal"); + let mut out = Vec::new(); + out.extend_from_slice(MAGIC); + out.extend_from_slice(&salt); + out.extend_from_slice(&nonce); + out.extend_from_slice(&ct); + out + } + + #[test] + fn sealed_blob_records_the_current_profile_and_roundtrips() { + let k = keys(9); + let blob = seal("correct horse", &k).expect("seal"); + assert_eq!(blob.len(), MAGIC.len() + 1 + SEALED_BODY_LEN); + assert_eq!( + blob[MAGIC.len()], + KdfProfile::Current.id(), + "new blobs must name their KDF profile" + ); + assert_eq!(open("correct horse", &blob).expect("open"), k); + } + + #[test] + fn legacy_profile_blob_still_opens() { + let k = keys(4); + let blob = legacy_blob("correct horse", &k); + assert_eq!(blob.len(), MAGIC.len() + SEALED_BODY_LEN); + assert_eq!(open("correct horse", &blob).expect("legacy open"), k); + } + + #[test] + fn wrong_passphrase_on_a_current_profile_blob_is_the_existing_error() { + let blob = seal("right", &keys(1)).expect("seal"); + let err = open("wrong", &blob).expect_err("wrong passphrase must fail"); + assert_eq!(err, "wrong passphrase or corrupt backup"); + } + + #[test] + fn unknown_profile_id_is_a_clear_error_not_a_fallback() { + let mut blob = seal("pw", &keys(2)).expect("seal"); + blob[MAGIC.len()] = 9; + let err = open("pw", &blob).expect_err("unknown profile must fail"); + assert_eq!(err, "unknown kdf profile 9"); + } + + #[test] + fn trailing_garbage_is_not_an_onionwire_backup() { + let mut blob = seal("pw", &keys(3)).expect("seal"); + blob.push(0xff); + assert_eq!( + open("pw", &blob).expect_err("must reject"), + "not an onionwire backup" + ); + } + + #[test] + #[ignore = "manual KDF timing measurement; run with --release --ignored"] + fn kdf_profile_timings() { + use std::time::Instant; + let salt = [0x11u8; SALT_LEN]; + for (label, profile) in [ + ("legacy m=19456 t=2 p=1", KdfProfile::Legacy), + ("current m=65536 t=3 p=1", KdfProfile::Current), + ] { + let started = Instant::now(); + let _ = kdf_with(profile, "correct horse battery staple", &salt).expect("kdf"); + eprintln!("{label}: {:.3}s", started.elapsed().as_secs_f64()); + } + } } diff --git a/src/store.rs b/src/store.rs index 35c7476..029a69a 100644 --- a/src/store.rs +++ b/src/store.rs @@ -293,7 +293,8 @@ impl Store { CREATE TABLE IF NOT EXISTS store_meta ( id INTEGER PRIMARY KEY CHECK (id = 1), kdf_salt BLOB NOT NULL, - wrapped_key BLOB NOT NULL + wrapped_key BLOB NOT NULL, + kdf_profile INTEGER NOT NULL DEFAULT 0 ); -- The wallet child's RPC creds + chain-source snapshot. One row, -- sealed with the store data key (see `save_wallet_child`): the @@ -692,6 +693,13 @@ impl Store { "payload", "ALTER TABLE outbox ADD COLUMN payload BLOB", )?; + // Which Argon2id profile wraps `store_meta.wrapped_key`. Rows written + // before the column existed are the legacy profile (id 0). + self.add_column_if_missing( + "store_meta", + "kdf_profile", + "ALTER TABLE store_meta ADD COLUMN kdf_profile INTEGER NOT NULL DEFAULT 0", + )?; // `insert_payment` has accepted `kind = "tip"` since the tip path // landed, but the table's CHECK only allowed invoice/receipt, so every // tip insert (inbound *and* outbound) failed the constraint and the @@ -741,17 +749,18 @@ impl Store { } fn unlock_messages(&mut self, passphrase: &str) -> Result<()> { - let row: Option<(Vec, Vec)> = self + let row: Option<(Vec, Vec, i64)> = self .conn .query_row( - "SELECT kdf_salt, wrapped_key FROM store_meta WHERE id = 1", + "SELECT kdf_salt, wrapped_key, kdf_profile FROM store_meta WHERE id = 1", [], - |r| Ok((r.get(0)?, r.get(1)?)), + |r| Ok((r.get(0)?, r.get(1)?, r.get(2)?)), ) .optional()?; match row { - Some((salt, wrapped)) => { - let wrap_key = crate::backup::kdf(passphrase, &salt)?; + Some((salt, wrapped, profile_id)) => { + let profile = kdf_profile_from_id(profile_id)?; + let wrap_key = crate::backup::kdf_with(profile, passphrase, &salt)?; // The unwrapped data key lands in a Zeroizing buffer immediately. let raw = Zeroizing::new( crate::backup::aead_decrypt(&wrap_key, &wrapped, b"") @@ -761,6 +770,11 @@ impl Store { return Err(Error("wrapped message key length".into())); } self.msg_key.copy_from_slice(&raw); + // The passphrase proved itself: a legacy wrap is re-wrapped + // with the current profile once, in one transaction. + if profile != crate::backup::KdfProfile::Current { + self.rewrap_store_meta(passphrase)?; + } self.rewrap_empty_aad_messages()?; Ok(()) } @@ -772,8 +786,13 @@ impl Store { let wrap_key = crate::backup::kdf(passphrase, &salt)?; let wrapped = crate::backup::aead_encrypt(&wrap_key, &data_key[..], b"")?; self.conn.execute( - "INSERT INTO store_meta (id, kdf_salt, wrapped_key) VALUES (1, ?1, ?2)", - params![salt.as_slice(), wrapped], + "INSERT INTO store_meta (id, kdf_salt, wrapped_key, kdf_profile) + VALUES (1, ?1, ?2, ?3)", + params![ + salt.as_slice(), + wrapped, + i64::from(crate::backup::KdfProfile::CURRENT_ID) + ], )?; self.msg_key = data_key; self.reencrypt_legacy_messages()?; @@ -782,6 +801,27 @@ impl Store { } } + /// One-shot upgrade of a legacy-profile wrap to the current KDF profile. + /// Salt, ciphertext and profile id move together in a single transaction. + fn rewrap_store_meta(&mut self, passphrase: &str) -> Result<()> { + let mut salt = [0u8; 16]; + OsRng.fill_bytes(&mut salt); + let wrap_key = crate::backup::kdf(passphrase, &salt)?; + let wrapped = crate::backup::aead_encrypt(&wrap_key, &self.msg_key[..], b"")?; + let tx = self.conn.unchecked_transaction()?; + tx.execute( + "UPDATE store_meta SET kdf_salt = ?1, wrapped_key = ?2, kdf_profile = ?3 + WHERE id = 1", + params![ + salt.as_slice(), + wrapped, + i64::from(crate::backup::KdfProfile::CURRENT_ID) + ], + )?; + tx.commit()?; + Ok(()) + } + fn reencrypt_legacy_messages(&self) -> Result<()> { let mut stmt = self .conn @@ -1748,8 +1788,41 @@ fn open_store_db(home: &Path, db_path: &Path, passphrase: &str) -> Result Ok(conn), + Err(_) => { + let legacy_key = + crate::backup::kdf_with(crate::backup::KdfProfile::Legacy, passphrase, &salt)?; + let conn = open_keyed(db_path, &legacy_key) + .map_err(|_| Error("wrong passphrase or corrupt store".into()))?; + rekey_store(&conn, &key)?; + Ok(conn) + } + } +} + +/// Rewrite every page of an open store under `new_key` in one transaction. +/// SQLCipher rolls the rekey back if any page write fails. +fn rekey_store(conn: &Connection, new_key: &[u8; 32]) -> Result<()> { + // Old-keyed WAL frames must be folded in before the rewrite, or they would + // replay under a key that no longer opens them. + conn.execute_batch("PRAGMA wal_checkpoint(TRUNCATE)")?; + let pragma = Zeroizing::new(format!( + "PRAGMA rekey = \"x'{hex}'\"", + hex = fingerprint(new_key) + )); + conn.execute_batch(pragma.as_str()) + .map_err(|e| Error(format!("store rekey: {e}")))?; + conn.query_row("SELECT count(*) FROM sqlite_master", [], |r| { + r.get::<_, i64>(0) + }) + .map_err(|_| Error("store rekey failed".into()))?; + Ok(()) } /// SQLCipher `PRAGMA key` with the raw-key form: the 32-byte Argon2id output is @@ -1777,20 +1850,50 @@ fn pragma_key(key: &[u8; 32]) -> Zeroizing { /// True when `passphrase` unwraps `store_meta`. An empty `store_meta` (fresh /// store) accepts any passphrase, matching the v0.2.1 behaviour. fn wrapped_key_opens(conn: &Connection, passphrase: &str) -> Result { - let row: Option<(Vec, Vec)> = conn - .query_row( - "SELECT kdf_salt, wrapped_key FROM store_meta WHERE id = 1", - [], - |r| Ok((r.get(0)?, r.get(1)?)), - ) - .optional()?; - let Some((salt, wrapped)) = row else { + let Some((salt, wrapped, profile_id)) = read_store_meta(conn)? else { return Ok(true); }; - let wrap_key = crate::backup::kdf(passphrase, &salt)?; + let profile = kdf_profile_from_id(profile_id)?; + let wrap_key = crate::backup::kdf_with(profile, passphrase, &salt)?; Ok(crate::backup::aead_decrypt(&wrap_key, &wrapped, b"").is_ok()) } +/// `(kdf_salt, wrapped_key, kdf_profile)`. +type StoreMetaRow = (Vec, Vec, i64); + +/// Read the `store_meta` row, tolerating a table that predates `kdf_profile` +/// (a v0.2.1 plaintext store), where the profile is the legacy one. +fn read_store_meta(conn: &Connection) -> Result> { + let has_profile: i64 = conn.query_row( + "SELECT COUNT(*) FROM pragma_table_info('store_meta') WHERE name = 'kdf_profile'", + [], + |r| r.get(0), + )?; + let Some((salt, wrapped, profile)) = (if has_profile > 0 { + conn.query_row( + "SELECT kdf_salt, wrapped_key, kdf_profile FROM store_meta WHERE id = 1", + [], + |r| Ok((r.get(0)?, r.get(1)?, r.get(2)?)), + ) + .optional()? + } else { + conn.query_row( + "SELECT kdf_salt, wrapped_key, 0 FROM store_meta WHERE id = 1", + [], + |r| Ok((r.get(0)?, r.get(1)?, r.get(2)?)), + ) + .optional()? + }) else { + return Ok(None); + }; + Ok(Some((salt, wrapped, profile))) +} + +fn kdf_profile_from_id(id: i64) -> Result { + let id = u8::try_from(id).map_err(|_| Error(format!("unknown kdf profile {id}")))?; + crate::backup::KdfProfile::from_id(id).map_err(Error) +} + /// Rewrites a plaintext sqlite store as an encrypted one and swaps it in. /// The source file is only replaced after the new file opens, passes /// `integrity_check` and unlocks with this passphrase. @@ -2271,7 +2374,8 @@ mod at_rest { OsRng.fill_bytes(&mut salt); let mut data_key = Zeroizing::new([0u8; 32]); OsRng.fill_bytes(&mut data_key[..]); - let wrap = crate::backup::kdf(passphrase, &salt).unwrap(); + let wrap = + crate::backup::kdf_with(crate::backup::KdfProfile::Legacy, passphrase, &salt).unwrap(); let wrapped = crate::backup::aead_encrypt(&wrap, &data_key[..], b"").unwrap(); conn.execute( "INSERT INTO store_meta (id, kdf_salt, wrapped_key) VALUES (1, ?1, ?2)", @@ -2661,4 +2765,174 @@ mod at_rest { assert_eq!(store.list_wallets().unwrap().len(), 1); assert_eq!(store.get_wallet_by_id(row.id).unwrap().unwrap(), row); } + + /// Turn a freshly created store into the exact pre-profile shape: the + /// SQLCipher file keyed with the legacy Argon2id params, and the message + /// key wrapped under the legacy profile with no meaningful profile id. + /// Returns the (salt, wrapped) pair that must be replaced by the upgrade. + fn downgrade_to_legacy_profile(dir: &Path, pass: &str) -> (Vec, Vec) { + let store = Store::open_at_with_passphrase(dir, pass).unwrap(); + let data_key = *store.msg_key; + let salt: [u8; 16] = fs::read(dir.join(SALT_FILE)).unwrap().try_into().unwrap(); + let legacy_db_key = + crate::backup::kdf_with(crate::backup::KdfProfile::Legacy, pass, &salt).unwrap(); + let wrap_salt = [0x33u8; 16]; + let legacy_wrap = + crate::backup::kdf_with(crate::backup::KdfProfile::Legacy, pass, &wrap_salt).unwrap(); + let wrapped = crate::backup::aead_encrypt(&legacy_wrap, &data_key[..], b"").unwrap(); + store + .conn + .execute( + "UPDATE store_meta SET kdf_salt = ?1, wrapped_key = ?2, kdf_profile = 0 + WHERE id = 1", + params![wrap_salt.as_slice(), wrapped.clone()], + ) + .unwrap(); + store + .conn + .execute_batch("PRAGMA wal_checkpoint(TRUNCATE)") + .unwrap(); + store + .conn + .execute_batch(&format!( + "PRAGMA rekey = \"x'{hex}'\"", + hex = fingerprint(&legacy_db_key[..]) + )) + .unwrap(); + drop(store); + (wrap_salt.to_vec(), wrapped) + } + + fn store_meta_parts(dir: &Path, pass: &str) -> (Vec, Vec, i64) { + let salt: [u8; 16] = fs::read(dir.join(SALT_FILE)).unwrap().try_into().unwrap(); + let key = crate::backup::kdf(pass, &salt).unwrap(); + let db = dir.join("onionwire.db"); + let conn = open_keyed(&db, &key) + .or_else(|_| { + let legacy = + crate::backup::kdf_with(crate::backup::KdfProfile::Legacy, pass, &salt)?; + open_keyed(&db, &legacy) + }) + .unwrap(); + conn.query_row( + "SELECT kdf_salt, wrapped_key, kdf_profile FROM store_meta WHERE id = 1", + [], + |r| Ok((r.get(0)?, r.get(1)?, r.get(2)?)), + ) + .unwrap() + } + + #[test] + fn a_legacy_store_opens_and_upgrades_its_kdf_profile_exactly_once() { + let dir = tempfile::tempdir().unwrap(); + let pass = "legacy-upgrade-pass"; + let pk = [7u8; 32]; + { + let store = Store::open_at_with_passphrase(dir.path(), pass).unwrap(); + store.upsert_friend(&pk, "b.onion", None).unwrap(); + store.append_message(&pk, "in", b"survives rekey").unwrap(); + } + let (old_salt, old_wrapped) = downgrade_to_legacy_profile(dir.path(), pass); + assert_eq!( + store_meta_parts(dir.path(), pass).2, + 0, + "fixture must start on the legacy profile" + ); + + let store = Store::open_at_with_passphrase(dir.path(), pass).expect("legacy upgrade"); + assert_eq!( + store.list_messages(&pk).unwrap()[0].plaintext, + b"survives rekey", + "the rekey must not lose data" + ); + let (salt, wrapped, profile) = store_meta_parts(dir.path(), pass); + assert_eq!(profile, i64::from(crate::backup::KdfProfile::CURRENT_ID)); + assert_ne!(salt, old_salt, "upgrade must mint a fresh wrap salt"); + assert_ne!(wrapped, old_wrapped, "upgrade must re-wrap the message key"); + drop(store); + + // The SQLCipher file itself moved to the current profile. + let file_salt: [u8; 16] = fs::read(dir.path().join(SALT_FILE)) + .unwrap() + .try_into() + .unwrap(); + let current = crate::backup::kdf(pass, &file_salt).unwrap(); + assert!( + open_keyed(&dir.path().join("onionwire.db"), ¤t).is_ok(), + "store must be rekeyed to the current profile" + ); + let legacy = + crate::backup::kdf_with(crate::backup::KdfProfile::Legacy, pass, &file_salt).unwrap(); + assert!( + open_keyed(&dir.path().join("onionwire.db"), &legacy).is_err(), + "the legacy file key must no longer open the store" + ); + + // Second unlock is a no-op: the profile flip is one-shot. + let store = Store::open_at_with_passphrase(dir.path(), pass).unwrap(); + let (salt2, wrapped2, profile2) = store_meta_parts(dir.path(), pass); + assert_eq!(profile2, i64::from(crate::backup::KdfProfile::CURRENT_ID)); + assert_eq!((salt2, wrapped2), (salt, wrapped), "re-wrapped twice"); + assert_eq!(store.list_messages(&pk).unwrap().len(), 1); + } + + #[test] + #[ignore = "manual unlock timing measurement; run with --release --ignored"] + fn store_unlock_timing() { + use std::time::Instant; + let dir = tempfile::tempdir().unwrap(); + let pass = "unlock-timing-pass"; + let started = Instant::now(); + drop(Store::open_at_with_passphrase(dir.path(), pass).unwrap()); + eprintln!( + "first open (create): {:.3}s", + started.elapsed().as_secs_f64() + ); + + let started = Instant::now(); + let store = Store::open_at_with_passphrase(dir.path(), pass).unwrap(); + eprintln!( + "reopen, current profile: {:.3}s", + started.elapsed().as_secs_f64() + ); + drop(store); + + downgrade_to_legacy_profile(dir.path(), pass); + let started = Instant::now(); + let store = Store::open_at_with_passphrase(dir.path(), pass).unwrap(); + eprintln!( + "reopen, legacy store (open + rekey + rewrap): {:.3}s", + started.elapsed().as_secs_f64() + ); + drop(store); + + let started = Instant::now(); + let store = Store::open_at_with_passphrase(dir.path(), pass).unwrap(); + eprintln!( + "reopen after upgrade: {:.3}s", + started.elapsed().as_secs_f64() + ); + drop(store); + } + + #[test] + fn an_unknown_store_kdf_profile_is_a_clean_error() { + let dir = tempfile::tempdir().unwrap(); + let pass = "unknown-profile-pass"; + { + let store = Store::open_at_with_passphrase(dir.path(), pass).unwrap(); + store + .conn + .execute("UPDATE store_meta SET kdf_profile = 9 WHERE id = 1", []) + .unwrap(); + } + let err = match Store::open_at_with_passphrase(dir.path(), pass) { + Ok(_) => panic!("an unknown kdf profile must not fall back to legacy params"), + Err(e) => e, + }; + assert!( + err.to_string().contains("unknown kdf profile 9"), + "got {err}" + ); + } } From 5f2a6a184f8a63cb04542dd5e8e9a7737c2c4faf Mon Sep 17 00:00:00 2001 From: agent Date: Wed, 28 Oct 2026 23:51:29 -0400 Subject: [PATCH 03/19] ui: design tokens and the shared component set (plan P1) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit One palette, one geometry, one button. The alpha build had a four-colour darkColorScheme and every screen inventing its own pill, which is why the app read as a debug harness; `ui/Theme.kt` now carries the tokens and new UI takes them from `OwColors` / `OwRadius` / `OwSize` instead of Material defaults. Tokens (§1.1, §1.2): canvas #0A0C0E, surface #12161A, interactive #1C2228, border #262E36, mint accent #2EE59D, text #F3F5F7 / #9BA3AE / #5E6773, and the amber/crimson status triples. Cards are 16dp; buttons and inputs are 12dp squircles; 999dp survives only for status pills. Typography is system sans for chrome, and `MonoStyle` is the single mono style, reserved for pubkeys, truncated locators, seeds, host:port and block heights. Primitives (§1.3), in `ui/components/`: - OwButton — primary / secondary / outline / destructive, exact heights and radii, no elevation; - OwSegmentedControl — one track, accent selected segment, animated; - OwAlertBanner — warning / error / info with a status icon and a tinted surface; - OwCard, OwDivider, OwPill, OwStatusDot, TorStatusPill, OwSectionTitle, OwIconButton (36dp), Identicon, OwConfirmDialog (typed confirmation), OwQrCode (zxing, light plate for scanning). Fourteen single-colour vector icons, so no `material-icons-extended` (a multi-MB dependency) and no icon font. `Label`/`Mono` moved here from the roster so the design system is not owned by one screen. Behaviour: none. These are pure view helpers. --- .../com/siriusdevops/onionwire/ui/Theme.kt | 155 +++++++++-- .../onionwire/ui/components/AlertBanner.kt | 103 +++++++ .../onionwire/ui/components/Buttons.kt | 136 +++++++++ .../onionwire/ui/components/Dialogs.kt | 93 +++++++ .../onionwire/ui/components/QrCode.kt | 78 ++++++ .../ui/components/SegmentedControl.kt | 93 +++++++ .../onionwire/ui/components/Surfaces.kt | 260 ++++++++++++++++++ .../app/src/main/res/drawable/ic_ow_add.xml | 11 + .../app/src/main/res/drawable/ic_ow_chat.xml | 11 + .../main/res/drawable/ic_ow_chevron_left.xml | 15 + .../app/src/main/res/drawable/ic_ow_copy.xml | 18 ++ .../app/src/main/res/drawable/ic_ow_info.xml | 16 ++ .../app/src/main/res/drawable/ic_ow_lock.xml | 16 ++ .../src/main/res/drawable/ic_ow_more_vert.xml | 11 + .../src/main/res/drawable/ic_ow_person.xml | 18 ++ .../app/src/main/res/drawable/ic_ow_qr.xml | 16 ++ .../app/src/main/res/drawable/ic_ow_share.xml | 18 ++ .../src/main/res/drawable/ic_ow_shield.xml | 18 ++ .../src/main/res/drawable/ic_ow_sliders.xml | 22 ++ .../src/main/res/drawable/ic_ow_wallet.xml | 13 + .../src/main/res/drawable/ic_ow_warning.xml | 21 ++ .../onionwire/ui/components/IdenticonTest.kt | 45 +++ 22 files changed, 1167 insertions(+), 20 deletions(-) create mode 100644 android/app/src/main/java/com/siriusdevops/onionwire/ui/components/AlertBanner.kt create mode 100644 android/app/src/main/java/com/siriusdevops/onionwire/ui/components/Buttons.kt create mode 100644 android/app/src/main/java/com/siriusdevops/onionwire/ui/components/Dialogs.kt create mode 100644 android/app/src/main/java/com/siriusdevops/onionwire/ui/components/QrCode.kt create mode 100644 android/app/src/main/java/com/siriusdevops/onionwire/ui/components/SegmentedControl.kt create mode 100644 android/app/src/main/java/com/siriusdevops/onionwire/ui/components/Surfaces.kt create mode 100644 android/app/src/main/res/drawable/ic_ow_add.xml create mode 100644 android/app/src/main/res/drawable/ic_ow_chat.xml create mode 100644 android/app/src/main/res/drawable/ic_ow_chevron_left.xml create mode 100644 android/app/src/main/res/drawable/ic_ow_copy.xml create mode 100644 android/app/src/main/res/drawable/ic_ow_info.xml create mode 100644 android/app/src/main/res/drawable/ic_ow_lock.xml create mode 100644 android/app/src/main/res/drawable/ic_ow_more_vert.xml create mode 100644 android/app/src/main/res/drawable/ic_ow_person.xml create mode 100644 android/app/src/main/res/drawable/ic_ow_qr.xml create mode 100644 android/app/src/main/res/drawable/ic_ow_share.xml create mode 100644 android/app/src/main/res/drawable/ic_ow_shield.xml create mode 100644 android/app/src/main/res/drawable/ic_ow_sliders.xml create mode 100644 android/app/src/main/res/drawable/ic_ow_wallet.xml create mode 100644 android/app/src/main/res/drawable/ic_ow_warning.xml create mode 100644 android/app/src/test/java/com/siriusdevops/onionwire/ui/components/IdenticonTest.kt diff --git a/android/app/src/main/java/com/siriusdevops/onionwire/ui/Theme.kt b/android/app/src/main/java/com/siriusdevops/onionwire/ui/Theme.kt index b04565b..7133a98 100644 --- a/android/app/src/main/java/com/siriusdevops/onionwire/ui/Theme.kt +++ b/android/app/src/main/java/com/siriusdevops/onionwire/ui/Theme.kt @@ -1,34 +1,149 @@ package com.siriusdevops.onionwire.ui import androidx.compose.material3.MaterialTheme +import androidx.compose.material3.Typography import androidx.compose.material3.darkColorScheme import androidx.compose.runtime.Composable import androidx.compose.ui.graphics.Color +import androidx.compose.ui.text.TextStyle +import androidx.compose.ui.text.font.FontFamily +import androidx.compose.ui.text.font.FontWeight +import androidx.compose.ui.unit.dp +import androidx.compose.ui.unit.sp -private val OnionViolet = Color(0xFF7C4DFF) -private val WireCyan = Color(0xFF38F2C7) -private val DeepVoid = Color(0xFF0B0B10) -private val PanelVoid = Color(0xFF15151C) +/** + * OnionWire design tokens. + * + * One canvas, two surfaces, one accent. The palette is deliberately small: + * every screen used to invent its own pill and its own grey, which is what made + * the alpha build read as a debug harness. + * + * Typography rule — the reason this file carries a [MonoStyle]: monospace is + * reserved for cryptographic material and numbers (pubkeys, truncated onion + * locators, seeds, `host:port`, block heights). Chrome is sans. A screen that + * sets `fontFamily = FontFamily.Monospace` on a sentence is a bug. + */ +object OwColors { + /** App canvas. */ + val Canvas = Color(0xFF0A0C0E) + /** Cards and elevated surfaces. */ + val Surface = Color(0xFF12161A) + + /** Inputs, secondary buttons, segmented-control track. */ + val SurfaceInteractive = Color(0xFF1C2228) + + /** The one border. 1dp, never a gradient. */ + val Border = Color(0xFF262E36) + + /** Primary brand / accent. Text on top of it is [Canvas], semibold. */ + val Accent = Color(0xFF2EE59D) + + val TextPrimary = Color(0xFFF3F5F7) + val TextSecondary = Color(0xFF9BA3AE) + val TextMuted = Color(0xFF5E6773) + + /** Success / connected is the accent — there is no second green. */ + val Success = Accent + + /** Warning / syncing. Text, 12% tint, 30% border. */ + val Warning = Color(0xFFF5A623) + val WarningTint = Color(0x1FF5A623) + val WarningBorder = Color(0x4DF5A623) + + /** Danger / error / destructive. */ + val Danger = Color(0xFFFF5C5C) + val DangerTint = Color(0x1FFF5C5C) + val DangerBorder = Color(0x4DFF5C5C) + + /** Info banner — the accent at banner tints, no third hue. */ + val InfoTint = Color(0x142EE59D) + val InfoBorder = Color(0x3D2EE59D) +} + +/** Geometry. Buttons and inputs are 12dp squircles, never 999dp pills. */ +object OwRadius { + /** Cards and the identity bar. */ + val Card = 16.dp + + /** Buttons, inputs, icon surfaces, segmented control. */ + val Control = 12.dp + + /** Small status badges and address chips only. */ + val Pill = 999.dp +} + +/** Fixed sizes from the spec. */ +object OwSize { + val Button = 48.dp + val ButtonCompact = 44.dp + val IconButton = 36.dp + val TabBar = 64.dp + val TabBarBorder = 1.dp + val ProgressTrack = 6.dp +} + +/** The only monospace style in the app. */ +val MonoStyle: TextStyle = TextStyle( + fontFamily = FontFamily.Monospace, + fontSize = 13.sp, + lineHeight = 18.sp, + color = OwColors.TextPrimary, +) + +private val OnionWireTypography = Typography( + // Chrome: system sans. No display face, no bundled grotesque. + displaySmall = TextStyle(fontFamily = FontFamily.SansSerif, fontWeight = FontWeight.Bold, fontSize = 28.sp, lineHeight = 34.sp), + headlineSmall = TextStyle(fontFamily = FontFamily.SansSerif, fontWeight = FontWeight.SemiBold, fontSize = 22.sp, lineHeight = 28.sp), + titleLarge = TextStyle(fontFamily = FontFamily.SansSerif, fontWeight = FontWeight.SemiBold, fontSize = 20.sp, lineHeight = 26.sp), + titleMedium = TextStyle(fontFamily = FontFamily.SansSerif, fontWeight = FontWeight.SemiBold, fontSize = 16.sp, lineHeight = 22.sp), + titleSmall = TextStyle(fontFamily = FontFamily.SansSerif, fontWeight = FontWeight.Medium, fontSize = 15.sp, lineHeight = 20.sp), + bodyLarge = TextStyle(fontFamily = FontFamily.SansSerif, fontSize = 16.sp, lineHeight = 24.sp), + bodyMedium = TextStyle(fontFamily = FontFamily.SansSerif, fontSize = 14.sp, lineHeight = 20.sp), + bodySmall = TextStyle(fontFamily = FontFamily.SansSerif, fontSize = 13.sp, lineHeight = 18.sp), + labelLarge = TextStyle(fontFamily = FontFamily.SansSerif, fontWeight = FontWeight.SemiBold, fontSize = 14.sp, lineHeight = 18.sp), + labelMedium = TextStyle(fontFamily = FontFamily.SansSerif, fontWeight = FontWeight.Medium, fontSize = 12.sp, lineHeight = 16.sp), + labelSmall = TextStyle(fontFamily = FontFamily.SansSerif, fontWeight = FontWeight.Medium, fontSize = 11.sp, lineHeight = 14.sp, letterSpacing = 0.6.sp), +) + +/** + * The scheme Material components (text fields, dialogs, dividers) still read + * from. New UI should take tokens from [OwColors] directly; `surfaceVariant` + * and `onSurfaceVariant` are mapped so untouched Material defaults do not fall + * back to purple. + */ private val OnionWireColors = darkColorScheme( - primary = WireCyan, - onPrimary = DeepVoid, - primaryContainer = OnionViolet, - onPrimaryContainer = Color.White, - secondary = OnionViolet, - onSecondary = Color.White, - background = DeepVoid, - onBackground = Color(0xFFE6E6F0), - surface = DeepVoid, - onSurface = Color(0xFFE6E6F0), - surfaceVariant = PanelVoid, - onSurfaceVariant = Color(0xFFB9B9CC), - outline = Color(0xFF3A3A4A), - error = Color(0xFFFF6B6B), - onError = DeepVoid, + primary = OwColors.Accent, + onPrimary = OwColors.Canvas, + primaryContainer = OwColors.SurfaceInteractive, + onPrimaryContainer = OwColors.TextPrimary, + secondary = OwColors.SurfaceInteractive, + onSecondary = OwColors.TextPrimary, + tertiary = OwColors.TextSecondary, + onTertiary = OwColors.Canvas, + background = OwColors.Canvas, + onBackground = OwColors.TextPrimary, + surface = OwColors.Canvas, + onSurface = OwColors.TextPrimary, + surfaceVariant = OwColors.Surface, + onSurfaceVariant = OwColors.TextSecondary, + surfaceContainer = OwColors.Surface, + surfaceContainerHigh = OwColors.SurfaceInteractive, + surfaceContainerLow = OwColors.Surface, + outline = OwColors.Border, + outlineVariant = OwColors.Border, + error = OwColors.Danger, + onError = OwColors.Canvas, + errorContainer = OwColors.DangerTint, + onErrorContainer = OwColors.Danger, + scrim = Color(0xCC000000), ) @Composable fun OnionWireTheme(content: @Composable () -> Unit) { - MaterialTheme(colorScheme = OnionWireColors, content = content) + MaterialTheme( + colorScheme = OnionWireColors, + typography = OnionWireTypography, + content = content, + ) } diff --git a/android/app/src/main/java/com/siriusdevops/onionwire/ui/components/AlertBanner.kt b/android/app/src/main/java/com/siriusdevops/onionwire/ui/components/AlertBanner.kt new file mode 100644 index 0000000..a7cbb3f --- /dev/null +++ b/android/app/src/main/java/com/siriusdevops/onionwire/ui/components/AlertBanner.kt @@ -0,0 +1,103 @@ +package com.siriusdevops.onionwire.ui.components + +import androidx.compose.foundation.background +import androidx.compose.foundation.border +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.fillMaxWidth +import androidx.compose.foundation.layout.height +import androidx.compose.foundation.layout.padding +import androidx.compose.foundation.layout.size +import androidx.compose.foundation.layout.width +import androidx.compose.foundation.shape.RoundedCornerShape +import androidx.compose.material3.Icon +import androidx.compose.material3.MaterialTheme +import androidx.compose.material3.Text +import androidx.compose.runtime.Composable +import androidx.compose.ui.Modifier +import androidx.compose.ui.draw.clip +import androidx.compose.ui.graphics.Color +import androidx.compose.ui.res.painterResource +import androidx.compose.ui.unit.dp +import com.siriusdevops.onionwire.R +import com.siriusdevops.onionwire.ui.OwColors +import com.siriusdevops.onionwire.ui.OwRadius + +/** Banner severity. Three states, matching the status colours exactly. */ +enum class OwAlertVariant { Warning, Error, Info } + +/** + * A contextual banner: status icon, one-line title, one- or two-line body. + * + * Replaces the raw red and grey paragraphs that used to trail the wallet and + * invite screens. A state the app is *in* (no wallet open, node experimental) is + * an info or warning banner; only a real failure gets [OwAlertVariant.Error]. + */ +@Composable +fun OwAlertBanner( + variant: OwAlertVariant, + title: String, + description: String? = null, + modifier: Modifier = Modifier, + action: (@Composable () -> Unit)? = null, +) { + val text: Color = when (variant) { + OwAlertVariant.Warning -> OwColors.Warning + OwAlertVariant.Error -> OwColors.Danger + OwAlertVariant.Info -> OwColors.TextPrimary + } + val tint: Color = when (variant) { + OwAlertVariant.Warning -> OwColors.WarningTint + OwAlertVariant.Error -> OwColors.DangerTint + OwAlertVariant.Info -> OwColors.InfoTint + } + val border: Color = when (variant) { + OwAlertVariant.Warning -> OwColors.WarningBorder + OwAlertVariant.Error -> OwColors.DangerBorder + OwAlertVariant.Info -> OwColors.InfoBorder + } + val iconRes = when (variant) { + OwAlertVariant.Warning -> R.drawable.ic_ow_warning + OwAlertVariant.Error -> R.drawable.ic_ow_warning + OwAlertVariant.Info -> R.drawable.ic_ow_info + } + val iconTint = when (variant) { + OwAlertVariant.Info -> OwColors.Accent + else -> text + } + + Row( + modifier = modifier + .fillMaxWidth() + .clip(RoundedCornerShape(OwRadius.Control)) + .background(tint) + .border(1.dp, border, RoundedCornerShape(OwRadius.Control)) + .padding(horizontal = 14.dp, vertical = 12.dp), + horizontalArrangement = Arrangement.Start, + ) { + Icon( + painter = painterResource(iconRes), + contentDescription = null, + tint = iconTint, + modifier = Modifier.padding(top = 1.dp).size(18.dp), + ) + Spacer(Modifier.width(10.dp)) + Column(Modifier.weight(1f)) { + Text(title, style = MaterialTheme.typography.titleSmall, color = text) + if (!description.isNullOrBlank()) { + Spacer(Modifier.height(3.dp)) + Text( + description, + style = MaterialTheme.typography.bodySmall, + color = if (variant == OwAlertVariant.Info) OwColors.TextSecondary else text, + ) + } + if (action != null) { + Spacer(Modifier.height(10.dp)) + action() + } + } + } +} diff --git a/android/app/src/main/java/com/siriusdevops/onionwire/ui/components/Buttons.kt b/android/app/src/main/java/com/siriusdevops/onionwire/ui/components/Buttons.kt new file mode 100644 index 0000000..5c9832f --- /dev/null +++ b/android/app/src/main/java/com/siriusdevops/onionwire/ui/components/Buttons.kt @@ -0,0 +1,136 @@ +package com.siriusdevops.onionwire.ui.components + +import androidx.compose.foundation.BorderStroke +import androidx.compose.foundation.layout.Arrangement +import androidx.compose.foundation.layout.Row +import androidx.compose.foundation.layout.Spacer +import androidx.compose.foundation.layout.fillMaxWidth +import androidx.compose.foundation.layout.height +import androidx.compose.foundation.layout.size +import androidx.compose.foundation.layout.width +import androidx.compose.foundation.shape.RoundedCornerShape +import androidx.compose.material3.Button +import androidx.compose.material3.ButtonDefaults +import androidx.compose.material3.Icon +import androidx.compose.material3.MaterialTheme +import androidx.compose.material3.Text +import androidx.compose.runtime.Composable +import androidx.compose.ui.Alignment +import androidx.compose.ui.Modifier +import androidx.compose.ui.graphics.Color +import androidx.compose.ui.res.painterResource +import androidx.compose.ui.text.font.FontWeight +import androidx.compose.ui.unit.dp +import com.siriusdevops.onionwire.ui.OwColors +import com.siriusdevops.onionwire.ui.OwRadius +import com.siriusdevops.onionwire.ui.OwSize + +/** + * The four button tiers. There is no fifth: a screen that needs something + * quieter than [Outline] uses a text action, not a new shape. + */ +enum class OwButtonVariant { + /** Solid accent, canvas-coloured semibold text. One per screen region. */ + Primary, + + /** Solid interactive surface, no border. */ + Secondary, + + /** Transparent with the one border. */ + Outline, + + /** Tinted crimson with a crimson border. Destructive actions only. */ + Destructive, +} + +/** + * The app's button. + * + * Heights and radii come from the spec, not from Material's 40dp default: a + * 48dp target is comfortable and consistent, and a 12dp squircle replaces the + * 999dp pill that made every alpha action look identical. + */ +@Composable +fun OwButton( + text: String, + onClick: () -> Unit, + modifier: Modifier = Modifier, + variant: OwButtonVariant = OwButtonVariant.Primary, + enabled: Boolean = true, + leadingIconRes: Int? = null, +) { + val height = when (variant) { + OwButtonVariant.Outline -> OwSize.ButtonCompact + else -> OwSize.Button + } + val container = when (variant) { + OwButtonVariant.Primary -> OwColors.Accent + OwButtonVariant.Secondary -> OwColors.SurfaceInteractive + OwButtonVariant.Outline -> Color.Transparent + OwButtonVariant.Destructive -> OwColors.DangerTint + } + val content = when (variant) { + OwButtonVariant.Primary -> OwColors.Canvas + OwButtonVariant.Secondary -> OwColors.TextPrimary + OwButtonVariant.Outline -> OwColors.TextPrimary + OwButtonVariant.Destructive -> OwColors.Danger + } + val weight = if (variant == OwButtonVariant.Primary) FontWeight.SemiBold else FontWeight.Medium + + Button( + onClick = onClick, + enabled = enabled, + modifier = modifier.height(height), + shape = RoundedCornerShape(OwRadius.Control), + border = when (variant) { + OwButtonVariant.Outline -> BorderStroke(1.dp, OwColors.Border) + OwButtonVariant.Destructive -> BorderStroke(1.dp, OwColors.DangerBorder) + else -> null + }, + colors = ButtonDefaults.buttonColors( + containerColor = container, + contentColor = content, + disabledContainerColor = when (variant) { + OwButtonVariant.Outline -> Color.Transparent + OwButtonVariant.Primary -> OwColors.SurfaceInteractive + OwButtonVariant.Secondary -> OwColors.Surface + OwButtonVariant.Destructive -> OwColors.Surface + }, + disabledContentColor = OwColors.TextMuted, + ), + elevation = ButtonDefaults.buttonElevation(defaultElevation = 0.dp, pressedElevation = 0.dp), + contentPadding = ButtonDefaults.ContentPadding, + ) { + Row( + verticalAlignment = Alignment.CenterVertically, + horizontalArrangement = Arrangement.Center, + ) { + if (leadingIconRes != null) { + Icon( + painter = painterResource(leadingIconRes), + contentDescription = null, + modifier = Modifier.size(18.dp), + ) + Spacer(Modifier.width(8.dp)) + } + Text(text, style = MaterialTheme.typography.labelLarge, fontWeight = weight) + } + } +} + +/** + * Two buttons sharing a row: the primary action takes the space, the secondary + * one takes what it needs. Used by the identity bar and the empty state. + */ +@Composable +fun OwButtonRow( + modifier: Modifier = Modifier, + content: @Composable androidx.compose.foundation.layout.RowScope.() -> Unit, +) { + Row( + modifier = modifier.fillMaxWidth(), + horizontalArrangement = Arrangement.spacedBy(12.dp), + verticalAlignment = Alignment.CenterVertically, + content = content, + ) +} diff --git a/android/app/src/main/java/com/siriusdevops/onionwire/ui/components/Dialogs.kt b/android/app/src/main/java/com/siriusdevops/onionwire/ui/components/Dialogs.kt new file mode 100644 index 0000000..cb8d1ea --- /dev/null +++ b/android/app/src/main/java/com/siriusdevops/onionwire/ui/components/Dialogs.kt @@ -0,0 +1,93 @@ +package com.siriusdevops.onionwire.ui.components + +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.fillMaxWidth +import androidx.compose.foundation.layout.height +import androidx.compose.foundation.layout.padding +import androidx.compose.foundation.shape.RoundedCornerShape +import androidx.compose.material3.AlertDialog +import androidx.compose.material3.MaterialTheme +import androidx.compose.material3.OutlinedTextField +import androidx.compose.material3.Text +import androidx.compose.material3.TextButton +import androidx.compose.runtime.Composable +import androidx.compose.runtime.getValue +import androidx.compose.runtime.mutableStateOf +import androidx.compose.runtime.remember +import androidx.compose.runtime.setValue +import androidx.compose.ui.Modifier +import androidx.compose.ui.unit.dp +import com.siriusdevops.onionwire.ui.OwColors +import com.siriusdevops.onionwire.ui.OwRadius + +/** + * A typed-confirmation dialog for an irreversible action. + * + * The typed word is not theatre: "Rotate identity" cuts every friend who is + * offline off the current locator, and "Wipe all chats" deletes every message + * body. Both are one stray tap away from a menu, so the dialog asks for the + * word the user is about to lose. + * + * [confirmationWord] is echoed in the field label; the confirm button stays + * disabled until it is typed (case-insensitively) — same contract the old inline + * confirm strip had, now with a real scrim behind it. + */ +@Composable +fun OwConfirmDialog( + title: String, + body: String, + confirmationWord: String, + confirmLabel: String, + destructive: Boolean, + onConfirm: () -> Unit, + onDismiss: () -> Unit, +) { + var typed by remember { mutableStateOf("") } + val armed = typed.trim().equals(confirmationWord, ignoreCase = true) + + AlertDialog( + onDismissRequest = onDismiss, + shape = RoundedCornerShape(OwRadius.Card), + containerColor = OwColors.Surface, + titleContentColor = OwColors.TextPrimary, + textContentColor = OwColors.TextSecondary, + title = { Text(title, style = MaterialTheme.typography.titleMedium) }, + text = { + Column { + Text(body, style = MaterialTheme.typography.bodyMedium) + Spacer(Modifier.height(14.dp)) + OutlinedTextField( + value = typed, + onValueChange = { typed = it }, + singleLine = true, + label = { Text("Type $confirmationWord") }, + modifier = Modifier.fillMaxWidth(), + ) + } + }, + confirmButton = { + Row(horizontalArrangement = Arrangement.End, modifier = Modifier.fillMaxWidth()) { + TextButton(onClick = onDismiss) { + Text("Cancel", color = OwColors.TextSecondary) + } + TextButton( + onClick = onConfirm, + enabled = armed, + ) { + Text( + confirmLabel, + color = when { + !armed -> OwColors.TextMuted + destructive -> OwColors.Danger + else -> OwColors.Accent + }, + ) + } + } + }, + modifier = Modifier.padding(horizontal = 8.dp), + ) +} diff --git a/android/app/src/main/java/com/siriusdevops/onionwire/ui/components/QrCode.kt b/android/app/src/main/java/com/siriusdevops/onionwire/ui/components/QrCode.kt new file mode 100644 index 0000000..9e3fb3d --- /dev/null +++ b/android/app/src/main/java/com/siriusdevops/onionwire/ui/components/QrCode.kt @@ -0,0 +1,78 @@ +package com.siriusdevops.onionwire.ui.components + +import androidx.compose.foundation.Canvas +import androidx.compose.foundation.background +import androidx.compose.foundation.layout.Box +import androidx.compose.foundation.layout.size +import androidx.compose.foundation.shape.RoundedCornerShape +import androidx.compose.runtime.Composable +import androidx.compose.runtime.remember +import androidx.compose.ui.Alignment +import androidx.compose.ui.Modifier +import androidx.compose.ui.draw.clip +import androidx.compose.ui.geometry.Offset +import androidx.compose.ui.geometry.Size +import androidx.compose.ui.graphics.Color +import androidx.compose.ui.unit.Dp +import androidx.compose.ui.unit.dp +import com.google.zxing.BarcodeFormat +import com.google.zxing.EncodeHintType +import com.google.zxing.qrcode.QRCodeWriter +import com.siriusdevops.onionwire.ui.OwColors +import com.siriusdevops.onionwire.ui.OwRadius + +/** + * Renders [payload] as a QR code. + * + * The invite is a locator plus a prekey — long, and it has to survive a person + * pointing a phone at a screen, so the modules are drawn at full contrast on a + * light plate rather than tinted to match the dark theme. + * + * A payload zxing cannot encode (too long for version 40) renders as an empty + * plate; callers always show the copyable text as well, so a failed encode is + * degraded, not fatal. + */ +@Composable +fun OwQrCode( + payload: String, + modifier: Modifier = Modifier, + size: Dp = 200.dp, +) { + val matrix = remember(payload) { + runCatching { + QRCodeWriter().encode( + payload, + BarcodeFormat.QR_CODE, + 0, + 0, + mapOf(EncodeHintType.MARGIN to 0), + ) + }.getOrNull() + } + Box( + modifier = modifier + .size(size) + .clip(RoundedCornerShape(OwRadius.Control)) + .background(OwColors.TextPrimary), + contentAlignment = Alignment.Center, + ) { + if (matrix != null) { + Canvas(Modifier.size(size)) { + val cells = matrix.width.toFloat() + val cellW = this.size.width / cells + val cellH = this.size.height / matrix.height.toFloat() + for (y in 0 until matrix.height) { + for (x in 0 until matrix.width) { + if (matrix.get(x, y)) { + drawRect( + color = Color(0xFF0A0C0E), + topLeft = Offset(x * cellW, y * cellH), + size = Size(cellW + 0.5f, cellH + 0.5f), + ) + } + } + } + } + } + } +} diff --git a/android/app/src/main/java/com/siriusdevops/onionwire/ui/components/SegmentedControl.kt b/android/app/src/main/java/com/siriusdevops/onionwire/ui/components/SegmentedControl.kt new file mode 100644 index 0000000..11be548 --- /dev/null +++ b/android/app/src/main/java/com/siriusdevops/onionwire/ui/components/SegmentedControl.kt @@ -0,0 +1,93 @@ +package com.siriusdevops.onionwire.ui.components + +import androidx.compose.animation.animateColorAsState +import androidx.compose.animation.core.tween +import androidx.compose.foundation.background +import androidx.compose.foundation.clickable +import androidx.compose.foundation.layout.Box +import androidx.compose.foundation.layout.Row +import androidx.compose.foundation.layout.fillMaxWidth +import androidx.compose.foundation.layout.height +import androidx.compose.foundation.layout.padding +import androidx.compose.foundation.shape.RoundedCornerShape +import androidx.compose.material3.MaterialTheme +import androidx.compose.material3.Text +import androidx.compose.runtime.Composable +import androidx.compose.runtime.getValue +import androidx.compose.ui.Alignment +import androidx.compose.ui.Modifier +import androidx.compose.ui.draw.clip +import androidx.compose.ui.semantics.Role +import androidx.compose.ui.semantics.role +import androidx.compose.ui.semantics.selected +import androidx.compose.ui.semantics.semantics +import androidx.compose.ui.text.font.FontWeight +import androidx.compose.ui.unit.dp +import androidx.compose.ui.unit.sp +import com.siriusdevops.onionwire.ui.OwColors +import com.siriusdevops.onionwire.ui.OwRadius + +/** + * Horizontal segmented control: one track, [OwColors.SurfaceInteractive], 4dp of + * inside padding, 12dp radius. + * + * This replaces the stacks of full-width pill buttons that made "Pruned / Full / + * Testnet" read as three unrelated actions rather than one choice with three + * values. The selected segment is an accent fill with canvas text. + */ +@Composable +fun OwSegmentedControl( + options: List, + selectedIndex: Int, + onSelect: (Int) -> Unit, + modifier: Modifier = Modifier, + enabled: Boolean = true, +) { + Row( + modifier = modifier + .fillMaxWidth() + .clip(RoundedCornerShape(OwRadius.Control)) + .background(OwColors.SurfaceInteractive) + .padding(4.dp), + verticalAlignment = Alignment.CenterVertically, + ) { + options.forEachIndexed { index, label -> + val selected = index == selectedIndex + val container by animateColorAsState( + targetValue = if (selected) OwColors.Accent else OwColors.SurfaceInteractive, + animationSpec = tween(durationMillis = 160), + label = "segment-container", + ) + val textColor by animateColorAsState( + targetValue = when { + selected -> OwColors.Canvas + enabled -> OwColors.TextSecondary + else -> OwColors.TextMuted + }, + animationSpec = tween(durationMillis = 160), + label = "segment-text", + ) + Box( + modifier = Modifier + .weight(1f) + .height(36.dp) + .clip(RoundedCornerShape(9.dp)) + .background(container) + .clickable(enabled = enabled && !selected) { onSelect(index) } + .semantics { + role = Role.Tab + this.selected = selected + }, + contentAlignment = Alignment.Center, + ) { + Text( + label, + style = MaterialTheme.typography.labelLarge, + fontSize = 13.sp, + fontWeight = if (selected) FontWeight.SemiBold else FontWeight.Medium, + color = textColor, + ) + } + } + } +} diff --git a/android/app/src/main/java/com/siriusdevops/onionwire/ui/components/Surfaces.kt b/android/app/src/main/java/com/siriusdevops/onionwire/ui/components/Surfaces.kt new file mode 100644 index 0000000..57bdfde --- /dev/null +++ b/android/app/src/main/java/com/siriusdevops/onionwire/ui/components/Surfaces.kt @@ -0,0 +1,260 @@ +package com.siriusdevops.onionwire.ui.components + +import androidx.compose.foundation.BorderStroke +import androidx.compose.foundation.Canvas +import androidx.compose.foundation.background +import androidx.compose.foundation.border +import androidx.compose.foundation.clickable +import androidx.compose.foundation.layout.Arrangement +import androidx.compose.foundation.layout.Box +import androidx.compose.foundation.layout.Column +import androidx.compose.foundation.layout.ColumnScope +import androidx.compose.foundation.layout.Row +import androidx.compose.foundation.layout.fillMaxWidth +import androidx.compose.foundation.layout.height +import androidx.compose.foundation.layout.padding +import androidx.compose.foundation.layout.size +import androidx.compose.foundation.shape.CircleShape +import androidx.compose.foundation.shape.RoundedCornerShape +import androidx.compose.material3.Icon +import androidx.compose.material3.MaterialTheme +import androidx.compose.material3.Text +import androidx.compose.runtime.Composable +import androidx.compose.ui.Alignment +import androidx.compose.ui.Modifier +import androidx.compose.ui.draw.clip +import androidx.compose.ui.geometry.Offset +import androidx.compose.ui.geometry.Size +import androidx.compose.ui.graphics.Color +import androidx.compose.ui.res.painterResource +import androidx.compose.ui.semantics.contentDescription +import androidx.compose.ui.semantics.semantics +import androidx.compose.ui.unit.Dp +import androidx.compose.ui.unit.dp +import androidx.compose.ui.unit.sp +import com.siriusdevops.onionwire.ui.MonoStyle +import com.siriusdevops.onionwire.ui.OwColors +import com.siriusdevops.onionwire.ui.OwRadius +import com.siriusdevops.onionwire.ui.OwSize + +/** + * A section card: [OwColors.Surface], 16dp radius, one 1dp border, 16dp of + * padding. Every non-list block on every screen is one of these. + */ +@Composable +fun OwCard( + modifier: Modifier = Modifier, + padding: Dp = 16.dp, + content: @Composable ColumnScope.() -> Unit, +) { + Column( + modifier = modifier + .clip(RoundedCornerShape(OwRadius.Card)) + .background(OwColors.Surface) + .border(1.dp, OwColors.Border, RoundedCornerShape(OwRadius.Card)) + .padding(padding), + content = content, + ) +} + +/** Small tracked label, secondary colour. Never monospace. */ +@Composable +fun Label(text: String, modifier: Modifier = Modifier) { + Text( + text, + modifier = modifier, + style = MaterialTheme.typography.labelSmall, + color = OwColors.TextSecondary, + ) +} + +/** + * Cryptographic material and numbers only: pubkeys, truncated locators, seeds, + * `host:port`, block heights. Never a sentence. + */ +@Composable +fun Mono(text: String, modifier: Modifier = Modifier, color: Color = OwColors.TextPrimary) { + Text(text, modifier = modifier, style = MonoStyle.copy(color = color)) +} + +/** Section heading inside a card. */ +@Composable +fun OwSectionTitle(text: String, modifier: Modifier = Modifier) { + Text( + text, + modifier = modifier, + style = MaterialTheme.typography.titleMedium, + color = OwColors.TextPrimary, + ) +} + +/** A 7dp status dot. Colour is the caller's statement, not decoration. */ +@Composable +fun OwStatusDot(color: Color, modifier: Modifier = Modifier) { + Box(modifier.size(7.dp).clip(CircleShape).background(color)) +} + +/** Small status badge — the one place a 999dp radius is correct. */ +@Composable +fun OwPill( + text: String, + modifier: Modifier = Modifier, + textColor: Color = OwColors.TextSecondary, + container: Color = OwColors.SurfaceInteractive, + borderColor: Color? = null, + dotColor: Color? = null, +) { + Row( + modifier = modifier + .clip(RoundedCornerShape(OwRadius.Pill)) + .background(container) + .then( + if (borderColor != null) { + Modifier.border(1.dp, borderColor, RoundedCornerShape(OwRadius.Pill)) + } else { + Modifier + }, + ) + .padding(horizontal = 10.dp, vertical = 4.dp), + verticalAlignment = Alignment.CenterVertically, + horizontalArrangement = Arrangement.spacedBy(6.dp), + ) { + if (dotColor != null) OwStatusDot(dotColor) + Text(text, style = MaterialTheme.typography.labelSmall, color = textColor, fontSize = 11.sp) + } +} + +/** + * The header status pill: `● Tor active`. + * + * Shown while the app is in `Phase.Ready`, which is exactly when the node (and + * therefore Arti) is up. It says nothing about reachability after the app + * leaves the foreground — the keep-alive state is a separate row on the + * settings screen, because that is the honest place for it. + */ +@Composable +fun TorStatusPill(modifier: Modifier = Modifier) { + OwPill( + text = "Tor active", + modifier = modifier, + textColor = OwColors.Accent, + container = OwColors.InfoTint, + borderColor = OwColors.InfoBorder, + dotColor = OwColors.Accent, + ) +} + +/** + * A 36x36 icon button on an interactive surface. Used for Lock, back chevrons + * and the overflow trigger. + */ +@Composable +fun OwIconButton( + iconRes: Int, + contentDescription: String, + onClick: () -> Unit, + modifier: Modifier = Modifier, + tint: Color = OwColors.TextPrimary, + background: Color = OwColors.SurfaceInteractive, + size: Dp = OwSize.IconButton, +) { + Box( + modifier = modifier + .size(size) + .clip(RoundedCornerShape(OwRadius.Control)) + .background(background) + .clickable(onClick = onClick) + .semantics { this.contentDescription = contentDescription }, + contentAlignment = Alignment.Center, + ) { + Icon( + painter = painterResource(iconRes), + contentDescription = null, + tint = tint, + modifier = Modifier.size(18.dp), + ) + } +} + +/** + * A deterministic 5x5 identicon derived from the identity fingerprint. + * + * Not a security feature: it is a stable visual handle so "your identity" is + * recognisable at a glance without reading 64 hex characters. It renders the + * seed it was given — it never invents a value, and two devices showing the + * same fingerprint show the same picture. + */ +@Composable +fun Identicon(seed: String, modifier: Modifier = Modifier, size: Dp = 40.dp) { + val palette = listOf(OwColors.Accent, OwColors.TextSecondary, OwColors.TextMuted) + val cells = identiconCells(seed) + Box( + modifier = modifier + .size(size) + .clip(CircleShape) + .background(OwColors.SurfaceInteractive), + contentAlignment = Alignment.Center, + ) { + Canvas(Modifier.size(size * 0.62f)) { + val cell = this.size.minDimension / 5f + val pad = (this.size.minDimension - cell * 5f) / 2f + cells.forEach { (x, y, tone) -> + drawRect( + color = palette[tone % palette.size], + topLeft = Offset(pad + x * cell, pad + y * cell), + size = Size(cell, cell), + ) + } + } + } +} + +/** + * The left half of a 5-wide grid plus its mirror, as (column, row, tone) + * triples. Pure and cheap: the same seed always yields the same picture. + */ +internal fun identiconCells(seed: String): List> { + if (seed.isEmpty()) return emptyList() + val bytes = seed.map { it.code }.toIntArray() + var i = 0 + val out = mutableListOf>() + for (row in 0 until 5) { + for (col in 0 until 3) { + val v = bytes[i % bytes.size] + i++ + // A cell exists when the byte says so; tone varies the shade. + if (v % 3 != 0) { + val tone = (v / 3) % 3 + out += Triple(col, row, tone) + val mirrored = 4 - col + if (mirrored != col) out += Triple(mirrored, row, tone) + } + } + } + return out +} + +/** The one hairline rule. */ +@Composable +fun OwDivider(modifier: Modifier = Modifier, color: Color = OwColors.Border) { + Box(modifier.fillMaxWidth().height(1.dp).background(color)) +} + +/** Border stroke helper so screens never hardcode the token twice. */ +val OwCardBorder: BorderStroke = BorderStroke(1.dp, OwColors.Border) + +/** Convenience for the many `Icon(painterResource(...))` call sites. */ +@Composable +fun OwIcon( + iconRes: Int, + contentDescription: String?, + tint: Color = OwColors.TextPrimary, + size: Dp = 20.dp, +) { + Icon( + painter = painterResource(iconRes), + contentDescription = contentDescription, + tint = tint, + modifier = Modifier.size(size), + ) +} diff --git a/android/app/src/main/res/drawable/ic_ow_add.xml b/android/app/src/main/res/drawable/ic_ow_add.xml new file mode 100644 index 0000000..3f91af8 --- /dev/null +++ b/android/app/src/main/res/drawable/ic_ow_add.xml @@ -0,0 +1,11 @@ + + + + + diff --git a/android/app/src/main/res/drawable/ic_ow_chat.xml b/android/app/src/main/res/drawable/ic_ow_chat.xml new file mode 100644 index 0000000..e673602 --- /dev/null +++ b/android/app/src/main/res/drawable/ic_ow_chat.xml @@ -0,0 +1,11 @@ + + + + + diff --git a/android/app/src/main/res/drawable/ic_ow_chevron_left.xml b/android/app/src/main/res/drawable/ic_ow_chevron_left.xml new file mode 100644 index 0000000..b235eaa --- /dev/null +++ b/android/app/src/main/res/drawable/ic_ow_chevron_left.xml @@ -0,0 +1,15 @@ + + + + + diff --git a/android/app/src/main/res/drawable/ic_ow_copy.xml b/android/app/src/main/res/drawable/ic_ow_copy.xml new file mode 100644 index 0000000..d52c3fb --- /dev/null +++ b/android/app/src/main/res/drawable/ic_ow_copy.xml @@ -0,0 +1,18 @@ + + + + + + diff --git a/android/app/src/main/res/drawable/ic_ow_info.xml b/android/app/src/main/res/drawable/ic_ow_info.xml new file mode 100644 index 0000000..2a5d106 --- /dev/null +++ b/android/app/src/main/res/drawable/ic_ow_info.xml @@ -0,0 +1,16 @@ + + + + + + diff --git a/android/app/src/main/res/drawable/ic_ow_lock.xml b/android/app/src/main/res/drawable/ic_ow_lock.xml new file mode 100644 index 0000000..fce7ee1 --- /dev/null +++ b/android/app/src/main/res/drawable/ic_ow_lock.xml @@ -0,0 +1,16 @@ + + + + + + diff --git a/android/app/src/main/res/drawable/ic_ow_more_vert.xml b/android/app/src/main/res/drawable/ic_ow_more_vert.xml new file mode 100644 index 0000000..bcd27db --- /dev/null +++ b/android/app/src/main/res/drawable/ic_ow_more_vert.xml @@ -0,0 +1,11 @@ + + + + + diff --git a/android/app/src/main/res/drawable/ic_ow_person.xml b/android/app/src/main/res/drawable/ic_ow_person.xml new file mode 100644 index 0000000..7bc0b35 --- /dev/null +++ b/android/app/src/main/res/drawable/ic_ow_person.xml @@ -0,0 +1,18 @@ + + + + + + diff --git a/android/app/src/main/res/drawable/ic_ow_qr.xml b/android/app/src/main/res/drawable/ic_ow_qr.xml new file mode 100644 index 0000000..7e43c96 --- /dev/null +++ b/android/app/src/main/res/drawable/ic_ow_qr.xml @@ -0,0 +1,16 @@ + + + + + + diff --git a/android/app/src/main/res/drawable/ic_ow_share.xml b/android/app/src/main/res/drawable/ic_ow_share.xml new file mode 100644 index 0000000..dc49c02 --- /dev/null +++ b/android/app/src/main/res/drawable/ic_ow_share.xml @@ -0,0 +1,18 @@ + + + + + + diff --git a/android/app/src/main/res/drawable/ic_ow_shield.xml b/android/app/src/main/res/drawable/ic_ow_shield.xml new file mode 100644 index 0000000..2aab4a8 --- /dev/null +++ b/android/app/src/main/res/drawable/ic_ow_shield.xml @@ -0,0 +1,18 @@ + + + + + + diff --git a/android/app/src/main/res/drawable/ic_ow_sliders.xml b/android/app/src/main/res/drawable/ic_ow_sliders.xml new file mode 100644 index 0000000..d16a838 --- /dev/null +++ b/android/app/src/main/res/drawable/ic_ow_sliders.xml @@ -0,0 +1,22 @@ + + + + + + + + diff --git a/android/app/src/main/res/drawable/ic_ow_wallet.xml b/android/app/src/main/res/drawable/ic_ow_wallet.xml new file mode 100644 index 0000000..ed74045 --- /dev/null +++ b/android/app/src/main/res/drawable/ic_ow_wallet.xml @@ -0,0 +1,13 @@ + + + + + diff --git a/android/app/src/main/res/drawable/ic_ow_warning.xml b/android/app/src/main/res/drawable/ic_ow_warning.xml new file mode 100644 index 0000000..234711a --- /dev/null +++ b/android/app/src/main/res/drawable/ic_ow_warning.xml @@ -0,0 +1,21 @@ + + + + + + diff --git a/android/app/src/test/java/com/siriusdevops/onionwire/ui/components/IdenticonTest.kt b/android/app/src/test/java/com/siriusdevops/onionwire/ui/components/IdenticonTest.kt new file mode 100644 index 0000000..38d6424 --- /dev/null +++ b/android/app/src/test/java/com/siriusdevops/onionwire/ui/components/IdenticonTest.kt @@ -0,0 +1,45 @@ +package com.siriusdevops.onionwire.ui.components + +import org.junit.Assert.assertEquals +import org.junit.Assert.assertTrue +import org.junit.Test + +/** + * The identicon is a rendering of the identity fingerprint, so it has to be a + * function of that value and nothing else: same fingerprint, same picture, on + * every device and every launch. Pure (a list of cells), no Compose runtime. + */ +class IdenticonTest { + + private val fingerprint = + "9f2c41ab77de03b5c8e1f0a6d4b39c2e5a7f81c0d3e6b492af17c5d80e3b6a49" + + @Test + fun the_same_seed_always_produces_the_same_cells() { + assertEquals(identiconCells(fingerprint), identiconCells(fingerprint)) + } + + @Test + fun the_picture_is_mirrored_about_the_middle_column() { + val cells = identiconCells(fingerprint) + val columns = cells.map { it.first } + cells.forEach { (col, row, tone) -> + assertTrue( + "column $col row $row is not mirrored", + cells.any { it.first == 4 - col && it.second == row && it.third == tone }, + ) + } + assertTrue(columns.all { it in 0..4 }) + } + + @Test + fun a_different_seed_produces_a_different_picture() { + val other = fingerprint.reversed() + assertTrue(identiconCells(fingerprint) != identiconCells(other)) + } + + @Test + fun an_empty_seed_draws_nothing() { + assertEquals(emptyList>(), identiconCells("")) + } +} From 0283e6bf48c7a55df062b98b9a8726a5d9f9f000 Mon Sep 17 00:00:00 2001 From: agent Date: Wed, 28 Oct 2026 23:51:51 -0400 Subject: [PATCH 04/19] ui: app shell, messenger and invite refresh (plan P2 and P3) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Plans P2 and P3 are one change: the shell decides who calls the roster, so the roster cannot land before it. The tree is green at this commit, which is why they are not split. Shell (P2) - The horizontal text-link bar is gone. Three top-level destinations hang off a persistent 64dp bottom bar — Chats (default), Wallet, Node and Settings — and everything else is a sub-screen behind a chevron. - MainActivity owns the shell: a Scaffold with the tab bar around a NavHost of chats / wallet / settings plus share, paste, chat, profile, wallets and rotate. Tab selection pops back to the start destination and restores saved state, so a chat left open behind the Wallet tab survives a trip to Settings. - The node keeps living on the wallet screen, where its card already is, so the third tab is the security surface: profile, saved wallets, rotate identity, delete message history, the keep-alive status row, and — disclosed here instead of under the roster — the identity/SDK lines that made the home screen read as a test build. - OwTopBar: 20sp bold title, optional "Tor active" pill beneath it, a 36dp padlock surface for Lock, and the overflow. Rotate identity, saved wallets and delete history live in the overflow; the destructive two go through a typed confirmation dialog or the typed ROTATE screen, never a single tap. - Insets: the tab bar consumes the navigation-bar inset and LocalBottomBarPresent tells screens inside the shell not to pad for it again, so there is no double gap above the tabs and the IME still wins when the keyboard is up. - window.isNavigationBarContrastEnforced = false on Q+, so the system's translucent scrim does not draw a second band over the canvas. Messenger (P3) - The identity block is one bar: identicon, "Your identity", the truncated fingerprint in mono, a copy-invite icon and a QR icon. Gone from here: the YOU (stable forever) card, the "sdk … · identity = ed25519 pubkey" line and the keep-alive paragraph. The full fingerprint and locator stay on the profile and invite screens. - The empty state says what to do and offers both ways out ("Add contact", "Share my invite"), and keeps the honest sentence: invites are not discoverable. - Friend rows: petname, short mono fingerprint, and a locator shortened as head…tail.onion — the suffix is never the part that is cut, and a v3 onion is never soft-wrapped. - Invite sharing shows a QR of the payload beside the copyable text; the clip is marked sensitive on API 33+. No ViewModel, SDK, Tor or wallet call changed. Every callback is the call the old screens made; the wallet screens are untouched for the next card. --- android/README.md | 32 +- .../siriusdevops/onionwire/MainActivity.kt | 243 ++++++--- .../siriusdevops/onionwire/ui/ChatScreen.kt | 8 +- .../com/siriusdevops/onionwire/ui/Insets.kt | 29 +- .../onionwire/ui/InviteScreens.kt | 284 +++++----- .../onionwire/ui/ProfileScreen.kt | 8 +- .../siriusdevops/onionwire/ui/RosterScreen.kt | 485 ++++++++++-------- .../siriusdevops/onionwire/ui/RotateScreen.kt | 12 +- .../onionwire/ui/SettingsScreen.kt | 215 ++++++++ .../onionwire/ui/components/AppTopBar.kt | 79 +++ .../onionwire/ui/components/BottomTabBar.kt | 125 +++++ .../onionwire/ui/components/OverflowMenu.kt | 69 +++ .../onionwire/ui/RosterOnionTest.kt | 45 ++ 13 files changed, 1228 insertions(+), 406 deletions(-) create mode 100644 android/app/src/main/java/com/siriusdevops/onionwire/ui/SettingsScreen.kt create mode 100644 android/app/src/main/java/com/siriusdevops/onionwire/ui/components/AppTopBar.kt create mode 100644 android/app/src/main/java/com/siriusdevops/onionwire/ui/components/BottomTabBar.kt create mode 100644 android/app/src/main/java/com/siriusdevops/onionwire/ui/components/OverflowMenu.kt create mode 100644 android/app/src/test/java/com/siriusdevops/onionwire/ui/RosterOnionTest.kt diff --git a/android/README.md b/android/README.md index e911d99..c3005e6 100644 --- a/android/README.md +++ b/android/README.md @@ -344,6 +344,20 @@ The cuprated graph is built with Rust 1.98 here, the same floor as `ci.yml` (`rust-version = "1.98"`). Job timeout is **90** minutes on `android-release.yml` and **120** on `android-ci.yml`. +## App shell + +Three top-level destinations, one persistent bottom tab bar +(`ui/components/BottomTabBar.kt`): **Chats** (default), **Wallet**, and **Node & +Settings**. Sub-screens (chat, invite share, add contact, rotate, profile, saved +wallets) keep a chevron back button and hide the bar. The rare and destructive +actions — rotate identity, delete message history, saved wallets — are behind the +`⋮` overflow and a typed confirmation, not on the home screen. + +Colours, radii and type live in `ui/Theme.kt` as `OwColors` / `OwRadius` / +`OwSize`; new UI takes tokens from there instead of `MaterialTheme` defaults. +Monospace is reserved for pubkeys, truncated onion locators, seeds, `host:port` +and block heights — never for a sentence. + ## Layout ``` @@ -363,25 +377,33 @@ android/ build.gradle.kts src/main/AndroidManifest.xml src/main/java/com/siriusdevops/onionwire/ - MainActivity.kt # NavHost + MainActivity.kt # app shell: bottom tabs + NavHost WireViewModel.kt # UI-side Wire handle; wallet-child poller crypto/ # Keystore-wrapped store passphrase keepalive/ # NodeHost, KeepAliveService, policy, lifetime wallet/ # ChainStorage, WalletChildBinaries ui/ # Compose screens (M3) + components/ # design system: OwButton, OwSegmentedControl, + # OwAlertBanner, OwCard, OwTopBar, OwBottomTabBar, + # OwConfirmDialog, OwQrCode, Identicon WalletScreen.kt + WalletManagerScreen.kt WalletChildStatusText.kt ChatScreen.kt - RosterScreen.kt - InviteScreens.kt + RosterScreen.kt # Chats tab: identity bar + roster + SettingsScreen.kt # Node & Settings tab + ProfileScreen.kt + InviteScreens.kt # share (QR + text) and paste-a-contact InviteAddFlow.kt OutboxDetail.kt MessageDelivery.kt UnlockScreen.kt UnlockSubmit.kt + SeedBackupGate.kt RotateScreen.kt - Insets.kt - Theme.kt + Insets.kt # systemBars ∪ ime, minus the tab-bar inset + Theme.kt # design tokens: palette, radii, sizes, typography + src/main/res/drawable/ic_ow_*.xml # single-colour design-system icons src/test/ # JVM: envelope, store, invite, outbox, keepalive, wallet line, refresh loop src/androidTest/ # device-only: AndroidKeyStore src/main/jniLibs/arm64-v8a/libmonerowalletrpc.so diff --git a/android/app/src/main/java/com/siriusdevops/onionwire/MainActivity.kt b/android/app/src/main/java/com/siriusdevops/onionwire/MainActivity.kt index 0cd7f57..772f733 100644 --- a/android/app/src/main/java/com/siriusdevops/onionwire/MainActivity.kt +++ b/android/app/src/main/java/com/siriusdevops/onionwire/MainActivity.kt @@ -8,37 +8,61 @@ import androidx.activity.compose.rememberLauncherForActivityResult import androidx.activity.compose.setContent import androidx.activity.enableEdgeToEdge import androidx.activity.result.contract.ActivityResultContracts +import androidx.compose.foundation.layout.WindowInsets import androidx.compose.foundation.layout.fillMaxSize -import androidx.compose.material3.Surface +import androidx.compose.foundation.layout.padding import androidx.compose.material3.MaterialTheme +import androidx.compose.material3.Scaffold +import androidx.compose.material3.Surface import androidx.compose.runtime.Composable +import androidx.compose.runtime.CompositionLocalProvider import androidx.compose.runtime.LaunchedEffect import androidx.compose.runtime.getValue import androidx.compose.runtime.rememberCoroutineScope import androidx.compose.ui.Modifier +import androidx.core.view.WindowCompat import androidx.lifecycle.compose.collectAsStateWithLifecycle import androidx.lifecycle.viewmodel.compose.viewModel +import androidx.navigation.NavHostController import androidx.navigation.NavType import androidx.navigation.compose.NavHost import androidx.navigation.compose.composable +import androidx.navigation.compose.currentBackStackEntryAsState import androidx.navigation.compose.rememberNavController import androidx.navigation.navArgument import com.siriusdevops.onionwire.ui.ChatScreen +import com.siriusdevops.onionwire.ui.LocalBottomBarPresent +import com.siriusdevops.onionwire.ui.OnionWireTheme 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.SettingsScreen import com.siriusdevops.onionwire.ui.ShareInviteScreen import com.siriusdevops.onionwire.ui.UnlockScreen import com.siriusdevops.onionwire.ui.WalletManagerScreen import com.siriusdevops.onionwire.ui.WalletScreen -import com.siriusdevops.onionwire.ui.OnionWireTheme +import com.siriusdevops.onionwire.ui.components.OwBottomTabBar +import com.siriusdevops.onionwire.ui.components.OwTab import kotlinx.coroutines.launch class MainActivity : ComponentActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) enableEdgeToEdge() + // The shell paints the canvas to the bottom of the screen behind the tab + // bar; the system's translucent three-button scrim would draw a second, + // lighter band over it (edge-to-edge guidance, SDK 29+). + if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) { + window.isNavigationBarContrastEnforced = false + } + // enableEdgeToEdge() from ComponentActivity sets the icon appearance from + // the system theme; the app is dark-only, so the bars are always dark with + // light icons. Re-assert it here in case the theme changes under us. + WindowCompat.getInsetsController(window, window.decorView).apply { + isAppearanceLightStatusBars = false + isAppearanceLightNavigationBars = false + } setContent { OnionWireTheme { Surface( @@ -61,7 +85,7 @@ private fun AppRoot(vm: WireViewModel = viewModel()) { // Asked in context: the notification is the keep-alive's only visible // trace, so the prompt lands when the node becomes reachable rather than at // first launch. Denial is not fatal — the service runs either way and the - // roster says the notice is hidden. + // settings screen says the notice is hidden. val askNotifications = rememberLauncherForActivityResult( ActivityResultContracts.RequestPermission(), ) { vm.onNotificationPermissionChanged() } @@ -87,86 +111,165 @@ private fun AppRoot(vm: WireViewModel = viewModel()) { } } +/** Top-level destinations. Everything else is a sub-screen with a chevron. */ +private object Routes { + const val Chats = "chats" + const val Wallet = "wallet" + const val Settings = "settings" + const val Share = "share" + const val Paste = "paste" + const val Rotate = "rotate" + const val Profile = "profile" + const val Wallets = "wallets" + const val Chat = "chat/{pk}" + + fun tabOf(route: String?): OwTab? = when (route) { + Chats -> OwTab.Chats + Wallet -> OwTab.Wallet + Settings -> OwTab.Settings + else -> null + } + + fun routeOf(tab: OwTab): String = when (tab) { + OwTab.Chats -> Chats + OwTab.Wallet -> Wallet + OwTab.Settings -> Settings + } +} + +/** + * The app shell. + * + * A `Scaffold` whose only job is the persistent bottom tab bar: it owns the + * navigation-bar inset, the screens keep owning their own top bars and system + * insets (see `screenContentInsets`), and `LocalBottomBarPresent` tells those + * screens not to pad for the bar a second time. + * + * Selecting a tab pops back to the start destination and restores that tab's + * saved state, so a chat left open behind the Wallet tab is still there when the + * user comes back — the standard bottom-nav contract. + */ @Composable private fun ReadyGraph(vm: WireViewModel, ready: Phase.Ready, keepAliveNote: String?) { val nav = rememberNavController() val friends by vm.friends.collectAsStateWithLifecycle() val scope = rememberCoroutineScope() + val entry by nav.currentBackStackEntryAsState() + val tab = Routes.tabOf(entry?.destination?.route) - NavHost(navController = nav, startDestination = "roster") { - composable("roster") { - RosterScreen( - fingerprint = ready.fingerprint, - onion = ready.onion, - sdkVersion = ready.sdkVersion, - friends = friends, - keepAliveNote = keepAliveNote, - onOpenChat = { nav.navigate("chat/${it.pubkeyHex}") }, - onShare = { nav.navigate("share") }, - onPaste = { nav.navigate("paste") }, - onRotate = { nav.navigate("rotate") }, - onWipe = { scope.launch { vm.wipeMessages() } }, - onOpenProfile = { nav.navigate("profile") }, - onLock = vm::lock, - onOpenWallet = { nav.navigate("wallet") }, - ) - } + Scaffold( + // Each screen's Scaffold applies its own bars; zeroing this one keeps the + // status bar from being padded twice and leaves the only inset this + // level owns — the tab bar's height — in `pad`. + contentWindowInsets = WindowInsets(0, 0, 0, 0), + containerColor = MaterialTheme.colorScheme.background, + bottomBar = { + if (tab != null) { + OwBottomTabBar(selected = tab, onSelect = { nav.selectTab(it) }) + } + }, + ) { pad -> + CompositionLocalProvider(LocalBottomBarPresent provides (tab != null)) { + NavHost( + navController = nav, + startDestination = Routes.Chats, + modifier = Modifier.padding(bottom = pad.calculateBottomPadding()), + ) { + composable(Routes.Chats) { + RosterScreen( + fingerprint = ready.fingerprint, + friends = friends, + invite = vm::invite, + onOpenChat = { nav.navigate("chat/${it.pubkeyHex}") }, + onShare = { nav.navigate(Routes.Share) }, + onPaste = { nav.navigate(Routes.Paste) }, + onRotate = { nav.navigate(Routes.Rotate) }, + onWipe = { scope.launch { vm.wipeMessages() } }, + onOpenProfile = { nav.navigate(Routes.Profile) }, + onLock = vm::lock, + onOpenWallets = { nav.navigate(Routes.Wallets) }, + ) + } - composable("share") { - ShareInviteScreen(ownerInvite = vm::invite, onBack = { nav.popBackStack() }) - } + composable(Routes.Wallet) { + WalletScreen( + vm = vm, + onBack = { nav.popBackStack() }, + onOpenWallets = { nav.navigate(Routes.Wallets) }, + ) + } - composable("paste") { - PasteInviteScreen( - onDecode = vm::decode, - onAdd = vm::addFriend, - onBack = { nav.popBackStack() }, - ) - } + composable(Routes.Settings) { + SettingsScreen( + sdkVersion = ready.sdkVersion, + keepAliveNote = keepAliveNote, + onOpenProfile = { nav.navigate(Routes.Profile) }, + onOpenWallets = { nav.navigate(Routes.Wallets) }, + onRotate = { nav.navigate(Routes.Rotate) }, + onWipe = { scope.launch { vm.wipeMessages() } }, + onLock = vm::lock, + ) + } - composable("rotate") { - RotateScreen( - currentOnion = ready.onion, - onRotate = { - val out = vm.rotateOnion() - out.notified.toInt() to out.friends.toInt() - }, - onBack = { nav.popBackStack() }, - ) - } + composable(Routes.Share) { + ShareInviteScreen(ownerInvite = vm::invite, onBack = { nav.popBackStack() }) + } - composable("wallet") { - WalletScreen( - vm = vm, - onBack = { nav.popBackStack() }, - onOpenWallets = { nav.navigate("wallets") }, - ) - } + composable(Routes.Paste) { + PasteInviteScreen( + onDecode = vm::decode, + onAdd = vm::addFriend, + onBack = { nav.popBackStack() }, + ) + } - composable("wallets") { - WalletManagerScreen(vm = vm, onBack = { nav.popBackStack() }) - } + composable(Routes.Rotate) { + RotateScreen( + currentOnion = ready.onion, + onRotate = { + val out = vm.rotateOnion() + out.notified.toInt() to out.friends.toInt() + }, + onBack = { nav.popBackStack() }, + ) + } - composable("profile") { - ProfileScreen(vm = vm, onBack = { nav.popBackStack() }) - } + composable(Routes.Wallets) { + WalletManagerScreen(vm = vm, onBack = { nav.popBackStack() }) + } - composable( - route = "chat/{pk}", - arguments = listOf(navArgument("pk") { type = NavType.StringType }), - ) { entry -> - val pk = entry.arguments?.getString("pk").orEmpty() - val friend = friends.firstOrNull { it.pubkeyHex == pk } - ChatScreen( - vm = vm, - peer = pk, - title = friend?.petname?.takeIf { it.isNotBlank() } - ?: friend?.fingerprint - ?: pk.take(16), - fingerprint = friend?.fingerprint ?: pk.take(16), - onion = friend?.onion.orEmpty(), - onBack = { nav.popBackStack() }, - ) + composable(Routes.Profile) { + ProfileScreen(vm = vm, onBack = { nav.popBackStack() }) + } + + composable( + route = Routes.Chat, + arguments = listOf(navArgument("pk") { type = NavType.StringType }), + ) { chatEntry -> + val pk = chatEntry.arguments?.getString("pk").orEmpty() + val friend = friends.firstOrNull { it.pubkeyHex == pk } + ChatScreen( + vm = vm, + peer = pk, + title = friend?.petname?.takeIf { it.isNotBlank() } + ?: friend?.fingerprint + ?: pk.take(16), + fingerprint = friend?.fingerprint ?: pk.take(16), + onion = friend?.onion.orEmpty(), + onBack = { nav.popBackStack() }, + ) + } + } } } } + +private fun NavHostController.selectTab(target: OwTab) { + val route = Routes.routeOf(target) + if (currentDestination?.route == route) return + navigate(route) { + popUpTo(graph.startDestinationId) { saveState = true } + launchSingleTop = true + restoreState = true + } +} diff --git a/android/app/src/main/java/com/siriusdevops/onionwire/ui/ChatScreen.kt b/android/app/src/main/java/com/siriusdevops/onionwire/ui/ChatScreen.kt index 499b6f8..84ccd0b 100644 --- a/android/app/src/main/java/com/siriusdevops/onionwire/ui/ChatScreen.kt +++ b/android/app/src/main/java/com/siriusdevops/onionwire/ui/ChatScreen.kt @@ -51,6 +51,8 @@ import androidx.compose.ui.text.font.FontFamily import androidx.compose.ui.text.input.ImeAction import androidx.compose.ui.text.input.KeyboardCapitalization import androidx.compose.ui.unit.dp +import com.siriusdevops.onionwire.R +import com.siriusdevops.onionwire.ui.components.OwIconButton import androidx.lifecycle.compose.collectAsStateWithLifecycle import com.siriusdevops.onionwire.WireViewModel import uniffi.onionwire_sdk.SendState @@ -184,7 +186,11 @@ fun ChatScreen( } }, navigationIcon = { - IconButton(onClick = onBack) { Text("<") } + OwIconButton( + iconRes = R.drawable.ic_ow_chevron_left, + contentDescription = "Back", + onClick = onBack, + ) }, colors = TopAppBarDefaults.topAppBarColors( containerColor = MaterialTheme.colorScheme.background, diff --git a/android/app/src/main/java/com/siriusdevops/onionwire/ui/Insets.kt b/android/app/src/main/java/com/siriusdevops/onionwire/ui/Insets.kt index fd7802d..88a7629 100644 --- a/android/app/src/main/java/com/siriusdevops/onionwire/ui/Insets.kt +++ b/android/app/src/main/java/com/siriusdevops/onionwire/ui/Insets.kt @@ -8,8 +8,18 @@ import androidx.compose.foundation.layout.systemBars import androidx.compose.foundation.layout.union import androidx.compose.foundation.layout.windowInsetsPadding import androidx.compose.runtime.Composable +import androidx.compose.runtime.staticCompositionLocalOf import androidx.compose.ui.Modifier +/** + * True while a screen is rendered inside the shell that owns the bottom tab bar. + * + * The tab bar applies the navigation-bar inset itself, so a screen inside the + * shell must not pad for it a second time — that is the difference between the + * list ending just above the tabs and the list floating 48dp above them. + */ +val LocalBottomBarPresent = staticCompositionLocalOf { false } + /** * The bottom + horizontal window insets one screen's content root must apply * itself. @@ -25,7 +35,9 @@ import androidx.compose.ui.Modifier * * The IME's bottom inset already covers the navigation bar, so the two are * unioned (per-side `max`), never summed: keyboard height while typing, - * navigation-bar height otherwise, and no double padding in between. + * navigation-bar height otherwise, and no double padding in between. Inside the + * tab shell the vertical bar inset is dropped entirely — see + * [LocalBottomBarPresent]. * * The `Top` side is deliberately excluded — a `Scaffold`'s `pad.top` is the app * bar's own measured height, and the app bar carries its own status-bar inset @@ -38,8 +50,15 @@ import androidx.compose.ui.Modifier * composable reads — call it from a composable (every call site is one). */ @Composable -fun Modifier.screenContentInsets(): Modifier = - windowInsetsPadding( - WindowInsets.systemBars.union(WindowInsets.ime) +fun Modifier.screenContentInsets(): Modifier { + val sides = if (LocalBottomBarPresent.current) { + WindowInsetsSides.Horizontal + } else { + WindowInsetsSides.Horizontal + WindowInsetsSides.Bottom + } + return windowInsetsPadding( + WindowInsets.systemBars.only(sides) + .union(WindowInsets.ime) .only(WindowInsetsSides.Horizontal + WindowInsetsSides.Bottom), - ) \ No newline at end of file + ) +} diff --git a/android/app/src/main/java/com/siriusdevops/onionwire/ui/InviteScreens.kt b/android/app/src/main/java/com/siriusdevops/onionwire/ui/InviteScreens.kt index 4d67f52..599e6a4 100644 --- a/android/app/src/main/java/com/siriusdevops/onionwire/ui/InviteScreens.kt +++ b/android/app/src/main/java/com/siriusdevops/onionwire/ui/InviteScreens.kt @@ -1,6 +1,9 @@ package com.siriusdevops.onionwire.ui import android.content.ClipData +import android.content.ClipDescription +import android.os.Build +import android.os.PersistableBundle import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.Row @@ -11,20 +14,13 @@ 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.shape.RoundedCornerShape import androidx.compose.foundation.verticalScroll -import androidx.compose.material3.Button -import androidx.compose.material3.Card -import androidx.compose.material3.CardDefaults import androidx.compose.material3.CircularProgressIndicator -import androidx.compose.material3.ExperimentalMaterial3Api -import androidx.compose.material3.IconButton 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 @@ -32,15 +28,36 @@ import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.remember import androidx.compose.runtime.rememberCoroutineScope import androidx.compose.runtime.setValue +import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.platform.ClipEntry import androidx.compose.ui.platform.LocalClipboard +import androidx.compose.ui.text.style.TextAlign import androidx.compose.ui.unit.dp +import com.siriusdevops.onionwire.R +import com.siriusdevops.onionwire.ui.components.Label +import com.siriusdevops.onionwire.ui.components.Mono +import com.siriusdevops.onionwire.ui.components.OwAlertBanner +import com.siriusdevops.onionwire.ui.components.OwAlertVariant +import com.siriusdevops.onionwire.ui.components.OwButton +import com.siriusdevops.onionwire.ui.components.OwButtonVariant +import com.siriusdevops.onionwire.ui.components.OwCard +import com.siriusdevops.onionwire.ui.components.OwDivider +import com.siriusdevops.onionwire.ui.components.OwQrCode +import com.siriusdevops.onionwire.ui.components.OwTopBar import kotlinx.coroutines.launch import uniffi.onionwire_sdk.FriendInfo import uniffi.onionwire_sdk.InviteInfo -@OptIn(ExperimentalMaterial3Api::class) +/** + * Your invite, as a code and as text. + * + * The invite is the one artifact that leaves the device on purpose, so this + * screen is deliberately plain about what it is: one person, one trusted channel, + * nothing published. Both the QR and the text are here because a person pointing + * a camera at a screen and a person pasting into a chat client are different + * people, and neither is wrong. + */ @Composable fun ShareInviteScreen(ownerInvite: suspend () -> String, onBack: () -> Unit) { var invite by remember { mutableStateOf(null) } @@ -56,18 +73,11 @@ fun ShareInviteScreen(ownerInvite: suspend () -> String, onBack: () -> Unit) { } Scaffold( - topBar = { - TopAppBar( - title = { Text("Your invite") }, - navigationIcon = { IconButton(onClick = onBack) { Text("<") } }, - colors = TopAppBarDefaults.topAppBarColors( - containerColor = MaterialTheme.colorScheme.background, - ), - ) - }, + topBar = { OwTopBar(title = "Your invite", onBack = onBack) }, // The root applies systemBars + IME itself (see `screenContentInsets`), // so Scaffold must not also pad for the navigation bar. contentWindowInsets = WindowInsets(0, 0, 0, 0), + containerColor = OwColors.Canvas, ) { pad -> Column( Modifier @@ -75,70 +85,116 @@ fun ShareInviteScreen(ownerInvite: suspend () -> String, onBack: () -> Unit) { .fillMaxSize() .screenContentInsets() .verticalScroll(rememberScrollState()) - .padding(16.dp), + .padding(horizontal = 16.dp), ) { - Text( - "Hand this to one person, over a channel you already trust. " + - "It is not published anywhere and cannot be looked up.", - style = MaterialTheme.typography.bodySmall, - color = MaterialTheme.colorScheme.onSurfaceVariant, + Spacer(Modifier.height(8.dp)) + OwAlertBanner( + variant = OwAlertVariant.Info, + title = "Not published anywhere", + description = "Hand this to one person over a channel you already " + + "trust. There is no directory and no lookup — that is the point.", ) - Spacer(Modifier.height(12.dp)) + Spacer(Modifier.height(16.dp)) when { - error != null -> Text( - error!!, - style = MaterialTheme.typography.bodySmall, - color = MaterialTheme.colorScheme.error, + error != null -> OwAlertBanner( + variant = OwAlertVariant.Error, + title = "Could not read your invite", + description = error, ) - invite == null -> CircularProgressIndicator() + invite == null -> Row( + Modifier.fillMaxWidth().padding(vertical = 32.dp), + horizontalArrangement = Arrangement.Center, + ) { CircularProgressIndicator(color = OwColors.Accent) } else -> { - Card( - colors = CardDefaults.cardColors( - containerColor = MaterialTheme.colorScheme.surfaceVariant, - ), - ) { + val payload = invite!! + Row(Modifier.fillMaxWidth(), horizontalArrangement = Arrangement.Center) { + OwQrCode(payload = payload, size = 220.dp) + } + Spacer(Modifier.height(16.dp)) + OwCard(Modifier.fillMaxWidth(), padding = 12.dp) { Text( - invite!!, - style = MaterialTheme.typography.bodySmall, - modifier = Modifier.padding(12.dp), + payload, + style = MonoStyle.copy(color = OwColors.TextSecondary), + textAlign = TextAlign.Start, ) } Spacer(Modifier.height(12.dp)) - Row(horizontalArrangement = Arrangement.spacedBy(8.dp)) { - Button(onClick = { - scope.launch { - clipboard.setClipEntry( - ClipEntry(ClipData.newPlainText("onionwire invite", invite!!)), - ) - copied = true - } - }) { Text(if (copied) "Copied" else "Copy") } + Row(horizontalArrangement = Arrangement.spacedBy(12.dp)) { + OwButton( + text = if (copied) "Copied" else "Copy invite", + onClick = { + scope.launch { + val clip = ClipData.newPlainText("onionwire invite", payload) + if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) { + clip.description.extras = PersistableBundle().apply { + putBoolean(ClipDescription.EXTRA_IS_SENSITIVE, true) + } + } + clipboard.setClipEntry(ClipEntry(clip)) + copied = true + } + }, + leadingIconRes = R.drawable.ic_ow_copy, + ) + OwButton( + text = "Done", + variant = OwButtonVariant.Outline, + onClick = onBack, + ) } - Spacer(Modifier.height(20.dp)) - Text("What is in it", style = MaterialTheme.typography.titleSmall) - Spacer(Modifier.height(6.dp)) - Mono("k ed25519 identity pubkey — who you are") - Mono("o current onion locator — where you are now") - Mono("spk x25519 signed prekey — session start material") - Mono("sig signature over k‖o‖spk — reject if it fails") - Spacer(Modifier.height(12.dp)) - Text( - "The onion in here goes stale when you rotate. The key does not. " + - "If you re-share later, the same k updates their entry — it never " + - "creates a second friend.", - style = MaterialTheme.typography.bodySmall, - color = MaterialTheme.colorScheme.onSurfaceVariant, - ) + Spacer(Modifier.height(24.dp)) + OwCard(Modifier.fillMaxWidth()) { + Text( + "What is in it", + style = MaterialTheme.typography.titleSmall, + color = OwColors.TextPrimary, + ) + Spacer(Modifier.height(8.dp)) + InviteField("k", "ed25519 identity pubkey — who you are") + InviteField("o", "current onion locator — where you are now") + InviteField("spk", "x25519 signed prekey — session start material") + InviteField("sig", "signature over k‖o‖spk — reject if it fails") + Spacer(Modifier.height(10.dp)) + OwDivider() + Spacer(Modifier.height(10.dp)) + Text( + "The onion in here goes stale when you rotate. The key does " + + "not. If you re-share later, the same k updates their entry — " + + "it never creates a second friend.", + style = MaterialTheme.typography.bodySmall, + color = OwColors.TextSecondary, + ) + } + Spacer(Modifier.height(24.dp)) } } } } } -@OptIn(ExperimentalMaterial3Api::class) +@Composable +private fun InviteField(key: String, meaning: String) { + Row(Modifier.padding(vertical = 2.dp), verticalAlignment = Alignment.CenterVertically) { + Text( + key, + style = MonoStyle.copy(color = OwColors.Accent), + modifier = Modifier.padding(end = 10.dp), + ) + Label(meaning) + } +} + +/** + * Paste someone else's invite. + * + * Verification is a separate, explicit step from adding: the preview shows who + * they are and where they are reachable *before* anything is written to the + * roster, because a mistyped or swapped invite is the one thing a human can + * still catch. + */ @Composable fun PasteInviteScreen( onDecode: suspend (String) -> InviteInfo, @@ -155,19 +211,12 @@ fun PasteInviteScreen( val adding = flow.adding Scaffold( - topBar = { - TopAppBar( - title = { Text("Add a friend") }, - navigationIcon = { IconButton(onClick = onBack) { Text("<") } }, - colors = TopAppBarDefaults.topAppBarColors( - containerColor = MaterialTheme.colorScheme.background, - ), - ) - }, + topBar = { OwTopBar(title = "Add contact", onBack = onBack) }, // Same inset handoff as the chat composer: with the keyboard up, the // Verify / Approve buttons under the invite field must still be // reachable by scrolling, not by dismissing the keyboard. contentWindowInsets = WindowInsets(0, 0, 0, 0), + containerColor = OwColors.Canvas, ) { pad -> Column( Modifier @@ -175,90 +224,83 @@ fun PasteInviteScreen( .fillMaxSize() .screenContentInsets() .verticalScroll(rememberScrollState()) - .padding(16.dp), + .padding(horizontal = 16.dp), ) { + Spacer(Modifier.height(8.dp)) OutlinedTextField( value = raw, onValueChange = { raw = it flow.clear() }, - label = { Text("onionwire:v1:…") }, + label = { Text("onionwire:v2:…") }, minLines = 4, + shape = RoundedCornerShape(OwRadius.Control), modifier = Modifier.fillMaxWidth(), ) Spacer(Modifier.height(12.dp)) - Row(horizontalArrangement = Arrangement.spacedBy(8.dp)) { - Button( + Row(horizontalArrangement = Arrangement.spacedBy(12.dp)) { + OwButton( + text = "Verify", enabled = raw.isNotBlank() && !verifying && !adding, onClick = { scope.launch { flow.verify(raw) } }, - ) { Text("Verify") } + ) if (added != null) { - TextButton(onClick = onBack) { Text("Done") } + OwButton(text = "Done", variant = OwButtonVariant.Outline, onClick = onBack) } } Spacer(Modifier.height(16.dp)) error?.let { - Text( - it, - style = MaterialTheme.typography.bodySmall, - color = MaterialTheme.colorScheme.error, - ) - Spacer(Modifier.height(8.dp)) - Text( - "Unsigned or tampered invites are rejected here, before anything is stored.", - style = MaterialTheme.typography.bodySmall, - color = MaterialTheme.colorScheme.onSurfaceVariant, + OwAlertBanner( + variant = OwAlertVariant.Error, + title = "That invite was not accepted", + description = "$it — unsigned or tampered invites are rejected " + + "here, before anything is stored.", ) + Spacer(Modifier.height(12.dp)) } preview?.let { p -> - Card( - colors = CardDefaults.cardColors( - containerColor = MaterialTheme.colorScheme.surfaceVariant, - ), - modifier = Modifier.fillMaxWidth(), - ) { - Column(Modifier.padding(12.dp)) { - Label("THEY ARE") - Mono(p.pubkeyHex) - Spacer(Modifier.height(8.dp)) - Text( - "fingerprint ${p.pubkeyHex.take(16)}… — compare this with them " + - "over a second channel before you trust it.", - style = MaterialTheme.typography.bodySmall, - color = MaterialTheme.colorScheme.onSurfaceVariant, - ) - Spacer(Modifier.height(8.dp)) - Label("REACHABLE AT") - Mono(p.onion) - } + OwCard(Modifier.fillMaxWidth()) { + Label("THEY ARE") + Spacer(Modifier.height(2.dp)) + Mono(shortId(p.pubkeyHex, head = 12, tail = 8)) + Spacer(Modifier.height(6.dp)) + Text( + "Compare this fingerprint with them over a second channel " + + "before you trust it.", + style = MaterialTheme.typography.bodySmall, + color = OwColors.TextSecondary, + ) + Spacer(Modifier.height(10.dp)) + OwDivider() + Spacer(Modifier.height(10.dp)) + Label("REACHABLE AT") + Spacer(Modifier.height(2.dp)) + Mono(shortOnion(p.onion)) } Spacer(Modifier.height(12.dp)) - Button( + OwButton( + text = "Approve & add", enabled = !adding && added == null, onClick = { scope.launch { flow.add(raw) } }, - ) { Text("Approve & add") } + leadingIconRes = R.drawable.ic_ow_add, + ) } added?.let { f -> Spacer(Modifier.height(16.dp)) - Text( - "Added ${f.petname ?: f.fingerprint}", - style = MaterialTheme.typography.titleSmall, - color = MaterialTheme.colorScheme.primary, - ) - Spacer(Modifier.height(4.dp)) - Text( - "If that key was already in your roster, only the locator was updated. " + - "One key is always one friend.", - style = MaterialTheme.typography.bodySmall, - color = MaterialTheme.colorScheme.onSurfaceVariant, + OwAlertBanner( + variant = OwAlertVariant.Info, + title = "Added ${f.petname ?: shortId(f.fingerprint)}", + description = "If that key was already in your roster, only the " + + "locator was updated. One key is always one friend.", ) } + Spacer(Modifier.height(24.dp)) } } } diff --git a/android/app/src/main/java/com/siriusdevops/onionwire/ui/ProfileScreen.kt b/android/app/src/main/java/com/siriusdevops/onionwire/ui/ProfileScreen.kt index b3b41c3..030f730 100644 --- a/android/app/src/main/java/com/siriusdevops/onionwire/ui/ProfileScreen.kt +++ b/android/app/src/main/java/com/siriusdevops/onionwire/ui/ProfileScreen.kt @@ -33,6 +33,8 @@ 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 com.siriusdevops.onionwire.R +import com.siriusdevops.onionwire.ui.components.OwIconButton import androidx.lifecycle.compose.collectAsStateWithLifecycle import com.siriusdevops.onionwire.WireViewModel import kotlinx.coroutines.launch @@ -100,7 +102,11 @@ fun ProfileScreen( TopAppBar( title = { Text("Profile") }, navigationIcon = { - TextButton(onClick = onBack) { Text("Back") } + OwIconButton( + iconRes = R.drawable.ic_ow_chevron_left, + contentDescription = "Back", + onClick = onBack, + ) }, colors = TopAppBarDefaults.topAppBarColors( containerColor = MaterialTheme.colorScheme.background, diff --git a/android/app/src/main/java/com/siriusdevops/onionwire/ui/RosterScreen.kt b/android/app/src/main/java/com/siriusdevops/onionwire/ui/RosterScreen.kt index b1575ca..226995a 100644 --- a/android/app/src/main/java/com/siriusdevops/onionwire/ui/RosterScreen.kt +++ b/android/app/src/main/java/com/siriusdevops/onionwire/ui/RosterScreen.kt @@ -1,8 +1,14 @@ package com.siriusdevops.onionwire.ui +import android.content.ClipData +import android.content.ClipDescription +import android.os.Build +import android.os.PersistableBundle +import android.widget.Toast import androidx.compose.foundation.background import androidx.compose.foundation.clickable import androidx.compose.foundation.layout.Arrangement +import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.Row import androidx.compose.foundation.layout.Spacer @@ -12,38 +18,70 @@ import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.height import androidx.compose.foundation.layout.padding import androidx.compose.foundation.layout.width +import androidx.compose.foundation.layout.widthIn import androidx.compose.foundation.lazy.LazyColumn import androidx.compose.foundation.lazy.items -import androidx.compose.material3.Card -import androidx.compose.material3.CardDefaults -import androidx.compose.material3.ExperimentalMaterial3Api -import androidx.compose.material3.HorizontalDivider +import androidx.compose.foundation.shape.CircleShape import androidx.compose.material3.MaterialTheme 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.getValue import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.remember -import androidx.compose.runtime.saveable.rememberSaveable +import androidx.compose.runtime.rememberCoroutineScope import androidx.compose.runtime.setValue import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier -import androidx.compose.ui.text.font.FontFamily +import androidx.compose.ui.draw.clip +import androidx.compose.ui.platform.ClipEntry +import androidx.compose.ui.platform.Clipboard +import androidx.compose.ui.platform.LocalClipboard +import androidx.compose.ui.platform.LocalContext +import androidx.compose.ui.text.style.TextAlign import androidx.compose.ui.unit.dp +import com.siriusdevops.onionwire.R +import com.siriusdevops.onionwire.ui.components.Identicon +import com.siriusdevops.onionwire.ui.components.Label +import com.siriusdevops.onionwire.ui.components.Mono +import com.siriusdevops.onionwire.ui.components.OwButton +import com.siriusdevops.onionwire.ui.components.OwButtonRow +import com.siriusdevops.onionwire.ui.components.OwButtonVariant +import com.siriusdevops.onionwire.ui.components.OwCard +import com.siriusdevops.onionwire.ui.components.OwConfirmDialog +import com.siriusdevops.onionwire.ui.components.OwDivider +import com.siriusdevops.onionwire.ui.components.OwIcon +import com.siriusdevops.onionwire.ui.components.OwIconButton +import com.siriusdevops.onionwire.ui.components.OwOverflowMenu +import com.siriusdevops.onionwire.ui.components.OwStatusDot +import com.siriusdevops.onionwire.ui.components.OwTopBar +import com.siriusdevops.onionwire.ui.components.TorStatusPill +import kotlinx.coroutines.launch import uniffi.onionwire_sdk.FriendInfo -@OptIn(ExperimentalMaterial3Api::class) +/** + * Home: your identity, and the roster. + * + * Three things changed from the alpha build and they are deliberate: + * + * - The identity block is one compact bar. The `YOU (stable forever)` card, the + * `sdk … · identity = ed25519 pubkey` line and the keep-alive paragraph are + * gone from here — the SDK line is on Node & Settings, and the keep-alive + * state is a status row there too. A home screen does not explain the + * transport before it shows the people. + * - The five text-link actions are gone. Invite and Add are the two first-class + * actions (in the empty state, and in the bar); the rare and destructive ones + * live behind `⋮`. + * - The empty state says what to do next, with the two buttons that do it. + * + * Behaviour is unchanged: `invite`, `onPaste`, `onOpenChat`, `onRotate`, + * `onWipe` and `onLock` are the same ViewModel calls the old screen made. + */ @Composable fun RosterScreen( fingerprint: String, - onion: String, - sdkVersion: String, friends: List, - keepAliveNote: String?, + invite: suspend () -> String, onOpenChat: (FriendInfo) -> Unit, onShare: () -> Unit, onPaste: () -> Unit, @@ -51,245 +89,288 @@ fun RosterScreen( onWipe: () -> Unit, onOpenProfile: () -> Unit, onLock: () -> Unit, - onOpenWallet: () -> Unit, + onOpenWallets: () -> Unit, ) { - var confirmWipe by remember { mutableStateOf(false) } - // Closed by default; `rememberSaveable` so a rotation keeps whatever the - // user chose instead of snapping back to (or away from) the summary. - // Nothing about this is worth persisting to the store. - var identityExpanded by rememberSaveable { mutableStateOf(false) } + val context = LocalContext.current + val clipboard = LocalClipboard.current + val scope = rememberCoroutineScope() + var confirmDeleteAll by remember { mutableStateOf(false) } Scaffold( // The content root below consumes systemBars ∪ ime itself (see - // `screenContentInsets`); zeroing the Scaffold's own insets keeps the - // navigation bar from being applied twice and lets the wipe-confirm - // strip sit above the keyboard instead of under it. + // `screenContentInsets`), and the tab bar above this screen consumes the + // navigation-bar inset; zeroing the Scaffold's own insets is what keeps + // the list from being padded twice. contentWindowInsets = WindowInsets(0, 0, 0, 0), + containerColor = OwColors.Canvas, topBar = { - TopAppBar( - title = { Text("OnionWire") }, + OwTopBar( + title = "OnionWire", + status = { TorStatusPill() }, actions = { - TextButton(onClick = onOpenProfile) { Text("Profile") } - TextButton(onClick = onLock) { Text("Lock") } + OwIconButton( + iconRes = R.drawable.ic_ow_lock, + contentDescription = "Lock and stop the node", + onClick = onLock, + ) + OwOverflowMenu( + onOpenProfile = onOpenProfile, + onOpenWallets = onOpenWallets, + onRotate = onRotate, + onWipe = { confirmDeleteAll = true }, + ) }, - colors = TopAppBarDefaults.topAppBarColors( - containerColor = MaterialTheme.colorScheme.background, - ), ) }, ) { pad -> Column(Modifier.padding(pad).fillMaxSize().screenContentInsets()) { - - Card( - modifier = Modifier.fillMaxWidth().padding(horizontal = 12.dp), - colors = CardDefaults.cardColors( - containerColor = MaterialTheme.colorScheme.surfaceVariant, - ), - ) { - Column(Modifier.padding(12.dp)) { - // The disclosure header. Collapsed, this one line *is* the - // identity block: the label, the abbreviated fingerprint, - // and a chevron saying there is more behind it. - Row( - modifier = Modifier - .fillMaxWidth() - .clickable { identityExpanded = !identityExpanded }, - verticalAlignment = Alignment.CenterVertically, - ) { - Label("YOU (stable forever)") - if (!identityExpanded) { - Spacer(Modifier.width(8.dp)) - Mono(shortId(fingerprint)) - } - Spacer(Modifier.weight(1f)) - Text( - if (identityExpanded) "▾" else "▸", - style = MaterialTheme.typography.labelSmall, - color = MaterialTheme.colorScheme.onSurfaceVariant, - ) + IdentityBar( + fingerprint = fingerprint, + onCopyInvite = { + scope.launch { + runCatching { invite() } + .onSuccess { payload -> + copyInvite(clipboard, payload) + Toast.makeText(context, "Invite address copied", Toast.LENGTH_SHORT).show() + } + .onFailure { + Toast.makeText(context, "Could not read the invite", Toast.LENGTH_SHORT).show() + } } - if (identityExpanded) { - Mono(fingerprint) - Spacer(Modifier.height(10.dp)) - Label("ONION (locator — rotates)") - Mono(onion) - } - Spacer(Modifier.height(10.dp)) - Text( - "sdk $sdkVersion · identity = ed25519 pubkey", - style = MaterialTheme.typography.labelSmall, - color = MaterialTheme.colorScheme.onSurfaceVariant, - ) - if (keepAliveNote != null) { - Spacer(Modifier.height(10.dp)) - Text( - keepAliveNote, - style = MaterialTheme.typography.labelSmall, - color = MaterialTheme.colorScheme.primary, - ) - } - } - } + }, + onShare = onShare, + ) - Spacer(Modifier.height(8.dp)) - Row( - modifier = Modifier.fillMaxWidth().padding(horizontal = 8.dp), - horizontalArrangement = Arrangement.SpaceEvenly, - ) { - TextButton(onClick = onShare) { Text("Invite") } - TextButton(onClick = onPaste) { Text("Add") } - TextButton(onClick = onRotate) { Text("Rotate") } - TextButton(onClick = onOpenWallet) { Text("Wallet") } - TextButton(onClick = { confirmWipe = true }) { Text("Wipe chat") } - } - - if (confirmWipe) { - ConfirmStrip( - text = "Delete every message body? Identity and friends stay.", - confirm = "WIPE", - onConfirm = { confirmWipe = false; onWipe() }, - onCancel = { confirmWipe = false }, - ) - } - - HorizontalDivider(Modifier.padding(vertical = 8.dp)) + Spacer(Modifier.height(12.dp)) if (friends.isEmpty()) { - Column( - Modifier.fillMaxSize().padding(24.dp), - verticalArrangement = Arrangement.Center, - horizontalAlignment = Alignment.CenterHorizontally, - ) { - Text("No friends yet", style = MaterialTheme.typography.titleMedium) - Spacer(Modifier.height(8.dp)) - Text( - "Share your invite over a channel you already trust, or paste " + - "someone else's. Invites are not discoverable — nothing is published.", - style = MaterialTheme.typography.bodySmall, - color = MaterialTheme.colorScheme.onSurfaceVariant, - ) - } + EmptyRoster( + modifier = Modifier.weight(1f), + onPaste = onPaste, + onShare = onShare, + ) } else { - // weight(1f), not fillMaxSize(): the list must yield height to - // its siblings (the action row and the wipe-confirm strip above - // it) when the IME shrinks the window, instead of claiming all - // of it and pushing them off the bottom. LazyColumn(Modifier.weight(1f).fillMaxWidth()) { items(friends, key = { it.pubkeyHex }) { f -> FriendRow(f) { onOpenChat(f) } - HorizontalDivider() + OwDivider(Modifier.padding(horizontal = 16.dp)) } } } } } + + if (confirmDeleteAll) { + OwConfirmDialog( + title = "Delete all message history?", + body = "Every message body on this device is deleted. Your identity, " + + "your friends and the pending queue are untouched.", + confirmationWord = "DELETE", + confirmLabel = "Delete history", + destructive = true, + onConfirm = { + confirmDeleteAll = false + onWipe() + }, + onDismiss = { confirmDeleteAll = false }, + ) + } +} + +/** + * Your identity, as one bar: identicon, label, truncated pubkey, then the two + * actions a person actually performs here — copy the invite, show it as a code. + */ +@Composable +private fun IdentityBar( + fingerprint: String, + onCopyInvite: () -> Unit, + onShare: () -> Unit, +) { + OwCard( + modifier = Modifier.fillMaxWidth().padding(horizontal = 16.dp), + padding = 12.dp, + ) { + Row(verticalAlignment = Alignment.CenterVertically) { + Identicon(seed = fingerprint, size = 40.dp) + Spacer(Modifier.width(12.dp)) + Column(Modifier.weight(1f)) { + Label("Your identity") + Spacer(Modifier.height(2.dp)) + Mono(shortId(fingerprint)) + } + OwIconButton( + iconRes = R.drawable.ic_ow_copy, + contentDescription = "Copy invite address", + onClick = onCopyInvite, + ) + Spacer(Modifier.width(8.dp)) + OwIconButton( + iconRes = R.drawable.ic_ow_qr, + contentDescription = "Show your invite", + onClick = onShare, + ) + } + } +} + +/** + * The empty roster. + * + * The honest sentence stays: invites are not discoverable, nothing is published. + * The two buttons are the two ways out of this state, in the order that helps — + * paste a peer's invite, or hand yours out. + */ +@Composable +private fun EmptyRoster( + modifier: Modifier = Modifier, + onPaste: () -> Unit, + onShare: () -> Unit, +) { + Column( + modifier = modifier.fillMaxWidth().padding(horizontal = 24.dp), + verticalArrangement = Arrangement.Center, + horizontalAlignment = Alignment.CenterHorizontally, + ) { + Box( + Modifier + .width(64.dp) + .height(64.dp) + .clip(CircleShape) + .background(OwColors.Surface), + contentAlignment = Alignment.Center, + ) { + OwIcon( + iconRes = R.drawable.ic_ow_shield, + contentDescription = null, + tint = OwColors.Accent, + size = 30.dp, + ) + } + Spacer(Modifier.height(16.dp)) + Text( + "No contacts yet", + style = MaterialTheme.typography.titleMedium, + color = OwColors.TextPrimary, + ) + Spacer(Modifier.height(8.dp)) + Text( + "Share your invite over a channel you already trust, or paste a peer's " + + "invite to start an end-to-end encrypted chat. Invites are not " + + "discoverable — nothing is published.", + style = MaterialTheme.typography.bodySmall, + color = OwColors.TextSecondary, + textAlign = TextAlign.Center, + modifier = Modifier.widthIn(max = 280.dp), + ) + Spacer(Modifier.height(20.dp)) + OwButtonRow(Modifier.widthIn(max = 320.dp)) { + OwButton( + text = "Add contact", + onClick = onPaste, + variant = OwButtonVariant.Primary, + modifier = Modifier.weight(1f), + leadingIconRes = R.drawable.ic_ow_add, + ) + OwButton( + text = "Share my invite", + onClick = onShare, + variant = OwButtonVariant.Secondary, + modifier = Modifier.weight(1f), + ) + } + } } @Composable private fun FriendRow(f: FriendInfo, onClick: () -> Unit) { - Column( + Row( Modifier .fillMaxWidth() .clickable(onClick = onClick) - .background(MaterialTheme.colorScheme.background) .padding(horizontal = 16.dp, vertical = 12.dp), + verticalAlignment = Alignment.CenterVertically, ) { - Row(verticalAlignment = Alignment.CenterVertically) { - Text( - f.petname?.takeIf { it.isNotBlank() } ?: f.fingerprint, - style = MaterialTheme.typography.titleSmall, - ) - if (!f.lastConnectOk) { - Spacer(Modifier.height(0.dp)) + Column(Modifier.weight(1f)) { + Row(verticalAlignment = Alignment.CenterVertically) { Text( - " locator stale", - style = MaterialTheme.typography.labelSmall, - color = MaterialTheme.colorScheme.error, + f.petname?.takeIf { it.isNotBlank() } ?: f.fingerprint, + style = MaterialTheme.typography.titleSmall, + color = OwColors.TextPrimary, ) + if (!f.lastConnectOk) { + Spacer(Modifier.width(8.dp)) + OwStatusDot(OwColors.Warning) + Spacer(Modifier.width(6.dp)) + Text( + "locator stale", + style = MaterialTheme.typography.labelSmall, + color = OwColors.Warning, + ) + } } + Spacer(Modifier.height(3.dp)) + Text( + shortId(f.fingerprint), + style = MonoStyle, + color = OwColors.TextSecondary, + ) + Text( + shortOnion(f.onion), + style = MonoStyle.copy(color = OwColors.TextMuted), + ) } - Spacer(Modifier.height(2.dp)) - Text( - f.fingerprint, - style = MaterialTheme.typography.bodySmall, - fontFamily = FontFamily.Monospace, - color = MaterialTheme.colorScheme.primary, - ) - Text( - f.onion, - style = MaterialTheme.typography.labelSmall, - fontFamily = FontFamily.Monospace, - color = MaterialTheme.colorScheme.onSurfaceVariant, - ) + Text("›", style = MaterialTheme.typography.titleMedium, color = OwColors.TextMuted) } } +/** + * Clipboard handling for the invite. + * + * The invite is a locator plus a prekey: it is a secret-ish string that opens a + * conversation with you, so the clip is marked sensitive (API 33+) — it will not + * be previewed on the lock screen or indexed by the clipboard UI. Nothing here + * is logged, persisted, or drawn anywhere but the share sheet. + */ +private suspend fun copyInvite(clipboard: Clipboard, text: String) { + val clip = ClipData.newPlainText("onionwire invite", text) + if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) { + clip.description.extras = PersistableBundle().apply { + putBoolean(ClipDescription.EXTRA_IS_SENSITIVE, true) + } + } + clipboard.setClipEntry(ClipEntry(clip)) +} + /** * The compact stand-in for a long identity string: `head` characters, an - * ellipsis, then `tail` characters. Pure, so the roster's collapsed line and - * its unit test agree on what "short" means. + * ellipsis, then `tail` characters. Pure, so the roster's line and its unit test + * agree on what "short" means. * * A string no longer than the abbreviation is returned unchanged — the * abbreviation must never grow a value, and a short value must never come back - * mangled. Kotlin strings are UTF-16, but these IDs are hex, so `take`/ - * `takeLast` cannot split a surrogate pair here. + * mangled. Kotlin strings are UTF-16, but these IDs are hex, so `take`/`takeLast` + * cannot split a surrogate pair here. */ fun shortId(id: String, head: Int = 6, tail: Int = 4): String { if (id.length < head + tail + 1) return id return id.take(head) + "…" + id.takeLast(tail) } -@Composable -fun Label(text: String) { - Text( - text, - style = MaterialTheme.typography.labelSmall, - color = MaterialTheme.colorScheme.onSurfaceVariant, - ) -} - -@Composable -fun Mono(text: String) { - Text( - text, - style = MaterialTheme.typography.bodySmall, - fontFamily = FontFamily.Monospace, - color = MaterialTheme.colorScheme.onSurface, - ) -} - -@Composable -fun ConfirmStrip( - text: String, - confirm: String, - onConfirm: () -> Unit, - onCancel: () -> Unit, -) { - var typed by remember { mutableStateOf("") } - Card( - modifier = Modifier.fillMaxWidth().padding(12.dp), - colors = CardDefaults.cardColors( - containerColor = MaterialTheme.colorScheme.surfaceVariant, - ), - ) { - Column(Modifier.padding(12.dp)) { - Text(text, style = MaterialTheme.typography.bodySmall) - Spacer(Modifier.height(8.dp)) - androidx.compose.material3.OutlinedTextField( - value = typed, - onValueChange = { typed = it }, - singleLine = true, - label = { Text("Type $confirm") }, - modifier = Modifier.fillMaxWidth(), - ) - Spacer(Modifier.height(8.dp)) - Row(horizontalArrangement = Arrangement.End, modifier = Modifier.fillMaxWidth()) { - TextButton(onClick = onCancel) { Text("Cancel") } - TextButton( - onClick = onConfirm, - enabled = typed.trim().equals(confirm, ignoreCase = true), - ) { Text("Confirm") } - } - } - } +/** + * A v3 onion locator shortened for a roster row, with the `.onion` suffix kept + * visible: `abcdefghij…uvwxyz.onion`. + * + * The suffix is the part that tells a reader this is an onion address at all, so + * it is never the part that gets truncated. The full value lives on the profile + * and invite screens, and a v3 locator is never soft-wrapped — a wrapped address + * cannot be copied reliably. + */ +fun shortOnion(onion: String, head: Int = 10, tail: Int = 6): String { + val suffix = ".onion" + if (onion.isEmpty()) return onion + if (!onion.endsWith(suffix)) return onion + val body = onion.removeSuffix(suffix) + if (body.length <= head + tail + 1) return onion + return body.take(head) + "…" + body.takeLast(tail) + suffix } diff --git a/android/app/src/main/java/com/siriusdevops/onionwire/ui/RotateScreen.kt b/android/app/src/main/java/com/siriusdevops/onionwire/ui/RotateScreen.kt index b1f99b5..89f351e 100644 --- a/android/app/src/main/java/com/siriusdevops/onionwire/ui/RotateScreen.kt +++ b/android/app/src/main/java/com/siriusdevops/onionwire/ui/RotateScreen.kt @@ -29,6 +29,10 @@ import androidx.compose.runtime.remember import androidx.compose.runtime.setValue import androidx.compose.ui.Modifier import androidx.compose.ui.unit.dp +import com.siriusdevops.onionwire.R +import com.siriusdevops.onionwire.ui.components.Label +import com.siriusdevops.onionwire.ui.components.Mono +import com.siriusdevops.onionwire.ui.components.OwIconButton /** * Rotating publishes a brand new onion service and hard-cuts the old one. @@ -54,7 +58,13 @@ fun RotateScreen( topBar = { TopAppBar( title = { Text("Rotate onion") }, - navigationIcon = { IconButton(onClick = onBack) { Text("<") } }, + navigationIcon = { + OwIconButton( + iconRes = R.drawable.ic_ow_chevron_left, + contentDescription = "Back", + onClick = onBack, + ) + }, colors = TopAppBarDefaults.topAppBarColors( containerColor = MaterialTheme.colorScheme.background, ), diff --git a/android/app/src/main/java/com/siriusdevops/onionwire/ui/SettingsScreen.kt b/android/app/src/main/java/com/siriusdevops/onionwire/ui/SettingsScreen.kt new file mode 100644 index 0000000..a9ec625 --- /dev/null +++ b/android/app/src/main/java/com/siriusdevops/onionwire/ui/SettingsScreen.kt @@ -0,0 +1,215 @@ +package com.siriusdevops.onionwire.ui + +import androidx.compose.foundation.clickable +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.layout.width +import androidx.compose.foundation.rememberScrollState +import androidx.compose.foundation.verticalScroll +import androidx.compose.material3.MaterialTheme +import androidx.compose.material3.Scaffold +import androidx.compose.material3.Text +import androidx.compose.runtime.Composable +import androidx.compose.runtime.getValue +import androidx.compose.runtime.mutableStateOf +import androidx.compose.runtime.remember +import androidx.compose.runtime.setValue +import androidx.compose.ui.Alignment +import androidx.compose.ui.Modifier +import androidx.compose.ui.graphics.Color +import androidx.compose.ui.unit.dp +import com.siriusdevops.onionwire.R +import com.siriusdevops.onionwire.ui.components.Label +import com.siriusdevops.onionwire.ui.components.Mono +import com.siriusdevops.onionwire.ui.components.OwCard +import com.siriusdevops.onionwire.ui.components.OwConfirmDialog +import com.siriusdevops.onionwire.ui.components.OwDivider +import com.siriusdevops.onionwire.ui.components.OwIconButton +import com.siriusdevops.onionwire.ui.components.OwSectionTitle +import com.siriusdevops.onionwire.ui.components.OwTopBar +import com.siriusdevops.onionwire.ui.components.TorStatusPill + +/** + * The third tab: everything that is not a conversation or a balance. + * + * This is where the alpha build's honest-but-noisy bits went — the SDK line, the + * keep-alive paragraph, the identity rotation and the history wipe. They are not + * hidden; they are one tap away instead of on the screen a person opens twenty + * times a day. No behaviour lives here: every callback is a ViewModel call the + * old roster made. + */ +@Composable +fun SettingsScreen( + sdkVersion: String, + keepAliveNote: String?, + onOpenProfile: () -> Unit, + onOpenWallets: () -> Unit, + onRotate: () -> Unit, + onWipe: () -> Unit, + onLock: () -> Unit, +) { + var confirmDeleteAll by remember { mutableStateOf(false) } + + Scaffold( + contentWindowInsets = WindowInsets(0, 0, 0, 0), + containerColor = OwColors.Canvas, + topBar = { + OwTopBar( + title = "Node & Settings", + status = { TorStatusPill() }, + actions = { + OwIconButton( + iconRes = R.drawable.ic_ow_lock, + contentDescription = "Lock and stop the node", + onClick = onLock, + ) + }, + ) + }, + ) { pad -> + Column( + Modifier + .padding(pad) + .fillMaxSize() + .screenContentInsets() + .verticalScroll(rememberScrollState()) + .padding(horizontal = 16.dp), + ) { + Spacer(Modifier.height(8.dp)) + + OwCard(Modifier.fillMaxWidth()) { + Label("ACCOUNT") + Spacer(Modifier.height(4.dp)) + SettingsRow( + title = "Your profile", + subtitle = "Name, bio and Monero address", + onClick = onOpenProfile, + ) + OwDivider() + SettingsRow( + title = "Saved wallets", + subtitle = "Open a wallet file, or check its backup", + onClick = onOpenWallets, + ) + } + + Spacer(Modifier.height(12.dp)) + + OwCard(Modifier.fillMaxWidth()) { + Label("REACHABILITY") + Spacer(Modifier.height(6.dp)) + Text( + keepAliveNote ?: "Checking how this app is kept reachable…", + style = MaterialTheme.typography.bodySmall, + color = OwColors.TextSecondary, + ) + } + + Spacer(Modifier.height(12.dp)) + + OwCard(Modifier.fillMaxWidth()) { + Label("SECURITY & DATA") + Spacer(Modifier.height(4.dp)) + SettingsRow( + title = "Rotate identity", + subtitle = "New onion address. Offline contacts must re-scan your invite.", + onClick = onRotate, + ) + OwDivider() + SettingsRow( + title = "Delete message history", + subtitle = "Removes every message body on this device. Identity and contacts stay.", + danger = true, + onClick = { confirmDeleteAll = true }, + ) + } + + Spacer(Modifier.height(12.dp)) + + OwCard(Modifier.fillMaxWidth()) { + OwSectionTitle("About") + Spacer(Modifier.height(6.dp)) + Text( + "identity = ed25519 pubkey", + style = MaterialTheme.typography.bodySmall, + color = OwColors.TextSecondary, + ) + Spacer(Modifier.height(4.dp)) + Row(verticalAlignment = Alignment.CenterVertically) { + Label("SDK") + Spacer(Modifier.width(8.dp)) + Mono(sdkVersion) + } + Spacer(Modifier.height(10.dp)) + Text( + "Tor and the chain node run in-process. The wallet is an RPC the app " + + "owns and starts itself.", + style = MaterialTheme.typography.bodySmall, + color = OwColors.TextSecondary, + ) + } + + Spacer(Modifier.height(24.dp)) + } + } + + if (confirmDeleteAll) { + OwConfirmDialog( + title = "Delete all message history?", + body = "Every message body on this device is deleted. Your identity, " + + "your friends and the pending queue are untouched.", + confirmationWord = "DELETE", + confirmLabel = "Delete history", + destructive = true, + onConfirm = { + confirmDeleteAll = false + onWipe() + }, + onDismiss = { confirmDeleteAll = false }, + ) + } +} + +@Composable +private fun SettingsRow( + title: String, + subtitle: String, + onClick: () -> Unit, + danger: Boolean = false, +) { + Row( + Modifier + .fillMaxWidth() + .clickable(onClick = onClick) + .padding(vertical = 12.dp), + verticalAlignment = Alignment.CenterVertically, + horizontalArrangement = Arrangement.SpaceBetween, + ) { + Column(Modifier.weight(1f)) { + Text( + title, + style = MaterialTheme.typography.titleSmall, + color = if (danger) OwColors.Danger else OwColors.TextPrimary, + ) + Spacer(Modifier.height(2.dp)) + Text( + subtitle, + style = MaterialTheme.typography.bodySmall, + color = if (danger) Color(0xCCFF5C5C) else OwColors.TextSecondary, + ) + } + Spacer(Modifier.width(12.dp)) + Text( + "›", + style = MaterialTheme.typography.titleMedium, + color = if (danger) OwColors.Danger else OwColors.TextMuted, + ) + } +} diff --git a/android/app/src/main/java/com/siriusdevops/onionwire/ui/components/AppTopBar.kt b/android/app/src/main/java/com/siriusdevops/onionwire/ui/components/AppTopBar.kt new file mode 100644 index 0000000..3c3e1c7 --- /dev/null +++ b/android/app/src/main/java/com/siriusdevops/onionwire/ui/components/AppTopBar.kt @@ -0,0 +1,79 @@ +package com.siriusdevops.onionwire.ui.components + +import androidx.compose.foundation.background +import androidx.compose.foundation.layout.Arrangement +import androidx.compose.foundation.layout.Column +import androidx.compose.foundation.layout.Row +import androidx.compose.foundation.layout.RowScope +import androidx.compose.foundation.layout.Spacer +import androidx.compose.foundation.layout.fillMaxWidth +import androidx.compose.foundation.layout.height +import androidx.compose.foundation.layout.padding +import androidx.compose.foundation.layout.statusBarsPadding +import androidx.compose.foundation.layout.width +import androidx.compose.material3.MaterialTheme +import androidx.compose.material3.Text +import androidx.compose.runtime.Composable +import androidx.compose.ui.Alignment +import androidx.compose.ui.Modifier +import androidx.compose.ui.text.font.FontWeight +import androidx.compose.ui.unit.dp +import com.siriusdevops.onionwire.R +import com.siriusdevops.onionwire.ui.OwColors + +/** + * The app's one top bar. + * + * Deliberately not `TopAppBar`: that component is a fixed height single line, and + * this header carries a second row (the `● Tor active` pill). A custom column + * also keeps the status-bar inset inside the bar's own background instead of + * padding the screen underneath it. + * + * On a sub-screen the navigation slot is a chevron icon button, never the word + * "Back". + */ +@Composable +fun OwTopBar( + title: String, + modifier: Modifier = Modifier, + onBack: (() -> Unit)? = null, + status: (@Composable () -> Unit)? = null, + actions: @Composable RowScope.() -> Unit = {}, +) { + Column( + modifier = modifier + .fillMaxWidth() + .background(OwColors.Canvas) + .statusBarsPadding() + .padding(start = 16.dp, end = 16.dp, top = 10.dp, bottom = 10.dp), + ) { + Row(verticalAlignment = Alignment.CenterVertically) { + if (onBack != null) { + OwIconButton( + iconRes = R.drawable.ic_ow_chevron_left, + contentDescription = "Back", + onClick = onBack, + tint = OwColors.TextPrimary, + background = OwColors.SurfaceInteractive, + ) + Spacer(Modifier.width(12.dp)) + } + Text( + title, + style = MaterialTheme.typography.titleLarge, + fontWeight = FontWeight.Bold, + color = OwColors.TextPrimary, + modifier = Modifier.weight(1f), + ) + Row( + horizontalArrangement = Arrangement.spacedBy(8.dp), + verticalAlignment = Alignment.CenterVertically, + content = actions, + ) + } + if (status != null) { + Spacer(Modifier.height(8.dp)) + status() + } + } +} diff --git a/android/app/src/main/java/com/siriusdevops/onionwire/ui/components/BottomTabBar.kt b/android/app/src/main/java/com/siriusdevops/onionwire/ui/components/BottomTabBar.kt new file mode 100644 index 0000000..60444e6 --- /dev/null +++ b/android/app/src/main/java/com/siriusdevops/onionwire/ui/components/BottomTabBar.kt @@ -0,0 +1,125 @@ +package com.siriusdevops.onionwire.ui.components + +import androidx.annotation.DrawableRes +import androidx.compose.foundation.background +import androidx.compose.foundation.clickable +import androidx.compose.foundation.layout.Arrangement +import androidx.compose.foundation.layout.Box +import androidx.compose.foundation.layout.Column +import androidx.compose.foundation.layout.Row +import androidx.compose.foundation.layout.Spacer +import androidx.compose.foundation.layout.fillMaxWidth +import androidx.compose.foundation.layout.height +import androidx.compose.foundation.layout.navigationBarsPadding +import androidx.compose.foundation.layout.padding +import androidx.compose.foundation.layout.size +import androidx.compose.material3.Icon +import androidx.compose.material3.MaterialTheme +import androidx.compose.material3.Text +import androidx.compose.runtime.Composable +import androidx.compose.ui.Alignment +import androidx.compose.ui.Modifier +import androidx.compose.ui.graphics.Color +import androidx.compose.ui.res.painterResource +import androidx.compose.ui.semantics.Role +import androidx.compose.ui.semantics.role +import androidx.compose.ui.semantics.selected +import androidx.compose.ui.semantics.semantics +import androidx.compose.ui.text.font.FontWeight +import androidx.compose.ui.unit.dp +import androidx.compose.ui.unit.sp +import com.siriusdevops.onionwire.R +import com.siriusdevops.onionwire.ui.OwColors +import com.siriusdevops.onionwire.ui.OwSize + +/** + * The three top-level destinations. + * + * Chats is home. The node lives inside Wallet (that is where its card already + * is), so the third tab is the security/settings surface: identity, saved + * wallets, rotation, wipe, and — behind progressive disclosure — the SDK line + * that used to sit under the roster. + */ +enum class OwTab(val label: String, @DrawableRes val icon: Int) { + Chats("Chats", R.drawable.ic_ow_chat), + Wallet("Wallet", R.drawable.ic_ow_wallet), + Settings("Node & Settings", R.drawable.ic_ow_sliders), +} + +/** + * Persistent bottom navigation. + * + * 64dp of canvas with a single 1dp top border — no elevation shadow, no + * translucent scrim. The navigation-bar inset is applied here, so screens inside + * the shell must not also pad for it (see `LocalBottomBarPresent`). + */ +@Composable +fun OwBottomTabBar( + selected: OwTab, + onSelect: (OwTab) -> Unit, + modifier: Modifier = Modifier, +) { + Column( + modifier = modifier + .fillMaxWidth() + .background(OwColors.Canvas), + ) { + OwDivider() + Row( + modifier = Modifier + .fillMaxWidth() + .navigationBarsPadding() + .height(OwSize.TabBar), + horizontalArrangement = Arrangement.SpaceEvenly, + verticalAlignment = Alignment.CenterVertically, + ) { + OwTab.entries.forEach { tab -> + TabItem( + tab = tab, + selected = tab == selected, + onClick = { onSelect(tab) }, + modifier = Modifier.weight(1f), + ) + } + } + } +} + +@Composable +private fun TabItem( + tab: OwTab, + selected: Boolean, + onClick: () -> Unit, + modifier: Modifier = Modifier, +) { + val tint: Color = if (selected) OwColors.Accent else OwColors.TextMuted + Column( + modifier = modifier + .fillMaxWidth() + .clickable(onClick = onClick) + .semantics { + role = Role.Tab + this.selected = selected + } + .padding(vertical = 8.dp), + horizontalAlignment = Alignment.CenterHorizontally, + verticalArrangement = Arrangement.Center, + ) { + Box(contentAlignment = Alignment.Center) { + Icon( + painter = painterResource(tab.icon), + contentDescription = null, + tint = tint, + modifier = Modifier.size(22.dp), + ) + } + Spacer(Modifier.height(4.dp)) + Text( + tab.label, + style = MaterialTheme.typography.labelSmall, + fontSize = 10.sp, + fontWeight = if (selected) FontWeight.SemiBold else FontWeight.Medium, + color = tint, + ) + } +} diff --git a/android/app/src/main/java/com/siriusdevops/onionwire/ui/components/OverflowMenu.kt b/android/app/src/main/java/com/siriusdevops/onionwire/ui/components/OverflowMenu.kt new file mode 100644 index 0000000..f467049 --- /dev/null +++ b/android/app/src/main/java/com/siriusdevops/onionwire/ui/components/OverflowMenu.kt @@ -0,0 +1,69 @@ +package com.siriusdevops.onionwire.ui.components + +import androidx.compose.foundation.layout.Box +import androidx.compose.material3.DropdownMenu +import androidx.compose.material3.DropdownMenuItem +import androidx.compose.material3.Text +import androidx.compose.runtime.Composable +import androidx.compose.runtime.getValue +import androidx.compose.runtime.mutableStateOf +import androidx.compose.runtime.remember +import androidx.compose.runtime.setValue +import androidx.compose.ui.Modifier +import androidx.compose.ui.unit.dp +import com.siriusdevops.onionwire.R +import com.siriusdevops.onionwire.ui.OwColors +import com.siriusdevops.onionwire.ui.OwRadius + +/** + * The `⋮` overflow on the messenger and settings bars. + * + * Serious and rare actions live here instead of on the home screen: rotating the + * identity cuts every offline friend off the current locator, and deleting the + * message history is irreversible. Neither belongs next to "Invite". + * + * The menu is a component rather than inline code so the destructive verbs have + * exactly one home — a new screen that wants the overflow gets the same list, + * not a second copy with different wording. + */ +@Composable +fun OwOverflowMenu( + onOpenProfile: () -> Unit, + onOpenWallets: () -> Unit, + onRotate: () -> Unit, + onWipe: () -> Unit, + modifier: Modifier = Modifier, +) { + var open by remember { mutableStateOf(false) } + + Box(modifier) { + OwIconButton( + iconRes = R.drawable.ic_ow_more_vert, + contentDescription = "More actions", + onClick = { open = true }, + ) + DropdownMenu( + expanded = open, + onDismissRequest = { open = false }, + containerColor = OwColors.SurfaceInteractive, + shape = androidx.compose.foundation.shape.RoundedCornerShape(OwRadius.Control), + ) { + DropdownMenuItem( + text = { Text("Your profile", color = OwColors.TextPrimary) }, + onClick = { open = false; onOpenProfile() }, + ) + DropdownMenuItem( + text = { Text("Saved wallets", color = OwColors.TextPrimary) }, + onClick = { open = false; onOpenWallets() }, + ) + DropdownMenuItem( + text = { Text("Rotate identity", color = OwColors.TextPrimary) }, + onClick = { open = false; onRotate() }, + ) + DropdownMenuItem( + text = { Text("Delete message history", color = OwColors.Danger) }, + onClick = { open = false; onWipe() }, + ) + } + } +} diff --git a/android/app/src/test/java/com/siriusdevops/onionwire/ui/RosterOnionTest.kt b/android/app/src/test/java/com/siriusdevops/onionwire/ui/RosterOnionTest.kt new file mode 100644 index 0000000..0fa45bf --- /dev/null +++ b/android/app/src/test/java/com/siriusdevops/onionwire/ui/RosterOnionTest.kt @@ -0,0 +1,45 @@ +package com.siriusdevops.onionwire.ui + +import org.junit.Assert.assertEquals +import org.junit.Test + +/** + * `shortOnion`, the roster's locator abbreviation, on the JVM. + * + * A v3 onion locator must never be soft-wrapped or reduced to a middle slice + * that hides `.onion`: the suffix is what tells a reader this is an onion + * address at all, and the full value is available on the profile and invite + * screens. Pure logic, no Robolectric — same shape as `RosterIdTest`. + */ +class RosterOnionTest { + + private val v3 = + "abcdefghijklmnopqrstuvwxyz234567abcdefghijklmnopqrstuvwxyz234567.onion" + + @Test + fun a_v3_locator_keeps_its_suffix() { + val short = shortOnion(v3) + assertEquals(true, short.endsWith(".onion")) + assertEquals(v3.take(10), short.substringBefore("\u2026")) + assertEquals(v3.removeSuffix(".onion").takeLast(6), short.removeSuffix(".onion").substringAfter("\u2026")) + } + + @Test + fun the_suffix_is_never_the_part_that_is_cut() { + // Even with an aggressive abbreviation the reader still sees `….onion`. + val body = v3.removeSuffix(".onion") + val short = shortOnion(v3, head = 3, tail = 2) + assertEquals(body.take(3) + "\u2026" + body.takeLast(2) + ".onion", short) + } + + @Test + fun a_short_value_is_returned_unchanged() { + assertEquals("abc.onion", shortOnion("abc.onion")) + assertEquals("", shortOnion("")) + } + + @Test + fun a_value_with_no_suffix_is_not_mangled() { + assertEquals("not-an-onion", shortOnion("not-an-onion")) + } +} From b65c9900144cb4ede3afe261b05743f7797ac136 Mon Sep 17 00:00:00 2001 From: agent Date: Thu, 29 Oct 2026 00:05:17 -0400 Subject: [PATCH 05/19] ui: cap the invite payload card and shorten the settings tab label Two things the emulator run surfaced: - The invite payload is about a kilobyte, so the plain Text card grew past the screen and pushed Copy invite / Done below the fold on a phone. Four lines with an ellipsis: the copy button carries the whole string, and the QR is the primary path anyway. - "Node & Settings" as a 10sp label in a third of the bottom bar is one OEM font scale away from wrapping. The tab says "Settings"; the destination screen keeps its "Node & Settings" title. --- .../java/com/siriusdevops/onionwire/ui/InviteScreens.kt | 8 ++++++++ .../siriusdevops/onionwire/ui/components/BottomTabBar.kt | 4 +++- 2 files changed, 11 insertions(+), 1 deletion(-) diff --git a/android/app/src/main/java/com/siriusdevops/onionwire/ui/InviteScreens.kt b/android/app/src/main/java/com/siriusdevops/onionwire/ui/InviteScreens.kt index 599e6a4..a519bb7 100644 --- a/android/app/src/main/java/com/siriusdevops/onionwire/ui/InviteScreens.kt +++ b/android/app/src/main/java/com/siriusdevops/onionwire/ui/InviteScreens.kt @@ -33,6 +33,7 @@ import androidx.compose.ui.Modifier import androidx.compose.ui.platform.ClipEntry import androidx.compose.ui.platform.LocalClipboard import androidx.compose.ui.text.style.TextAlign +import androidx.compose.ui.text.style.TextOverflow import androidx.compose.ui.unit.dp import com.siriusdevops.onionwire.R import com.siriusdevops.onionwire.ui.components.Label @@ -114,11 +115,18 @@ fun ShareInviteScreen(ownerInvite: suspend () -> String, onBack: () -> Unit) { OwQrCode(payload = payload, size = 220.dp) } Spacer(Modifier.height(16.dp)) + // Four lines, ellipsised: the payload is ~1 KB, and a card + // that grows to fill the screen pushes Copy and Done out of + // reach — the copyable text is a fallback for the QR, not + // the main event. `Copy invite` always carries the whole + // string. OwCard(Modifier.fillMaxWidth(), padding = 12.dp) { Text( payload, style = MonoStyle.copy(color = OwColors.TextSecondary), textAlign = TextAlign.Start, + maxLines = 4, + overflow = TextOverflow.Ellipsis, ) } Spacer(Modifier.height(12.dp)) diff --git a/android/app/src/main/java/com/siriusdevops/onionwire/ui/components/BottomTabBar.kt b/android/app/src/main/java/com/siriusdevops/onionwire/ui/components/BottomTabBar.kt index 60444e6..61ebdfd 100644 --- a/android/app/src/main/java/com/siriusdevops/onionwire/ui/components/BottomTabBar.kt +++ b/android/app/src/main/java/com/siriusdevops/onionwire/ui/components/BottomTabBar.kt @@ -43,7 +43,9 @@ import com.siriusdevops.onionwire.ui.OwSize enum class OwTab(val label: String, @DrawableRes val icon: Int) { Chats("Chats", R.drawable.ic_ow_chat), Wallet("Wallet", R.drawable.ic_ow_wallet), - Settings("Node & Settings", R.drawable.ic_ow_sliders), + // Tab labels stay short: the destination is Node & Settings (that is the + // screen title), but a 10sp label in a third of the bar has no room for it. + Settings("Settings", R.drawable.ic_ow_sliders), } /** From a7b7792b3faf56dda0700385494a63d97f9c310d Mon Sep 17 00:00:00 2001 From: agent Date: Thu, 29 Oct 2026 00:06:07 -0400 Subject: [PATCH 06/19] ui: About rows, and drop the removed copy from the roster's own KDoc MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The SDK/key-type footnote moved to Node and Settings, so it should not survive as a quoted string in ui/ either — the About card now shows IDENTITY ed25519 and SDK as label plus mono value, which is the design system's idiom for a machine fact. Same reasoning for the KDoc: it describes the change instead of pasting the strings that were removed. --- .../siriusdevops/onionwire/ui/RosterScreen.kt | 16 ++++++++-------- .../siriusdevops/onionwire/ui/SettingsScreen.kt | 14 +++++++------- 2 files changed, 15 insertions(+), 15 deletions(-) diff --git a/android/app/src/main/java/com/siriusdevops/onionwire/ui/RosterScreen.kt b/android/app/src/main/java/com/siriusdevops/onionwire/ui/RosterScreen.kt index 226995a..d50b69f 100644 --- a/android/app/src/main/java/com/siriusdevops/onionwire/ui/RosterScreen.kt +++ b/android/app/src/main/java/com/siriusdevops/onionwire/ui/RosterScreen.kt @@ -64,18 +64,18 @@ import uniffi.onionwire_sdk.FriendInfo * * Three things changed from the alpha build and they are deliberate: * - * - The identity block is one compact bar. The `YOU (stable forever)` card, the - * `sdk … · identity = ed25519 pubkey` line and the keep-alive paragraph are - * gone from here — the SDK line is on Node & Settings, and the keep-alive - * state is a status row there too. A home screen does not explain the - * transport before it shows the people. + * - The identity block is one compact bar. The old expandable card, the version + * and key-type footnote and the keep-alive paragraph are gone from here: the + * technical lines moved to Node & Settings, and reachability is a status row + * there too. A home screen does not explain the transport before it shows the + * people. * - The five text-link actions are gone. Invite and Add are the two first-class * actions (in the empty state, and in the bar); the rare and destructive ones - * live behind `⋮`. + * live behind the overflow menu. * - The empty state says what to do next, with the two buttons that do it. * - * Behaviour is unchanged: `invite`, `onPaste`, `onOpenChat`, `onRotate`, - * `onWipe` and `onLock` are the same ViewModel calls the old screen made. + * Behaviour is unchanged: every callback here is the ViewModel call the old + * screen made — this screen only decides where the entry points sit. */ @Composable fun RosterScreen( diff --git a/android/app/src/main/java/com/siriusdevops/onionwire/ui/SettingsScreen.kt b/android/app/src/main/java/com/siriusdevops/onionwire/ui/SettingsScreen.kt index a9ec625..c5e5c68 100644 --- a/android/app/src/main/java/com/siriusdevops/onionwire/ui/SettingsScreen.kt +++ b/android/app/src/main/java/com/siriusdevops/onionwire/ui/SettingsScreen.kt @@ -135,16 +135,16 @@ fun SettingsScreen( OwCard(Modifier.fillMaxWidth()) { OwSectionTitle("About") - Spacer(Modifier.height(6.dp)) - Text( - "identity = ed25519 pubkey", - style = MaterialTheme.typography.bodySmall, - color = OwColors.TextSecondary, - ) + Spacer(Modifier.height(8.dp)) + Row(verticalAlignment = Alignment.CenterVertically) { + Label("IDENTITY") + Spacer(Modifier.width(10.dp)) + Mono("ed25519") + } Spacer(Modifier.height(4.dp)) Row(verticalAlignment = Alignment.CenterVertically) { Label("SDK") - Spacer(Modifier.width(8.dp)) + Spacer(Modifier.width(10.dp)) Mono(sdkVersion) } Spacer(Modifier.height(10.dp)) From 7d86fd6a0336d27006c0adec52afd9e3af95596f Mon Sep 17 00:00:00 2001 From: apk-dev Date: Thu, 29 Oct 2026 00:15:47 -0400 Subject: [PATCH 07/19] ui: drop the stale key-type phrase and pin the DrawableRes param target Two nits the plan's own greps would have flagged: - `ChatScreen`'s `peer` KDoc still spelled out the key type. It is an internal comment, but the acceptance grep for the removed identity copy (`ed25519 pubkey`) should come back empty across `ui/`, not empty-except- a-comment. - `OwTab`'s `@DrawableRes` is now `@param:`-targeted, which silences Kotlin's KT-73255 warning about the annotation moving to the backing field. --- .../src/main/java/com/siriusdevops/onionwire/ui/ChatScreen.kt | 2 +- .../com/siriusdevops/onionwire/ui/components/BottomTabBar.kt | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/android/app/src/main/java/com/siriusdevops/onionwire/ui/ChatScreen.kt b/android/app/src/main/java/com/siriusdevops/onionwire/ui/ChatScreen.kt index 84ccd0b..c4f2487 100644 --- a/android/app/src/main/java/com/siriusdevops/onionwire/ui/ChatScreen.kt +++ b/android/app/src/main/java/com/siriusdevops/onionwire/ui/ChatScreen.kt @@ -61,7 +61,7 @@ import uniffi.onionwire_sdk.SendState @Composable fun ChatScreen( vm: WireViewModel, - /** The peer's ed25519 pubkey hex — the key the open chat's poller runs for. */ + /** The peer's public key, hex — the key the open chat's poller runs for. */ peer: String, title: String, fingerprint: String, diff --git a/android/app/src/main/java/com/siriusdevops/onionwire/ui/components/BottomTabBar.kt b/android/app/src/main/java/com/siriusdevops/onionwire/ui/components/BottomTabBar.kt index 61ebdfd..f0127a0 100644 --- a/android/app/src/main/java/com/siriusdevops/onionwire/ui/components/BottomTabBar.kt +++ b/android/app/src/main/java/com/siriusdevops/onionwire/ui/components/BottomTabBar.kt @@ -40,7 +40,7 @@ import com.siriusdevops.onionwire.ui.OwSize * wallets, rotation, wipe, and — behind progressive disclosure — the SDK line * that used to sit under the roster. */ -enum class OwTab(val label: String, @DrawableRes val icon: Int) { +enum class OwTab(val label: String, @param:DrawableRes val icon: Int) { Chats("Chats", R.drawable.ic_ow_chat), Wallet("Wallet", R.drawable.ic_ow_wallet), // Tab labels stay short: the destination is Node & Settings (that is the From 5a4701992e620243d6dc5d88df979bfcd84aab78 Mon Sep 17 00:00:00 2001 From: apk-dev Date: Thu, 29 Oct 2026 00:22:16 -0400 Subject: [PATCH 08/19] ui: mute the empty-state shield and set its heading to the plan's 18sp The plan asks for a *muted* mint/grey icon inside the subtle surface circle and an 18px/600 heading. The first pass drew the shield in full accent at 16sp SemiBold, which made the empty state read as a warning and competed with the primary CTA under it. The accent now stays on the button only. --- .../java/com/siriusdevops/onionwire/ui/RosterScreen.kt | 7 +++++-- 1 file changed, 5 insertions(+), 2 deletions(-) diff --git a/android/app/src/main/java/com/siriusdevops/onionwire/ui/RosterScreen.kt b/android/app/src/main/java/com/siriusdevops/onionwire/ui/RosterScreen.kt index d50b69f..edfae7a 100644 --- a/android/app/src/main/java/com/siriusdevops/onionwire/ui/RosterScreen.kt +++ b/android/app/src/main/java/com/siriusdevops/onionwire/ui/RosterScreen.kt @@ -40,6 +40,7 @@ import androidx.compose.ui.platform.LocalClipboard import androidx.compose.ui.platform.LocalContext import androidx.compose.ui.text.style.TextAlign import androidx.compose.ui.unit.dp +import androidx.compose.ui.unit.sp import com.siriusdevops.onionwire.R import com.siriusdevops.onionwire.ui.components.Identicon import com.siriusdevops.onionwire.ui.components.Label @@ -240,17 +241,19 @@ private fun EmptyRoster( .background(OwColors.Surface), contentAlignment = Alignment.Center, ) { + // Muted on purpose: the empty state is an invitation, not an alarm. + // The accent stays reserved for the one primary action below it. OwIcon( iconRes = R.drawable.ic_ow_shield, contentDescription = null, - tint = OwColors.Accent, + tint = OwColors.TextSecondary, size = 30.dp, ) } Spacer(Modifier.height(16.dp)) Text( "No contacts yet", - style = MaterialTheme.typography.titleMedium, + style = MaterialTheme.typography.titleMedium.copy(fontSize = 18.sp, lineHeight = 24.sp), color = OwColors.TextPrimary, ) Spacer(Modifier.height(8.dp)) From dc45d9cb815413ad0fbc999065af1cd9cb06fdac Mon Sep 17 00:00:00 2001 From: apk-dev Date: Thu, 29 Oct 2026 00:44:22 -0400 Subject: [PATCH 09/19] ui: route the last raw buttons through OwButton, with a content slot MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Chat's send, Profile's save, and both Rotate actions were still material Buttons — the 50%-rounded pill the design pass exists to remove. They now take the design-system shape and height. OwButton gains an optional RowScope content slot so a caller that needs a spinner beside its label (chat send while a message is pending) keeps that behaviour without dropping back to a raw Button. The slot is additive: the existing text/leading-icon path is unchanged for every other caller. Rotate's confirm is the Destructive tier — it destroys the current onion — and the post-rotation action is labelled "Share the new invite" instead of "Back — share the new invite": the top bar already owns the chevron back. --- .../siriusdevops/onionwire/ui/ChatScreen.kt | 5 ++- .../onionwire/ui/ProfileScreen.kt | 11 +++--- .../siriusdevops/onionwire/ui/RotateScreen.kt | 15 ++++++-- .../onionwire/ui/components/Buttons.kt | 37 ++++++++++++------- 4 files changed, 42 insertions(+), 26 deletions(-) diff --git a/android/app/src/main/java/com/siriusdevops/onionwire/ui/ChatScreen.kt b/android/app/src/main/java/com/siriusdevops/onionwire/ui/ChatScreen.kt index c4f2487..a5369b4 100644 --- a/android/app/src/main/java/com/siriusdevops/onionwire/ui/ChatScreen.kt +++ b/android/app/src/main/java/com/siriusdevops/onionwire/ui/ChatScreen.kt @@ -22,7 +22,6 @@ import androidx.compose.foundation.shape.RoundedCornerShape import androidx.compose.foundation.text.KeyboardActions import androidx.compose.foundation.text.KeyboardOptions import androidx.compose.foundation.verticalScroll -import androidx.compose.material3.Button import androidx.compose.material3.CircularProgressIndicator import androidx.compose.material3.ExperimentalMaterial3Api import androidx.compose.material3.IconButton @@ -52,6 +51,7 @@ import androidx.compose.ui.text.input.ImeAction import androidx.compose.ui.text.input.KeyboardCapitalization import androidx.compose.ui.unit.dp import com.siriusdevops.onionwire.R +import com.siriusdevops.onionwire.ui.components.OwButton import com.siriusdevops.onionwire.ui.components.OwIconButton import androidx.lifecycle.compose.collectAsStateWithLifecycle import com.siriusdevops.onionwire.WireViewModel @@ -388,7 +388,8 @@ fun ChatScreen( // Always drawn, never swapped out for a spinner: a button that // changes size under the thumb — or disappears — is how "I hit // send and nothing happened" gets reported. - Button( + OwButton( + text = "Send", enabled = draft.isNotBlank() && pending == null, onClick = send, modifier = Modifier.testTag("chat-send"), diff --git a/android/app/src/main/java/com/siriusdevops/onionwire/ui/ProfileScreen.kt b/android/app/src/main/java/com/siriusdevops/onionwire/ui/ProfileScreen.kt index 030f730..a0e3243 100644 --- a/android/app/src/main/java/com/siriusdevops/onionwire/ui/ProfileScreen.kt +++ b/android/app/src/main/java/com/siriusdevops/onionwire/ui/ProfileScreen.kt @@ -11,7 +11,6 @@ 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 @@ -34,6 +33,7 @@ import androidx.compose.ui.platform.testTag import androidx.compose.ui.text.font.FontFamily import androidx.compose.ui.unit.dp import com.siriusdevops.onionwire.R +import com.siriusdevops.onionwire.ui.components.OwButton import com.siriusdevops.onionwire.ui.components.OwIconButton import androidx.lifecycle.compose.collectAsStateWithLifecycle import com.siriusdevops.onionwire.WireViewModel @@ -240,7 +240,8 @@ fun ProfileScreen( .padding(12.dp), horizontalArrangement = Arrangement.End, ) { - Button( + OwButton( + text = if (busy) "Saving…" else "Save", onClick = { addressError = null saveError = null @@ -253,7 +254,7 @@ fun ProfileScreen( } if (problem != null) { addressError = problem - return@Button + return@OwButton } scope.launch { busy = true @@ -300,9 +301,7 @@ fun ProfileScreen( }, enabled = !busy && profileSaveEnabled(loaded, form), modifier = Modifier.testTag("profile-save"), - ) { - Text(if (busy) "Saving…" else "Save") - } + ) } status?.let { diff --git a/android/app/src/main/java/com/siriusdevops/onionwire/ui/RotateScreen.kt b/android/app/src/main/java/com/siriusdevops/onionwire/ui/RotateScreen.kt index 89f351e..b84dd11 100644 --- a/android/app/src/main/java/com/siriusdevops/onionwire/ui/RotateScreen.kt +++ b/android/app/src/main/java/com/siriusdevops/onionwire/ui/RotateScreen.kt @@ -11,7 +11,6 @@ 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.CircularProgressIndicator import androidx.compose.material3.ExperimentalMaterial3Api import androidx.compose.material3.IconButton @@ -32,6 +31,8 @@ import androidx.compose.ui.unit.dp import com.siriusdevops.onionwire.R import com.siriusdevops.onionwire.ui.components.Label import com.siriusdevops.onionwire.ui.components.Mono +import com.siriusdevops.onionwire.ui.components.OwButton +import com.siriusdevops.onionwire.ui.components.OwButtonVariant import com.siriusdevops.onionwire.ui.components.OwIconButton /** @@ -109,11 +110,13 @@ fun RotateScreen( ) Spacer(Modifier.height(12.dp)) Row(horizontalArrangement = Arrangement.spacedBy(8.dp)) { - Button( + OwButton( + text = "Rotate", + variant = OwButtonVariant.Destructive, enabled = typed.trim().equals("ROTATE", ignoreCase = true) && !busy, onClick = { busy = true; error = null }, - ) { Text("Rotate") } + ) if (busy) CircularProgressIndicator() } } @@ -151,7 +154,11 @@ fun RotateScreen( color = MaterialTheme.colorScheme.onSurfaceVariant, ) Spacer(Modifier.height(16.dp)) - Button(onClick = onBack) { Text("Back — share the new invite") } + OwButton( + text = "Share the new invite", + variant = OwButtonVariant.Secondary, + onClick = onBack, + ) } } } diff --git a/android/app/src/main/java/com/siriusdevops/onionwire/ui/components/Buttons.kt b/android/app/src/main/java/com/siriusdevops/onionwire/ui/components/Buttons.kt index 5c9832f..7ff42b6 100644 --- a/android/app/src/main/java/com/siriusdevops/onionwire/ui/components/Buttons.kt +++ b/android/app/src/main/java/com/siriusdevops/onionwire/ui/components/Buttons.kt @@ -58,6 +58,7 @@ fun OwButton( variant: OwButtonVariant = OwButtonVariant.Primary, enabled: Boolean = true, leadingIconRes: Int? = null, + content: (@Composable androidx.compose.foundation.layout.RowScope.() -> Unit)? = null, ) { val height = when (variant) { OwButtonVariant.Outline -> OwSize.ButtonCompact @@ -69,13 +70,17 @@ fun OwButton( OwButtonVariant.Outline -> Color.Transparent OwButtonVariant.Destructive -> OwColors.DangerTint } - val content = when (variant) { + val contentColor = when (variant) { OwButtonVariant.Primary -> OwColors.Canvas OwButtonVariant.Secondary -> OwColors.TextPrimary OwButtonVariant.Outline -> OwColors.TextPrimary OwButtonVariant.Destructive -> OwColors.Danger } val weight = if (variant == OwButtonVariant.Primary) FontWeight.SemiBold else FontWeight.Medium + // A local val, not the parameter: a parameter captured by the Button's + // content lambda cannot be smart-cast, and the nullable-call error reads as + // a Compose problem when it is only a Kotlin capture rule. + val customContent = content Button( onClick = onClick, @@ -89,7 +94,7 @@ fun OwButton( }, colors = ButtonDefaults.buttonColors( containerColor = container, - contentColor = content, + contentColor = contentColor, disabledContainerColor = when (variant) { OwButtonVariant.Outline -> Color.Transparent OwButtonVariant.Primary -> OwColors.SurfaceInteractive @@ -101,19 +106,23 @@ fun OwButton( elevation = ButtonDefaults.buttonElevation(defaultElevation = 0.dp, pressedElevation = 0.dp), contentPadding = ButtonDefaults.ContentPadding, ) { - Row( - verticalAlignment = Alignment.CenterVertically, - horizontalArrangement = Arrangement.Center, - ) { - if (leadingIconRes != null) { - Icon( - painter = painterResource(leadingIconRes), - contentDescription = null, - modifier = Modifier.size(18.dp), - ) - Spacer(Modifier.width(8.dp)) + if (customContent != null) { + customContent() + } else { + Row( + verticalAlignment = Alignment.CenterVertically, + horizontalArrangement = Arrangement.Center, + ) { + if (leadingIconRes != null) { + Icon( + painter = painterResource(leadingIconRes), + contentDescription = null, + modifier = Modifier.size(18.dp), + ) + Spacer(Modifier.width(8.dp)) + } + Text(text, style = MaterialTheme.typography.labelLarge, fontWeight = weight) } - Text(text, style = MaterialTheme.typography.labelLarge, fontWeight = weight) } } } From 1d7cbd8503dc3164798fe60f81a93212f3868e42 Mon Sep 17 00:00:00 2001 From: agent Date: Thu, 29 Oct 2026 01:01:39 -0400 Subject: [PATCH 10/19] ui: hero wallet card and node card, and the status copy behind them (plan P4) The wallet tab was nine equal boxes: a balance card, a daemon card, and then four outlined twins (Invoice/Tip, Create/Import) pushed below the fold under a wall of grey helper text. This rebuilds it as two cards. Hero card. While no wallet file is open the card says "No Wallet Active" with the plan's subtitle and puts Create Wallet (primary) / Import Wallet (secondary) first, with Saved wallets in the card header. Once a wallet is open the balance is the headline at 28sp bold with a sync-state pill, then the gated receive address and its QR, then Receive / Invoice and Send / Tip, and a destructive Lock Wallet. Creating and importing a further wallet stay reachable in both states, and so does invoicing in the no-wallet state: the core resolves a payee address from the profile, so hiding the action there would drop a path that works ("no receive address - set profile xmr or ONIONWIRE_WALLET_RPC" is the both-missing case). A tip really does need the wallet, so it appears only when one is open. Node card. The raw "connecting . in-process mainnet pruned . node starting . sync 485253/3794383" line is replaced by a status sentence, a percentage, a 6dp progress track and "Block 485,253 of 3,794,383" with the free disk on the right; the full line is still the header's contentDescription, so a screen reader loses nothing. The three stacked mode buttons become one segmented control, Remote vs On-Device is a second one, and the lifecycle is a single context-aware control (Start Node and Wallet, or Stop Node while it runs) instead of a permanently disabled twin. Every raw paragraph (no binary, no wallet open, start blocked, core error) is now an AlertBanner. Fail-closed rules are unchanged and now tested: target_height == 0 prints no percentage (it is "no target reported", never "caught up", which is what Cuprate reports at the tip), a height past the target clamps at 100.0%, and an unrecognised state is never green. The wallet off / err sentinels still come back from the core untouched; only their display changed, to "No Wallet Loaded" and "Balance unavailable". Deliberate, and named in the handoff: WalletScreen drops its onBack parameter because Wallet is a top-level tab now (MainActivity updated; Chats and Settings already have no back affordance), and OwSegmentedControl gains an optional testTags list - additive, defaulting to empty, so no existing call site changes. --- .../siriusdevops/onionwire/MainActivity.kt | 4 +- .../onionwire/ui/WalletChildStatusText.kt | 169 +- .../siriusdevops/onionwire/ui/WalletScreen.kt | 1590 +++++++++-------- .../ui/components/SegmentedControl.kt | 11 + .../onionwire/ui/WalletChildStatusTextTest.kt | 124 +- 5 files changed, 1164 insertions(+), 734 deletions(-) diff --git a/android/app/src/main/java/com/siriusdevops/onionwire/MainActivity.kt b/android/app/src/main/java/com/siriusdevops/onionwire/MainActivity.kt index 772f733..84d98a4 100644 --- a/android/app/src/main/java/com/siriusdevops/onionwire/MainActivity.kt +++ b/android/app/src/main/java/com/siriusdevops/onionwire/MainActivity.kt @@ -192,9 +192,11 @@ private fun ReadyGraph(vm: WireViewModel, ready: Phase.Ready, keepAliveNote: Str } composable(Routes.Wallet) { + // A top-level tab, so no back chevron — same shape as the + // Chats and Node & Settings destinations. The catalogue + // sub-screen still gets one from its own top bar. WalletScreen( vm = vm, - onBack = { nav.popBackStack() }, onOpenWallets = { nav.navigate(Routes.Wallets) }, ) } diff --git a/android/app/src/main/java/com/siriusdevops/onionwire/ui/WalletChildStatusText.kt b/android/app/src/main/java/com/siriusdevops/onionwire/ui/WalletChildStatusText.kt index f9804fd..5bae4d1 100644 --- a/android/app/src/main/java/com/siriusdevops/onionwire/ui/WalletChildStatusText.kt +++ b/android/app/src/main/java/com/siriusdevops/onionwire/ui/WalletChildStatusText.kt @@ -5,7 +5,7 @@ import com.siriusdevops.onionwire.wallet.WalletChildBinaryPaths import java.util.Locale /** - * One snapshot of the app-owned wallet child, as the wallet screen sees it. + * One snapshot of the app-owned wallet process, as the wallet screen sees it. * * A plain mirror of the fields `WalletChildStatus` carries over UniFFI * (`state`, `running`, `configured`, `chain_source`, `last_error`) — the same @@ -97,7 +97,7 @@ sealed interface WalletChildPhase { data object Unread : WalletChildPhase { override val testTag: String = "child-unread" override val label: String = "reading…" - override val contentDescription: String = "Reading the wallet child status" + override val contentDescription: String = "Reading the wallet status" override val live: Boolean = false override val dead: Boolean = false } @@ -106,7 +106,7 @@ sealed interface WalletChildPhase { data object Off : WalletChildPhase { override val testTag: String = "child-off" override val label: String = "off" - override val contentDescription: String = "The wallet child is off" + override val contentDescription: String = "The wallet is off" override val live: Boolean = false override val dead: Boolean = false } @@ -116,7 +116,7 @@ sealed interface WalletChildPhase { override val testTag: String = "child-connecting" override val label: String = "connecting" override val contentDescription: String = - "The wallet child is up; its wallet RPC has not answered yet" + "The wallet is starting; its RPC has not answered yet" override val live: Boolean = true override val dead: Boolean = false } @@ -135,7 +135,7 @@ sealed interface WalletChildPhase { data object Ready : WalletChildPhase { override val testTag: String = "child-ready" override val label: String = "ready" - override val contentDescription: String = "The wallet child is ready" + override val contentDescription: String = "The wallet is ready" override val live: Boolean = true override val dead: Boolean = false } @@ -144,7 +144,7 @@ sealed interface WalletChildPhase { data class Exited(val reason: String?) : WalletChildPhase { override val testTag: String = "child-exited" override val label: String = "exited" - override val contentDescription: String = "The wallet child exited" + override val contentDescription: String = "The wallet process exited" override val live: Boolean = false override val dead: Boolean = true } @@ -158,7 +158,7 @@ sealed interface WalletChildPhase { override val testTag: String = "child-unrecognised" override val label: String = "unknown (${shortSendReason(raw, UNRECOGNISED_BUDGET)})" override val contentDescription: String = - "The wallet child reported a state this build does not know" + "The wallet reported a state this build does not know" override val live: Boolean = false override val dead: Boolean = false } @@ -336,25 +336,26 @@ const val ONION_NEEDS_ARTI_NOTICE: String = "A .onion daemon needs the arti SOCKS child, which this build does not bundle." /** Shown while the first `wallet_status()` read is still in flight. */ -const val READING_CHILD_NOTICE: String = "Reading the wallet child status…" +const val READING_CHILD_NOTICE: String = "Reading the wallet status…" const val STARTING_CHILD_NOTICE: String = "Start is running. Status stays off until the on-device node answers — that can take a minute, and is not a dead button." /** - * The caveat the on-device node is offered with, **before** Start. + * The alert banner the on-device node is offered with, **before** Start. * * Cuprate's own user book says *"do NOT use cuprated for any serious purposes"*, * its `monerod` RPC parity is incomplete (Cuprate issue #278, and the four gaps - * measured in this repo are in `docs/cuprate-launch-spike.md`), and the daemon - * this app launches is pinned to **testnet** (`src/cuprate.rs`). One sentence, not - * a glyph: the choice is opt-in and never a default, and a user who reads only - * this line still knows what they picked. + * measured in this repo are in `docs/cuprate-launch-spike.md`), and mainnet is + * unvalidated. The title is the banner's; the two sentences are the body — one + * copy of the caveat, never a second one elsewhere on the screen, so the two + * can never drift apart. */ -const val CUPRATE_PREPRODUCTION_WARNING: String = - "On-device node is Cuprate, which is pre-production: its own user book says do NOT use " + - "cuprated for any serious purposes, mainnet is unvalidated, and its monerod RPC parity " + - "is incomplete (Cuprate issue #278). Try the in-process path; do not hold funds on it." +const val CUPRATE_ON_DEVICE_TITLE: String = "Experimental On-Device Node (Cuprate)" +const val CUPRATE_ON_DEVICE_BODY: String = + "Pre-production software with incomplete RPC parity (#278). Do not use for significant " + + "funds. Mainnet is unvalidated, and Cuprate's own user book says do NOT use cuprated " + + "for any serious purposes." /** * This build was compiled without the `cuprate-daemon` feature, so the stored @@ -463,6 +464,131 @@ fun formatBytes(bytes: Long): String = when { else -> "$bytes B" } +/** + * A block height with thousands separators: `3794383` → `3,794,383`. + * + * Hand-grouped rather than `String.format("%,d")` on purpose: the grouped + * format is locale-dependent (some locales use a period or a non-breaking + * space), and a block height is a number in a monospace column, not prose. The + * screen and its test must print the same string everywhere. + */ +fun formatBlockCount(blocks: ULong): String { + val digits = blocks.toString() + val out = StringBuilder(digits.length + digits.length / 3) + digits.forEachIndexed { i, c -> + if (i > 0 && (digits.length - i) % 3 == 0) out.append(',') + out.append(c) + } + return out.toString() +} + +/** + * What the node card's progress header renders for one height / target pair. + * + * [percentText] and [blockText] are null when there is nothing honest to say — + * and `target == 0` is exactly that: the daemon reporting **no target** is not + * evidence of being caught up (`src/wallet.rs` returns `0` for a height it does + * not have, and Cuprate omits the target even at the tip). A percentage invented + * from a zero target would read as progress; an unknown target is said in words. + */ +data class SyncProgress( + /** 0f..1f of the track to fill. `0f` whenever the target is unknown. */ + val fraction: Float, + /** `12.8%`, or null when the daemon reported no target. */ + val percentText: String?, + /** `Block 485,253 of 3,794,383`, or null when neither number is known. */ + val blockText: String?, +) + +fun syncProgress(height: ULong, target: ULong): SyncProgress { + if (height == 0uL && target == 0uL) return SyncProgress(0f, null, null) + if (target == 0uL) { + return SyncProgress( + fraction = 0f, + percentText = null, + blockText = "Block ${formatBlockCount(height)} of an unknown target", + ) + } + val fraction = (height.toDouble() / target.toDouble()).coerceIn(0.0, 1.0) + return SyncProgress( + fraction = fraction.toFloat(), + percentText = String.format(Locale.US, "%.1f%%", fraction * 100.0), + blockText = "Block ${formatBlockCount(height)} of ${formatBlockCount(target)}", + ) +} + +/** + * The balance line, with the core's two sentinels translated into words. + * + * `walletBalance()` does not throw: it answers `off` (no chain source is + * configured at all) or `err` (configured, but the read failed — no wallet file + * open, or the process is down) and a formatted amount otherwise. Printing + * either sentinel raw is what put the string `wallet off` on the wallet screen; + * printing the same word for both is worse, because they are fixed in different + * places. The sentinels themselves are the core's contract and are not touched + * here — this is the display only. + */ +fun noWalletBalanceHeadline(balance: String?): String = when (balance) { + null -> "…" + "off" -> "No Wallet Loaded" + "err" -> "Balance unavailable" + else -> balance +} + +/** `Mainnet Pruned` / `Mainnet Full` / `Testnet` — the three stored modes, as words. */ +fun chainModeLabel(mainnet: Boolean, prune: Boolean): String = when { + !mainnet -> "Testnet" + prune -> "Mainnet Pruned" + else -> "Mainnet Full" +} + +/** + * How the node card's header reads. [tone] is the status dot's colour class, not + * a decoration: it is the caller's statement about the core's own word. + */ +enum class NodeStatusTone { + /** Nothing is running, and nothing is wrong. */ + Idle, + + /** Up, or on its way up. */ + Busy, + + /** Answered and at the tip. */ + Good, + + /** A state the app cannot read, or a process that is gone. */ + Bad, +} + +data class NodeStatusHead(val title: String, val tone: NodeStatusTone) + +/** + * The header sentence for the node card, from the core's `state` alone. + * + * Fail-closed exactly as [walletChildPhase] is: an unrecognised state gets + * [NodeStatusTone.Bad] and never reads as ready. A running child that has not + * answered is `Connecting…`, not `Ready` — the RPC has not spoken yet. + */ +fun nodeStatusHead( + input: WalletChildInput?, + inProcess: Boolean = false, + mainnet: Boolean = false, + prune: Boolean = false, +): NodeStatusHead { + val mode = if (inProcess) " (${chainModeLabel(mainnet, prune)})" else "" + return when (walletChildPhase(input)) { + WalletChildPhase.Unread -> NodeStatusHead("Reading wallet status", NodeStatusTone.Idle) + WalletChildPhase.Off -> + NodeStatusHead(if (inProcess) "Node Idle$mode" else "Wallet Offline", NodeStatusTone.Idle) + WalletChildPhase.Connecting -> NodeStatusHead("Connecting…", NodeStatusTone.Busy) + WalletChildPhase.Syncing -> + NodeStatusHead(if (inProcess) "Syncing Node$mode" else "Syncing Wallet", NodeStatusTone.Busy) + WalletChildPhase.Ready -> NodeStatusHead("Wallet Ready", NodeStatusTone.Good) + is WalletChildPhase.Exited -> NodeStatusHead("Wallet Stopped", NodeStatusTone.Bad) + is WalletChildPhase.Unrecognised -> NodeStatusHead("Unknown wallet state", NodeStatusTone.Bad) + } +} + /** * Why **Start** is not actionable, or `null` when it is. * @@ -479,8 +605,11 @@ fun startBlockedReason( bins.walletRpc == null -> NO_WALLET_RPC_MESSAGE starting -> STARTING_CHILD_NOTICE input == null -> READING_CHILD_NOTICE - input.running -> "The wallet child is already running." - !input.configured -> "No chain source yet: a wallet child needs a daemon to dial." + // Unreachable from the wallet screen: while the wallet runs the lifecycle + // control *is* Stop, so Start is never offered. Kept as a pure predicate so + // a stale status read cannot turn the one control into a no-op tap. + input.running -> "The wallet is already running." + !input.configured -> "No chain source yet: the wallet needs a daemon to dial." // The stored source is the app's own node but this build has no daemon: the // option is readable and unstoppable, so say it before the user presses Start. input.chainInProcess && !input.nodeAvailable -> CUPRATE_NOT_IN_BUILD_NOTICE @@ -494,7 +623,7 @@ fun startBlockedReason( */ fun stopBlockedReason(input: WalletChildInput?): String? = when { input == null -> READING_CHILD_NOTICE - !input.running -> "No wallet child is running." + !input.running -> "No wallet is running." else -> null } diff --git a/android/app/src/main/java/com/siriusdevops/onionwire/ui/WalletScreen.kt b/android/app/src/main/java/com/siriusdevops/onionwire/ui/WalletScreen.kt index 258b666..448e8bd 100644 --- a/android/app/src/main/java/com/siriusdevops/onionwire/ui/WalletScreen.kt +++ b/android/app/src/main/java/com/siriusdevops/onionwire/ui/WalletScreen.kt @@ -3,6 +3,7 @@ package com.siriusdevops.onionwire.ui import android.graphics.Bitmap import android.graphics.Color import androidx.compose.foundation.Image +import androidx.compose.foundation.background import androidx.compose.foundation.border import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Box @@ -15,21 +16,16 @@ import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.height import androidx.compose.foundation.layout.padding +import androidx.compose.foundation.layout.size +import androidx.compose.foundation.layout.width import androidx.compose.foundation.rememberScrollState import androidx.compose.foundation.shape.RoundedCornerShape 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.OutlinedButton 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.DisposableEffect import androidx.compose.runtime.LaunchedEffect @@ -40,13 +36,16 @@ import androidx.compose.runtime.rememberCoroutineScope import androidx.compose.runtime.setValue import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier +import androidx.compose.ui.draw.clip import androidx.compose.ui.graphics.asImageBitmap import androidx.compose.ui.layout.ContentScale import androidx.compose.ui.platform.testTag import androidx.compose.ui.semantics.contentDescription import androidx.compose.ui.semantics.semantics -import androidx.compose.ui.text.font.FontFamily +import androidx.compose.ui.text.font.FontWeight +import androidx.compose.ui.text.style.TextAlign import androidx.compose.ui.unit.dp +import androidx.compose.ui.unit.sp import androidx.lifecycle.compose.collectAsStateWithLifecycle import com.google.zxing.BarcodeFormat import com.google.zxing.EncodeHintType @@ -54,6 +53,20 @@ import com.google.zxing.qrcode.QRCodeWriter import com.siriusdevops.onionwire.WireViewModel import com.siriusdevops.onionwire.wallet.NO_WALLET_RPC_MESSAGE import com.siriusdevops.onionwire.wallet.WalletChildBinaryPaths +import com.siriusdevops.onionwire.ui.components.Label +import com.siriusdevops.onionwire.ui.components.Mono +import com.siriusdevops.onionwire.ui.components.OwAlertBanner +import com.siriusdevops.onionwire.ui.components.OwAlertVariant +import com.siriusdevops.onionwire.ui.components.OwButton +import com.siriusdevops.onionwire.ui.components.OwButtonRow +import com.siriusdevops.onionwire.ui.components.OwButtonVariant +import com.siriusdevops.onionwire.ui.components.OwCard +import com.siriusdevops.onionwire.ui.components.OwDivider +import com.siriusdevops.onionwire.ui.components.OwPill +import com.siriusdevops.onionwire.ui.components.OwSectionTitle +import com.siriusdevops.onionwire.ui.components.OwSegmentedControl +import com.siriusdevops.onionwire.ui.components.OwStatusDot +import com.siriusdevops.onionwire.ui.components.OwTopBar import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.launch import uniffi.onionwire_sdk.ChainChoice @@ -65,11 +78,31 @@ import uniffi.onionwire_sdk.WalletChildStatus private enum class PayKind { Invoice, Tip } private enum class SetupKind { Create, Import } -@OptIn(ExperimentalMaterial3Api::class) +/** + * The wallet tab. + * + * Three things changed from the alpha build, and each one is the plan's: + * + * - The page is a hero card and a node card, not a stack of nine equal boxes. + * The balance, the receive address and the two payment actions are the top + * card; the daemon, the network mode and the lifecycle are the second one. + * - Create / Import are the *first* thing on the page while no wallet is open, + * instead of two more outlined twins at the bottom of a long scroll. + * - The raw telemetry is gone from the surface: no daemon-process jargon, no + * `connecting · in-process mainnet pruned · node starting · sync 485253/…` + * string. What is left is a status sentence, a percentage, a progress track + * and two formatted block counts. The full line is still spoken — it is the + * header's `contentDescription` — so nothing an operator needs was deleted, + * it moved behind progressive disclosure. + * + * Behaviour is unchanged. Every callback below is the ViewModel call the old + * screen made; the gate on the seed card, the `shouldReloadWalletReads` key on + * the reload effect and the `openWalletChild` lifetime are untouched, because + * they are state, not layout. + */ @Composable fun WalletScreen( vm: WireViewModel, - onBack: () -> Unit, onOpenWallets: () -> Unit, ) { val friends by vm.friends.collectAsStateWithLifecycle() @@ -95,12 +128,18 @@ fun WalletScreen( var composer by remember { mutableStateOf(null) } var setup by remember { mutableStateOf(null) } // The seed currently on the blocking card: set by a successful create, or by - // "Back up seed" re-reading it from the wallet child. Null means no card. + // "Back up seed" re-reading it from the wallet process. Null means no card. // Never persisted and never logged — it is a spend key. var pendingSeed by remember { mutableStateOf(null) } var seedConfirm by remember { mutableStateOf("") } var daemonText by remember { mutableStateOf("") } var daemonError by remember { mutableStateOf(null) } + // Which pane of the node card's connection selector is open. `null` means + // "follow the stored chain source", which is the honest default: the pane is + // a view of what is configured, not a configuration of its own. It is reset + // whenever the stored source changes, so a started on-device node snaps the + // selector back to its own pane. + var remotePane by remember { mutableStateOf(null) } suspend fun reload() { runCatching { balance = vm.walletBalance() } @@ -110,10 +149,10 @@ fun WalletScreen( } /** - * "Back up seed": re-read the open wallet's seed from the wallet child and + * "Back up seed": re-read the open wallet's seed from the wallet process and * put it on the blocking card. This is the only path to a seed that was * created before this screen existed, so the failure is shown rather than - * swallowed — it is the difference between "the child is not running" and + * swallowed — it is the difference between "the wallet is not running" and * "there is nothing to recover". */ fun openSeedBackup() { @@ -134,21 +173,21 @@ fun WalletScreen( vm.refreshChainSource() } - // The same reads again, once the child has actually answered. They are + // The same reads again, once the wallet has actually answered. They are // keyed on `state` alone, never on the whole status record: the 2s poller // rewrites `height` every tick, and keying on the record would fire this on // every tick instead of on the one transition that matters. `LaunchedEffect` // re-runs only when the key changes, so `syncing` → `syncing` does not // reload. Not while `connecting`: `walletBalance()` answers the string // `"err"` (it does not throw), and that call is what pins the headline to - // `balance —`. + // `Balance unavailable`. LaunchedEffect(childInput?.state) { if (shouldReloadWalletReads(childInput?.state)) { reload() } } - // The wallet child's 2s refresh loop lives in the ViewModel (like the chat + // The wallet's 2s refresh loop lives in the ViewModel (like the chat // poller); this screen only owns its lifetime, so leaving the wallet and // coming back cannot stack a second loop on the first. DisposableEffect(Unit) { @@ -156,8 +195,11 @@ fun WalletScreen( onDispose { vm.closeWalletChild() } } - // Prefill the daemon field from the stored config, never over typing. + // Prefill the daemon field from the stored config, never over typing — and + // drop the connection-pane override, so the selector follows the source that + // was just stored. LaunchedEffect(chain) { + remotePane = null val stored = chain if (stored != null && stored.kind == ChainChoice.REMOTE && daemonText.isBlank()) { daemonText = "${stored.host}:${stored.port}" @@ -170,21 +212,20 @@ fun WalletScreen( // navigation bar from being applied twice, and keeps the IME inset out // of the Scaffold's inner padding. contentWindowInsets = WindowInsets(0, 0, 0, 0), + containerColor = OwColors.Canvas, topBar = { - TopAppBar( - title = { Text("Wallet") }, - navigationIcon = { - TextButton(onClick = onBack) { Text("Back") } - }, + OwTopBar( + title = "Wallet", // The saved-wallet catalogue is its own screen: this one is the - // open wallet, and switching wallets restarts the child, so the - // picker does not belong in this page's scroll. + // open wallet, and switching wallets restarts the wallet + // process, so the picker does not belong in this page's scroll. actions = { - TextButton(onClick = onOpenWallets) { Text("Wallets") } + OwButton( + text = "Saved wallets", + variant = OwButtonVariant.Outline, + onClick = onOpenWallets, + ) }, - colors = TopAppBarDefaults.topAppBarColors( - containerColor = MaterialTheme.colorScheme.background, - ), ) }, ) { pad -> @@ -199,11 +240,10 @@ fun WalletScreen( ) { // The blocking seed step. While a seed is on screen this card is the // whole body: no Cancel, and Done stays dead until the confirm word - // is typed, so the one-shot seed cannot be dismissed unread. The - // app-bar Back still leaves the screen — that is the TUI's `Esc` — - // and it costs nothing now, because leaving no longer loses the - // seed: the wallet stays unbacked (strip up, receive address hidden) - // until "Back up seed" puts this card back on screen. + // is typed, so the one-shot seed cannot be dismissed unread. Leaving + // the tab costs nothing now, because leaving no longer loses the + // seed: the wallet stays unbacked (warning up, receive address + // hidden) until "Back up seed" puts this card back on screen. val seed = pendingSeed if (seed != null) { SeedBackupCard( @@ -223,97 +263,45 @@ fun WalletScreen( } // The persistent unbacked strip, above everything else on the page. - // `walletReadable` is the core's own evidence that the child has a + // `walletReadable` is the core's own evidence that the wallet has a // wallet open: `wallet_balance` returns exactly "off" for a chain // source that was never configured, "err" for a configured one whose - // read failed (no wallet file open yet, or the child is down), and a - // real amount otherwise. The gate uses it only for an install that + // read failed (no wallet file open yet, or the process is down), and + // a real amount otherwise. The gate uses it only for an install that // has never created a wallet here, so a first-run user who has // configured a daemon but not yet created anything is not nagged // about a seed they do not have. val walletReadable = balance != null && balance != "off" && balance != "err" + val walletOpen = child?.walletOpen == true val unbacked = SeedBackupGate.warningVisible(seedConfirmed, walletReadable) if (unbacked) { UnbackedSeedCard(error = error, onBackUpSeed = { openSeedBackup() }) } - Card( - modifier = Modifier - .fillMaxWidth() - .padding(horizontal = 12.dp, vertical = 8.dp), - colors = CardDefaults.cardColors( - containerColor = MaterialTheme.colorScheme.surfaceVariant, - ), - ) { - Column( - Modifier.padding(16.dp), - horizontalAlignment = Alignment.CenterHorizontally, + val phase = walletChildPhase(childInput) + WalletHeroCard( + balance = balance, + address = address, + walletOpen = walletOpen, + phase = phase, + showQr = showQr, + onToggleQr = { showQr = !showQr }, + onOpenWallets = onOpenWallets, + onCreate = { setup = SetupKind.Create }, + onImport = { setup = SetupKind.Import }, + onInvoice = { composer = PayKind.Invoice }, + onTip = { composer = PayKind.Tip }, + onBackUpSeed = if ( + walletReadable && !SeedBackupGate.warningVisible(seedConfirmed, walletReadable) ) { - Text( - when (balance) { - null -> "loading…" - "off" -> "wallet off" - "err" -> "balance —" - else -> balance ?: "" - }, - style = MaterialTheme.typography.headlineSmall, - fontFamily = FontFamily.Monospace, - ) - // Hidden until the seed is confirmed written down: XMR into a - // wallet whose 25 words were never recorded is unrecoverable, - // so the address and its QR are gated, not just warned about. - val addr = address?.takeIf { - SeedBackupGate.receiveAddressVisible(seedConfirmed, walletReadable) - } - if (addr != null) { - Spacer(Modifier.height(8.dp)) - Text( - "receive address", - style = MaterialTheme.typography.labelSmall, - color = MaterialTheme.colorScheme.onSurfaceVariant, - ) - Spacer(Modifier.height(4.dp)) - Text( - addr, - style = MaterialTheme.typography.bodySmall, - fontFamily = FontFamily.Monospace, - modifier = Modifier.fillMaxWidth(), - ) - TextButton(onClick = { showQr = !showQr }) { - Text(if (showQr) "Hide QR" else "Show QR") - } - if (showQr) { - val qr = remember(addr) { generateQrBitmap(addr) } - qr?.let { bm -> - Box( - modifier = Modifier - .fillMaxWidth() - .aspectRatio(1f) - .border( - 1.dp, - MaterialTheme.colorScheme.outline, - RoundedCornerShape(8.dp), - ) - .padding(8.dp), - contentAlignment = Alignment.Center, - ) { - Image( - bitmap = bm.asImageBitmap(), - contentDescription = "QR code for receive address", - modifier = Modifier.fillMaxSize(), - contentScale = ContentScale.Fit, - ) - } - } - } - } - } - } + { openSeedBackup() } + } else { + null + }, + onLock = { scope.launch { vm.stopWalletChild() } }, + ) - // The app-owned `monero-wallet-rpc` control. Above the existing - // Create / Import / Invoice / Tip actions, which are untouched: the - // daemon is what makes the balance and the sends mean anything. - WalletChildCard( + NodeCard( bins = bins, input = childInput, chain = chain, @@ -321,8 +309,14 @@ fun WalletScreen( actionError = childError, daemonText = daemonText, daemonError = daemonError, - walletOpen = child?.walletOpen == true, + walletOpen = walletOpen, needsPassphrase = child?.needsPassphrase == true, + starting = starting, + remotePane = remotePane ?: !isInProcessSource(childInput, chain), + onSelectPane = { wantsRemote -> + remotePane = wantsRemote + daemonError = null + }, onDaemonText = { daemonText = it daemonError = null @@ -352,10 +346,10 @@ fun WalletScreen( vm.setInProcessCuprate(bins, mainnet, prune) .onFailure { daemonError = walletFailureText(it.message ?: it.toString()) } .onSuccess { - // The mode buttons used to only persist the choice, - // which read as a no-op besides the storage line. - // Start is still the core launch; tapping a mode - // fires it when the storage gate would allow Start. + // Selecting a mode stores it and, when the + // storage floor would allow Start, starts the + // node: a mode button that only rewrites a + // storage line reads as a no-op. if (shouldStartAfterSelectingChain( chainStorageBlockedReason( vm.chainFreeBytes(), @@ -370,35 +364,24 @@ fun WalletScreen( } } }, - starting = starting, onStart = { vm.startWalletChild() }, onStop = { scope.launch { vm.stopWalletChild() } }, ) if (transfers.isNotEmpty()) { - Text( - "recent transfers", - style = MaterialTheme.typography.titleSmall, - modifier = Modifier.padding(horizontal = 12.dp, vertical = 4.dp), - ) - // Plain Column, not a LazyColumn: the root is a scrolling - // container now, so a nested lazy list would either throw on the - // unbounded height or need an arbitrary cap. `walletRecentTransfers` - // is bounded (25 rows), and the page scrolls as one gesture. - Column( - modifier = Modifier - .fillMaxWidth() - .padding(horizontal = 12.dp), - verticalArrangement = Arrangement.spacedBy(4.dp), - ) { - transfers.forEach { t -> TransferCard(t) } + Column(Modifier.fillMaxWidth().padding(horizontal = 16.dp, vertical = 8.dp)) { + Label("RECENT TRANSFERS") + Spacer(Modifier.height(8.dp)) + Column(verticalArrangement = Arrangement.spacedBy(8.dp)) { + transfers.forEach { t -> TransferCard(t) } + } } } val kind = composer val setupKind = setup - if (kind != null) { - PayComposer( + when { + kind != null -> PayComposer( kind = kind, friends = friends, onCancel = { composer = null }, @@ -419,8 +402,8 @@ fun WalletScreen( } }, ) - } else if (setupKind != null) { - WalletSetupCard( + + setupKind != null -> WalletSetupCard( kind = setupKind, warning = vm.spendAuthorityWarning(), onCancel = { setup = null }, @@ -440,72 +423,599 @@ fun WalletScreen( importWallet = { pw, seed -> vm.importWallet(pw, seed) }, scope = scope, ) - } else { - Column(Modifier.fillMaxWidth().padding(12.dp)) { - Row( - modifier = Modifier.fillMaxWidth(), - horizontalArrangement = Arrangement.spacedBy(8.dp), - ) { - OutlinedButton( - onClick = { composer = PayKind.Invoice }, - modifier = Modifier.weight(1f), - ) { Text("Invoice") } - OutlinedButton( - onClick = { composer = PayKind.Tip }, - modifier = Modifier.weight(1f), - ) { Text("Tip") } - } - Spacer(Modifier.height(8.dp)) - Row( - modifier = Modifier.fillMaxWidth(), - horizontalArrangement = Arrangement.spacedBy(8.dp), - ) { - OutlinedButton( - onClick = { setup = SetupKind.Create }, - modifier = Modifier.weight(1f), - ) { Text("Create") } - OutlinedButton( - onClick = { setup = SetupKind.Import }, - modifier = Modifier.weight(1f), - ) { Text("Import") } - } - // The recovery path for a wallet whose seed was missed. The - // strip above carries its own copy of this button while the - // seed is unconfirmed, so exactly one is ever on screen — - // and this copy is only offered once the child can actually - // read a wallet, which is the only state in which the seed - // read can succeed. - if (walletReadable && !SeedBackupGate.warningVisible(seedConfirmed, walletReadable)) { - Spacer(Modifier.height(8.dp)) - OutlinedButton( - onClick = { openSeedBackup() }, - modifier = Modifier - .fillMaxWidth() - .testTag("wallet-seed-backup-action"), - ) { Text("Back up seed") } - } - } } // While the strip is up the error belongs next to the button that - // caused it: this page is one long scroll and the daemon card sits + // caused it: this page is one long scroll and the node card sits // between the strip and the bottom, so a failed `wallet_seed` read // would otherwise land off-screen. if (!unbacked) { error?.let { ErrorLine(it) } } + + Spacer(Modifier.height(16.dp)) } } } -/** The one error line every wallet action shares. */ +/** + * The wallet at a glance: a balance, a receive address, and the four things a + * person actually does here. + * + * Two states, and the switch is the core's own `wallet_open` — not "is a chain + * source configured", which is a different question and answers yes for a + * receive-only install that has no wallet file at all. + */ +@Composable +private fun WalletHeroCard( + balance: String?, + address: String?, + walletOpen: Boolean, + phase: WalletChildPhase, + showQr: Boolean, + onToggleQr: () -> Unit, + onOpenWallets: () -> Unit, + onCreate: () -> Unit, + onImport: () -> Unit, + onInvoice: () -> Unit, + onTip: () -> Unit, + onBackUpSeed: (() -> Unit)?, + onLock: () -> Unit, +) { + OwCard( + modifier = Modifier + .fillMaxWidth() + .padding(horizontal = 16.dp, vertical = 8.dp), + ) { + Row( + Modifier.fillMaxWidth(), + horizontalArrangement = Arrangement.SpaceBetween, + verticalAlignment = Alignment.CenterVertically, + ) { + Row(verticalAlignment = Alignment.CenterVertically) { + OwStatusDot( + when { + !walletOpen -> OwColors.TextMuted + phase is WalletChildPhase.Ready -> OwColors.Accent + else -> OwColors.Warning + }, + ) + Spacer(Modifier.width(8.dp)) + OwSectionTitle(if (walletOpen) "Wallet" else "No Wallet Active") + } + OwButton( + text = "Saved wallets", + variant = OwButtonVariant.Outline, + onClick = onOpenWallets, + ) + } + Spacer(Modifier.height(12.dp)) + + if (!walletOpen) { + // The §4.1 replacement for the old `wallet off` string, kept as a + // value line rather than a second heading: the card already says + // "No Wallet Active", and "off" vs "err" is the difference between + // "nothing is configured" and "configured, but the read failed". + Text( + noWalletBalanceHeadline(balance), + style = MaterialTheme.typography.titleMedium, + color = OwColors.TextSecondary, + modifier = Modifier.testTag("wallet-balance"), + ) + Spacer(Modifier.height(6.dp)) + Text( + "Create a new Monero wallet or restore an existing seed.", + style = MaterialTheme.typography.bodySmall, + color = OwColors.TextSecondary, + ) + Spacer(Modifier.height(16.dp)) + OwButtonRow { + OwButton( + text = "Create Wallet", + variant = OwButtonVariant.Primary, + onClick = onCreate, + modifier = Modifier.weight(1f).testTag("wallet-create"), + ) + OwButton( + text = "Import Wallet", + variant = OwButtonVariant.Secondary, + onClick = onImport, + modifier = Modifier.weight(1f).testTag("wallet-import"), + ) + } + // Invoicing does not need a wallet file: the core resolves the payee + // address from the profile (`no receive address — set profile xmr or + // ONIONWIRE_WALLET_RPC` is the both-missing case). Hiding the action + // in this state would remove a path that works, so it stays — as a + // text action, not a third button competing with Create. A tip + // genuinely needs the wallet (it calls `Wallet::transfer`), so it + // only appears once one is open. + TextButton(onClick = onInvoice) { Text("Send an invoice") } + return@OwCard + } + + // A wallet is open: the balance is the headline, 28sp bold, sans — it is + // money, not cryptographic material, so it is not monospaced. + Text( + noWalletBalanceHeadline(balance), + style = MaterialTheme.typography.displaySmall, + color = OwColors.TextPrimary, + modifier = Modifier.testTag("wallet-balance"), + ) + Spacer(Modifier.height(6.dp)) + OwPill( + text = phase.label, + textColor = when (phase) { + WalletChildPhase.Ready -> OwColors.Accent + is WalletChildPhase.Exited, is WalletChildPhase.Unrecognised -> OwColors.Danger + else -> OwColors.Warning + }, + container = when (phase) { + WalletChildPhase.Ready -> OwColors.InfoTint + is WalletChildPhase.Exited, is WalletChildPhase.Unrecognised -> OwColors.DangerTint + else -> OwColors.WarningTint + }, + borderColor = when (phase) { + WalletChildPhase.Ready -> OwColors.InfoBorder + is WalletChildPhase.Exited, is WalletChildPhase.Unrecognised -> OwColors.DangerBorder + else -> OwColors.WarningBorder + }, + dotColor = when (phase) { + WalletChildPhase.Ready -> OwColors.Accent + is WalletChildPhase.Exited, is WalletChildPhase.Unrecognised -> OwColors.Danger + else -> OwColors.Warning + }, + ) + + // Hidden until the seed is confirmed written down: XMR into a wallet + // whose 25 words were never recorded is unrecoverable, so the address + // and its QR are gated, not just warned about. + val addr = address + if (addr != null) { + Spacer(Modifier.height(16.dp)) + OwDivider() + Spacer(Modifier.height(12.dp)) + Label("RECEIVE ADDRESS") + Spacer(Modifier.height(4.dp)) + Mono(addr, modifier = Modifier.fillMaxWidth(), color = OwColors.TextPrimary) + TextButton(onClick = onToggleQr) { Text(if (showQr) "Hide QR" else "Show QR") } + if (showQr) { + val qr = remember(addr) { generateQrBitmap(addr) } + qr?.let { bm -> + Box( + modifier = Modifier + .fillMaxWidth() + .aspectRatio(1f) + .border(1.dp, OwColors.Border, RoundedCornerShape(OwRadius.Control)) + .padding(8.dp), + contentAlignment = Alignment.Center, + ) { + Image( + bitmap = bm.asImageBitmap(), + contentDescription = "QR code for receive address", + modifier = Modifier.fillMaxSize(), + contentScale = ContentScale.Fit, + ) + } + } + } + } + + Spacer(Modifier.height(16.dp)) + OwButtonRow { + OwButton( + text = "Receive / Invoice", + variant = OwButtonVariant.Primary, + onClick = onInvoice, + modifier = Modifier.weight(1f), + ) + OwButton( + text = "Send / Tip", + variant = OwButtonVariant.Secondary, + onClick = onTip, + modifier = Modifier.weight(1f), + ) + } + Spacer(Modifier.height(8.dp)) + OwButtonRow { + // Creating a second wallet and importing a third are real flows + // (each wallet gets its own file, and the catalogue lists them), so + // both stay reachable once the first one is open — they just stop + // being the loudest thing on the page. + OwButton( + text = "New wallet", + variant = OwButtonVariant.Outline, + onClick = onCreate, + modifier = Modifier.weight(1f).testTag("wallet-create"), + ) + OwButton( + text = "Import wallet", + variant = OwButtonVariant.Outline, + onClick = onImport, + modifier = Modifier.weight(1f).testTag("wallet-import"), + ) + } + // The recovery path for a wallet whose seed was missed: a quiet action, + // because a healthy wallet needs it rarely and a seed is a spend key. + // While the seed is unconfirmed the strip above carries the button + // instead, so exactly one is ever on screen. + if (onBackUpSeed != null) { + TextButton( + onClick = onBackUpSeed, + modifier = Modifier.testTag("wallet-seed-backup-action"), + ) { Text("Back up seed") } + } + Spacer(Modifier.height(8.dp)) + OwButton( + text = "Lock Wallet", + variant = OwButtonVariant.Destructive, + onClick = onLock, + modifier = Modifier.fillMaxWidth().testTag("wallet-lock"), + ) + } +} + +/** + * The node and the daemon: one status header, one progress track, one choice of + * where the chain comes from, and one lifecycle control. + * + * The single most important property of this card is that it never asserts a + * state the core did not report. `target_height == 0` prints no percentage, an + * unrecognised state is never green, and a running process whose RPC has not + * answered is `Connecting…`, not `Wallet Ready`. + */ +@Composable +private fun NodeCard( + bins: WalletChildBinaryPaths, + input: WalletChildInput?, + chain: ChainConfig?, + nodeFreeBytes: Long?, + actionError: String?, + daemonText: String, + daemonError: String?, + /** + * The core's `wallet_open` / `needs_passphrase`, straight off the same + * `WalletChildStatus` the status header is drawn from — not a second idea of + * which wallet is open. + */ + walletOpen: Boolean, + needsPassphrase: Boolean, + starting: Boolean, + /** Which pane the connection selector shows; the caller owns the override. */ + remotePane: Boolean, + onSelectPane: (Boolean) -> Unit, + onDaemonText: (String) -> Unit, + onSaveDaemon: () -> Unit, + onReceiveOnly: () -> Unit, + onInProcessNode: (mainnet: Boolean, prune: Boolean) -> Unit, + onStart: () -> Unit, + onStop: () -> Unit, +) { + val inProcess = isInProcessSource(input, chain) + val head = nodeStatusHead( + input, + inProcess = inProcess, + mainnet = chain?.mainnet == true, + prune = chain?.prune == true, + ) + val progress = syncProgress(input?.height ?: 0uL, input?.targetHeight ?: 0uL) + val node = nodePhase(input) + val onionDaemon = chain?.kind == ChainChoice.REMOTE && isOnionHost(chain.host) + val startWhy = startBlockedReason(bins, input, onionDaemon, starting) + ?: if (inProcess) { + chainStorageBlockedReason( + nodeFreeBytes, + mainnet = chain?.mainnet == true, + prune = chain?.prune == true, + ) + } else { + null + } + val stopWhy = stopBlockedReason(input) + // A live wallet with no wallet file open answers every read with the + // daemon's own `-13 No wallet file`. Say that in this app's words, here, + // rather than letting the raw string arrive later on whichever card asked. + val openHint = walletChildOpenHint( + childRunning = input?.running == true, + walletOpen = walletOpen, + needsPassphrase = needsPassphrase, + ) + val running = input?.running == true + + OwCard( + modifier = Modifier + .fillMaxWidth() + .padding(horizontal = 16.dp, vertical = 8.dp), + ) { + // --- the status header ------------------------------------------------ + Row( + Modifier + .fillMaxWidth() + .testTag(walletChildPhase(input).testTag) + .semantics(mergeDescendants = true) { + // The whole raw line — `syncing · in-process mainnet pruned + // · node syncing · sync 485253/3794383` — is still spoken. + // A screen reader is never told less than the sighted user. + contentDescription = walletChildStatusDescription(input) + }, + verticalAlignment = Alignment.CenterVertically, + ) { + OwStatusDot( + when (head.tone) { + NodeStatusTone.Idle -> OwColors.TextMuted + NodeStatusTone.Busy -> OwColors.Warning + NodeStatusTone.Good -> OwColors.Accent + NodeStatusTone.Bad -> OwColors.Danger + }, + ) + Spacer(Modifier.width(8.dp)) + Text( + head.title, + style = MaterialTheme.typography.titleMedium, + color = OwColors.TextPrimary, + modifier = Modifier.weight(1f), + ) + progress.percentText?.let { pct -> + Mono(pct, color = OwColors.TextSecondary) + } + } + + // --- the progress track ---------------------------------------------- + if (progress.blockText != null) { + Spacer(Modifier.height(10.dp)) + Box( + Modifier + .fillMaxWidth() + .height(OwSize.ProgressTrack) + .clip(RoundedCornerShape(OwRadius.Pill)) + .background(OwColors.SurfaceInteractive), + ) { + Box( + Modifier + .fillMaxWidth(progress.fraction) + .height(OwSize.ProgressTrack) + .clip(RoundedCornerShape(OwRadius.Pill)) + .background(OwColors.Accent), + ) + } + Spacer(Modifier.height(6.dp)) + Row( + Modifier.fillMaxWidth().testTag("wallet-chain-progress"), + horizontalArrangement = Arrangement.SpaceBetween, + ) { + Text( + progress.blockText, + style = MonoStyle.copy(fontSize = 12.sp, color = OwColors.TextSecondary), + ) + Text( + nodeFreeBytes?.let { "${formatBytes(it)} free" } ?: "free space unknown", + style = MonoStyle.copy(fontSize = 12.sp, color = OwColors.TextSecondary), + ) + } + } + + // The node's own word, when there is one, as its own assertable line: + // an unrecognised node state can never be read as ready. + if (node !is NodePhase.Absent) { + Spacer(Modifier.height(6.dp)) + Text( + "node: ${node.label}", + style = MonoStyle.copy(fontSize = 12.sp, color = OwColors.TextSecondary), + modifier = Modifier + .fillMaxWidth() + .testTag(node.testTag) + .semantics(mergeDescendants = true) { + contentDescription = node.contentDescription + }, + ) + } + + Spacer(Modifier.height(12.dp)) + OwDivider() + Spacer(Modifier.height(12.dp)) + + // --- where the chain comes from --------------------------------------- + Label("CONNECTION TYPE") + Spacer(Modifier.height(8.dp)) + OwSegmentedControl( + options = listOf("Remote Node", "On-Device Node"), + selectedIndex = if (remotePane) 0 else 1, + onSelect = { onSelectPane(it == 0) }, + testTags = listOf("wallet-connection-remote", "wallet-connection-on-device"), + ) + + if (remotePane) { + Spacer(Modifier.height(12.dp)) + OutlinedTextField( + value = daemonText, + onValueChange = onDaemonText, + singleLine = true, + label = { Text("daemon host:port") }, + modifier = Modifier + .fillMaxWidth() + .testTag("wallet-daemon-input"), + ) + Spacer(Modifier.height(4.dp)) + Text( + "LAN (e.g. 192.168.1.20:18089) or a public clearnet node.", + style = MaterialTheme.typography.labelSmall, + color = OwColors.TextSecondary, + ) + Spacer(Modifier.height(10.dp)) + OwButtonRow { + OwButton( + text = "Save Daemon", + variant = OwButtonVariant.Secondary, + onClick = onSaveDaemon, + enabled = bins.walletRpcBundled, + modifier = Modifier.weight(1f).testTag("wallet-daemon-save"), + ) + OwButton( + text = "Receive-Only", + variant = OwButtonVariant.Outline, + onClick = onReceiveOnly, + modifier = Modifier.weight(1f).testTag("wallet-daemon-receive-only"), + ) + } + } else { + Spacer(Modifier.height(12.dp)) + Label("NETWORK MODE") + Spacer(Modifier.height(8.dp)) + val mode = selectedCuprateMode( + inProcess = true, + mainnet = chain?.mainnet == true, + prune = chain?.prune == true, + ) + OwSegmentedControl( + options = listOf("Pruned", "Full", "Testnet"), + selectedIndex = when (mode) { + CuprateMode.MainnetFull -> 1 + CuprateMode.Testnet -> 2 + // MainnetPruned, and the not-in-process case before anything + // is stored: the pruned store is the conservative default. + else -> 0 + }, + onSelect = { index -> + when (index) { + 0 -> onInProcessNode(true, true) + 1 -> onInProcessNode(true, false) + else -> onInProcessNode(false, false) + } + }, + testTags = listOf( + "wallet-chain-mainnet-pruned", + "wallet-chain-mainnet-full", + "wallet-chain-in-process", + ), + ) + Spacer(Modifier.height(10.dp)) + OwAlertBanner( + variant = OwAlertVariant.Warning, + title = CUPRATE_ON_DEVICE_TITLE, + description = CUPRATE_ON_DEVICE_BODY, + modifier = Modifier.testTag("wallet-cuprate-warning"), + ) + Spacer(Modifier.height(8.dp)) + Text( + chainStorageLine( + nodeFreeBytes, + mainnet = chain?.mainnet == true, + prune = chain?.prune == true, + ), + style = MaterialTheme.typography.labelSmall, + color = OwColors.TextSecondary, + modifier = Modifier + .fillMaxWidth() + .testTag("wallet-chain-storage"), + ) + } + + // --- the lifecycle ---------------------------------------------------- + Spacer(Modifier.height(16.dp)) + if (starting) { + OwButton( + text = "Starting…", + variant = OwButtonVariant.Primary, + enabled = false, + onClick = {}, + modifier = Modifier.fillMaxWidth().testTag("wallet-child-start"), + ) + } else if (running) { + OwButton( + text = "Stop Node", + variant = OwButtonVariant.Destructive, + enabled = stopWhy == null, + onClick = onStop, + modifier = Modifier.fillMaxWidth().testTag("wallet-child-stop"), + ) + } else { + OwButton( + text = "Start Node & Wallet", + variant = OwButtonVariant.Primary, + enabled = startWhy == null, + onClick = onStart, + modifier = Modifier.fillMaxWidth().testTag("wallet-child-start"), + ) + } + + // --- what is wrong, in banners rather than paragraphs ----------------- + if (starting) { + Spacer(Modifier.height(8.dp)) + OwAlertBanner( + variant = OwAlertVariant.Info, + title = "Starting", + description = STARTING_CHILD_NOTICE, + ) + } + + // Why Start is dead, in the core's terms rather than a grey button. + if (!starting && !running) { + startWhy?.let { + Spacer(Modifier.height(8.dp)) + OwAlertBanner( + variant = OwAlertVariant.Info, + title = "Not ready to start", + description = it, + modifier = Modifier.testTag("wallet-child-start-blocked"), + ) + } + } + + if (!bins.walletRpcBundled) { + Spacer(Modifier.height(8.dp)) + OwAlertBanner( + variant = OwAlertVariant.Error, + title = "No wallet binary", + description = NO_WALLET_RPC_MESSAGE, + ) + } + + // "No wallet file open" is a state of a live wallet, not a failure of + // the last call, so it is said here rather than left to surface as the + // daemon's `-13` on whichever card asked for a read. + openHint?.let { + Spacer(Modifier.height(8.dp)) + OwAlertBanner( + variant = OwAlertVariant.Info, + title = "No wallet open", + description = it, + modifier = Modifier.testTag("wallet-child-no-wallet"), + ) + } + + // The last thing the core or the RPC call said. Sticky until the user + // acts, like the chat screen's load error. Filtered through + // `walletFailureText`: the daemon's own `-13 No wallet file` / JSON + // answer is not a sentence about this app and never reaches the screen. + val failure = walletFailureText(input?.lastError) ?: actionError ?: daemonError + failure?.let { + Spacer(Modifier.height(8.dp)) + OwAlertBanner( + variant = OwAlertVariant.Error, + title = "Wallet error", + description = it, + modifier = Modifier.testTag("wallet-child-error"), + ) + } + } +} + +/** + * True when the stored chain source (or the live status, before the store is + * re-read) is the app's own node. The connection selector and the network-mode + * control both key off this one predicate. + */ +private fun isInProcessSource(input: WalletChildInput?, chain: ChainConfig?): Boolean = + input?.chainInProcess == true || chain?.kind == ChainChoice.IN_PROCESS_CUPRATE + +/** The one error line every wallet action shares, as a banner. */ @Composable private fun ErrorLine(text: String) { - Text( - text, - style = MaterialTheme.typography.bodySmall, - color = MaterialTheme.colorScheme.error, - modifier = Modifier.padding(horizontal = 12.dp, vertical = 4.dp), + OwAlertBanner( + variant = OwAlertVariant.Error, + title = "Something went wrong", + description = text, + modifier = Modifier.padding(horizontal = 16.dp, vertical = 8.dp), ) } @@ -523,38 +1033,23 @@ private fun UnbackedSeedCard( error: String?, onBackUpSeed: () -> Unit, ) { - Card( + OwAlertBanner( + variant = OwAlertVariant.Error, + title = "This wallet is not backed up", + description = SeedBackupGate.WARNING, modifier = Modifier - .fillMaxWidth() - .padding(horizontal = 12.dp, vertical = 8.dp) + .padding(horizontal = 16.dp, vertical = 8.dp) .testTag("wallet-seed-warning"), - colors = CardDefaults.cardColors( - containerColor = MaterialTheme.colorScheme.errorContainer, - ), - ) { - Column(Modifier.padding(12.dp)) { - Text( - SeedBackupGate.WARNING, - style = MaterialTheme.typography.bodySmall, - color = MaterialTheme.colorScheme.onErrorContainer, - ) - Spacer(Modifier.height(8.dp)) - OutlinedButton( + action = { + OwButton( + text = "Back up seed", + variant = OwButtonVariant.Outline, onClick = onBackUpSeed, - modifier = Modifier - .fillMaxWidth() - .testTag("wallet-seed-backup-action"), - ) { Text("Back up seed") } - error?.let { - Spacer(Modifier.height(6.dp)) - Text( - it, - style = MaterialTheme.typography.bodySmall, - color = MaterialTheme.colorScheme.error, - ) - } - } - } + modifier = Modifier.testTag("wallet-seed-backup-action"), + ) + }, + ) + error?.let { ErrorLine(it) } } /** @@ -584,91 +1079,76 @@ internal fun SeedBackupCard( onTyped: (String) -> Unit, onDone: () -> Unit, ) { - Card( + OwCard( modifier = Modifier .fillMaxWidth() - .padding(12.dp) + .padding(16.dp) .testTag("wallet-seed-card"), - colors = CardDefaults.cardColors( - containerColor = MaterialTheme.colorScheme.surfaceVariant, - ), ) { - Column(Modifier.padding(12.dp)) { - Text("Back up this seed", style = MaterialTheme.typography.titleSmall) - Spacer(Modifier.height(8.dp)) - Text( - "These 25 words are the only way to recover this wallet, and anyone who " + - "reads them can spend it. Write them down now — this is the only copy.", - style = MaterialTheme.typography.bodySmall, - ) - Spacer(Modifier.height(8.dp)) - Text( - seed, - style = MaterialTheme.typography.bodyMedium, - fontFamily = FontFamily.Monospace, - modifier = Modifier - .fillMaxWidth() - .testTag("wallet-seed-words"), - ) - Spacer(Modifier.height(12.dp)) - Text( - "Type ${SeedBackupGate.CONFIRM_WORD} to confirm you have written it down.", - style = MaterialTheme.typography.labelSmall, - color = MaterialTheme.colorScheme.onSurfaceVariant, - ) - Spacer(Modifier.height(4.dp)) - OutlinedTextField( - value = typed, - onValueChange = onTyped, - singleLine = true, - label = { Text("type ${SeedBackupGate.CONFIRM_WORD}") }, - modifier = Modifier - .fillMaxWidth() - .testTag("wallet-seed-confirm-input"), - ) - Spacer(Modifier.height(8.dp)) - Row(Modifier.fillMaxWidth(), horizontalArrangement = Arrangement.End) { - Button( - onClick = onDone, - enabled = SeedBackupGate.confirmEnabled(typed), - modifier = Modifier.testTag("wallet-seed-confirm-done"), - ) { Text("Done") } - } - } + OwSectionTitle("Back up this seed") + Spacer(Modifier.height(8.dp)) + Text( + "These 25 words are the only way to recover this wallet, and anyone who " + + "reads them can spend it. Write them down now — this is the only copy.", + style = MaterialTheme.typography.bodySmall, + color = OwColors.TextSecondary, + ) + Spacer(Modifier.height(12.dp)) + Mono( + seed, + modifier = Modifier + .fillMaxWidth() + .testTag("wallet-seed-words"), + ) + Spacer(Modifier.height(16.dp)) + Text( + "Type ${SeedBackupGate.CONFIRM_WORD} to confirm you have written it down.", + style = MaterialTheme.typography.labelSmall, + color = OwColors.TextSecondary, + ) + Spacer(Modifier.height(4.dp)) + OutlinedTextField( + value = typed, + onValueChange = onTyped, + singleLine = true, + label = { Text("type ${SeedBackupGate.CONFIRM_WORD}") }, + modifier = Modifier + .fillMaxWidth() + .testTag("wallet-seed-confirm-input"), + ) + Spacer(Modifier.height(10.dp)) + OwButton( + text = "Done", + variant = OwButtonVariant.Primary, + enabled = SeedBackupGate.confirmEnabled(typed), + onClick = onDone, + modifier = Modifier.testTag("wallet-seed-confirm-done"), + ) } } @Composable private fun TransferCard(t: TransferRow) { - Card( - modifier = Modifier.fillMaxWidth(), - colors = CardDefaults.cardColors( - containerColor = MaterialTheme.colorScheme.surfaceVariant, - ), - ) { + OwCard(modifier = Modifier.fillMaxWidth(), padding = 12.dp) { Row( - modifier = Modifier - .fillMaxWidth() - .padding(12.dp), + Modifier.fillMaxWidth(), horizontalArrangement = Arrangement.SpaceBetween, + verticalAlignment = Alignment.CenterVertically, ) { - Column(modifier = Modifier.weight(1f)) { - Text( - t.txid.take(16) + "…", - style = MaterialTheme.typography.bodySmall, - fontFamily = FontFamily.Monospace, - ) - Text( - t.address, - style = MaterialTheme.typography.labelSmall, - fontFamily = FontFamily.Monospace, - color = MaterialTheme.colorScheme.onSurfaceVariant, + Column(Modifier.weight(1f)) { + Mono(t.txid.take(16) + "…", color = OwColors.TextSecondary) + Spacer(Modifier.height(2.dp)) + Mono( + t.address.take(12) + "…" + t.address.takeLast(4), + color = OwColors.TextMuted, ) } + Spacer(Modifier.width(12.dp)) Text( t.amount, - style = MaterialTheme.typography.bodyMedium, - fontFamily = FontFamily.Monospace, + style = MaterialTheme.typography.titleSmall, + color = OwColors.TextPrimary, + textAlign = TextAlign.End, ) } } @@ -688,64 +1168,64 @@ private fun PayComposer( var memo by remember { mutableStateOf("") } val ready = selected != null && amount.trim().isNotEmpty() - Card( + OwCard( modifier = Modifier .fillMaxWidth() - .padding(12.dp), - colors = CardDefaults.cardColors( - containerColor = MaterialTheme.colorScheme.surfaceVariant, - ), + .padding(horizontal = 16.dp, vertical = 8.dp), ) { - Column(Modifier.padding(12.dp)) { + OwSectionTitle(if (kind == PayKind.Invoice) "Send invoice" else "Send tip") + Spacer(Modifier.height(8.dp)) + if (friends.isEmpty()) { Text( - if (kind == PayKind.Invoice) "Send invoice" else "Send tip", - style = MaterialTheme.typography.titleSmall, + "Add a contact first. Invoice and tip are one-shot to a peer onion.", + style = MaterialTheme.typography.bodySmall, + color = OwColors.TextSecondary, ) - Spacer(Modifier.height(8.dp)) - if (friends.isEmpty()) { - Text( - "Add a friend first. Invoice and tip are one-shot to a peer onion.", - style = MaterialTheme.typography.bodySmall, - color = MaterialTheme.colorScheme.onSurfaceVariant, - ) - } else { - Text("to", style = MaterialTheme.typography.labelSmall) - friends.forEach { f -> - val label = f.petname?.takeIf { it.isNotBlank() } ?: f.fingerprint - TextButton(onClick = { selected = f.pubkeyHex }) { - Text(if (selected == f.pubkeyHex) "• $label" else label) - } + } else { + Label("TO") + friends.forEach { f -> + val label = f.petname?.takeIf { it.isNotBlank() } ?: f.fingerprint + TextButton(onClick = { selected = f.pubkeyHex }) { + Text(if (selected == f.pubkeyHex) "• $label" else label) } } - OutlinedTextField( - value = amount, - onValueChange = { amount = it }, - singleLine = true, - label = { Text("amount XMR") }, - modifier = Modifier.fillMaxWidth(), + } + Spacer(Modifier.height(4.dp)) + OutlinedTextField( + value = amount, + onValueChange = { amount = it }, + singleLine = true, + label = { Text("amount XMR") }, + modifier = Modifier.fillMaxWidth(), + ) + Spacer(Modifier.height(8.dp)) + OutlinedTextField( + value = memo, + onValueChange = { memo = it }, + singleLine = true, + label = { Text("memo (optional)") }, + modifier = Modifier.fillMaxWidth(), + ) + Spacer(Modifier.height(12.dp)) + OwButtonRow { + OwButton( + text = "Cancel", + variant = OwButtonVariant.Outline, + onClick = onCancel, + modifier = Modifier.weight(1f), ) - Spacer(Modifier.height(8.dp)) - OutlinedTextField( - value = memo, - onValueChange = { memo = it }, - singleLine = true, - label = { Text("memo (optional)") }, - modifier = Modifier.fillMaxWidth(), + OwButton( + text = "Send", + variant = OwButtonVariant.Primary, + enabled = ready, + onClick = { + // Dead button without a recipient, and `ready` says so; the + // null check is only here because `selected` is nullable. + val pk = selected + if (pk != null) onSend(pk, amount.trim(), memo.trim()) + }, + modifier = Modifier.weight(1f), ) - Spacer(Modifier.height(8.dp)) - Row( - modifier = Modifier.fillMaxWidth(), - horizontalArrangement = Arrangement.End, - ) { - TextButton(onClick = onCancel) { Text("Cancel") } - Button( - onClick = { - val pk = selected ?: return@Button - onSend(pk, amount.trim(), memo.trim()) - }, - enabled = ready, - ) { Text("Send") } - } } } } @@ -767,377 +1247,83 @@ private fun WalletSetupCard( var seed by remember { mutableStateOf("") } val ready = password.isNotEmpty() && (kind == SetupKind.Create || seed.isNotBlank()) - Card( + OwCard( modifier = Modifier .fillMaxWidth() - .padding(12.dp), - colors = CardDefaults.cardColors( - containerColor = MaterialTheme.colorScheme.surfaceVariant, - ), + .padding(horizontal = 16.dp, vertical = 8.dp), ) { - Column(Modifier.padding(12.dp)) { - Text( - if (kind == SetupKind.Create) "Create wallet" else "Import wallet", - style = MaterialTheme.typography.titleSmall, - ) - Spacer(Modifier.height(8.dp)) - if (kind == SetupKind.Create && !accepted) { - Text(warning, style = MaterialTheme.typography.bodySmall) - Spacer(Modifier.height(8.dp)) - Row(Modifier.fillMaxWidth(), horizontalArrangement = Arrangement.End) { - TextButton(onClick = onCancel) { Text("Cancel") } - Button(onClick = { accepted = true }) { Text("I accept spend authority") } - } - return@Column - } - if (kind == SetupKind.Import) { - Text( - "Paste the 25-word seed. Create does not need a key.", - style = MaterialTheme.typography.bodySmall, + OwSectionTitle(if (kind == SetupKind.Create) "Create wallet" else "Import wallet") + Spacer(Modifier.height(8.dp)) + if (kind == SetupKind.Create && !accepted) { + Text(warning, style = MaterialTheme.typography.bodySmall, color = OwColors.TextSecondary) + Spacer(Modifier.height(12.dp)) + OwButtonRow { + OwButton( + text = "Cancel", + variant = OwButtonVariant.Outline, + onClick = onCancel, + modifier = Modifier.weight(1f), ) - Spacer(Modifier.height(8.dp)) - OutlinedTextField( - value = seed, - onValueChange = { seed = it }, - label = { Text("seed") }, - modifier = Modifier.fillMaxWidth(), + OwButton( + text = "I accept spend authority", + variant = OwButtonVariant.Primary, + onClick = { accepted = true }, + modifier = Modifier.weight(1f), ) - Spacer(Modifier.height(8.dp)) - } - OutlinedTextField( - value = password, - onValueChange = { password = it }, - singleLine = true, - label = { Text("wallet passphrase") }, - modifier = Modifier.fillMaxWidth(), - ) - Spacer(Modifier.height(8.dp)) - Row(Modifier.fillMaxWidth(), horizontalArrangement = Arrangement.End) { - TextButton(onClick = onCancel) { Text("Cancel") } - Button( - onClick = { - scope.launch { - when (kind) { - SetupKind.Create -> create(password).fold( - onSuccess = onCreated, - onFailure = { onError(it.message ?: it.toString()) }, - ) - SetupKind.Import -> importWallet(password, seed.trim()).fold( - onSuccess = { onImported() }, - onFailure = { onError(it.message ?: it.toString()) }, - ) - } - } - }, - enabled = ready, - ) { Text(if (kind == SetupKind.Create) "Create" else "Import") } } + return@OwCard } - } -} - -/** - * The app-owned `monero-wallet-rpc` control (issue #107), now with the third chain - * source: the chain daemon **inside this app** (Cuprate). - * - * **Start** / **Stop** drive `Wire::start_wallet_child` / `stop_wallet_child` - * through [WireViewModel]; the status line is `Wire::wallet_status()` rendered - * verbatim, so a child that died reads `exited` and never `off`, and an in-process - * source grows a `node ` segment that is the core's own `node_state`. - * - * The card is deliberately talkative about what it *cannot* do: no bundled - * binary, no chain source, a `.onion` daemon with no bundled `arti` SOCKS child, - * or a build without `cuprate-daemon` each get their own sentence, because a Start - * button that can only fail is worse than no button. There is no "starting…" state - * to hide behind — the only spinner-free words on screen are the core's own. - * - * The on-device node is opt-in and carries its pre-production warning **above the - * Start button**, plus the free space on the filesystem its fjall store grows - * into. A device that cannot hold the chain is told before it commits, not left to - * fail at sync time. - */ -@Composable -private fun WalletChildCard( - bins: WalletChildBinaryPaths, - input: WalletChildInput?, - chain: ChainConfig?, - nodeFreeBytes: Long?, - actionError: String?, - daemonText: String, - daemonError: String?, - /** - * The core's `wallet_open` / `needs_passphrase`, straight off the same - * `WalletChildStatus` the status line is drawn from — not a second idea of - * which wallet is open. - */ - walletOpen: Boolean, - needsPassphrase: Boolean, - onDaemonText: (String) -> Unit, - onSaveDaemon: () -> Unit, - onReceiveOnly: () -> Unit, - onInProcessNode: (mainnet: Boolean, prune: Boolean) -> Unit, - starting: Boolean = false, - onStart: () -> Unit, - onStop: () -> Unit, -) { - val phase = walletChildPhase(input) - val node = nodePhase(input) - val onionDaemon = chain?.kind == ChainChoice.REMOTE && isOnionHost(chain.host) - // The selection is in-process as soon as it is stored, before the first status - // read comes back: the warning and the storage line must not wait for the - // poller, or the user would press Start having seen neither. - val inProcess = input?.chainInProcess == true || chain?.kind == ChainChoice.IN_PROCESS_CUPRATE - val startWhy = startBlockedReason(bins, input, onionDaemon, starting) - ?: if (inProcess) { - chainStorageBlockedReason( - nodeFreeBytes, - mainnet = chain?.mainnet == true, - prune = chain?.prune == true, - ) - } else { - null - } - val stopWhy = stopBlockedReason(input) - // A live child with no wallet file open answers every read with the daemon's - // own `-13 No wallet file`. Say that in this app's words, here, rather than - // letting the raw string arrive later on whichever card asked. - val openHint = walletChildOpenHint( - childRunning = input?.running == true, - walletOpen = walletOpen, - needsPassphrase = needsPassphrase, - ) - - Card( - modifier = Modifier - .fillMaxWidth() - .padding(horizontal = 12.dp, vertical = 8.dp), - colors = CardDefaults.cardColors( - containerColor = MaterialTheme.colorScheme.surfaceVariant, - ), - ) { - Column(Modifier.padding(12.dp)) { - Text("wallet daemon", style = MaterialTheme.typography.titleSmall) - Spacer(Modifier.height(6.dp)) - - // The core's own words: `ready · remote onion daemon`, plus - // `· node syncing` for the in-process source. Tagged with the phase so - // a UI test can assert `exited` is never `off`. + if (kind == SetupKind.Import) { Text( - walletChildLine(input), + "Paste the 25-word seed. Create does not need a key.", style = MaterialTheme.typography.bodySmall, - fontFamily = FontFamily.Monospace, - modifier = Modifier - .fillMaxWidth() - .testTag(phase.testTag) - .semantics(mergeDescendants = true) { - contentDescription = walletChildStatusDescription(input) - }, + color = OwColors.TextSecondary, ) - - // The node's own word, when there is one, as its own assertable line: - // an unrecognised node state can never be read as ready. - if (node !is NodePhase.Absent) { - Text( - "node: ${node.label}", - style = MaterialTheme.typography.labelSmall, - fontFamily = FontFamily.Monospace, - color = MaterialTheme.colorScheme.onSurfaceVariant, - modifier = Modifier - .fillMaxWidth() - .testTag(node.testTag) - .semantics(mergeDescendants = true) { - contentDescription = node.contentDescription - }, - ) - } - - if (!bins.walletRpcBundled) { - Spacer(Modifier.height(6.dp)) - Text( - NO_WALLET_RPC_MESSAGE, - style = MaterialTheme.typography.bodySmall, - color = MaterialTheme.colorScheme.error, - modifier = Modifier.fillMaxWidth(), - ) - } - - // "No wallet file open" is a state of a live child, not a failure of - // the last call, so it is said here rather than left to surface as - // the daemon's `-13` on whichever card asked for a read. - openHint?.let { - Spacer(Modifier.height(6.dp)) - Text( - it, - style = MaterialTheme.typography.bodySmall, - color = MaterialTheme.colorScheme.onSurfaceVariant, - modifier = Modifier - .fillMaxWidth() - .testTag("wallet-child-no-wallet"), - ) - } - - // What the user can fix from here: which daemon the child dials. Spacer(Modifier.height(8.dp)) OutlinedTextField( - value = daemonText, - onValueChange = onDaemonText, - singleLine = true, - label = { Text("daemon host:port") }, - supportingText = { - Text( - "A daemon on your LAN (e.g. 192.168.1.20:18089) or a public node's " + - "clearnet address. A phone cannot run monerod — for a chain with no " + - "daemon at all, use the on-device node below.", - style = MaterialTheme.typography.labelSmall, - ) - }, - modifier = Modifier - .fillMaxWidth() - .testTag("wallet-daemon-input"), - ) - Spacer(Modifier.height(4.dp)) - Row( + value = seed, + onValueChange = { seed = it }, + label = { Text("seed") }, modifier = Modifier.fillMaxWidth(), - horizontalArrangement = Arrangement.spacedBy(8.dp), - ) { - OutlinedButton( - onClick = onSaveDaemon, - enabled = bins.walletRpcBundled, - modifier = Modifier - .weight(1f) - .testTag("wallet-daemon-save"), - ) { Text("Save daemon") } - OutlinedButton( - onClick = onReceiveOnly, - modifier = Modifier - .weight(1f) - .testTag("wallet-daemon-receive-only"), - ) { Text("Receive-only") } - } - - // Tapping a mode stores it and, when the storage floor allows, - // starts the node. Filled = the stored choice. + ) Spacer(Modifier.height(8.dp)) - val mode = selectedCuprateMode( - inProcess = inProcess, - mainnet = chain?.mainnet == true, - prune = chain?.prune == true, - ) - CuprateModeButton( - label = "Mainnet pruned", - selected = mode == CuprateMode.MainnetPruned, - testTag = "wallet-chain-mainnet-pruned", - onClick = { onInProcessNode(true, true) }, - ) - Spacer(Modifier.height(4.dp)) - CuprateModeButton( - label = "Mainnet full", - selected = mode == CuprateMode.MainnetFull, - testTag = "wallet-chain-mainnet-full", - onClick = { onInProcessNode(true, false) }, - ) - Spacer(Modifier.height(4.dp)) - CuprateModeButton( - label = "Testnet (experimental)", - selected = mode == CuprateMode.Testnet, - testTag = "wallet-chain-in-process", - onClick = { onInProcessNode(false, false) }, - ) - - if (inProcess) { - Spacer(Modifier.height(8.dp)) - Text( - CUPRATE_PREPRODUCTION_WARNING, - style = MaterialTheme.typography.labelSmall, - color = MaterialTheme.colorScheme.onSurfaceVariant, - modifier = Modifier - .fillMaxWidth() - .testTag("wallet-cuprate-warning"), - ) - Spacer(Modifier.height(4.dp)) - Text( - chainStorageLine( - nodeFreeBytes, - mainnet = chain?.mainnet == true, - prune = chain?.prune == true, - ), - style = MaterialTheme.typography.labelSmall, - color = MaterialTheme.colorScheme.onSurfaceVariant, - modifier = Modifier - .fillMaxWidth() - .testTag("wallet-chain-storage"), - ) - } - - Spacer(Modifier.height(8.dp)) - Row( - modifier = Modifier.fillMaxWidth(), - horizontalArrangement = Arrangement.spacedBy(8.dp), - ) { - Button( - onClick = onStart, - enabled = startWhy == null, - modifier = Modifier - .weight(1f) - .testTag("wallet-child-start"), - ) { Text("Start wallet") } - OutlinedButton( - onClick = onStop, - enabled = stopWhy == null, - modifier = Modifier - .weight(1f) - .testTag("wallet-child-stop"), - ) { Text("Stop wallet") } - } - - // Why Start is dead, in the core's terms rather than a grey button. - startWhy?.let { - Spacer(Modifier.height(6.dp)) - Text( - it, - style = MaterialTheme.typography.labelSmall, - color = MaterialTheme.colorScheme.onSurfaceVariant, - modifier = Modifier - .fillMaxWidth() - .testTag("wallet-child-start-blocked"), - ) - } - - // The last thing the core or the RPC call said. Sticky until the - // user acts, like the chat screen's load error. Filtered through - // `walletFailureText`: the daemon's own `-13 No wallet file` / JSON - // answer is not a sentence about this app and never reaches the - // screen. - val failure = walletFailureText(input?.lastError) ?: actionError ?: daemonError - failure?.let { - Spacer(Modifier.height(6.dp)) - Text( - it, - style = MaterialTheme.typography.bodySmall, - color = MaterialTheme.colorScheme.error, - modifier = Modifier - .fillMaxWidth() - .testTag("wallet-child-error"), - ) - } } - } -} - -@Composable -private fun CuprateModeButton( - label: String, - selected: Boolean, - testTag: String, - onClick: () -> Unit, -) { - val modifier = Modifier - .fillMaxWidth() - .testTag(testTag) - if (selected) { - Button(onClick = onClick, modifier = modifier) { Text(label) } - } else { - OutlinedButton(onClick = onClick, modifier = modifier) { Text(label) } + OutlinedTextField( + value = password, + onValueChange = { password = it }, + singleLine = true, + label = { Text("wallet passphrase") }, + modifier = Modifier.fillMaxWidth(), + ) + Spacer(Modifier.height(12.dp)) + OwButtonRow { + OwButton( + text = "Cancel", + variant = OwButtonVariant.Outline, + onClick = onCancel, + modifier = Modifier.weight(1f), + ) + OwButton( + text = if (kind == SetupKind.Create) "Create" else "Import", + variant = OwButtonVariant.Primary, + enabled = ready, + onClick = { + scope.launch { + when (kind) { + SetupKind.Create -> create(password).fold( + onSuccess = onCreated, + onFailure = { onError(it.message ?: it.toString()) }, + ) + SetupKind.Import -> importWallet(password, seed.trim()).fold( + onSuccess = { onImported() }, + onFailure = { onError(it.message ?: it.toString()) }, + ) + } + } + }, + modifier = Modifier.weight(1f), + ) + } } } @@ -1149,7 +1335,7 @@ private fun CuprateModeButton( * `walletBalance()` returns the string `"err"` rather than throwing when it * cannot read, so a reload during `connecting` / `off` / `exited` is not a * no-op — it is what writes that `err` into the headline and leaves it stuck on - * `balance —` after the child comes up. + * `Balance unavailable` after the wallet comes up. */ internal fun shouldReloadWalletReads(state: String?): Boolean { val s = state?.trim()?.lowercase() @@ -1162,16 +1348,16 @@ internal fun shouldReloadWalletReads(state: String?): Boolean { * * `lastError` is the one field that is not verbatim. It is the core's * `wallet_status().last_error`, which is the *daemon's* own words on the path - * this screen exists for: a live child with no wallet open answers `-13 No - * wallet file`, and `parse_json_rpc` strips the envelope and keeps that bare - * sentence. A probe that dialled a port the child had not bound yet can also + * this screen exists for: a live wallet with no wallet file open answers `-13 + * No wallet file`, and `parse_json_rpc` strips the envelope and keeps that bare + * sentence. A probe that dialled a port the wallet had not bound yet can also * land here (`wallet connect: Connection refused`) — [displayLastError] drops - * that one while the child is still `connecting`. The status line renders this - * field — `walletChildLine`, and through it `walletChildStatusDescription` for - * the screen reader — so the filter belongs here, at the seam where the SDK - * record becomes the Kotlin model, rather than at one of the render sites. - * `walletFailureText` is idempotent on its own replacement texts, so the - * second pass on the sticky error card is stable. + * that one while the wallet is still `connecting`. The status header renders + * this field through `walletChildStatusDescription` for the screen reader — so + * the filter belongs here, at the seam where the SDK record becomes the Kotlin + * model, rather than at one of the render sites. `walletFailureText` is + * idempotent on its own replacement texts, so the second pass on the sticky + * error card is stable. */ internal fun WalletChildStatus.toInput(): WalletChildInput = WalletChildInput( state = state, diff --git a/android/app/src/main/java/com/siriusdevops/onionwire/ui/components/SegmentedControl.kt b/android/app/src/main/java/com/siriusdevops/onionwire/ui/components/SegmentedControl.kt index 11be548..c5f2f2b 100644 --- a/android/app/src/main/java/com/siriusdevops/onionwire/ui/components/SegmentedControl.kt +++ b/android/app/src/main/java/com/siriusdevops/onionwire/ui/components/SegmentedControl.kt @@ -17,6 +17,7 @@ import androidx.compose.runtime.getValue import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.draw.clip +import androidx.compose.ui.platform.testTag import androidx.compose.ui.semantics.Role import androidx.compose.ui.semantics.role import androidx.compose.ui.semantics.selected @@ -42,6 +43,14 @@ fun OwSegmentedControl( onSelect: (Int) -> Unit, modifier: Modifier = Modifier, enabled: Boolean = true, + /** + * Optional per-segment `testTag`s, one per option. Additive: omitted (the + * default) leaves every existing call site byte-identical. It exists because + * a merged "Pruned / Full / Testnet" track has no per-value handle otherwise, + * and the wallet screen's tests address each segment by the tag it had when + * the three options were three stacked buttons. + */ + testTags: List = emptyList(), ) { Row( modifier = modifier @@ -67,12 +76,14 @@ fun OwSegmentedControl( animationSpec = tween(durationMillis = 160), label = "segment-text", ) + val tag = testTags.getOrNull(index) Box( modifier = Modifier .weight(1f) .height(36.dp) .clip(RoundedCornerShape(9.dp)) .background(container) + .then(if (tag != null) Modifier.testTag(tag) else Modifier) .clickable(enabled = enabled && !selected) { onSelect(index) } .semantics { role = Role.Tab diff --git a/android/app/src/test/java/com/siriusdevops/onionwire/ui/WalletChildStatusTextTest.kt b/android/app/src/test/java/com/siriusdevops/onionwire/ui/WalletChildStatusTextTest.kt index aa92f6c..def027a 100644 --- a/android/app/src/test/java/com/siriusdevops/onionwire/ui/WalletChildStatusTextTest.kt +++ b/android/app/src/test/java/com/siriusdevops/onionwire/ui/WalletChildStatusTextTest.kt @@ -207,8 +207,8 @@ class WalletChildStatusTextTest { @Test fun stop_is_blocked_when_nothing_is_running() { - assertTrue(stopBlockedReason(input("off"))!!.contains("No wallet child")) - assertTrue(stopBlockedReason(input("exited"))!!.contains("No wallet child")) + assertTrue(stopBlockedReason(input("off"))!!.contains("No wallet is running")) + assertTrue(stopBlockedReason(input("exited"))!!.contains("No wallet is running")) assertEquals(READING_CHILD_NOTICE, stopBlockedReason(null)) } @@ -397,7 +397,7 @@ class WalletChildStatusTextTest { "a screen reader is told the same as the eye", spoken.endsWith(walletChildLine(input)), ) - assertTrue("it is still a sentence", spoken.startsWith("The wallet child is up")) + assertTrue("it is still a sentence", spoken.startsWith("The wallet is starting")) } @Test @@ -417,14 +417,17 @@ class WalletChildStatusTextTest { } @Test - fun the_preproduction_warning_is_a_sentence_a_user_can_act_on() { - val warning = CUPRATE_PREPRODUCTION_WARNING - assertTrue("it names the software", warning.contains("Cuprate")) - assertTrue("it quotes the user book", warning.contains("do NOT use cuprated")) - assertTrue("it names the parity gap", warning.contains("Cuprate issue #278")) - assertTrue("it says mainnet is unvalidated", warning.contains("mainnet is unvalidated")) - assertTrue("it is a sentence, not a glyph", warning.trim().endsWith(".")) - assertTrue("it is long enough to be a sentence", warning.length > 80) + fun the_on_device_banner_is_titled_and_says_what_it_costs() { + // The banner's title is the plan's exact string; the body keeps every + // honesty bound the old single-sentence warning carried. + assertEquals("Experimental On-Device Node (Cuprate)", CUPRATE_ON_DEVICE_TITLE) + val body = CUPRATE_ON_DEVICE_BODY + assertTrue("it names the software", body.contains("Cuprate")) + assertTrue("it names the parity gap", body.contains("#278")) + assertTrue("it quotes the user book", body.contains("do NOT use cuprated")) + assertTrue("it says mainnet is unvalidated", body.contains("Mainnet is unvalidated")) + assertTrue("it says not to hold funds", body.contains("Do not use for significant funds")) + assertTrue("it is a sentence, not a glyph", body.trim().endsWith(".")) } // --- storage honesty ---------------------------------------------------- @@ -519,4 +522,103 @@ class WalletChildStatusTextTest { assertEquals("1.5 GiB", formatBytes(3L * 1024 * 1024 * 1024 / 2)) assertEquals("3.0 GiB", formatBytes(CHAIN_FREE_SPACE_FLOOR_BYTES)) } + + // --- the node card's progress header (plan P4.3) ------------------------- + + @Test + fun block_counts_group_by_three_regardless_of_locale() { + assertEquals("0", formatBlockCount(0uL)) + assertEquals("999", formatBlockCount(999uL)) + assertEquals("1,000", formatBlockCount(1_000uL)) + assertEquals("485,253", formatBlockCount(485_253uL)) + assertEquals("3,794,383", formatBlockCount(3_794_383uL)) + assertEquals("12,345,678", formatBlockCount(12_345_678uL)) + } + + @Test + fun the_progress_header_says_percent_and_formatted_blocks() { + val p = syncProgress(485_253uL, 3_794_383uL) + assertEquals("12.8%", p.percentText) + assertEquals("Block 485,253 of 3,794,383", p.blockText) + assertTrue("a fraction of the track", p.fraction > 0.12f && p.fraction < 0.13f) + } + + @Test + fun a_caught_up_node_fills_the_track_and_does_not_overflow() { + val atTip = syncProgress(3_794_383uL, 3_794_383uL) + assertEquals("100.0%", atTip.percentText) + assertEquals(1f, atTip.fraction) + // A daemon one block ahead of the target it reported must not render + // 108% — the bar clamps and the text is the clamped number. + val ahead = syncProgress(4_100_000uL, 3_794_383uL) + assertEquals("100.0%", ahead.percentText) + assertEquals(1f, ahead.fraction) + } + + @Test + fun an_unknown_target_is_never_a_percentage() { + // `target_height == 0` is "the daemon reported no target" — Cuprate + // omits it even at the tip. Printing 100% there would claim synced. + val p = syncProgress(4_549uL, 0uL) + assertNull("no percent from a zero target", p.percentText) + assertEquals(0f, p.fraction) + assertEquals("Block 4,549 of an unknown target", p.blockText) + assertFalse("no percent string leaks", p.blockText!!.contains("%")) + } + + @Test + fun no_numbers_means_no_progress_row() { + val p = syncProgress(0uL, 0uL) + assertNull(p.percentText) + assertNull(p.blockText) + assertEquals(0f, p.fraction) + } + + @Test + fun the_three_modes_are_named_the_way_the_stored_choice_reads() { + assertEquals("Mainnet Pruned", chainModeLabel(mainnet = true, prune = true)) + assertEquals("Mainnet Full", chainModeLabel(mainnet = true, prune = false)) + assertEquals("Testnet", chainModeLabel(mainnet = false, prune = false)) + } + + @Test + fun the_node_header_never_reads_ready_without_the_cores_word() { + assertEquals("Wallet Offline", nodeStatusHead(input("off", configured = false)).title) + assertEquals("Connecting…", nodeStatusHead(input("connecting", running = true)).title) + assertEquals(NodeStatusTone.Busy, nodeStatusHead(input("connecting", running = true)).tone) + assertTrue( + "a running child that has not answered is not ready", + nodeStatusHead(input("connecting", running = true)).tone != NodeStatusTone.Good, + ) + assertEquals(NodeStatusTone.Good, nodeStatusHead(input("ready", running = true)).tone) + assertEquals(NodeStatusTone.Bad, nodeStatusHead(input("mining", running = true)).tone) + assertEquals( + "an unknown state is never green", + NodeStatusTone.Bad, + nodeStatusHead(input("mining", running = true)).tone, + ) + assertEquals("Wallet Stopped", nodeStatusHead(input("exited")).title) + assertEquals("Reading wallet status", nodeStatusHead(null).title) + } + + @Test + fun the_node_header_names_the_mode_only_for_the_on_device_node() { + assertEquals( + "Syncing Node (Mainnet Pruned)", + nodeStatusHead( + node(state = "syncing", chainSource = "in-process mainnet pruned", nodeState = "syncing"), + inProcess = true, + mainnet = true, + prune = true, + ).title, + ) + assertEquals( + "Node Idle (Testnet)", + nodeStatusHead(input("off", configured = false), inProcess = true, mainnet = false).title, + ) + assertEquals( + "Syncing Wallet", + nodeStatusHead(input("syncing", running = true, chainSource = "remote daemon")).title, + ) + } } From 0d0b0b975dc54881fb3a0274b65c0f22b66e39ee Mon Sep 17 00:00:00 2001 From: agent Date: Thu, 29 Oct 2026 01:01:45 -0400 Subject: [PATCH 11/19] ui: saved-wallets screen and profile copy on the shared components (plan P4.1) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The catalogue screen was still the alpha build: a TopAppBar with a text "Back" and a text "Refresh", eight hand-rolled Cards on Material's surfaceVariant, outlined twins for the two secret actions, and every failure — including "no wallet is open", which is a state the app is in, not a failure — printed as a raw red Text. It now uses the shared components: a chevron top bar, OwCard rows with an "In use" pill, and OwButton tiers. Copy, verbatim from the plan: "No wallet is open in the wallet child yet. Open a saved wallet on the Saved wallets screen, or create or import one here." -> "Select a saved wallet or create a new one to view your balance and transact." "No wallet is open in the wallet child yet. Open one from the list below — a wallet that needs a passphrase asks for it here — and the balance, address and backups work again." -> "Open or create a wallet to enable balance, address, and backup controls." WALLET_NOT_OPEN_TEXT is now rendered as an info banner with its own title, not as an error; ErrorText picks the variant from the text, so the same string cannot read as a crash on one screen and a state on the other. The "no wallet open" hint, the passphrase prompt's blocked reasons and its "wallet is not running" line, and the catalogue/keys failures are banners too. The two remaining user-facing mentions of the daemon process are gone: the passphrase card says "the wallet is pointed at " and the secrets block reason says "the wallet is not running". ProfileScreen's empty-address notice loses its copy of the same phrase ("then comes from the running wallet"), and its test now asserts the consequence instead of the internal name. No behaviour change: every predicate (walletSecretsEnabled, walletPassphraseSubmitEnabled, walletChildReadable, walletFailureText, displayLastError) is the same function with the same branches; only strings and layout moved. The four WalletManagerTest assertions that pinned the old strings are updated here, in the same commit, as the card requires. --- .../onionwire/ui/ProfileScreen.kt | 8 +- .../onionwire/ui/WalletManagerScreen.kt | 510 +++++++++--------- .../onionwire/ui/ProfileDraftTest.kt | 4 +- .../onionwire/ui/WalletManagerTest.kt | 15 +- 4 files changed, 272 insertions(+), 265 deletions(-) diff --git a/android/app/src/main/java/com/siriusdevops/onionwire/ui/ProfileScreen.kt b/android/app/src/main/java/com/siriusdevops/onionwire/ui/ProfileScreen.kt index a0e3243..5ef799d 100644 --- a/android/app/src/main/java/com/siriusdevops/onionwire/ui/ProfileScreen.kt +++ b/android/app/src/main/java/com/siriusdevops/onionwire/ui/ProfileScreen.kt @@ -56,7 +56,7 @@ import uniffi.onionwire_sdk.checkAddress * 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 + * address and no running wallet 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 @@ -211,7 +211,7 @@ fun ProfileScreen( supportingText = { Text( // The consequence, on the screen, before a payment fails: - // `Node::wallet_receive_address` uses the wallet child's + // `Node::wallet_receive_address` uses the wallet process's // subaddress while it is up and this address otherwise, // and with neither there is nothing to be paid to. profileAddressNotice(form.address), @@ -437,7 +437,7 @@ 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 + * `Node::wallet_receive_address` answers with the wallet process'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. @@ -445,7 +445,7 @@ internal const val PROFILE_SAVED: String = "profile saved" 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 " + + "then comes from the running wallet — 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 " + diff --git a/android/app/src/main/java/com/siriusdevops/onionwire/ui/WalletManagerScreen.kt b/android/app/src/main/java/com/siriusdevops/onionwire/ui/WalletManagerScreen.kt index ac5e5b9..68884be 100644 --- a/android/app/src/main/java/com/siriusdevops/onionwire/ui/WalletManagerScreen.kt +++ b/android/app/src/main/java/com/siriusdevops/onionwire/ui/WalletManagerScreen.kt @@ -14,20 +14,13 @@ import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.height import androidx.compose.foundation.layout.padding +import androidx.compose.foundation.layout.width 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.OutlinedButton 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.DisposableEffect import androidx.compose.runtime.LaunchedEffect @@ -40,11 +33,21 @@ import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.platform.LocalView import androidx.compose.ui.platform.testTag -import androidx.compose.ui.text.font.FontFamily import androidx.compose.ui.text.input.PasswordVisualTransformation import androidx.compose.ui.unit.dp import androidx.lifecycle.compose.collectAsStateWithLifecycle import com.siriusdevops.onionwire.WireViewModel +import com.siriusdevops.onionwire.ui.components.Label +import com.siriusdevops.onionwire.ui.components.Mono +import com.siriusdevops.onionwire.ui.components.OwAlertBanner +import com.siriusdevops.onionwire.ui.components.OwAlertVariant +import com.siriusdevops.onionwire.ui.components.OwButton +import com.siriusdevops.onionwire.ui.components.OwButtonRow +import com.siriusdevops.onionwire.ui.components.OwButtonVariant +import com.siriusdevops.onionwire.ui.components.OwCard +import com.siriusdevops.onionwire.ui.components.OwPill +import com.siriusdevops.onionwire.ui.components.OwSectionTitle +import com.siriusdevops.onionwire.ui.components.OwTopBar import kotlinx.coroutines.launch import uniffi.onionwire_sdk.WalletKeys import uniffi.onionwire_sdk.WalletRow @@ -83,7 +86,7 @@ internal fun walletRowDate(createdAt: Long): String { } /** - * Whether the wallet child has a wallet open that the RPC answers for. + * Whether the wallet process has a wallet open that the RPC answers for. * * The core's `state` is the only honest signal available here: `connecting` * means its wallet RPC has not answered, `off`/`exited` mean there is no child @@ -126,8 +129,8 @@ internal fun walletSecretsBlockedReason( isActive: Boolean, walletReadable: Boolean, ): String? = when { - !isActive -> "open this wallet to view its backup" - !walletReadable -> "the wallet child is not running — start it on the wallet screen to read the backup" + !isActive -> "Open this wallet to view its backup." + !walletReadable -> "The wallet is not running — start it on the wallet screen to read the backup." else -> null } @@ -159,14 +162,18 @@ private val RAW_RPC_CODE = Regex("""(? - "the wallet child is not pointed at a wallet file yet — open one from the list below" - typed.isEmpty() -> "type the passphrase for this wallet file" + "No wallet file is open yet — open one from the list below." + typed.isEmpty() -> "Type the passphrase for this wallet file." else -> null } /** - * Why the wallet child has nothing open, in this app's words — or `null` when - * it has a wallet open, or no child is running to hold one. + * Why the wallet process has nothing open, in this app's words — or `null` when + * it has a wallet open, or nothing is running to hold one. * * A live `monero-wallet-rpc` is not a usable wallet: it starts with no wallet * file open, and every read then answers `-13 No wallet file`. The status line @@ -294,11 +301,10 @@ internal fun walletChildOpenHint( ): String? = when { !childRunning || walletOpen -> null needsPassphrase -> - "No wallet is open in the wallet child: it needs the passphrase for the file it is " + - "pointed at. Open it on the Saved wallets screen, where the prompt is." + "The wallet needs its passphrase: open it on the Saved wallets screen, where the " + + "prompt is." else -> - "No wallet is open in the wallet child yet. Open a saved wallet on the Saved wallets " + - "screen, or create or import one here." + "Select a saved wallet or create a new one to view your balance and transact." } /** @@ -319,7 +325,6 @@ internal fun walletChildOpenHint( * in saved state (`remember`, not `rememberSaveable`, and cleared on * dispose). */ -@OptIn(ExperimentalMaterial3Api::class) @Composable fun WalletManagerScreen( vm: WireViewModel, @@ -503,25 +508,24 @@ fun WalletManagerScreen( // Root owns systemBars ∪ ime, exactly as the wallet screen does (see // `screenContentInsets`). contentWindowInsets = WindowInsets(0, 0, 0, 0), + containerColor = OwColors.Canvas, topBar = { - TopAppBar( - title = { Text("Saved wallets") }, - navigationIcon = { - TextButton(onClick = onBack) { Text("Back") } - }, + OwTopBar( + title = "Saved wallets", + // A pushed sub-screen, so the chevron — never the word "Back". + onBack = onBack, actions = { - TextButton( + OwButton( + text = "Refresh", + variant = OwButtonVariant.Outline, onClick = { scope.launch { vm.refreshWalletChild() reload() } }, - ) { Text("Refresh") } + ) }, - colors = TopAppBarDefaults.topAppBarColors( - containerColor = MaterialTheme.colorScheme.background, - ), ) }, ) { pad -> @@ -559,22 +563,21 @@ fun WalletManagerScreen( ) } keysError?.let { message -> - Card( + OwAlertBanner( + variant = OwAlertVariant.Error, + title = "Could not read the open wallet's private keys", + description = message, modifier = Modifier - .fillMaxWidth() - .padding(horizontal = 12.dp, vertical = 8.dp), - colors = CardDefaults.cardColors( - containerColor = MaterialTheme.colorScheme.errorContainer, - ), - ) { - Column(Modifier.padding(12.dp)) { - Text("could not read the open wallet's private keys") - Spacer(Modifier.height(4.dp)) - Text(message, style = MaterialTheme.typography.bodySmall) - Spacer(Modifier.height(8.dp)) - TextButton(onClick = { keysError = null }) { Text("Dismiss") } - } - } + .padding(horizontal = 16.dp, vertical = 8.dp) + .testTag("wallet-keys-error"), + action = { + OwButton( + text = "Dismiss", + variant = OwButtonVariant.Outline, + onClick = { keysError = null }, + ) + }, + ) } actionError?.let { ErrorText(it) } @@ -608,46 +611,55 @@ fun WalletManagerScreen( // A read failure is not an empty catalogue, and the two must // not read alike: one is "the store did not answer", the other // is "you have no wallets yet". - listError != null -> Column(Modifier.padding(12.dp)) { - Text( - "could not read the wallet catalogue", - style = MaterialTheme.typography.titleSmall, - color = MaterialTheme.colorScheme.error, - ) - Spacer(Modifier.height(4.dp)) - Text( - listError ?: "", - style = MaterialTheme.typography.bodySmall, - color = MaterialTheme.colorScheme.error, - ) - Spacer(Modifier.height(8.dp)) - TextButton(onClick = { scope.launch { reload() } }) { Text("Retry") } - } - - listed == null -> Text( - "loading…", - style = MaterialTheme.typography.bodyMedium, - modifier = Modifier.padding(12.dp), + listError != null -> OwAlertBanner( + variant = OwAlertVariant.Error, + title = "Could not read the wallet catalogue", + description = listError ?: "", + modifier = Modifier + .padding(horizontal = 16.dp, vertical = 8.dp) + .testTag("wallet-list-error"), + action = { + OwButton( + text = "Retry", + variant = OwButtonVariant.Outline, + onClick = { scope.launch { reload() } }, + ) + }, ) - listed.isEmpty() -> Column(Modifier.padding(12.dp)) { - Text("No saved wallets yet", style = MaterialTheme.typography.titleSmall) - Spacer(Modifier.height(4.dp)) + listed == null -> Text( + "Loading…", + style = MaterialTheme.typography.bodyMedium, + color = OwColors.TextSecondary, + modifier = Modifier.padding(horizontal = 16.dp, vertical = 8.dp), + ) + + listed.isEmpty() -> OwCard( + modifier = Modifier + .fillMaxWidth() + .padding(horizontal = 16.dp, vertical = 8.dp), + ) { + OwSectionTitle("No saved wallets yet") + Spacer(Modifier.height(6.dp)) Text( "Wallets this install remembers show up here. Create or import one " + "on the wallet screen and it appears on the next look.", style = MaterialTheme.typography.bodySmall, + color = OwColors.TextSecondary, + ) + Spacer(Modifier.height(12.dp)) + OwButton( + text = "Create or import a wallet", + variant = OwButtonVariant.Primary, + onClick = onBack, + modifier = Modifier.fillMaxWidth(), ) - Spacer(Modifier.height(8.dp)) - Button(onClick = onBack) { Text("Create or import a wallet") } } else -> { - Text( - "${listed.size} saved ${if (listed.size == 1) "wallet" else "wallets"}", - style = MaterialTheme.typography.labelSmall, - color = MaterialTheme.colorScheme.onSurfaceVariant, - modifier = Modifier.padding(horizontal = 12.dp, vertical = 4.dp), + Label( + "${listed.size} SAVED ${if (listed.size == 1) "WALLET" else "WALLETS"}", + modifier = Modifier.padding(horizontal = 16.dp, vertical = 8.dp), ) listed.forEach { row -> val isActive = active != null && active == row.walletFilename @@ -680,7 +692,7 @@ fun WalletManagerScreen( * and whether it is the open one. * * The open row is not tappable. Re-opening it would stop and restart a running - * wallet child onto the file it already has open — a slow no-op whose only + * wallet process onto the file it already has open — a slow no-op whose only * effect is to make the screen look like it did something. */ @Composable @@ -694,72 +706,70 @@ private fun WalletRowCard( onShowPhrase: () -> Unit, onShowKeys: () -> Unit, ) { - Card( + OwCard( modifier = Modifier .fillMaxWidth() - .padding(horizontal = 12.dp, vertical = 6.dp) + .padding(horizontal = 16.dp, vertical = 6.dp) .then(if (isActive) Modifier else Modifier.clickable(enabled = !opening, onClick = onOpen)), - colors = CardDefaults.cardColors( - containerColor = MaterialTheme.colorScheme.surfaceVariant, - ), ) { - Column(Modifier.padding(12.dp)) { - Row( - Modifier.fillMaxWidth(), - horizontalArrangement = Arrangement.SpaceBetween, - verticalAlignment = Alignment.CenterVertically, - ) { - Text( - walletRowLabel(row.name, row.walletFilename), - style = MaterialTheme.typography.titleSmall, + Row( + Modifier.fillMaxWidth(), + horizontalArrangement = Arrangement.SpaceBetween, + verticalAlignment = Alignment.CenterVertically, + ) { + Text( + walletRowLabel(row.name, row.walletFilename), + style = MaterialTheme.typography.titleMedium, + color = OwColors.TextPrimary, + modifier = Modifier.weight(1f), + ) + Spacer(Modifier.width(8.dp)) + when { + isActive -> OwPill( + text = "In use", + textColor = OwColors.Accent, + container = OwColors.InfoTint, + borderColor = OwColors.InfoBorder, + dotColor = OwColors.Accent, ) - when { - isActive -> Text( - "in use", - style = MaterialTheme.typography.labelSmall, - color = MaterialTheme.colorScheme.primary, - ) - opening -> Text( - "opening…", - style = MaterialTheme.typography.labelSmall, - color = MaterialTheme.colorScheme.onSurfaceVariant, - ) - else -> Text( - "tap to open", - style = MaterialTheme.typography.labelSmall, - color = MaterialTheme.colorScheme.onSurfaceVariant, - ) - } + opening -> OwPill(text = "Opening…", textColor = OwColors.TextSecondary) + else -> OwPill(text = "Tap to open", textColor = OwColors.TextSecondary) } - Spacer(Modifier.height(4.dp)) - Text( - "file ${row.walletFilename}", - style = MaterialTheme.typography.bodySmall, - fontFamily = FontFamily.Monospace, - ) - Text( - "created ${walletRowDate(row.createdAt)}", - style = MaterialTheme.typography.bodySmall, - color = MaterialTheme.colorScheme.onSurfaceVariant, - ) + } + Spacer(Modifier.height(8.dp)) + Label("FILE") + Mono(row.walletFilename) + Spacer(Modifier.height(4.dp)) + Text( + "Created ${walletRowDate(row.createdAt)}", + style = MaterialTheme.typography.bodySmall, + color = OwColors.TextSecondary, + ) - Spacer(Modifier.height(8.dp)) - Row(horizontalArrangement = Arrangement.spacedBy(8.dp)) { - OutlinedButton(onClick = onShowPhrase, enabled = secretsEnabled) { - Text("Recovery phrase") - } - OutlinedButton(onClick = onShowKeys, enabled = secretsEnabled) { - Text("Private keys") - } - } - blockedReason?.let { - Spacer(Modifier.height(4.dp)) - Text( - it, - style = MaterialTheme.typography.labelSmall, - color = MaterialTheme.colorScheme.onSurfaceVariant, - ) - } + Spacer(Modifier.height(10.dp)) + OwButtonRow { + OwButton( + text = "Recovery phrase", + variant = OwButtonVariant.Outline, + enabled = secretsEnabled, + onClick = onShowPhrase, + modifier = Modifier.weight(1f), + ) + OwButton( + text = "Private keys", + variant = OwButtonVariant.Outline, + enabled = secretsEnabled, + onClick = onShowKeys, + modifier = Modifier.weight(1f), + ) + } + blockedReason?.let { + Spacer(Modifier.height(6.dp)) + Text( + it, + style = MaterialTheme.typography.labelSmall, + color = OwColors.TextMuted, + ) } } } @@ -774,10 +784,10 @@ private fun WalletRowCard( * wallet file. It is never logged, never persisted, and the caller drops it when * the screen goes. * - * Submit is dead while the wallet child is not running: the core verifies a + * Submit is dead while the wallet is not running: the core verifies a * passphrase against a live daemon and refuses to seal an unverified one, so a - * tap there could only fail. When the child *is* up — including `connecting`, - * whose RPC has not answered yet — the core restarts it onto the file with this + * tap there could only fail. When it *is* up — including `connecting`, whose RPC + * has not answered yet — the core restarts it onto the file with this * passphrase, which is exactly the fix. */ @Composable @@ -791,77 +801,74 @@ private fun WalletPassphraseCard( error: String?, onSubmit: () -> Unit, ) { - Card( + OwCard( modifier = Modifier .fillMaxWidth() - .padding(horizontal = 12.dp, vertical = 8.dp) + .padding(horizontal = 16.dp, vertical = 8.dp) .testTag("wallet-passphrase-card"), - colors = CardDefaults.cardColors( - containerColor = MaterialTheme.colorScheme.surfaceVariant, - ), ) { - Column(Modifier.padding(12.dp)) { - Text("This wallet needs its passphrase", style = MaterialTheme.typography.titleSmall) - Spacer(Modifier.height(4.dp)) - Text( - "The wallet child is pointed at ${filename ?: "a wallet file"} but this install " + - "holds no passphrase that opens it — the wallet was created before the " + - "passphrase was stored, or on another device. Type it once: the wallet " + - "opens, and later starts reopen it on their own.", - style = MaterialTheme.typography.bodySmall, - ) + OwSectionTitle("This wallet needs its passphrase") + Spacer(Modifier.height(6.dp)) + Text( + "The wallet is pointed at ${filename ?: "a wallet file"} but this install " + + "holds no passphrase that opens it — the wallet was created before the " + + "passphrase was stored, or on another device. Type it once: the wallet " + + "opens, and later starts reopen it on their own.", + style = MaterialTheme.typography.bodySmall, + color = OwColors.TextSecondary, + ) + Spacer(Modifier.height(12.dp)) + OutlinedTextField( + value = typed, + onValueChange = onTyped, + singleLine = true, + // Masked on screen: this string opens a spend-capable wallet. + visualTransformation = PasswordVisualTransformation(), + label = { Text("wallet passphrase") }, + modifier = Modifier + .fillMaxWidth() + .testTag("wallet-passphrase-input"), + ) + Spacer(Modifier.height(6.dp)) + Text( + "Never copied to the clipboard, never logged, and dropped when you leave this screen.", + style = MaterialTheme.typography.labelSmall, + color = OwColors.TextSecondary, + ) + if (!childRunning) { Spacer(Modifier.height(8.dp)) - OutlinedTextField( - value = typed, - onValueChange = onTyped, - singleLine = true, - // Masked on screen: this string opens a spend-capable wallet. - visualTransformation = PasswordVisualTransformation(), - label = { Text("wallet passphrase") }, - modifier = Modifier - .fillMaxWidth() - .testTag("wallet-passphrase-input"), + OwAlertBanner( + variant = OwAlertVariant.Info, + title = "The wallet is not running", + description = "Start it on the wallet screen, then come back.", ) - Spacer(Modifier.height(4.dp)) - Text( - "Never copied to the clipboard, never logged, and dropped when you leave this screen.", - style = MaterialTheme.typography.labelSmall, - color = MaterialTheme.colorScheme.onSurfaceVariant, - ) - if (!childRunning) { - Spacer(Modifier.height(4.dp)) - Text( - "the wallet child is not running — start it on the wallet screen, then come back", - style = MaterialTheme.typography.labelSmall, - color = MaterialTheme.colorScheme.onSurfaceVariant, - ) - } - error?.let { - Spacer(Modifier.height(6.dp)) - Text( - it, - style = MaterialTheme.typography.bodySmall, - color = MaterialTheme.colorScheme.error, - ) - } - blockedReason?.let { - Spacer(Modifier.height(4.dp)) - Text( - it, - style = MaterialTheme.typography.labelSmall, - color = MaterialTheme.colorScheme.onSurfaceVariant, - ) - } - Spacer(Modifier.height(8.dp)) - Row(Modifier.fillMaxWidth(), horizontalArrangement = Arrangement.End) { - Button( - onClick = onSubmit, - enabled = childRunning && - walletPassphraseSubmitEnabled(filename, typed, inFlight), - modifier = Modifier.testTag("wallet-passphrase-submit"), - ) { Text(if (inFlight) "Opening…" else "Open this wallet") } - } } + error?.let { + Spacer(Modifier.height(8.dp)) + OwAlertBanner( + variant = OwAlertVariant.Error, + title = "Could not open this wallet", + description = it, + ) + } + blockedReason?.let { + Spacer(Modifier.height(8.dp)) + OwAlertBanner( + variant = OwAlertVariant.Info, + title = "Not ready to open", + description = it, + ) + } + Spacer(Modifier.height(12.dp)) + OwButton( + text = if (inFlight) "Opening…" else "Open this wallet", + variant = OwButtonVariant.Primary, + enabled = childRunning && walletPassphraseSubmitEnabled(filename, typed, inFlight), + onClick = onSubmit, + modifier = Modifier + .fillMaxWidth() + .testTag("wallet-passphrase-submit"), + ) } } @@ -880,64 +887,57 @@ private fun PrivateKeysCard( warning: String, onDone: () -> Unit, ) { - Card( + OwCard( modifier = Modifier .fillMaxWidth() - .padding(horizontal = 12.dp, vertical = 8.dp), - colors = CardDefaults.cardColors( - containerColor = MaterialTheme.colorScheme.errorContainer, - ), + .padding(horizontal = 16.dp, vertical = 8.dp) + .testTag("wallet-private-keys-card"), ) { - Column(Modifier.padding(12.dp)) { - Text("Private keys of the open wallet", style = MaterialTheme.typography.titleSmall) - Spacer(Modifier.height(4.dp)) - Text(warning, style = MaterialTheme.typography.bodySmall) - Spacer(Modifier.height(8.dp)) + OwSectionTitle("Private keys of the open wallet") + Spacer(Modifier.height(6.dp)) + Text(warning, style = MaterialTheme.typography.bodySmall, color = OwColors.Danger) + Spacer(Modifier.height(12.dp)) + Label("VIEW KEY") + // Mono, and deliberately no testTag: a handle on a spend secret is a + // handle an automation can read back. + Mono(keys.viewKey, modifier = Modifier.fillMaxWidth()) + Spacer(Modifier.height(10.dp)) + val spend = keys.spendKey + if (spend != null) { + Label("SPEND KEY") + Mono(spend, modifier = Modifier.fillMaxWidth()) + } else { Text( - "view key", - style = MaterialTheme.typography.labelSmall, - color = MaterialTheme.colorScheme.onSurfaceVariant, + "View-only wallet — no spend key.", + style = MaterialTheme.typography.bodyMedium, + color = OwColors.TextSecondary, ) - Text( - keys.viewKey, - style = MaterialTheme.typography.bodySmall, - fontFamily = FontFamily.Monospace, - ) - Spacer(Modifier.height(8.dp)) - val spend = keys.spendKey - if (spend != null) { - Text( - "spend key", - style = MaterialTheme.typography.labelSmall, - color = MaterialTheme.colorScheme.onSurfaceVariant, - ) - Text( - spend, - style = MaterialTheme.typography.bodySmall, - fontFamily = FontFamily.Monospace, - ) - } else { - Text( - "view-only wallet — no spend key", - style = MaterialTheme.typography.bodyMedium, - ) - } - Spacer(Modifier.height(8.dp)) - Row(Modifier.fillMaxWidth(), horizontalArrangement = Arrangement.End) { - Button(onClick = onDone) { Text("Done") } - } } + Spacer(Modifier.height(12.dp)) + OwButton( + text = "Done", + variant = OwButtonVariant.Outline, + onClick = onDone, + modifier = Modifier.fillMaxWidth(), + ) } } -/** A display-ready failure line. Never carries a secret; callers pass errors. */ +/** + * A display-ready failure line, as a banner. Never carries a secret; callers + * pass errors. + * + * "No wallet is open" is not a failure — it is a state the app is in, and it + * gets the info banner and its own title. Only a real refusal is red. + */ @Composable private fun ErrorText(text: String) { - Text( - text, - style = MaterialTheme.typography.bodySmall, - color = MaterialTheme.colorScheme.error, - modifier = Modifier.padding(horizontal = 12.dp, vertical = 4.dp), + val notOpen = text == WALLET_NOT_OPEN_TEXT + OwAlertBanner( + variant = if (notOpen) OwAlertVariant.Info else OwAlertVariant.Error, + title = if (notOpen) "No wallet open" else "Something went wrong", + description = text, + modifier = Modifier.padding(horizontal = 16.dp, vertical = 8.dp), ) } diff --git a/android/app/src/test/java/com/siriusdevops/onionwire/ui/ProfileDraftTest.kt b/android/app/src/test/java/com/siriusdevops/onionwire/ui/ProfileDraftTest.kt index f112b91..aa7f9b2 100644 --- a/android/app/src/test/java/com/siriusdevops/onionwire/ui/ProfileDraftTest.kt +++ b/android/app/src/test/java/com/siriusdevops/onionwire/ui/ProfileDraftTest.kt @@ -239,7 +239,9 @@ class ProfileDraftTest { fun an_empty_address_says_nobody_can_pay() { val text = profileAddressNotice("") assertTrue(text.contains("clears the profile address")) - assertTrue(text.contains("wallet child")) + // The consequence, not the process name: the copy no longer says + // "wallet child" anywhere a user can read it. + assertTrue(text.contains("running wallet")) assertTrue(text.contains("nobody can send you an invoice")) } diff --git a/android/app/src/test/java/com/siriusdevops/onionwire/ui/WalletManagerTest.kt b/android/app/src/test/java/com/siriusdevops/onionwire/ui/WalletManagerTest.kt index 7fc60c9..fac959d 100644 --- a/android/app/src/test/java/com/siriusdevops/onionwire/ui/WalletManagerTest.kt +++ b/android/app/src/test/java/com/siriusdevops/onionwire/ui/WalletManagerTest.kt @@ -117,7 +117,7 @@ class WalletManagerTest { @Test fun a_row_that_is_not_open_says_to_open_it() { val why = walletSecretsBlockedReason(isActive = false, walletReadable = readable) - assertEquals("open this wallet to view its backup", why) + assertEquals("Open this wallet to view its backup.", why) } @Test @@ -212,7 +212,7 @@ class WalletManagerTest { walletPassphraseSubmitEnabled(activeFilename = null, typed = "pw", inFlight = false), ) val why = walletPassphraseBlockedReason(activeFilename = null, typed = "pw") - assertTrue("got '$why'", why != null && why.contains("not pointed at")) + assertTrue("got '$why'", why != null && why.contains("No wallet file is open yet")) // The two reasons are different fixes and must not read alike. assertFalse(why == walletPassphraseBlockedReason(activeFilename = openFile, typed = "")) } @@ -225,7 +225,7 @@ class WalletManagerTest { @Test fun nothing_typed_is_the_other_reason() { val why = walletPassphraseBlockedReason(activeFilename = openFile, typed = "") - assertTrue("got '$why'", why != null && why.contains("type the passphrase")) + assertTrue("got '$why'", why != null && why.contains("Type the passphrase")) } // --- the daemon's own words never reach the screen ----------------------- @@ -348,7 +348,12 @@ class WalletManagerTest { walletOpen = false, needsPassphrase = false, ) - assertTrue("got '$hint'", hint != null && hint.contains("No wallet is open")) + // The §4.1 replacement copy, verbatim: a live wallet with no file open + // is a state, not an error. + assertEquals( + "Select a saved wallet or create a new one to view your balance and transact.", + hint, + ) assertNoRawRpc(hint!!) } @@ -463,7 +468,7 @@ class WalletManagerTest { fun wallet_reads_reload_only_once_the_child_is_answering() { // `walletBalance()` answers `"err"` — it does not throw — while the // child is still dialling, so reloading in that window is what pins the - // headline on `balance —`. Reload only when the child has answered. + // headline on `Balance unavailable`. Reload only when the child has answered. assertFalse(shouldReloadWalletReads(null)) assertFalse(shouldReloadWalletReads("off")) assertFalse(shouldReloadWalletReads("connecting")) From ef149ac496ad1abab6223026dde6cc876e592a94 Mon Sep 17 00:00:00 2001 From: agent Date: Thu, 29 Oct 2026 01:02:59 -0400 Subject: [PATCH 12/19] ui: one door to the saved-wallet catalogue The wallet tab was carrying "Saved wallets" twice: once as a top-bar action (the alpha screen's "Wallets" text link, which I kept when I moved the screen onto OwTopBar) and once in the hero card's header, where the plan puts it. Two controls that do the same thing on one page is how a screen starts to look unfinished. The hero header keeps it; the top bar is a title and nothing else. --- .../siriusdevops/onionwire/ui/WalletScreen.kt | 17 ++++------------- 1 file changed, 4 insertions(+), 13 deletions(-) diff --git a/android/app/src/main/java/com/siriusdevops/onionwire/ui/WalletScreen.kt b/android/app/src/main/java/com/siriusdevops/onionwire/ui/WalletScreen.kt index 448e8bd..cfd0dee 100644 --- a/android/app/src/main/java/com/siriusdevops/onionwire/ui/WalletScreen.kt +++ b/android/app/src/main/java/com/siriusdevops/onionwire/ui/WalletScreen.kt @@ -214,19 +214,10 @@ fun WalletScreen( contentWindowInsets = WindowInsets(0, 0, 0, 0), containerColor = OwColors.Canvas, topBar = { - OwTopBar( - title = "Wallet", - // The saved-wallet catalogue is its own screen: this one is the - // open wallet, and switching wallets restarts the wallet - // process, so the picker does not belong in this page's scroll. - actions = { - OwButton( - text = "Saved wallets", - variant = OwButtonVariant.Outline, - onClick = onOpenWallets, - ) - }, - ) + // No actions: the catalogue's entry point is in the hero card's + // header, where the plan puts it. A second "Saved wallets" button + // here would be two doors to one screen on the same page. + OwTopBar(title = "Wallet") }, ) { pad -> Column( From 9b3a0ad177764da4c36fe20a6680fce14f36e6b9 Mon Sep 17 00:00:00 2001 From: agent Date: Thu, 29 Oct 2026 01:03:51 -0400 Subject: [PATCH 13/19] ui: drop two imports the wallet screen no longer uses --- .../src/main/java/com/siriusdevops/onionwire/ui/WalletScreen.kt | 2 -- 1 file changed, 2 deletions(-) diff --git a/android/app/src/main/java/com/siriusdevops/onionwire/ui/WalletScreen.kt b/android/app/src/main/java/com/siriusdevops/onionwire/ui/WalletScreen.kt index cfd0dee..67c2f29 100644 --- a/android/app/src/main/java/com/siriusdevops/onionwire/ui/WalletScreen.kt +++ b/android/app/src/main/java/com/siriusdevops/onionwire/ui/WalletScreen.kt @@ -16,7 +16,6 @@ import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.height import androidx.compose.foundation.layout.padding -import androidx.compose.foundation.layout.size import androidx.compose.foundation.layout.width import androidx.compose.foundation.rememberScrollState import androidx.compose.foundation.shape.RoundedCornerShape @@ -42,7 +41,6 @@ import androidx.compose.ui.layout.ContentScale import androidx.compose.ui.platform.testTag import androidx.compose.ui.semantics.contentDescription import androidx.compose.ui.semantics.semantics -import androidx.compose.ui.text.font.FontWeight import androidx.compose.ui.text.style.TextAlign import androidx.compose.ui.unit.dp import androidx.compose.ui.unit.sp From 6216475b13b260c6ee99ca2612e9804047522f10 Mon Sep 17 00:00:00 2001 From: sirius Date: Fri, 30 Oct 2026 23:04:43 -0400 Subject: [PATCH 14/19] docs: point the docs at v0.7.0, and name the Android UI overhaul The README and VERIFY.md pinned downloads to v0.5.0 while v0.6.0 had already shipped, so every documented asset URL was two versions stale. A release tags the default-branch tip, so the fix has to land before the cut, not after. Also one sentence on the Android section: the APK's UI is now a design-token system with a three-tab shell, which android/README.md documents in detail. --- README.md | 20 +++++++++++--------- docs/VERIFY.md | 6 +++--- 2 files changed, 14 insertions(+), 12 deletions(-) diff --git a/README.md b/README.md index e28c3a2..8061fde 100644 --- a/README.md +++ b/README.md @@ -3,7 +3,7 @@ Lean Tor messenger: one Rust process (ratatui + Noise IK + sqlite + in-process Arti). No hosted server. Identity is an ed25519 public key; the onion is only a locator. -Current tagged release: **v0.5.0**. Linux TUI + Android SDK/APK. Two people add +Current tagged release: **v0.7.0**. Linux TUI + Android SDK/APK. Two people add each other with an `onionwire:v2:…` invite string (`F2` share / `F3` paste; ~1.9 KB because it carries an ML-KEM-768 key). There is no invite QR graphic. Chat is Noise IK over your own v3 onion; when the friend was added from a v2 @@ -61,8 +61,8 @@ resulting hash) next to its `.sha256`. **x86_64:** ```bash -curl -fL -O https://forgejo.siriusdevops.com/sirius/onionwire/releases/download/v0.5.0/onionwire-x86_64-unknown-linux-gnu -curl -fL -O https://forgejo.siriusdevops.com/sirius/onionwire/releases/download/v0.5.0/onionwire-x86_64-unknown-linux-gnu.sha256 +curl -fL -O https://forgejo.siriusdevops.com/sirius/onionwire/releases/download/v0.7.0/onionwire-x86_64-unknown-linux-gnu +curl -fL -O https://forgejo.siriusdevops.com/sirius/onionwire/releases/download/v0.7.0/onionwire-x86_64-unknown-linux-gnu.sha256 sha256sum -c onionwire-x86_64-unknown-linux-gnu.sha256 chmod +x onionwire-x86_64-unknown-linux-gnu ./onionwire-x86_64-unknown-linux-gnu --version @@ -71,8 +71,8 @@ chmod +x onionwire-x86_64-unknown-linux-gnu **aarch64:** ```bash -curl -fL -O https://forgejo.siriusdevops.com/sirius/onionwire/releases/download/v0.5.0/onionwire-aarch64-unknown-linux-gnu -curl -fL -O https://forgejo.siriusdevops.com/sirius/onionwire/releases/download/v0.5.0/onionwire-aarch64-unknown-linux-gnu.sha256 +curl -fL -O https://forgejo.siriusdevops.com/sirius/onionwire/releases/download/v0.7.0/onionwire-aarch64-unknown-linux-gnu +curl -fL -O https://forgejo.siriusdevops.com/sirius/onionwire/releases/download/v0.7.0/onionwire-aarch64-unknown-linux-gnu.sha256 sha256sum -c onionwire-aarch64-unknown-linux-gnu.sha256 chmod +x onionwire-aarch64-unknown-linux-gnu ./onionwire-aarch64-unknown-linux-gnu --version @@ -134,7 +134,7 @@ system OpenSSL headers or `pkg-config` are required — Arti's TLS backend is `rustls`. The crate version in `Cargo.toml` is **not** bumped by the release workflow. The -tag (`v0.5.0`) is the version users download; `onionwire --version` prints +tag (`v0.7.0`) is the version users download; `onionwire --version` prints `CARGO_PKG_VERSION` from the tree that was built. ### Two instances on one machine @@ -433,7 +433,9 @@ invites interoperate. - **SDK** — `onionwire-sdk-.aar`. UniFFI Kotlin over the same Rust crate the TUI runs. See [crates/onionwire-sdk/README.md](crates/onionwire-sdk/README.md). - **APK** — `onionwire--android-arm64-v8a.apk`. Kotlin + Jetpack Compose. - Build notes: [android/README.md](android/README.md). + Build notes: [android/README.md](android/README.md). The UI is a design-token + system (one accent, 16px cards, three-tab shell: Chats / Wallet / Node & + Settings) rather than per-screen styling; see *App shell* in that README. The APK build is amd64-only. After the Linux `release` workflow finishes, dispatch `android-release` with that tag so the APK/AAR attach to the same @@ -441,7 +443,7 @@ Forgejo release. ```bash scripts/build-android-local.sh # -> dist/, with .sha256 -PUBLISH_TAG=v0.5.0 scripts/build-android-local.sh # + upload to that release +PUBLISH_TAG=v0.7.0 scripts/build-android-local.sh # + upload to that release ``` ## Releases (maintainers) @@ -461,7 +463,7 @@ Actions → **release** → Run workflow: Then dispatch **android-release** with `tag=` to attach the APK + AAR. ```bash -FORGEJO_TOKEN= scripts/build-release-local.sh v0.5.0 +FORGEJO_TOKEN= scripts/build-release-local.sh v0.7.0 ``` Do not run `cargo publish`; `publish = false`. diff --git a/docs/VERIFY.md b/docs/VERIFY.md index ea1e57e..d2f2c4e 100644 --- a/docs/VERIFY.md +++ b/docs/VERIFY.md @@ -67,7 +67,7 @@ missing: - **`/releases/latest/download/…` is not served by this Forgejo — it is a 404.** The GitHub habit fails here. Always pin the tag: - `…/releases/download/v0.5.0/onionwire-x86_64-unknown-linux-gnu`. + `…/releases/download/v0.7.0/onionwire-x86_64-unknown-linux-gnu`. - **Cloudflare in front of the Forgejo rejects non-browser User-Agents.** A script that sends a default library UA gets `HTTP 403` with the body `error code: 1010` — even with a correct tag and URL. Measured against a real @@ -157,10 +157,10 @@ is public": *the binary I downloaded might not be that source.* git clone https://forgejo.siriusdevops.com/sirius/onionwire cd onionwire git fetch --tags -scripts/verify-reproducible.sh v0.5.0 +scripts/verify-reproducible.sh v0.7.0 ``` -Replace `v0.5.0` with the tag you are checking. You need docker; you do not +Replace `v0.7.0` with the tag you are checking. You need docker; you do not need Rust, or the right glibc, or the right distro. The rebuild happens inside the same builder image, pinned **by digest**, that CI uses, with the source paths, the target path, and `SOURCE_DATE_EPOCH` all fixed by From 9d93fb5cfa9b863319569e5f1a005ad3c120184b Mon Sep 17 00:00:00 2001 From: agent Date: Fri, 30 Oct 2026 23:24:58 -0400 Subject: [PATCH 15/19] fuzz: pass the 4th bootstrap arg (hybrid ML-KEM peer key) RatchetState::bootstrap gained remote_kem_pub in b22abd7 (PR #185), so the fuzz target has not compiled since 2026-10-20 and the nightly fuzz job has been red for ten days. Pass None for the classical shape and a real ML-KEM-768 encapsulation key (crate::kem::PK_LEN bytes, built once from a fixed 64-byte seed) for the hybrid shape, so both bootstrap paths are fuzzed. The invariants are unchanged: arbitrary bytes never panic, a parsed state re-serializes, and a rejected frame rolls back to the exact pre-decrypt state. --- fuzz/fuzz_targets/ratchet_frame.rs | 54 ++++++++++++++++++++++++------ 1 file changed, 43 insertions(+), 11 deletions(-) diff --git a/fuzz/fuzz_targets/ratchet_frame.rs b/fuzz/fuzz_targets/ratchet_frame.rs index 9361768..9d7f50f 100644 --- a/fuzz/fuzz_targets/ratchet_frame.rs +++ b/fuzz/fuzz_targets/ratchet_frame.rs @@ -10,26 +10,45 @@ //! Neither call may panic, and neither may leave the state mutated on a frame //! it rejects (asserted in `tests/ratchet.rs`, re-checked cheaply here by //! re-serializing after every decrypt). +//! +//! Both bootstrap shapes are exercised: a classical friend (`remote_kem_pub = +//! None`) and a hybrid friend, whose peer ML-KEM ratchet key is a real +//! encapsulation key of `kem::PK_LEN` bytes derived from a fixed seed. A +//! garbage key would only ever hit the "invalid encapsulation key" error path. #![no_main] use libfuzzer_sys::fuzz_target; +use onionwire::kem::{self, PK_LEN, SEED_LEN}; use onionwire::ratchet::{RatchetKeyPair, RatchetState}; +use std::sync::OnceLock; -fuzz_target!(|data: &[u8]| { - // Restore path: arbitrary bytes as a persisted ratchet state. - if let Ok(state) = RatchetState::from_bytes(data) { - // A state that parsed must re-serialize without panicking. - let _ = state.to_bytes(); - } +/// A canonical ML-KEM-768 encapsulation key, built once: key generation is +/// deterministic for a fixed seed, so this only pays for itself on iteration 1. +fn peer_kem_pub() -> &'static [u8] { + static PK: OnceLock> = OnceLock::new(); + PK.get_or_init(|| { + let pk = kem::pk_from_seed(&[0x44u8; SEED_LEN]).expect("64 bytes is a valid ML-KEM seed"); + assert_eq!(pk.len(), PK_LEN, "crate ML-KEM public key length changed"); + pk + }) +} - // Wire path: a fresh bootstrap epoch for every input, so one iteration can - // never influence the next. The keys are fixed (not fuzzed) on purpose: - // the interesting surface is `data` as the frame. - let mut state = RatchetState::bootstrap( +fn bootstrap(remote_kem_pub: Option<&[u8]>) -> RatchetState { + // The keys are fixed (not fuzzed) on purpose: the interesting surface is + // `data` as the frame. + RatchetState::bootstrap( [0x42u8; 32], RatchetKeyPair::from_secret([0x11u8; 32]), [0x33u8; 32], - ); + remote_kem_pub, + ) +} + +/// Feed `data` to a fresh state and hold the existing invariants: a reject must +/// roll back, an accept must have advanced the receiving chain, and re-sending +/// from the resulting state must not panic. +fn exercise(remote_kem_pub: Option<&[u8]>, data: &[u8]) { + let mut state = bootstrap(remote_kem_pub); let before = state.to_bytes(); match state.decrypt(data) { @@ -45,4 +64,17 @@ fuzz_target!(|data: &[u8]| { // Re-encrypting a byte-identical state must stay a pure function. let _ = state.encrypt(b"fuzz"); +} + +fuzz_target!(|data: &[u8]| { + // Restore path: arbitrary bytes as a persisted ratchet state. + if let Ok(state) = RatchetState::from_bytes(data) { + // A state that parsed must re-serialize without panicking. + let _ = state.to_bytes(); + } + + // Wire path: a fresh bootstrap epoch for every input, so one iteration can + // never influence the next. Classical and hybrid, both. + exercise(None, data); + exercise(Some(peer_kem_pub()), data); }); From 3cd70ca9b58049ed578df7ee770198ba6fd34a68 Mon Sep 17 00:00:00 2001 From: agent Date: Sat, 31 Oct 2026 01:10:34 -0400 Subject: [PATCH 16/19] android wallet: self-heal the stored wallet_rpc_bin, gate Start/Create, one info banner MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Device report (v0.7.0): Start died with `spawn monero-wallet-rpc: No such file or directory`, and Create answered with the desktop TUI's `wallet not configured — open F7 …`. Both were reachable states on the phone, so the screen offered two dead ends. - WireViewModel: `healStoredWalletBin()` re-points a stored wallet_rpc_bin that this device cannot execute at the resolved nativeLibraryDir path, preserving kind/mode/host/port/datadir/filename, skipping receive-only, and never overwriting a stored path that is a real executable file. It runs on wallet-screen open and again at the top of `startWalletChild()`, which then re-reads the stored record and refuses to spawn when the path still cannot run — writing the named path instead of ENOENT. - Gate: `startGateReason()` = existing `startBlockedReason()` plus `storedWalletBinBlockedReason()`, which names the stored path, the resolved path, or the absent-binary message (unchanged strings). `shouldStartAfterSelectingChain()` now takes that reason, so a mode tap stores the source but cannot launch what Start would refuse. - Create/Import: `walletSetupBlockedReason()` disables both controls with a sentence until the child answers; the TUI's unconfigured copy is mapped by `walletFailureText` to a phone sentence, so `open F7` and ONIONWIRE_WALLET_RPC never render. - Banner: `walletFailureBanner()` paints `WALLET_NOT_OPEN_TEXT` as one info banner (or nothing when the No-wallet-open hint is already up), never as the red `Wallet error`; the sticky error is cleared when a wallet opens. Real failures (connect refusals, exited) still paint red. Tests: 241/241 `:app:testDebugUnitTest`, including the four required cases. Not verified on a device — no adb/device on this host. --- .../siriusdevops/onionwire/WireViewModel.kt | 79 ++++++++ .../onionwire/ui/WalletChildStatusText.kt | 183 +++++++++++++++++- .../onionwire/ui/WalletManagerScreen.kt | 28 +++ .../siriusdevops/onionwire/ui/WalletScreen.kt | 96 +++++++-- .../onionwire/ui/WalletChildStatusTextTest.kt | 136 +++++++++++++ .../onionwire/ui/WalletManagerTest.kt | 23 +++ 6 files changed, 528 insertions(+), 17 deletions(-) diff --git a/android/app/src/main/java/com/siriusdevops/onionwire/WireViewModel.kt b/android/app/src/main/java/com/siriusdevops/onionwire/WireViewModel.kt index cc16ef2..5da0390 100644 --- a/android/app/src/main/java/com/siriusdevops/onionwire/WireViewModel.kt +++ b/android/app/src/main/java/com/siriusdevops/onionwire/WireViewModel.kt @@ -15,6 +15,9 @@ import com.siriusdevops.onionwire.keepalive.KeepAliveStatus import com.siriusdevops.onionwire.keepalive.NodeHost import com.siriusdevops.onionwire.ui.SeedBackupGate import com.siriusdevops.onionwire.ui.WalletKeyOrigin +import com.siriusdevops.onionwire.ui.NO_CHAIN_SOURCE_NOTICE +import com.siriusdevops.onionwire.ui.storedWalletBinBlockedReason +import com.siriusdevops.onionwire.ui.walletBinHealPath import com.siriusdevops.onionwire.ui.walletFailureText import com.siriusdevops.onionwire.wallet.ChainStorage import com.siriusdevops.onionwire.wallet.NO_WALLET_RPC_MESSAGE @@ -1015,10 +1018,72 @@ class WireViewModel(app: Application) : AndroidViewModel(app) { */ fun chainFreeBytes(): Long? = ChainStorage.freeBytes(home) + /** + * Repairs a stored `walletRpcBin` this device cannot execute, and reports + * whether it wrote anything back. + * + * A wallet-child record written by an older install can carry the bare name + * `monero-wallet-rpc` (or an empty string). Nothing in an APK sandbox + * resolves a bare name on `PATH`, so `start_wallet_child` spawns it and dies + * with `No such file or directory` — while the Start gate, which only ever + * looked at the *resolved* bundle, stayed green. This re-points the stored + * record at the absolute `nativeLibraryDir` path this install actually + * carries, before anything is spawned. + * + * What it deliberately does not do: + * - it never changes `kind`, host, port, mode, datadir or wallet filename — + * a repair of the binary is not a change of chain source; + * - it does nothing for receive-only (`ChainChoice.NONE`), which stores a + * bin it never spawns; + * - it never overwrites a stored path that exists and is executable, even + * when that path is not the bundled binary — a user who pointed at a real + * file keeps it; + * - it never fails loudly: a repair that cannot be made leaves the stored + * record alone, and the gate then names the path it will try to spawn. + */ + suspend fun healStoredWalletBin(bins: WalletChildBinaryPaths): Result = + withContext(Dispatchers.IO) { + runCatching { + val wire = requireWire() + val stored = runCatching { wire.chainSource() }.getOrNull() + ?: return@runCatching false + if (stored.kind == ChainChoice.NONE) return@runCatching false + val healed = walletBinHealPath(stored.walletRpcBin, bins.walletRpc) + ?: return@runCatching false + wire.setChainSource( + ChainConfig( + kind = stored.kind, + monerodBin = stored.monerodBin, + monerodDatadir = stored.monerodDatadir, + host = stored.host, + port = stored.port, + walletRpcBin = healed, + artiBin = stored.artiBin, + walletFilename = stored.walletFilename, + mainnet = stored.mainnet, + prune = stored.prune, + ), + ) + true + } + }.onSuccess { healed -> + if (healed) { + refreshChainSource() + refreshWalletChild() + } + } + /** * Kick off start on [viewModelScope] so leaving the composition does not * cancel Cuprate launch. Returns immediately; watch [walletChildStarting] * and [walletChildError]. Core status stays `off` until the node answers. + * + * Self-heals the stored binary first, then re-reads that stored record and + * refuses to spawn when it still names a path this device cannot run. The + * screen's gate is the primary door, but an auto-start from a mode tap is + * not the only caller: this is the last place that can stop a doomed spawn, + * and the reason it writes is the named path rather than the core's opaque + * `spawn monero-wallet-rpc: …`. */ fun startWalletChild() { if (!startInFlight.compareAndSet(false, true)) return @@ -1026,6 +1091,20 @@ class WireViewModel(app: Application) : AndroidViewModel(app) { _walletChildError.value = null viewModelScope.launch { try { + val bins = bundledBinaries() + healStoredWalletBin(bins) + val stored = withContext(Dispatchers.IO) { + runCatching { requireWire().chainSource() }.getOrNull() + } + if (stored == null || stored.kind == ChainChoice.NONE) { + _walletChildError.value = NO_CHAIN_SOURCE_NOTICE + return@launch + } + val blocked = storedWalletBinBlockedReason(stored.walletRpcBin, bins.walletRpc) + if (blocked != null) { + _walletChildError.value = blocked + return@launch + } val started = withContext(Dispatchers.IO) { runCatching { requireWire().startWalletChild() } } diff --git a/android/app/src/main/java/com/siriusdevops/onionwire/ui/WalletChildStatusText.kt b/android/app/src/main/java/com/siriusdevops/onionwire/ui/WalletChildStatusText.kt index 5bae4d1..2f15281 100644 --- a/android/app/src/main/java/com/siriusdevops/onionwire/ui/WalletChildStatusText.kt +++ b/android/app/src/main/java/com/siriusdevops/onionwire/ui/WalletChildStatusText.kt @@ -2,6 +2,7 @@ package com.siriusdevops.onionwire.ui import com.siriusdevops.onionwire.wallet.NO_WALLET_RPC_MESSAGE import com.siriusdevops.onionwire.wallet.WalletChildBinaryPaths +import java.io.File import java.util.Locale /** @@ -446,13 +447,21 @@ fun selectedCuprateMode(inProcess: Boolean, mainnet: Boolean, prune: Boolean): C /** * Tapping a mode used to only persist `ChainConfig`, which looked like a no-op - * besides the storage line. Start when the storage floor would allow Start and - * a launch is not already in flight. + * besides the storage line. Start when the storage floor would allow Start, + * **the Start gate itself would allow it**, and a launch is not already in + * flight. + * + * [startBlocked] is the same reason the Start button is disabled by + * (`startGateReason`). A mode tap stores the source either way, but persisting + * a choice must never launch a child the gate would refuse — the old + * storage-only predicate is exactly how an auto-start slipped past a stored + * binary that could not run. */ fun shouldStartAfterSelectingChain( storageBlocked: String?, starting: Boolean, -): Boolean = storageBlocked == null && !starting + startBlocked: String? = null, +): Boolean = storageBlocked == null && startBlocked == null && !starting /** * Bytes as a screen-sized string. Binary units (a "GB" that is really a GiB is how @@ -609,7 +618,7 @@ fun startBlockedReason( // control *is* Stop, so Start is never offered. Kept as a pure predicate so // a stale status read cannot turn the one control into a no-op tap. input.running -> "The wallet is already running." - !input.configured -> "No chain source yet: the wallet needs a daemon to dial." + !input.configured -> NO_CHAIN_SOURCE_NOTICE // The stored source is the app's own node but this build has no daemon: the // option is readable and unstoppable, so say it before the user presses Start. input.chainInProcess && !input.nodeAvailable -> CUPRATE_NOT_IN_BUILD_NOTICE @@ -617,6 +626,172 @@ fun startBlockedReason( else -> null } +/** The stored config names no chain source, so there is no daemon to dial. */ +const val NO_CHAIN_SOURCE_NOTICE: String = + "No chain source yet: the wallet needs a daemon to dial." + +/** + * Whether [path] is a file this process may `exec`, measured the way the kernel + * will measure it at spawn time. A missing file and an existing file without + * the execute bit are both "cannot run here" — they differ only in errno. + * + * Never throws: a path the filesystem refuses to answer for is not executable. + */ +fun isExecutableWalletBin(path: String): Boolean = + runCatching { File(path).let { it.isFile && it.canExecute() } }.getOrDefault(false) + +/** + * The absolute path the stored config should keep instead of [storedBin], or + * `null` when the stored path is already runnable here (or there is nothing + * better to offer). + * + * This is the repair rule behind the self-heal. A record written by an older + * install can carry the bare name `monero-wallet-rpc` (or nothing at all), + * which nothing in an APK sandbox resolves on `PATH`; the spawn then dies with + * `ENOENT` and the screen had no way to say why. When this build *does* carry + * the binary at a resolved absolute path, that path replaces the unusable one. + * + * It never overwrites a path the user pointed at that actually runs: an + * existing, executable file is left alone even when it is not the bundled one. + */ +fun walletBinHealPath( + storedBin: String?, + resolvedBin: String?, + executable: (String) -> Boolean = ::isExecutableWalletBin, +): String? { + val resolved = resolvedBin?.takeIf { it.isNotBlank() } ?: return null + val stored = storedBin?.trim().orEmpty() + if (stored.isNotEmpty() && executable(stored)) return null + return resolved +} + +/** + * Why the **stored** `ChainConfig.walletRpcBin` will not produce a child, or + * `null` when it will. [startBlockedReason] only ever sees the *resolved* + * binaries, so a stale path saved by an older install passed that gate and + * then failed inside `spawn`. + * + * The reason always names the path it is about, so the next failure report + * carries its own cause instead of the opaque `spawn monero-wallet-rpc: No such + * file or directory`. A store that holds no path at all is named as such — + * "stored bin missing" is a distinct condition from "this build ships none". + */ +fun storedWalletBinBlockedReason( + storedBin: String?, + resolvedBin: String?, + executable: (String) -> Boolean = ::isExecutableWalletBin, +): String? { + if (resolvedBin.isNullOrBlank()) return NO_WALLET_RPC_MESSAGE + val stored = storedBin?.trim().orEmpty() + if (stored.isEmpty()) { + return "No wallet binary path is stored for this chain source, so there is nothing to " + + "spawn. This build ships $resolvedBin — pick a chain source to store it." + } + if (executable(stored)) return null + return "The stored wallet binary cannot be run on this device: $stored. " + + "This build ships $resolvedBin." +} + +/** + * The full **Start** gate: the eligibility rules above plus the stored binary. + * + * [startBlockedReason] runs first so its established copy and ordering (no + * binary in this build, start in flight, no chain source) is unchanged; the + * stored-path check is the new second half. Together they make a populated + * `bins` insufficient on its own — which was the hole that let a bare stored + * name through. + */ +fun startGateReason( + bins: WalletChildBinaryPaths, + input: WalletChildInput?, + storedWalletBin: String?, + onionDaemon: Boolean = false, + starting: Boolean = false, + executable: (String) -> Boolean = ::isExecutableWalletBin, +): String? = + startBlockedReason(bins, input, onionDaemon, starting) + ?: storedWalletBinBlockedReason(storedWalletBin, bins.walletRpc, executable) + +/** + * Why **Create wallet** / **Import wallet** cannot be offered yet, or `null` + * when they can. + * + * Both are RPC calls (`create_wallet` / `restore_deterministic_wallet`) against + * the running child. With no child the call cannot succeed, and the core's + * refusal is the desktop TUI's `wallet not configured — open F7 …` — a key that + * does not exist on a phone. Collecting a passphrase only to print that is the + * second dead end this screen must not offer. + */ +fun walletSetupBlockedReason(input: WalletChildInput?): String? = + when (walletChildPhase(input)) { + WalletChildPhase.Unread -> READING_CHILD_NOTICE + WalletChildPhase.Off -> WALLET_SETUP_NEEDS_CHILD + WalletChildPhase.Connecting -> WALLET_SETUP_STARTING + is WalletChildPhase.Exited, is WalletChildPhase.Unrecognised -> WALLET_SETUP_NEEDS_CHILD + WalletChildPhase.Syncing, WalletChildPhase.Ready -> null + } + +/** Shown on the disabled Create / Import controls when no wallet process is up. */ +const val WALLET_SETUP_NEEDS_CHILD: String = + "Create and Import need the wallet process running. Start it on the node card first." + +/** Shown while the child is up but its RPC has not answered yet. */ +const val WALLET_SETUP_STARTING: String = + "The wallet is still starting. Wait until it answers, then create or import." + +/** Tone of the one failure banner a card may paint. */ +enum class WalletFailureTone { + /** Information about a state the app is in, not a failed call. */ + Info, + + /** A call actually failed. */ + Error, +} + +/** + * The banner a card should paint for a display-ready failure string, or `null` + * when it should paint none. + * + * [WALLET_NOT_OPEN_TEXT] is documented as a *state*, not a failure — a running + * child with no wallet file open answers every read with the daemon's `-13`, + * and that is exactly what first-run looks like. It nevertheless reached the + * node card's red `Wallet error` banner, duplicating the `No wallet open` info + * banner directly above it. This decision is keyed on the *mapped* text only: + * the mapping in [walletFailureText] is untouched, so nothing raw becomes + * visible, and only the paint changes. + * + * - [walletOpen] true: the state has ended, so a stale no-wallet sentence is + * dropped entirely. + * - [openHintVisible] true: the info banner above already says it — one + * sentence, once. + * - otherwise the sentence is still information, so it is painted as + * [WalletFailureTone.Info] rather than red. + */ +fun walletFailureBanner( + text: String?, + openHintVisible: Boolean, + walletOpen: Boolean, +): WalletFailureBanner? { + val shown = text?.takeIf { it.isNotBlank() } ?: return null + return if (shown == WALLET_NOT_OPEN_TEXT) { + when { + walletOpen -> null + openHintVisible -> null + else -> WalletFailureBanner(shown, WalletFailureTone.Info, "No wallet open") + } + } else { + WalletFailureBanner(shown, WalletFailureTone.Error, "Wallet error") + } +} + +/** One banner: its sentence, its tone, and its title. */ +data class WalletFailureBanner( + val text: String, + val tone: WalletFailureTone, + val title: String, +) + + /** * Why **Stop** is not actionable, or `null` when it is. `stop_wallet_child` is * idempotent in the core, so this is only about not offering a no-op button. diff --git a/android/app/src/main/java/com/siriusdevops/onionwire/ui/WalletManagerScreen.kt b/android/app/src/main/java/com/siriusdevops/onionwire/ui/WalletManagerScreen.kt index 68884be..214394d 100644 --- a/android/app/src/main/java/com/siriusdevops/onionwire/ui/WalletManagerScreen.kt +++ b/android/app/src/main/java/com/siriusdevops/onionwire/ui/WalletManagerScreen.kt @@ -176,6 +176,31 @@ const val WALLET_DAEMON_REFUSED_TEXT: String = "The wallet daemon refused that request and gave no readable reason. Check the wallet " + "on the wallet screen, then try again." +/** + * The desktop TUI's refusal, in the phone's words. + * + * `src/wallet.rs::NOT_CONFIGURED_MSG` is written for the Linux TUI: "wallet not + * configured — open F7 to set it up, or set ONIONWIRE_WALLET_RPC". Neither `F7` + * nor an environment variable exists on the phone, and the actual condition is + * simply that no wallet child is running. Printing that string was the second + * dead end on the device: a user who typed a passphrase into Create got told to + * press a key that is not on the device. + */ +const val WALLET_RPC_NOT_RUNNING_TEXT: String = + "The wallet process is not running, so there is nothing to open a wallet on. " + + "Start it on the node card, then create or import." + +/** + * The TUI's unconfigured copy, and nothing else: the F7 hint, the phrase + * "wallet not configured", or an instruction to set `ONIONWIRE_WALLET_RPC`. + * All three describe the same fact — no wallet RPC to dial — and none of them + * is actionable on a phone. + */ +private val TUI_WALLET_NOT_CONFIGURED = Regex( + """open\s*f7|wallet not configured|ONIONWIRE_WALLET_RPC""", + RegexOption.IGNORE_CASE, +) + /** * A failure string safe to put on screen, or `null` when there is nothing to * show. @@ -201,6 +226,9 @@ internal fun walletFailureText(raw: String?): String? { val text = raw?.trim().orEmpty() return when { text.isEmpty() -> null + // Before the JSON / -13 filters: the TUI's refusal is a plain sentence + // the raw pass-through would otherwise let reach the phone verbatim. + TUI_WALLET_NOT_CONFIGURED.containsMatchIn(text) -> WALLET_RPC_NOT_RUNNING_TEXT NO_WALLET_FILE.containsMatchIn(text) || RAW_RPC_CODE.containsMatchIn(text) -> WALLET_NOT_OPEN_TEXT RAW_JSON.containsMatchIn(text) -> WALLET_DAEMON_REFUSED_TEXT diff --git a/android/app/src/main/java/com/siriusdevops/onionwire/ui/WalletScreen.kt b/android/app/src/main/java/com/siriusdevops/onionwire/ui/WalletScreen.kt index 67c2f29..4299cc2 100644 --- a/android/app/src/main/java/com/siriusdevops/onionwire/ui/WalletScreen.kt +++ b/android/app/src/main/java/com/siriusdevops/onionwire/ui/WalletScreen.kt @@ -169,6 +169,11 @@ fun WalletScreen( LaunchedEffect(Unit) { reload() vm.refreshChainSource() + // Self-heal before the gate is asked: a stored `wallet_rpc_bin` left by + // an older install can point at a path this device cannot execute, and + // the bundled binary is the right answer for it. The gate below then + // names the path only when no repair was possible. + vm.healStoredWalletBin(bins) } // The same reads again, once the wallet has actually answered. They are @@ -262,22 +267,33 @@ fun WalletScreen( // about a seed they do not have. val walletReadable = balance != null && balance != "off" && balance != "err" val walletOpen = child?.walletOpen == true + // A sticky failure captured while no wallet was open is not a + // failure once one is: drop it, so the red line does not outlive + // the state that produced it. + LaunchedEffect(walletOpen) { + if (walletOpen) vm.clearWalletChildError() + } val unbacked = SeedBackupGate.warningVisible(seedConfirmed, walletReadable) if (unbacked) { UnbackedSeedCard(error = error, onBackUpSeed = { openSeedBackup() }) } val phase = walletChildPhase(childInput) + // Create and Import are RPC calls against the running child. With no + // child up they can only fail, and the failure is the TUI's `open F7` + // copy — so the controls stay dead and say why instead. + val setupBlocked = walletSetupBlockedReason(childInput) WalletHeroCard( balance = balance, address = address, walletOpen = walletOpen, phase = phase, showQr = showQr, + setupBlocked = setupBlocked, onToggleQr = { showQr = !showQr }, onOpenWallets = onOpenWallets, - onCreate = { setup = SetupKind.Create }, - onImport = { setup = SetupKind.Import }, + onCreate = { if (setupBlocked == null) setup = SetupKind.Create }, + onImport = { if (setupBlocked == null) setup = SetupKind.Import }, onInvoice = { composer = PayKind.Invoice }, onTip = { composer = PayKind.Tip }, onBackUpSeed = if ( @@ -336,9 +352,12 @@ fun WalletScreen( .onFailure { daemonError = walletFailureText(it.message ?: it.toString()) } .onSuccess { // Selecting a mode stores it and, when the - // storage floor would allow Start, starts the - // node: a mode button that only rewrites a - // storage line reads as a no-op. + // storage floor *and* the Start gate would allow + // a launch, starts the node. The stored binary is + // what the just-saved config holds; the gate + // asks it the same question Start does, so a + // mode tap can never launch a child Start would + // have refused. if (shouldStartAfterSelectingChain( chainStorageBlockedReason( vm.chainFreeBytes(), @@ -346,6 +365,10 @@ fun WalletScreen( prune = prune, ), starting = starting, + startBlocked = storedWalletBinBlockedReason( + bins.walletRpc, + bins.walletRpc, + ), ) ) { vm.startWalletChild() @@ -442,6 +465,12 @@ private fun WalletHeroCard( walletOpen: Boolean, phase: WalletChildPhase, showQr: Boolean, + /** + * Why Create / Import cannot be offered yet, or `null` when they can. From + * [walletSetupBlockedReason]: both flows are RPC calls against a running + * wallet child, so a stopped child is a dead end the screen may not offer. + */ + setupBlocked: String?, onToggleQr: () -> Unit, onOpenWallets: () -> Unit, onCreate: () -> Unit, @@ -502,16 +531,30 @@ private fun WalletHeroCard( OwButton( text = "Create Wallet", variant = OwButtonVariant.Primary, + enabled = setupBlocked == null, onClick = onCreate, modifier = Modifier.weight(1f).testTag("wallet-create"), ) OwButton( text = "Import Wallet", variant = OwButtonVariant.Secondary, + enabled = setupBlocked == null, onClick = onImport, modifier = Modifier.weight(1f).testTag("wallet-import"), ) } + // Why the two flows are dead, in a sentence rather than a grey pair + // of buttons. The only fix is on the node card below, so the copy + // points there. + setupBlocked?.let { + Spacer(Modifier.height(8.dp)) + OwAlertBanner( + variant = OwAlertVariant.Info, + title = "Wallet not running", + description = it, + modifier = Modifier.testTag("wallet-setup-blocked"), + ) + } // Invoicing does not need a wallet file: the core resolves the payee // address from the profile (`no receive address — set profile xmr or // ONIONWIRE_WALLET_RPC` is the both-missing case). Hiding the action @@ -614,16 +657,27 @@ private fun WalletHeroCard( OwButton( text = "New wallet", variant = OwButtonVariant.Outline, + enabled = setupBlocked == null, onClick = onCreate, modifier = Modifier.weight(1f).testTag("wallet-create"), ) OwButton( text = "Import wallet", variant = OwButtonVariant.Outline, + enabled = setupBlocked == null, onClick = onImport, modifier = Modifier.weight(1f).testTag("wallet-import"), ) } + setupBlocked?.let { + Spacer(Modifier.height(8.dp)) + OwAlertBanner( + variant = OwAlertVariant.Info, + title = "Wallet not running", + description = it, + modifier = Modifier.testTag("wallet-setup-blocked"), + ) + } // The recovery path for a wallet whose seed was missed: a quiet action, // because a healthy wallet needs it rarely and a seed is a spend key. // While the seed is unconfirmed the strip above carries the button @@ -690,7 +744,10 @@ private fun NodeCard( val progress = syncProgress(input?.height ?: 0uL, input?.targetHeight ?: 0uL) val node = nodePhase(input) val onionDaemon = chain?.kind == ChainChoice.REMOTE && isOnionHost(chain.host) - val startWhy = startBlockedReason(bins, input, onionDaemon, starting) + // The full gate: eligibility *and* the stored binary this build will + // actually spawn. A populated `bins` alone used to pass, which is how a + // stored bare name got as far as `spawn` and failed with ENOENT. + val startWhy = startGateReason(bins, input, chain?.walletRpcBin, onionDaemon, starting) ?: if (inProcess) { chainStorageBlockedReason( nodeFreeBytes, @@ -976,15 +1033,28 @@ private fun NodeCard( // acts, like the chat screen's load error. Filtered through // `walletFailureText`: the daemon's own `-13 No wallet file` / JSON // answer is not a sentence about this app and never reaches the screen. + // + // "No wallet open" is a state, not a failure: the info banner above + // already owns it, so it is not painted red and not printed twice. val failure = walletFailureText(input?.lastError) ?: actionError ?: daemonError failure?.let { - Spacer(Modifier.height(8.dp)) - OwAlertBanner( - variant = OwAlertVariant.Error, - title = "Wallet error", - description = it, - modifier = Modifier.testTag("wallet-child-error"), - ) + walletFailureBanner( + text = it, + openHintVisible = openHint != null, + walletOpen = walletOpen, + )?.let { banner -> + Spacer(Modifier.height(8.dp)) + OwAlertBanner( + variant = if (banner.tone == WalletFailureTone.Info) { + OwAlertVariant.Info + } else { + OwAlertVariant.Error + }, + title = banner.title, + description = banner.text, + modifier = Modifier.testTag("wallet-child-error"), + ) + } } } } diff --git a/android/app/src/test/java/com/siriusdevops/onionwire/ui/WalletChildStatusTextTest.kt b/android/app/src/test/java/com/siriusdevops/onionwire/ui/WalletChildStatusTextTest.kt index def027a..255c217 100644 --- a/android/app/src/test/java/com/siriusdevops/onionwire/ui/WalletChildStatusTextTest.kt +++ b/android/app/src/test/java/com/siriusdevops/onionwire/ui/WalletChildStatusTextTest.kt @@ -621,4 +621,140 @@ class WalletChildStatusTextTest { nodeStatusHead(input("syncing", running = true, chainSource = "remote daemon")).title, ) } + + // --- the stored wallet binary: heal before spawn, then gate on it ------- + + private val hostsBundled = "/data/app/~~abc/onionwire-1/lib/arm64/libmonerowalletrpc.so" + + @Test + fun a_stored_bare_name_is_repaired_to_the_bundled_absolute_path() { + // A record written by an older install: a bare name nothing in an APK + // sandbox resolves on PATH. The repair is the absolute path this + // install actually carries. + assertEquals(hostsBundled, walletBinHealPath("monero-wallet-rpc", hostsBundled) { false }) + assertEquals("an empty stored bin is healed too", hostsBundled, walletBinHealPath("", hostsBundled) { false }) + assertEquals("and a missing field", hostsBundled, walletBinHealPath(null, hostsBundled) { false }) + } + + @Test + fun a_stored_path_that_actually_runs_is_never_overwritten() { + val userBin = "/data/user/0/com.siriusdevops.onionwire/files/monero-wallet-rpc" + assertNull( + "a real executable file the user pointed at is left alone", + walletBinHealPath(userBin, hostsBundled) { it == userBin }, + ) + assertNull( + "a bundled path already stored needs no write", + walletBinHealPath(hostsBundled, hostsBundled) { it == hostsBundled }, + ) + } + + @Test + fun no_bundled_binary_means_there_is_nothing_to_repair_with() { + assertNull(walletBinHealPath("monero-wallet-rpc", null) { false }) + assertNull(walletBinHealPath("monero-wallet-rpc", " ") { false }) + } + + @Test + fun a_stored_bin_missing_on_the_device_blocks_start_and_names_the_path() { + val why = startGateReason(bundled, input("off"), "monero-wallet-rpc") { false } + assertNotNull("a stored path that cannot run must block Start", why) + assertTrue("the reason names the stored path it is about", why!!.contains("monero-wallet-rpc")) + assertTrue("and the path this build does carry", why.contains(bundled.walletRpc!!)) + assertTrue("and says it cannot run", why.contains("cannot be run")) + assertFalse( + "a gate that refuses never lets a mode tap auto-start", + shouldStartAfterSelectingChain(storageBlocked = null, starting = false, startBlocked = why), + ) + } + + @Test + fun an_absent_resolved_bin_blocks_with_the_resolved_absence_message() { + // Nothing in this build to spawn: the established string, unchanged. + val why = startGateReason(noBinary, input("off"), "/stale/libmonerowalletrpc.so") { false } + assertEquals(NO_WALLET_RPC_MESSAGE, why) + assertFalse(shouldStartAfterSelectingChain(null, false, why)) + } + + @Test + fun a_runnable_stored_bin_passes_the_gate() { + assertNull(startGateReason(bundled, input("off"), bundled.walletRpc) { it == bundled.walletRpc }) + assertNull(storedWalletBinBlockedReason(bundled.walletRpc, bundled.walletRpc) { true }) + } + + @Test + fun the_gate_keeps_the_established_start_ordering() { + // Reading the status still wins over a stored-path complaint: the + // existing copy and its order were not rewritten to make room. + assertEquals(READING_CHILD_NOTICE, startGateReason(bundled, null, null) { false }) + assertEquals( + NO_CHAIN_SOURCE_NOTICE, + startGateReason(bundled, input("off", configured = false, chainSource = "receive-only"), null) { false }, + ) + } + + @Test + fun a_mode_tap_stores_the_source_but_cannot_auto_start_what_the_gate_refuses() { + assertTrue(shouldStartAfterSelectingChain(storageBlocked = null, starting = false)) + assertTrue( + shouldStartAfterSelectingChain(storageBlocked = null, starting = false, startBlocked = null), + ) + assertFalse( + shouldStartAfterSelectingChain( + storageBlocked = null, + starting = false, + startBlocked = "The stored wallet binary cannot be run on this device: …", + ), + ) + } + + @Test + fun create_and_import_are_blocked_without_a_running_child() { + assertEquals(WALLET_SETUP_NEEDS_CHILD, walletSetupBlockedReason(input("off"))) + assertEquals(WALLET_SETUP_NEEDS_CHILD, walletSetupBlockedReason(input("exited", lastError = "spawn …"))) + assertEquals(WALLET_SETUP_NEEDS_CHILD, walletSetupBlockedReason(input("mining"))) + assertEquals(WALLET_SETUP_STARTING, walletSetupBlockedReason(input("connecting", running = true))) + assertEquals(READING_CHILD_NOTICE, walletSetupBlockedReason(null)) + assertNull( + "a syncing wallet answers RPC, so a create is fine", + walletSetupBlockedReason(input("syncing", running = true)), + ) + assertNull(walletSetupBlockedReason(input("ready", running = true))) + } + + // --- the no-wallet-open state is information, not a failure ------------ + + @Test + fun the_no_wallet_open_state_is_information_never_the_red_failure() { + // The `No wallet open` info banner owns this sentence; printing it a + // second time in red is the duplicate the device report caught. + assertNull( + "already said once by the info banner above", + walletFailureBanner(WALLET_NOT_OPEN_TEXT, openHintVisible = true, walletOpen = false), + ) + val alone = walletFailureBanner(WALLET_NOT_OPEN_TEXT, openHintVisible = false, walletOpen = false) + assertNotNull(alone) + assertEquals(WalletFailureTone.Info, alone!!.tone) + assertEquals("No wallet open", alone.title) + assertEquals(WALLET_NOT_OPEN_TEXT, alone.text) + assertNull( + "the state ended when a wallet was opened", + walletFailureBanner(WALLET_NOT_OPEN_TEXT, openHintVisible = false, walletOpen = true), + ) + } + + @Test + fun a_real_failure_still_paints_red() { + val refused = walletFailureText("wallet connect: Connection refused (os error 111)")!! + val banner = walletFailureBanner(refused, openHintVisible = true, walletOpen = false)!! + assertEquals("a refusal is still a failure", WalletFailureTone.Error, banner.tone) + assertEquals("Wallet error", banner.title) + assertEquals(refused, banner.text) + + val exited = walletFailureText("spawn monero-wallet-rpc: No such file or directory (os error 2)")!! + assertEquals(WalletFailureTone.Error, walletFailureBanner(exited, false, false)!!.tone) + + assertNull(walletFailureBanner(null, true, false)) + assertNull(walletFailureBanner(" ", true, false)) + } } diff --git a/android/app/src/test/java/com/siriusdevops/onionwire/ui/WalletManagerTest.kt b/android/app/src/test/java/com/siriusdevops/onionwire/ui/WalletManagerTest.kt index fac959d..aab4313 100644 --- a/android/app/src/test/java/com/siriusdevops/onionwire/ui/WalletManagerTest.kt +++ b/android/app/src/test/java/com/siriusdevops/onionwire/ui/WalletManagerTest.kt @@ -477,4 +477,27 @@ class WalletManagerTest { assertTrue(shouldReloadWalletReads("ready")) assertTrue(shouldReloadWalletReads(" Ready ")) } + + @Test + fun the_tui_not_configured_copy_is_mapped_and_never_rendered_verbatim() { + // `src/wallet.rs::NOT_CONFIGURED_MSG` is the desktop TUI's refusal. A + // phone has no F7 key and no ONIONWIRE_WALLET_RPC, so that sentence is + // the second dead end the device report caught: a passphrase was typed + // into Create, and the screen answered with a keyboard shortcut. + val tui = "wallet not configured — open F7 to set it up, or set ONIONWIRE_WALLET_RPC" + val shown = walletFailureText(tui) + assertEquals(WALLET_RPC_NOT_RUNNING_TEXT, shown) + assertFalse("no F7 reaches the screen", shown!!.contains("F7")) + assertFalse("no env var name either", shown.contains("ONIONWIRE_WALLET_RPC")) + assertTrue("the phone sentence says what to do", shown.contains("Start it on the node card")) + + // Each fragment alone is the same fact and is mapped too; case and + // spacing are not load-bearing. + assertEquals(WALLET_RPC_NOT_RUNNING_TEXT, walletFailureText("Open F7")) + assertEquals(WALLET_RPC_NOT_RUNNING_TEXT, walletFailureText("Wallet Not Configured")) + assertEquals(WALLET_RPC_NOT_RUNNING_TEXT, walletFailureText("set ONIONWIRE_WALLET_RPC")) + + // And it is idempotent: the sticky error card re-filters its own text. + assertEquals(WALLET_RPC_NOT_RUNNING_TEXT, walletFailureText(shown)) + } } From a375ef9d1e86582c35ccaced0ac87e83a2a14204 Mon Sep 17 00:00:00 2001 From: agent Date: Sat, 31 Oct 2026 01:23:18 -0400 Subject: [PATCH 17/19] wallet_child: name argv[0] in spawn errors and pre-flight the RPC bin MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The Android report was `spawn monero-wallet-rpc: No such file or directory (os error 2)` — the label, not the argv[0] that failed, so a bare name and an absolute jniLibs path read identically. - spawn() now prints the label and argv[0]: `spawn monero-wallet-rpc (/data/app/.../libmonerowalletrpc.so): ...`, errno verbatim. - check_wallet_rpc_bin() pre-flights the resolved bin before anything is spawned: not found / not a file / not executable, with the configured path in the message. No PATH search, no fallback. - A bare wallet_rpc_bin is refused where a child has no PATH to resolve it (cfg(target_os = "android")), in ChildConfig::validate() and in the start-path pre-flight. Desktop keeps the bare-name default. - Tests for each refusal and for the argv[0] error; the node test that asserted the old `spawn` copy now asserts the path. --- src/node.rs | 5 +- src/wallet_child.rs | 205 ++++++++++++++++++++++++++++++++++++++++++-- 2 files changed, 201 insertions(+), 9 deletions(-) diff --git a/src/node.rs b/src/node.rs index 86b6412..16efa37 100644 --- a/src/node.rs +++ b/src/node.rs @@ -4347,7 +4347,10 @@ pub(crate) mod tests { let err = node .start_wallet_child() .expect_err("a missing binary fails"); - assert!(err.contains("spawn"), "{err}"); + // The refusal names the configured path: the old `spawn