From 4b2ec2fd68dd97afe25ef483e8e396faadebb9d4 Mon Sep 17 00:00:00 2001 From: monkopedia-coder Date: Tue, 26 May 2026 16:13:24 -0400 Subject: [PATCH] Stop FGS gracefully on dataSync run-time timeout (#450) (#452) Android 15+ enforces a cumulative ~6h/24h limit on dataSync foreground services. When the budget is exhausted while the service is running, the system calls Service.onTimeout() and requires a prompt stop; otherwise it force-kills the process with ForegroundServiceDidNotStopInTimeException (#450, #451). TunnelForegroundService handled the symmetric start-time case (ForegroundServiceStartNotAllowedException -> notify + stopSelf) but never overrode onTimeout, so a budget that ran out mid-session crashed silently. v1.0.2's keep-Ktor-alive-across-idle change made the service stay foregrounded longer, accelerating accumulation toward the cap. Override onTimeout to mirror the start-time path: suppress reconnect, post the existing FgsLimitNotifier, and stopSelf. Add a Robolectric test (@Config sdk=35) covering the handler, and a docs/ux-decisions.md entry for the new lifecycle moment at which the budget notification can appear. Co-authored-by: Claude Opus 4.7 --- docs/ux-decisions.md | 39 ++++++++++++++++ .../work/TunnelForegroundService.kt | 20 ++++++++ .../TunnelForegroundServiceLifecycleTest.kt | 46 +++++++++++++++++++ 3 files changed, 105 insertions(+) diff --git a/docs/ux-decisions.md b/docs/ux-decisions.md index 2007c3c8..7438af81 100644 --- a/docs/ux-decisions.md +++ b/docs/ux-decisions.md @@ -14,6 +14,45 @@ Newest entries on top. --- +## 2026-05-26 — Surface the FGS-budget notification on run-time timeout, not just at startup + +**Decision:** When Android calls `Service.onTimeout()` because the `dataSync` +foreground-service budget is exhausted *while the service is running*, +`TunnelForegroundService` posts the existing `FgsLimitNotifier` notification and +stops cleanly — the same notification already shown when the budget is exhausted +at startup. + +**Approved by:** Jason, in-session 2026-05-26 ("sure" — to implement the +onTimeout handler reusing FgsLimitNotifier). + +**Context:** Crashes #450/#451 (`ForegroundServiceDidNotStopInTimeException`) +were the service being force-killed when the cumulative 6h/24h dataSync FGS cap +ran out mid-session. The start-time half of this was already handled +(`ForegroundServiceStartNotAllowedException` → notify + stopSelf); the run-time +half (`onTimeout`) was missing, so the budget exhausting mid-run produced a +silent crash with no user-facing explanation. + +**Alternatives considered:** +- **Stop silently on timeout, no notification** — fixes the crash but the user + gets no signal that wakes have paused until the 24h window frees budget; + inconsistent with the start-time path, which does notify. +- **Distinct "ran out mid-session" copy** — more precise, but it's the same + underlying condition (budget exhausted, wakes paused, retries next window), so + a second message would be noise. + +**Trade-off accepted:** The same notification can now appear at a second moment +in the lifecycle (mid-session, not only at wake start). Accepted because the +user-facing meaning is identical — "FGS budget spent, wakes paused, will resume +when the rolling window frees up" — and a shared id means the two paths replace +rather than stack in the shade. + +**Relevant:** +- Crashes: #450 (FcmReceiver.startTunnelService frame), #451 (system-generated + frame) — same root cause, one fix. +- Mirrors the existing start-time handler in `TunnelForegroundService.startForegroundSafely`. + +--- + ## 2026-04-24 — Cert provisioning runs at Continue, not at first integration add **Decision:** Keep the post-#389 flow where relay subdomain registration and ACME cert provisioning fire immediately after the user taps Continue on NotificationPreferences, before Home loads. diff --git a/work/src/main/kotlin/com/rousecontext/work/TunnelForegroundService.kt b/work/src/main/kotlin/com/rousecontext/work/TunnelForegroundService.kt index dabc08be..5edcc798 100644 --- a/work/src/main/kotlin/com/rousecontext/work/TunnelForegroundService.kt +++ b/work/src/main/kotlin/com/rousecontext/work/TunnelForegroundService.kt @@ -289,6 +289,26 @@ class TunnelForegroundService : LifecycleService() { } } + /** + * Android 15+ enforces a cumulative ~6h-per-24h limit on `dataSync` + * foreground services. When that budget is exhausted *while the service is + * running*, the system calls this and requires us to stop within a couple + * seconds — otherwise it kills the process with + * `ForegroundServiceDidNotStopInTimeException` (#450, #451). + * + * This is the run-time mirror of the start-time + * `ForegroundServiceStartNotAllowedException` already handled in + * [startForegroundSafely]: post the same user-visible notification, suppress + * reconnect, and stop. The next FCM wake retries once the rolling window + * frees the budget back up. + */ + override fun onTimeout(startId: Int, fgsType: Int) { + Log.w(TAG, "FGS dataSync time limit reached (fgsType=$fgsType); stopping service") + intentionalDisconnect = true + FgsLimitNotifier.postLimitReachedNotification(this) + stopSelf() + } + override fun onDestroy() { Log.i(TAG, "TunnelForegroundService destroyed") intentionalDisconnect = true diff --git a/work/src/test/kotlin/com/rousecontext/work/TunnelForegroundServiceLifecycleTest.kt b/work/src/test/kotlin/com/rousecontext/work/TunnelForegroundServiceLifecycleTest.kt index b47315f9..e1cbddd6 100644 --- a/work/src/test/kotlin/com/rousecontext/work/TunnelForegroundServiceLifecycleTest.kt +++ b/work/src/test/kotlin/com/rousecontext/work/TunnelForegroundServiceLifecycleTest.kt @@ -1,10 +1,13 @@ package com.rousecontext.work import android.app.Notification +import android.content.pm.ServiceInfo +import android.os.Build import android.os.Looper import com.rousecontext.api.CrashReporter import com.rousecontext.bridge.SessionHandler import com.rousecontext.mcp.core.ProviderRegistry +import com.rousecontext.notifications.FgsLimitNotifier import com.rousecontext.notifications.ForegroundNotifier import com.rousecontext.notifications.NotificationChannels import com.rousecontext.notifications.SessionSummaryNotifier @@ -17,6 +20,7 @@ import io.mockk.every import io.mockk.mockk import io.mockk.mockkObject import io.mockk.unmockkObject +import io.mockk.verify import kotlin.time.Duration import kotlinx.coroutines.flow.Flow import kotlinx.coroutines.flow.MutableSharedFlow @@ -36,6 +40,7 @@ import org.koin.dsl.module import org.robolectric.Robolectric import org.robolectric.RobolectricTestRunner import org.robolectric.Shadows.shadowOf +import org.robolectric.annotation.Config /** * Tests [TunnelForegroundService] lifecycle transitions using Robolectric. @@ -282,6 +287,47 @@ class TunnelForegroundServiceLifecycleTest { ) } + // -- Test 7: onTimeout (run-time FGS budget exhaustion) stops the service (#450/#451) -- + + @Test + @Config(sdk = [Build.VERSION_CODES.VANILLA_ICE_CREAM]) + fun `onTimeout stops service and posts FGS limit notification`() { + // Android 15+ calls Service.onTimeout once the cumulative dataSync FGS + // budget is exhausted while the service is running. If we don't stop + // promptly the system kills us with ForegroundServiceDidNotStopInTime- + // Exception (#450/#451). This mirrors the start-time budget handler. + mockkObject(FgsLimitNotifier) + every { FgsLimitNotifier.postLimitReachedNotification(any()) } returns Unit + try { + fakeTunnelClient.stateFlow.value = TunnelState.DISCONNECTED + + val controller = Robolectric.buildService(TunnelForegroundService::class.java) + val service = controller.get() + controller.create() + drainMain() + controller.startCommand(0, 1) + drainMain() + fakeTunnelClient.stateFlow.value = TunnelState.CONNECTED + drainMain() + + // System signals the dataSync 6h budget is exhausted mid-run. + service.onTimeout(1, ServiceInfo.FOREGROUND_SERVICE_TYPE_DATA_SYNC) + drainMain() + + assertTrue( + "Service must stop itself when the FGS run-time timeout fires", + shadowOf(service).isStoppedBySelf + ) + assertTrue( + "intentionalDisconnect must be set so the stop doesn't trigger a reconnect", + service.intentionalDisconnect + ) + verify { FgsLimitNotifier.postLimitReachedNotification(any()) } + } finally { + unmockkObject(FgsLimitNotifier) + } + } + // -- Helpers -- /** Process all pending tasks on the main looper so lifecycleScope coroutines run. */