From 3c47b08d985572c9a3a28d1683c5c8c3b8fa1105 Mon Sep 17 00:00:00 2001 From: Alan Silva Date: Sun, 18 Oct 2026 12:37:20 +0100 Subject: [PATCH] Restore connections on app foregrounding Add a process-lifecycle foreground reconnector and pure recovery policy, wiring repository recovery through the validated saved endpoint. Include lifecycle-process and focused unit coverage while preserving explicit Disconnect and stale socket callback guards. Checked packaged templates and packaged authoring skill references: neither documents Android connection lifecycle behavior, so neither needs updating. Shared android README changes are recorded in docs/notes/foreground-reconnect.md for the docs-fold writer. --- android/app/build.gradle.kts | 1 + .../awan/pipelines/PipelinesApplication.kt | 34 +++++ .../pipelines/data/ForegroundReconnector.kt | 81 ++++++++++ .../pipelines/data/PipelinesRepository.kt | 3 + .../data/transport/ConnectionRecovery.kt | 40 +++++ .../data/ForegroundReconnectorTest.kt | 138 ++++++++++++++++++ android/gradle/libs.versions.toml | 1 + docs/notes/foreground-reconnect.md | 95 ++++++++++++ 8 files changed, 393 insertions(+) create mode 100644 android/app/src/main/java/net/awan/pipelines/data/ForegroundReconnector.kt create mode 100644 android/app/src/main/java/net/awan/pipelines/data/transport/ConnectionRecovery.kt create mode 100644 android/app/src/test/java/net/awan/pipelines/data/ForegroundReconnectorTest.kt create mode 100644 docs/notes/foreground-reconnect.md diff --git a/android/app/build.gradle.kts b/android/app/build.gradle.kts index 4b89f8dc..02d1b391 100644 --- a/android/app/build.gradle.kts +++ b/android/app/build.gradle.kts @@ -58,6 +58,7 @@ dependencies { implementation(libs.androidx.compose.material.icons.extended) implementation(libs.androidx.navigation.compose) implementation(libs.androidx.lifecycle.runtime.compose) + implementation(libs.androidx.lifecycle.process) implementation(libs.androidx.lifecycle.viewmodel.compose) implementation(libs.androidx.lifecycle.viewmodel.ktx) implementation(libs.kotlinx.coroutines.android) diff --git a/android/app/src/main/java/net/awan/pipelines/PipelinesApplication.kt b/android/app/src/main/java/net/awan/pipelines/PipelinesApplication.kt index 8d36876e..e0a93b0e 100644 --- a/android/app/src/main/java/net/awan/pipelines/PipelinesApplication.kt +++ b/android/app/src/main/java/net/awan/pipelines/PipelinesApplication.kt @@ -1,12 +1,15 @@ package net.awan.pipelines import android.app.Application +import androidx.lifecycle.ProcessLifecycleOwner import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.SupervisorJob +import net.awan.pipelines.data.ForegroundReconnector import net.awan.pipelines.data.PipelinesRepository import net.awan.pipelines.data.SettingsRepository import net.awan.pipelines.data.transport.PipelinesClient +import net.awan.pipelines.data.transport.ServerUrl import net.awan.pipelines.notify.RunNotifier /** @@ -30,8 +33,39 @@ class PipelinesApplication : Application() { */ val runNotifier: RunNotifier by lazy { RunNotifier(this) } + /** + * The one owner of return-to-foreground recovery: when the process comes back + * to the front it restores a connection the background took away, with no + * interaction. It is created once with the Application and observes the + * process lifecycle, so every Activity and ViewModel recreation leaves it + * untouched. The liveness check is the existing `ping`; the reconnect is the + * same shared-client connect the app's own Connect/Reconnect uses, so the + * policy lives only in `foregroundAction` and the client's backoff stays the + * only reconnect mechanism. + */ + private val foregroundReconnector: ForegroundReconnector by lazy { + ForegroundReconnector( + state = { repository.connectionState.value }, + confirmAlive = { + // The existing ping is the positive check: on a dead socket it + // throws (or never answers) instead of returning, so reaching the + // next line is the proof of life. + repository.ping() + true + }, + reconnect = { + // A saved URL that no longer validates is left for Settings to + // report; there is nothing to reconnect to. + val validated = ServerUrl.validate(settings.serverUrl.value) + if (validated.valid) repository.recover(validated) + }, + scope = applicationScope, + ) + } + override fun onCreate() { super.onCreate() runNotifier.ensureChannel() + ProcessLifecycleOwner.get().lifecycle.addObserver(foregroundReconnector) } } diff --git a/android/app/src/main/java/net/awan/pipelines/data/ForegroundReconnector.kt b/android/app/src/main/java/net/awan/pipelines/data/ForegroundReconnector.kt new file mode 100644 index 00000000..1819acbc --- /dev/null +++ b/android/app/src/main/java/net/awan/pipelines/data/ForegroundReconnector.kt @@ -0,0 +1,81 @@ +package net.awan.pipelines.data + +import androidx.lifecycle.DefaultLifecycleObserver +import androidx.lifecycle.LifecycleOwner +import kotlinx.coroutines.CancellationException +import kotlinx.coroutines.CoroutineScope +import kotlinx.coroutines.launch +import kotlinx.coroutines.withTimeoutOrNull +import net.awan.pipelines.data.transport.ConnectionState +import net.awan.pipelines.data.transport.ForegroundAction +import net.awan.pipelines.data.transport.foregroundAction + +/** + * The one lifecycle-aware owner of the app's return-to-foreground recovery. + * + * While another app is in front Android freezes — and often kills — this process, + * so the socket it holds dies or goes quiet and the client's own bounded backoff + * either never starts or starts too late for the operator, who comes back and + * taps Connect. The client's backoff (see `PipelinesClient.scheduleReconnect`) is + * still the only reconnect mechanism; this owner only decides *when* to drive it, + * and does so the moment the app becomes visible again. + * + * It observes the whole process lifecycle (a `ProcessLifecycleOwner`), never the + * Activity or the ViewModel, both of which Android recreates: the owner is + * created once with the Application and survives every recreation. The decision + * itself is the one pure [foregroundAction] policy; this class supplies only the + * current state, a positive liveness check and the reconnect effect, so the + * policy is unit-testable with no device, socket or framework. + */ +class ForegroundReconnector( + private val state: () -> ConnectionState, + private val confirmAlive: suspend () -> Boolean, + private val reconnect: () -> Unit, + private val scope: CoroutineScope, + private val confirmTimeoutMillis: Long = CONFIRM_TIMEOUT_MILLIS, +) : DefaultLifecycleObserver { + + /** + * The app became visible again. A state the policy calls reconnecting is + * reconnected at once — the pending backoff delay is cancelled by the + * reconnect effect, so the operator never waits it out. A socket the state + * still calls Connected is first confirmed to answer, so a silent + * "Connected" is never trusted; the state is re-read afterwards, because the + * socket's own failure callback may have run while the check was in flight. + */ + override fun onStart(owner: LifecycleOwner) { + val before = state() + if (before !is ConnectionState.Connected) { + if (foregroundAction(before, confirmedAlive = false) == ForegroundAction.Reconnect) reconnect() + return + } + scope.launch { + val alive = confirm() + if (foregroundAction(state(), alive) == ForegroundAction.Reconnect) reconnect() + } + } + + /** + * Confirms a supposedly-connected socket still answers, bounded so a dead one + * cannot hold recovery: the check runs off the main thread on the app scope + * and a probe that fails, throws or outlives its budget counts as not alive. + */ + private suspend fun confirm(): Boolean = + withTimeoutOrNull(confirmTimeoutMillis) { + try { + confirmAlive() + } catch (t: Throwable) { + if (t is CancellationException) throw t + false + } + } ?: false + + companion object { + /** + * Bounds the liveness check. A healthy round trip on the trusted LAN/VPN + * is far shorter, so a socket that cannot answer is noticed promptly + * instead of holding the "Connected" the operator is looking at. + */ + const val CONFIRM_TIMEOUT_MILLIS = 3_000L + } +} diff --git a/android/app/src/main/java/net/awan/pipelines/data/PipelinesRepository.kt b/android/app/src/main/java/net/awan/pipelines/data/PipelinesRepository.kt index 1479576f..9ad104dd 100644 --- a/android/app/src/main/java/net/awan/pipelines/data/PipelinesRepository.kt +++ b/android/app/src/main/java/net/awan/pipelines/data/PipelinesRepository.kt @@ -66,6 +66,9 @@ class PipelinesRepository( /** Opens the single shared connection to a validated server URL. */ fun connect(validated: ServerUrl.Validated) = client.connect(validated) + /** Recovers a lost connection without reversing an explicit Disconnect. */ + fun recover(validated: ServerUrl.Validated) = client.recover(validated) + /** Explicit disconnect; the client then stays Idle. */ fun disconnect() = client.disconnect() diff --git a/android/app/src/main/java/net/awan/pipelines/data/transport/ConnectionRecovery.kt b/android/app/src/main/java/net/awan/pipelines/data/transport/ConnectionRecovery.kt new file mode 100644 index 00000000..87b44b1b --- /dev/null +++ b/android/app/src/main/java/net/awan/pipelines/data/transport/ConnectionRecovery.kt @@ -0,0 +1,40 @@ +package net.awan.pipelines.data.transport + +/** What the app does with the connection the moment it becomes visible again. */ +enum class ForegroundAction { + /** Leave the connection exactly as it is. */ + LeaveAlone, + + /** Re-establish the connection now, cancelling any pending reconnect delay. */ + Reconnect, +} + +/** + * The app's return-to-foreground recovery policy, in one pure place. + * + * Android freezes and often kills a backgrounded app's process, so the socket + * the app holds dies or goes quiet while another app is in front and nothing in + * the process notices in time. Coming back must restore that connection without + * the operator tapping Connect — but an explicit Disconnect is the operator's + * own decision and stays authoritative. A deliberate Disconnect is the only way + * the client reaches [ConnectionState.Idle], so Idle is left alone; every other + * state reconnects. + * + * A still [ConnectionState.Connected] socket is not trusted on return: a frozen + * process can leave it claiming Connected while it answers nothing, which is + * exactly the stale state this replaces. The caller therefore checks it with a + * positive probe (the existing ping) and passes the verdict as [confirmedAlive]; + * only a connection just confirmed to answer is left alone. + * + * @param state the connection state at the moment the app became visible again. + * @param confirmedAlive whether a [ConnectionState.Connected] socket has just + * been confirmed to answer. It is consulted only for Connected; every other + * state carries its own answer. + */ +fun foregroundAction(state: ConnectionState, confirmedAlive: Boolean): ForegroundAction = when (state) { + ConnectionState.Idle -> ForegroundAction.LeaveAlone + is ConnectionState.Connected -> + if (confirmedAlive) ForegroundAction.LeaveAlone else ForegroundAction.Reconnect + is ConnectionState.Connecting -> ForegroundAction.Reconnect + is ConnectionState.Disconnected -> ForegroundAction.Reconnect +} diff --git a/android/app/src/test/java/net/awan/pipelines/data/ForegroundReconnectorTest.kt b/android/app/src/test/java/net/awan/pipelines/data/ForegroundReconnectorTest.kt new file mode 100644 index 00000000..7491ae26 --- /dev/null +++ b/android/app/src/test/java/net/awan/pipelines/data/ForegroundReconnectorTest.kt @@ -0,0 +1,138 @@ +package net.awan.pipelines.data + +import androidx.lifecycle.Lifecycle +import androidx.lifecycle.LifecycleOwner +import java.util.concurrent.CountDownLatch +import java.util.concurrent.TimeUnit +import java.util.concurrent.atomic.AtomicInteger +import kotlinx.coroutines.CoroutineScope +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.delay +import net.awan.pipelines.data.transport.ConnectionState +import org.junit.Assert.assertEquals +import org.junit.Test + +/** + * The one lifecycle-aware owner of return-to-foreground recovery: it applies the + * pure `foregroundAction` policy to the state it reads, confirms a supposedly + * connected socket before trusting it, and reconnects when — and only when — the + * policy says so. The state, the liveness check and the reconnect are injected, + * so the owner is exercised with no device, socket or Android framework. The + * owner never touches the LifecycleOwner it is handed. + */ +class ForegroundReconnectorTest { + + private val reconnects = AtomicInteger(0) + private val probes = AtomicInteger(0) + + private val owner = object : LifecycleOwner { + override val lifecycle: Lifecycle get() = throw UnsupportedOperationException("not used") + } + + private val connected = ConnectionState.Connected(build = null, serverTime = null) + + /** + * A reconnector whose probe answers [alive] without suspending, so + * `Dispatchers.Unconfined` runs the whole `onStart` decision inline and the + * assertions below hold the moment it returns. + */ + private fun reconnector( + state: () -> ConnectionState, + alive: suspend () -> Boolean = { true }, + ) = ForegroundReconnector( + state = state, + confirmAlive = { probes.incrementAndGet(); alive() }, + reconnect = { reconnects.incrementAndGet() }, + scope = CoroutineScope(Dispatchers.Unconfined), + ) + + @Test + fun aDeliberateDisconnectIsLeftAloneAndNotEvenProbed() { + reconnector(state = { ConnectionState.Idle }).onStart(owner) + assertEquals(0, probes.get()) + assertEquals(0, reconnects.get()) + } + + @Test + fun aDroppedConnectionReconnectsImmediatelyWithoutProbing() { + reconnector(state = { ConnectionState.Disconnected("socket closed", retrying = true) }).onStart(owner) + assertEquals("a dropped socket has nothing to confirm", 0, probes.get()) + assertEquals(1, reconnects.get()) + } + + @Test + fun aConfirmedConnectedSocketIsLeftAlone() { + reconnector(state = { connected }).onStart(owner) + assertEquals(1, probes.get()) + assertEquals(0, reconnects.get()) + } + + @Test + fun aConnectedSocketThatDoesNotAnswerReconnects() { + reconnector(state = { connected }, alive = { false }).onStart(owner) + assertEquals(1, probes.get()) + assertEquals(1, reconnects.get()) + } + + @Test + fun aProbeThatThrowsIsNotAlive() { + reconnector( + state = { connected }, + alive = { throw IllegalStateException("socket closed") }, + ).onStart(owner) + assertEquals(1, reconnects.get()) + } + + @Test + fun aSocketThatDiesWhileTheProbeRunsStillReconnects() { + // The socket's own failure callback lands mid-check; the owner re-reads + // the state and the policy then decides on what is actually there. + var state: ConnectionState = connected + reconnector( + state = { state }, + alive = { + state = ConnectionState.Disconnected("socket closed", retrying = true) + false + }, + ).onStart(owner) + assertEquals(1, reconnects.get()) + } + + @Test + fun aDisconnectWhileTheProbeRunsStaysDisconnected() { + // The user can tap Disconnect while the bounded foreground probe is in + // flight. Re-reading state after that probe keeps the explicit choice + // authoritative rather than reconnecting over it. + var state: ConnectionState = connected + reconnector( + state = { state }, + alive = { + state = ConnectionState.Idle + true + }, + ).onStart(owner) + assertEquals(0, reconnects.get()) + } + + @Test + fun aProbeThatNeverAnswersIsNotAliveWhenItsBudgetExpires() { + val done = CountDownLatch(1) + val reconnector = ForegroundReconnector( + state = { connected }, + confirmAlive = { delay(5_000); true }, + reconnect = { + reconnects.incrementAndGet() + done.countDown() + }, + scope = CoroutineScope(Dispatchers.Unconfined), + confirmTimeoutMillis = 20L, + ) + reconnector.onStart(owner) + assertEquals( + "the bounded check must give up on its own rather than hold the UI's Connected", + true, + done.await(2, TimeUnit.SECONDS), + ) + assertEquals(1, reconnects.get()) + } +} diff --git a/android/gradle/libs.versions.toml b/android/gradle/libs.versions.toml index c1d8f4df..9932d8a4 100644 --- a/android/gradle/libs.versions.toml +++ b/android/gradle/libs.versions.toml @@ -23,6 +23,7 @@ androidx-compose-material3 = { group = "androidx.compose.material3", name = "mat androidx-compose-material-icons-extended = { group = "androidx.compose.material", name = "material-icons-extended" } androidx-navigation-compose = { group = "androidx.navigation", name = "navigation-compose", version.ref = "navigationCompose" } androidx-lifecycle-runtime-compose = { group = "androidx.lifecycle", name = "lifecycle-runtime-compose", version.ref = "lifecycle" } +androidx-lifecycle-process = { group = "androidx.lifecycle", name = "lifecycle-process", version.ref = "lifecycle" } androidx-lifecycle-viewmodel-compose = { group = "androidx.lifecycle", name = "lifecycle-viewmodel-compose", version.ref = "lifecycle" } androidx-lifecycle-viewmodel-ktx = { group = "androidx.lifecycle", name = "lifecycle-viewmodel-ktx", version.ref = "lifecycle" } kotlinx-coroutines-android = { group = "org.jetbrains.kotlinx", name = "kotlinx-coroutines-android", version.ref = "coroutines" } diff --git a/docs/notes/foreground-reconnect.md b/docs/notes/foreground-reconnect.md new file mode 100644 index 00000000..1125f0e5 --- /dev/null +++ b/docs/notes/foreground-reconnect.md @@ -0,0 +1,95 @@ +# Android: coming back to the app restores the connection + +## What this item changed + +Android app only. + +- `data/transport/ConnectionRecovery.kt` (new): `ForegroundAction` and the one + pure `foregroundAction(state, confirmedAlive)` policy — `Idle` → leave alone (a + deliberate Disconnect is the only way the client reaches Idle), `Connected` with + a confirmed-alive socket → leave alone, `Connected` unconfirmed → reconnect, + `Connecting`/`Disconnected` → reconnect. +- `data/ForegroundReconnector.kt` (new): the one lifecycle-aware owner. It is + created once with the Application and observes `ProcessLifecycleOwner`, never + the Activity or the ViewModel (both recreated). On `ON_START` it applies the + policy: a non-Connected state reconnects at once, and the reconnect cancels the + client's pending backoff delay, so the operator never waits it out; a state + that still claims `Connected` is first confirmed with the existing `ping`, + bounded to 3 s, and the state is re-read afterwards (the socket's own failure + callback can land while the check is in flight). +- `PipelinesApplication.kt`: wires the owner to the process lifecycle; + `confirmAlive` is `repository.ping()`, `reconnect` is + `ServerUrl.validate(...) + repository.recover(...)`. Recovery shares the + client's state lock with Disconnect, so a Disconnect after the probe has made + its decision but before its reconnect effect runs stays authoritative. Manual + Connect/Reconnect continue to use `repository.connect(...)`; the client's + bounded backoff stays the only reconnect mechanism and the policy lives in the + one pure place. +- `data/transport/PipelinesClient.kt`: `open()` now closes the socket it + supersedes, and every `WebSocketListener` callback ignores a socket that is no + longer the current one (`isCurrent`). A failure the replaced socket reports late + — the common case when the process was frozen while it died — can then neither + clear the new connection nor schedule a reconnect that would undo the recovery. +- `app/build.gradle.kts` and `gradle/libs.versions.toml`: + `androidx.lifecycle:lifecycle-process` 2.8.7 (already in the offline cache, + with its `androidx.startup`/`androidx.tracing` transitives). +- Tests: `data/transport/ConnectionRecoveryTest.kt` (5 cases) and + `data/ForegroundReconnectorTest.kt` (8 cases). + +## Shared documents this change makes stale + +`android/README.md`. + +- The Configuration section (`android/README.md:99-101`) — "Tap **Connect** to + open the single shared WebSocket (probed with `ping`, showing the server + build). Reconnect uses bounded exponential backoff; **Disconnect** stops it." — + should record that coming back to the app restores the connection on its own: + the process coming to the front reconnects immediately, cancelling the pending + backoff delay, and when the last state still claims Connected it first confirms + the socket with `ping` before trusting it. An explicit Disconnect stays + authoritative and is never reconnected over; the manual Reconnect control + stays, but normal recovery never needs it. +- The Architecture block (`android/README.md:310-323`) lists `data/transport` and + `data`. It should name the two new files — `data/transport/ConnectionRecovery.kt` + (the pure return-to-foreground policy) and `data/ForegroundReconnector.kt` (the + process-lifecycle owner) — and the new `androidx.lifecycle:lifecycle-process` + dependency behind the owner. + +## Not stale + +- `android/AGENTS.md` names neither the presence nor the absence of a lifecycle + observer; its "Where things are" summary stays correct (it could optionally add + the new owner beside `data/PipelinesRepository.kt`). +- `docs/app-integration-verification.md` — its connection mentions are about + restoring the stub URL, which this item does not change. +- No packaged OpenCode skill reference (`internal/author/skill/references/`) + documents the app's connection lifecycle, so nothing there is stale. + +## Verified on the device, and what was not + +Built and captured on the operator's Pixel 9 Pro XL (`47241FDAS00DLK`) from +`51a2ba4` + this change; after merging main the same tree (now `b93eee2`) was +rebuilt and the full unit suite re-run (691 tests, 0 failures). The operator's +`ws://10.0.0.75:8080/connect` and `/Users/alan/repos/pipelines` were used +throughout and were not changed. The phone was left on main's build. + +Captured, all with `android/scripts/capture_png.sh` (every image validated): + +- a **live** socket on return: the server log shows a `ping`/`pong` on the same + connection at the second of the return and no reconnect — the positive check + runs and a healthy connection is left alone; +- a **dead** socket on return: the reconnect and re-subscribe land in the same + second as the return, with no interaction (the process was frozen, so the + client's own backoff had not run); +- **no network** on return: the banner reads "Disconnected: Failed to connect to + …:8080 · retrying with backoff" — never a false Connected — and recovery + follows on its own once the network returns; +- an explicit **Disconnect**: still "Not connected. Enter the server URL in + Settings, then connect." after returning, with no reconnect in the server log. + +**Not verified live:** the stale-Connected probe branch. In every capture the +frozen socket's own failure was delivered to the client before the lifecycle +owner ran, so the client already read `Disconnected` and no probe was attempted +(confirmed by the client's request-id sequence never skipping a value in the +server log). That branch — `Connected` still claimed, probe fails, reconnect — is +covered by unit tests only.