Compare commits

...
Author SHA1 Message Date
e3fb723a91 Merge pull request 'fix(android): keep Tor bootstrap alive after the unlock activity dies' (#116) from feat/android-bootstrap-survives-ui into main
Some checks failed
android-ci / android (push) Failing after 3m32s
Reviewed-on: #116
2026-09-19 01:51:38 +00:00
agent
396e468f1a
fix(android): keep Tor bootstrap alive after the unlock activity dies
Some checks failed
android-ci / android (pull_request) Has been cancelled
Open set Phase.Opening then ran openWire on viewModelScope, and the
keep-alive refused to start until Wire existed. Closing the activity
cancelled bootstrap, so the spinner vanished and the lock screen came
back idle. Run openWire on NodeHost's process scope, start the FGS on
the Open tap, and treat in-flight bootstrap as keep-alive work. IME Go
also submits unlock the same way as the Open button.
2026-09-18 21:46:34 -04:00
9 changed files with 226 additions and 30 deletions

View file

@ -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

View file

@ -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

View file

@ -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)

View file

@ -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<Wire>? = 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) {

View file

@ -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") }

View file

@ -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)
}

View file

@ -10,7 +10,9 @@
<string name="keep_alive_channel_name">Node keep-alive</string>
<string name="keep_alive_channel_description">Shown while OnionWire keeps your onion address reachable in the background.</string>
<string name="keep_alive_title">OnionWire is reachable</string>
<string name="keep_alive_title_opening">OnionWire is starting</string>
<string name="keep_alive_text">Tor and the outbox are running so peers can deliver messages.</string>
<string name="keep_alive_text_opening">Bootstrapping Tor. This can take minutes — keep the device awake.</string>
<string name="keep_alive_text_onion">Tor and the outbox are running so peers can reach %1$s…</string>
<string name="keep_alive_stop">Stop keep-alive</string>
<string name="keep_alive_note_off">Reachable only while this app is open.</string>

View file

@ -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))
}
}

View file

@ -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),
)
}
}