diff --git a/.forgejo/workflows/android-ci.yml b/.forgejo/workflows/android-ci.yml index 1262a87..b9e8ba7 100644 --- a/.forgejo/workflows/android-ci.yml +++ b/.forgejo/workflows/android-ci.yml @@ -154,6 +154,12 @@ jobs: rustc --version cargo ndk --version du -sh /opt/android-sdk /cargo /cargo-target /gradle || true + # Shared /gradle volume: a killed container leaves journal-1.lock. + # android/gradle.properties also sets org.gradle.parallel=true, which + # is how two JVMs (PIDs ~5 apart) show up on one lock. Drop the + # stale locks and force one Gradle process for this container. + find /gradle -name '*.lock' -type f -delete 2>/dev/null || true + export GRADLE_OPTS="${GRADLE_OPTS:-} -Dorg.gradle.parallel=false -Dorg.gradle.daemon=false" # No keystore here on purpose: this is a verification build, not a # release build. The script warns that Gradle fell back to the debug # key; that warning is expected in this job. @@ -228,6 +234,12 @@ jobs: docker volume create "$CARGO_VOLUME" >/dev/null docker volume create "$TARGET_VOLUME" >/dev/null docker volume create "$GRADLE_VOLUME" >/dev/null + # Cancelled jobs never reach the trailing `docker rm`, so a previous + # onionwire-android-* container can still hold GRADLE_VOLUME. The next + # Gradle then dies LockTimeoutException on /gradle/caches/journal-1 + # (owner PID vs our PID a few numbers apart — two JVMs, one volume). + trap 'docker rm -f "$BUILD_CONTAINER" >/dev/null 2>&1 || true' EXIT + docker ps -aq --filter name=onionwire-android- | xargs -r docker rm -f || true docker rm -f "$BUILD_CONTAINER" >/dev/null 2>&1 || true docker pull "$ANDROID_IMAGE" # 2 GB of Gradle heap, not 1: the only budget in this build that is close @@ -250,7 +262,7 @@ jobs: -e ONIONWIRE_REQUIRE_RELEASE_KEY=false \ -e RUST_TOOLCHAIN="$RUST_TOOLCHAIN" \ -e ANDROID_CMDLINE_TOOLS_URL="$ANDROID_CMDLINE_TOOLS_URL" \ - -e GRADLE_OPTS="-Dorg.gradle.daemon=false -Dorg.gradle.jvmargs=-Xmx2048m -XX:MaxMetaspaceSize=512m -Dfile.encoding=UTF-8" \ + -e GRADLE_OPTS="-Dorg.gradle.daemon=false -Dorg.gradle.parallel=false -Dorg.gradle.jvmargs=-Xmx2048m -XX:MaxMetaspaceSize=512m -Dfile.encoding=UTF-8" \ -v "$SDK_VOLUME":/opt/android-sdk \ -v "$CARGO_VOLUME":/cargo \ -v "$TARGET_VOLUME":/cargo-target \ diff --git a/.forgejo/workflows/android-release.yml b/.forgejo/workflows/android-release.yml index f725ddd..dd2a132 100644 --- a/.forgejo/workflows/android-release.yml +++ b/.forgejo/workflows/android-release.yml @@ -271,6 +271,8 @@ jobs: rustc --version cargo ndk --version du -sh /opt/android-sdk /cargo /cargo-target /gradle || true + find /gradle -name '*.lock' -type f -delete 2>/dev/null || true + export GRADLE_OPTS="${GRADLE_OPTS:-} -Dorg.gradle.parallel=false -Dorg.gradle.daemon=false" scripts/build-android-local.sh "$ONIONWIRE_VERSION" version="$ONIONWIRE_VERSION" abi="${ONIONWIRE_ANDROID_ABI:-arm64-v8a}" @@ -297,6 +299,10 @@ jobs: docker volume create "$CARGO_VOLUME" >/dev/null docker volume create "$TARGET_VOLUME" >/dev/null docker volume create "$GRADLE_VOLUME" >/dev/null + # Same shared GRADLE_VOLUME as android-ci.yml. A cancelled job leaves + # the build container running and journal-1.lock held. + trap 'docker rm -f "$BUILD_CONTAINER" >/dev/null 2>&1 || true' EXIT + docker ps -aq --filter name=onionwire-android- | xargs -r docker rm -f || true docker rm -f "$BUILD_CONTAINER" >/dev/null 2>&1 || true docker pull "$ANDROID_IMAGE" # 2 GB of Gradle heap, not 1: the only budget in this build that is close @@ -321,7 +327,7 @@ jobs: -e ONIONWIRE_VERSION="$VERSION" \ -e RUST_TOOLCHAIN="$RUST_TOOLCHAIN" \ -e ANDROID_CMDLINE_TOOLS_URL="$ANDROID_CMDLINE_TOOLS_URL" \ - -e GRADLE_OPTS="-Dorg.gradle.daemon=false -Dorg.gradle.jvmargs=-Xmx2048m -XX:MaxMetaspaceSize=512m -Dfile.encoding=UTF-8" \ + -e GRADLE_OPTS="-Dorg.gradle.daemon=false -Dorg.gradle.parallel=false -Dorg.gradle.jvmargs=-Xmx2048m -XX:MaxMetaspaceSize=512m -Dfile.encoding=UTF-8" \ -v "$SDK_VOLUME":/opt/android-sdk \ -v "$CARGO_VOLUME":/cargo \ -v "$TARGET_VOLUME":/cargo-target \ 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 3e5d7d5..81a1e92 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,7 @@ import com.siriusdevops.onionwire.wallet.ChainStorage import com.siriusdevops.onionwire.wallet.NO_WALLET_RPC_MESSAGE import com.siriusdevops.onionwire.wallet.WalletChildBinaries import com.siriusdevops.onionwire.wallet.WalletChildBinaryPaths +import kotlinx.coroutines.CancellationException import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.Job import kotlinx.coroutines.currentCoroutineContext @@ -151,10 +152,13 @@ class WireViewModel(app: Application) : AndroidViewModel(app) { // is already open would be theatre, and unlocking again would race the // live node for the sqlite file. val existing = NodeHost.current() - if (existing != null) { - viewModelScope.launch { adopt(existing) } - } else { - refreshUnlockState() + when { + existing != null -> viewModelScope.launch { adopt(existing) } + NodeHost.isOpening() -> { + _phase.value = Phase.Opening + viewModelScope.launch { resumeOpening() } + } + else -> refreshUnlockState() } viewModelScope.launch { @@ -308,17 +312,23 @@ class WireViewModel(app: Application) : AndroidViewModel(app) { return } _phase.value = Phase.Opening + NodeHost.noteOpening() + // Hold the process from this tap, not after Tor publishes: otherwise + // closing the activity cancels viewModelScope and kills bootstrap. + KeepAliveService.start(getApplication(), "") viewModelScope.launch { try { - // The SDK open is dispatched to Dispatchers.IO inside NodeHost: - // cold start is minutes of Tor bootstrap, which the main thread - // does not survive. val w = NodeHost.open(home, secret.concatToString()) if (storeAfterwards) store(secret) adopt(w) startKeepAlive(w) + } catch (t: CancellationException) { + throw t } catch (t: Throwable) { _phase.value = Phase.Failed(t.message ?: t.toString()) + if (!NodeHost.hasWorkForKeepAlive()) { + KeepAliveService.stop(getApplication()) + } } finally { StoreSecret.wipe(secret) } @@ -338,6 +348,19 @@ class WireViewModel(app: Application) : AndroidViewModel(app) { runCatching { refreshFriends() } } + /** Re-attach after the activity died mid-bootstrap. */ + private suspend fun resumeOpening() { + try { + val w = NodeHost.awaitOpen() + adopt(w) + startKeepAlive(w) + } catch (t: CancellationException) { + throw t + } catch (t: Throwable) { + _phase.value = Phase.Failed(t.message ?: t.toString()) + } + } + /** * Starts the foreground keep-alive. Always reached from a user-visible * unlock, so the API 31+ background-start restriction does not apply; if diff --git a/android/app/src/main/java/com/siriusdevops/onionwire/keepalive/KeepAlivePolicy.kt b/android/app/src/main/java/com/siriusdevops/onionwire/keepalive/KeepAlivePolicy.kt new file mode 100644 index 0000000..b2add16 --- /dev/null +++ b/android/app/src/main/java/com/siriusdevops/onionwire/keepalive/KeepAlivePolicy.kt @@ -0,0 +1,12 @@ +package com.siriusdevops.onionwire.keepalive + +/** + * Whether the foreground service has anything to hold. + * + * Bootstrap used to not count: the service bailed when `Wire` was still null, + * and `openWire` ran on the UI ViewModel scope, so closing the activity + * cancelled Tor bring-up. Opening is work; a published node is work; locked + * and idle is not. + */ +fun keepAliveHasWork(nodeOpen: Boolean, bootstrapInFlight: Boolean): Boolean = + nodeOpen || bootstrapInFlight diff --git a/android/app/src/main/java/com/siriusdevops/onionwire/keepalive/KeepAliveService.kt b/android/app/src/main/java/com/siriusdevops/onionwire/keepalive/KeepAliveService.kt index 51fabc8..bb0b52a 100644 --- a/android/app/src/main/java/com/siriusdevops/onionwire/keepalive/KeepAliveService.kt +++ b/android/app/src/main/java/com/siriusdevops/onionwire/keepalive/KeepAliveService.kt @@ -44,8 +44,10 @@ class KeepAliveService : Service() { return START_NOT_STICKY } - if (NodeHost.current() == null) { + if (!NodeHost.hasWorkForKeepAlive()) { // Nothing to keep alive. A notification here would be a lie. + // Bootstrap counts: the node is not `current()` until Tor has + // published, and that is exactly the window Android used to kill. stopSelf() return START_NOT_STICKY } @@ -125,14 +127,20 @@ class KeepAliveService : Service() { ) // Never the full v3 locator: a notification body is lock-screen public. val short = onion.take(ONION_PREFIX) - val text = if (short.isEmpty()) { - getString(R.string.keep_alive_text) + val opening = short.isEmpty() && NodeHost.isOpening() + val title = if (opening) { + getString(R.string.keep_alive_title_opening) } else { - getString(R.string.keep_alive_text_onion, short) + getString(R.string.keep_alive_title) + } + val text = when { + opening -> getString(R.string.keep_alive_text_opening) + short.isEmpty() -> getString(R.string.keep_alive_text) + else -> getString(R.string.keep_alive_text_onion, short) } return NotificationCompat.Builder(this, CHANNEL_ID) .setSmallIcon(R.drawable.ic_stat_onion) - .setContentTitle(getString(R.string.keep_alive_title)) + .setContentTitle(title) .setContentText(text) .setContentIntent(open) .addAction(0, getString(R.string.keep_alive_stop), stop) diff --git a/android/app/src/main/java/com/siriusdevops/onionwire/keepalive/NodeHost.kt b/android/app/src/main/java/com/siriusdevops/onionwire/keepalive/NodeHost.kt index 3aa0504..925fd3e 100644 --- a/android/app/src/main/java/com/siriusdevops/onionwire/keepalive/NodeHost.kt +++ b/android/app/src/main/java/com/siriusdevops/onionwire/keepalive/NodeHost.kt @@ -1,14 +1,15 @@ package com.siriusdevops.onionwire.keepalive import kotlinx.coroutines.CoroutineScope +import kotlinx.coroutines.Deferred import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.Job import kotlinx.coroutines.SupervisorJob +import kotlinx.coroutines.async import kotlinx.coroutines.flow.MutableStateFlow import kotlinx.coroutines.flow.StateFlow import kotlinx.coroutines.flow.asStateFlow import kotlinx.coroutines.launch -import kotlinx.coroutines.withContext import uniffi.onionwire_sdk.Wire import uniffi.onionwire_sdk.openWire import java.io.File @@ -45,8 +46,8 @@ sealed interface KeepAliveStatus { * service would have kept a notification up for a node the UI had already * killed. Neither side owns the node now; the policy does. * - * Threading: every mutation runs on the main thread except the SDK call inside - * [open], which is dispatched to [Dispatchers.IO] and hops back. + * Threading: [open] runs on [scope] (IO). [wire] is volatile so the main + * thread can read [current] while bootstrap completes off-main. */ object NodeHost { @@ -60,8 +61,23 @@ object NodeHost { private val lifetime = NodeLifetime() + @Volatile private var wire: Wire? = null + /** + * In-flight `openWire`. Lives on [scope], not the UI ViewModel: closing the + * activity must not cancel Tor bootstrap. Null when idle or already open. + */ + @Volatile + private var bootstrap: Deferred? = null + + /** + * Set before the keep-alive starts, before [bootstrap] exists, so the + * service does not `stopSelf` in the gap between Unlock and `openWire`. + */ + @Volatile + private var claimedOpening: Boolean = false + /** * The in-flight teardown, if any. Re-opening has to wait for it: the old * node holds the sqlite file and Arti's state lock until `shutdown()` @@ -75,6 +91,21 @@ object NodeHost { /** The live node, or null when locked. */ fun current(): Wire? = wire + /** Tor bring-up is running on [scope]. The UI may be gone. */ + fun isOpening(): Boolean = claimedOpening || bootstrap?.isActive == true + + /** The foreground service holds a published node *or* an in-flight open. */ + fun hasWorkForKeepAlive(): Boolean = + keepAliveHasWork(nodeOpen = wire != null, bootstrapInFlight = isOpening()) + + /** + * Call *before* [KeepAliveService.start] on the unlock path so the service + * sees bootstrap work before `openWire` has a job. + */ + fun noteOpening() { + claimedOpening = true + } + /** The live node, or a hard error. Callers are UI paths that require unlock. */ fun requireOpen(): Wire = wire ?: error("locked") @@ -82,15 +113,37 @@ object NodeHost { * Opens the node and anchors it to the UI. * * Suspends inside Arti's bootstrap — minutes on a cold start — so this must - * never run on the main thread. Callers are `viewModelScope` coroutines. + * never run on the main thread. The *work* runs on [scope], not the caller's + * job: a `viewModelScope` cancellation (activity gone) must not abort Tor. + * A second call while bootstrap is in flight joins the same job. */ suspend fun open(home: File, passphrase: String): Wire { stopping?.join() - val opened = withContext(Dispatchers.IO) { openWire(home.absolutePath, passphrase) } - wire = opened - _keepAlive.value = KeepAliveStatus.Off - lifetime.onOpened() - return opened + wire?.let { return it } + bootstrap?.let { return it.await() } + val job = scope.async { + val opened = openWire(home.absolutePath, passphrase) + wire = opened + // Keep-alive may already be On: it starts at unlock so Android + // will not kill us mid-bootstrap. Do not stomp that. + if (_keepAlive.value !is KeepAliveStatus.On) { + _keepAlive.value = KeepAliveStatus.Off + } + lifetime.onOpened() + opened + } + bootstrap = job + job.invokeOnCompletion { + if (bootstrap === job) bootstrap = null + claimedOpening = false + } + return job.await() + } + + /** Join an in-flight [open] without starting a second `openWire`. */ + suspend fun awaitOpen(): Wire { + wire?.let { return it } + return bootstrap?.await() ?: error("locked") } /** The UI is going away: finish, task swipe, or process death. */ @@ -123,7 +176,12 @@ object NodeHost { * stops the keep-alive first — a service that is still running would * re-anchor a node that no longer exists. */ - fun lock(): NodeAction = apply(lifetime.onLocked()) + fun lock(): NodeAction { + bootstrap?.cancel() + bootstrap = null + claimedOpening = false + return apply(lifetime.onLocked()) + } private fun apply(action: NodeAction): NodeAction { when (action) { diff --git a/android/app/src/main/java/com/siriusdevops/onionwire/ui/UnlockScreen.kt b/android/app/src/main/java/com/siriusdevops/onionwire/ui/UnlockScreen.kt index 4e57d5e..e4b87ab 100644 --- a/android/app/src/main/java/com/siriusdevops/onionwire/ui/UnlockScreen.kt +++ b/android/app/src/main/java/com/siriusdevops/onionwire/ui/UnlockScreen.kt @@ -10,6 +10,7 @@ import androidx.compose.foundation.layout.height import androidx.compose.foundation.layout.padding import androidx.compose.foundation.layout.safeDrawingPadding import androidx.compose.foundation.rememberScrollState +import androidx.compose.foundation.text.KeyboardActions import androidx.compose.foundation.text.KeyboardOptions import androidx.compose.foundation.verticalScroll import androidx.compose.material3.Button @@ -27,6 +28,7 @@ import androidx.compose.runtime.remember import androidx.compose.runtime.setValue import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier +import androidx.compose.ui.platform.LocalSoftwareKeyboardController import androidx.compose.ui.text.font.FontFamily import androidx.compose.ui.text.input.ImeAction import androidx.compose.ui.text.input.KeyboardType @@ -61,10 +63,19 @@ fun UnlockScreen( // Only meaningful under OneTap: reveal the form without giving up the // stored passphrase. var typeInstead by remember { mutableStateOf(false) } + val keyboard = LocalSoftwareKeyboardController.current val oneTap = unlock as? Unlock.OneTap val failed = phase is Phase.Failed val showForm = oneTap == null || typeInstead || failed + // IME Done and Open share this. Done with no KeyboardActions used to + // dismiss the keyboard and never call unlock, so bootstrap never started. + fun submit() { + val handed = unlockSubmit(pass, storePassphrase) ?: return + pass = "" + keyboard?.hide() + onUnlock(handed.passphrase, handed.remember) + } Column( modifier = Modifier @@ -151,7 +162,11 @@ fun UnlockScreen( visualTransformation = PasswordVisualTransformation(), keyboardOptions = KeyboardOptions( keyboardType = KeyboardType.Password, - imeAction = ImeAction.Done, + imeAction = ImeAction.Go, + ), + keyboardActions = KeyboardActions( + onGo = { submit() }, + onDone = { submit() }, ), label = { Text("wraps the local message key") }, modifier = Modifier.fillMaxWidth(), @@ -189,13 +204,7 @@ fun UnlockScreen( Spacer(Modifier.height(20.dp)) Button( - onClick = { - val typed = pass - // Drop the plaintext from Compose state the moment - // it is handed over; the ViewModel wipes its copy. - pass = "" - onUnlock(typed, storePassphrase) - }, + onClick = { submit() }, enabled = pass.isNotEmpty(), modifier = Modifier.fillMaxWidth(), ) { Text("Open") } diff --git a/android/app/src/main/java/com/siriusdevops/onionwire/ui/UnlockSubmit.kt b/android/app/src/main/java/com/siriusdevops/onionwire/ui/UnlockSubmit.kt new file mode 100644 index 0000000..7f1be30 --- /dev/null +++ b/android/app/src/main/java/com/siriusdevops/onionwire/ui/UnlockSubmit.kt @@ -0,0 +1,16 @@ +package com.siriusdevops.onionwire.ui + +/** + * One submit for IME Done and the Open button. + * + * The IME action used to be `Done` with no [androidx.compose.foundation.text.KeyboardActions]: + * the keyboard closed and [com.siriusdevops.onionwire.WireViewModel.unlock] was never + * called, so bootstrap never started. Empty stays a no-op — the SDK fails closed + * on an empty passphrase, and we do not open the node for it. + */ +internal data class UnlockSubmit(val passphrase: String, val remember: Boolean) + +internal fun unlockSubmit(pass: String, remember: Boolean): UnlockSubmit? { + if (pass.isEmpty()) return null + return UnlockSubmit(passphrase = pass, remember = remember) +} diff --git a/android/app/src/main/res/values/strings.xml b/android/app/src/main/res/values/strings.xml index 33e0458..b857106 100644 --- a/android/app/src/main/res/values/strings.xml +++ b/android/app/src/main/res/values/strings.xml @@ -10,7 +10,9 @@ Node keep-alive Shown while OnionWire keeps your onion address reachable in the background. OnionWire is reachable + OnionWire is starting Tor and the outbox are running so peers can deliver messages. + Bootstrapping Tor. This can take minutes — keep the device awake. Tor and the outbox are running so peers can reach %1$s… Stop keep-alive Reachable only while this app is open. diff --git a/android/app/src/test/java/com/siriusdevops/onionwire/keepalive/KeepAlivePolicyTest.kt b/android/app/src/test/java/com/siriusdevops/onionwire/keepalive/KeepAlivePolicyTest.kt new file mode 100644 index 0000000..f12fd6c --- /dev/null +++ b/android/app/src/test/java/com/siriusdevops/onionwire/keepalive/KeepAlivePolicyTest.kt @@ -0,0 +1,29 @@ +package com.siriusdevops.onionwire.keepalive + +import org.junit.Assert.assertFalse +import org.junit.Assert.assertTrue +import org.junit.Test + +/** + * The keep-alive used to refuse to start until [NodeHost.current] was set — + * which is only after Tor has published. Bootstrap itself ran on the UI + * ViewModel scope, so closing the activity cancelled `openWire` and the + * spinner vanished with no onion. + */ +class KeepAlivePolicyTest { + + @Test + fun bootstrap_in_flight_is_work_the_service_must_hold() { + assertTrue(keepAliveHasWork(nodeOpen = false, bootstrapInFlight = true)) + } + + @Test + fun a_live_node_is_work_the_service_must_hold() { + assertTrue(keepAliveHasWork(nodeOpen = true, bootstrapInFlight = false)) + } + + @Test + fun locked_and_idle_is_not_work() { + assertFalse(keepAliveHasWork(nodeOpen = false, bootstrapInFlight = false)) + } +} diff --git a/android/app/src/test/java/com/siriusdevops/onionwire/ui/UnlockSubmitTest.kt b/android/app/src/test/java/com/siriusdevops/onionwire/ui/UnlockSubmitTest.kt new file mode 100644 index 0000000..d91c221 --- /dev/null +++ b/android/app/src/test/java/com/siriusdevops/onionwire/ui/UnlockSubmitTest.kt @@ -0,0 +1,39 @@ +package com.siriusdevops.onionwire.ui + +import org.junit.Assert.assertEquals +import org.junit.Assert.assertNull +import org.junit.Test + +/** + * IME Done and the Open button must share one submit: the keyboard's action + * key used to dismiss the IME and never call unlock, so bootstrap never + * started. Empty stays a no-op (the SDK would fail closed; we never open). + */ +class UnlockSubmitTest { + + @Test + fun empty_passphrase_does_not_submit() { + assertNull(unlockSubmit("", remember = true)) + assertNull(unlockSubmit("", remember = false)) + } + + @Test + fun typed_passphrase_is_handed_over_with_the_remember_flag() { + assertEquals( + UnlockSubmit(passphrase = "correct horse", remember = true), + unlockSubmit("correct horse", remember = true), + ) + assertEquals( + UnlockSubmit(passphrase = "correct horse", remember = false), + unlockSubmit("correct horse", remember = false), + ) + } + + @Test + fun interior_spaces_are_part_of_the_passphrase_not_trimmed() { + assertEquals( + UnlockSubmit(passphrase = " lead", remember = false), + unlockSubmit(" lead", remember = false), + ) + } +} diff --git a/scripts/build-android-local.sh b/scripts/build-android-local.sh index 5731afc..90a784c 100755 --- a/scripts/build-android-local.sh +++ b/scripts/build-android-local.sh @@ -59,7 +59,11 @@ echo "==> verifying bundled native executables against $BINARY_MANIFEST" ( cd android && sha256sum -c "$(basename "$BINARY_MANIFEST")" ) echo "==> android build: version $version (versionCode $ONIONWIRE_VERSION_CODE), abi $abi" -( cd android && "./gradlew" --no-daemon \ +# --stacktrace only changes output on failure. Without it a Gradle task failure +# can land in the CI log with an empty cause chain (e.g. run 414: +# `:app:packageRelease ... IncrementalSplitterRunnable` and no `Caused by:`), +# which makes a one-off failure undiagnosable after the fact. +( cd android && "./gradlew" --no-daemon --stacktrace \ "-Ponionwire.abis=$abi" \ "-Ponionwire.versionName=$version" \ "-Ponionwire.versionCode=$ONIONWIRE_VERSION_CODE" \