Colota - Android GPS Location tracker
fix(service): read service liveness instead of the tracking flag in the bridge guards (#606)
Max Dietrich92534bea8eb3
diff --git a/apps/mobile/android/app/src/main/java/com/colota/bridge/LocationServiceModule.kt b/apps/mobile/android/app/src/main/java/com/colota/bridge/LocationServiceModule.ktindex ec07a427..e2cde643 100644--- a/apps/mobile/android/app/src/main/java/com/colota/bridge/LocationServiceModule.kt+++ b/apps/mobile/android/app/src/main/java/com/colota/bridge/LocationServiceModule.kt@@ -318,12 +318,12 @@ class LocationServiceModule(reactContext: ReactApplicationContext) :fun stopService() {AppLogger.d(TAG, "Stopping Service via UI")+ // Before the stop, not after: a liveness check racing an async write would see the user's+ // intent still true with the service already gone, and restart what they just turned off.+ dbHelper.saveSetting(SettingsKeys.TRACKING_ENABLED, "false")+val intent = Intent(reactApplicationContext, LocationForegroundService::class.java)reactApplicationContext.stopService(intent)-- moduleScope.launch(Dispatchers.IO) {- dbHelper.saveSetting(SettingsKeys.TRACKING_ENABLED, "false")- }}@ReactMethod@@ -489,8 +489,7 @@ class LocationServiceModule(reactContext: ReactApplicationContext) :}private fun triggerZoneRecheck() {- val isTracking = dbHelper.getSetting(SettingsKeys.TRACKING_ENABLED, "false") == "true"- if (!isTracking) return+ if (!LocationForegroundService.isRunning) returntry {startServiceWithAction(LocationForegroundService.ACTION_RECHECK_ZONE)} catch (e: Exception) {@@ -499,13 +498,11 @@ class LocationServiceModule(reactContext: ReactApplicationContext) :}private fun refreshNotificationIfTracking() {- val isTracking = dbHelper.getSetting(SettingsKeys.TRACKING_ENABLED, "false") == "true"- if (isTracking) {- try {- startServiceWithAction(LocationForegroundService.ACTION_REFRESH_NOTIFICATION)- } catch (e: Exception) {- AppLogger.w(TAG, "Notification refresh skipped: service not running")- }+ if (!LocationForegroundService.isRunning) return+ try {+ startServiceWithAction(LocationForegroundService.ACTION_REFRESH_NOTIFICATION)+ } catch (e: Exception) {+ AppLogger.w(TAG, "Notification refresh skipped: service not running")}}@@ -700,13 +697,11 @@ class LocationServiceModule(reactContext: ReactApplicationContext) :}private fun triggerProfileRecheck() {- val isTracking = dbHelper.getSetting(SettingsKeys.TRACKING_ENABLED, "false") == "true"- if (isTracking) {- try {- startServiceWithAction(LocationForegroundService.ACTION_RECHECK_PROFILES)- } catch (e: Exception) {- AppLogger.w(TAG, "Profile recheck skipped: service not running")- }+ if (!LocationForegroundService.isRunning) return+ try {+ startServiceWithAction(LocationForegroundService.ACTION_RECHECK_PROFILES)+ } catch (e: Exception) {+ AppLogger.w(TAG, "Profile recheck skipped: service not running")}}@@ -796,6 +791,12 @@ class LocationServiceModule(reactContext: ReactApplicationContext) :promise.resolve(deviceInfo.isLocationEnabled())}+ /** Whether a service instance is alive. TRACKING_ENABLED is the user's intent, not this. */+ @ReactMethod+ fun isServiceRunning(promise: Promise) {+ promise.resolve(LocationForegroundService.isRunning)+ }+@ReactMethodfun openLocationSettings(promise: Promise) {promise.resolve(deviceInfo.openLocationSettings())diff --git a/apps/mobile/android/app/src/main/java/com/colota/data/SettingsKeys.kt b/apps/mobile/android/app/src/main/java/com/colota/data/SettingsKeys.ktindex b22048e9..82fd69c9 100644--- a/apps/mobile/android/app/src/main/java/com/colota/data/SettingsKeys.kt+++ b/apps/mobile/android/app/src/main/java/com/colota/data/SettingsKeys.kt@@ -7,6 +7,8 @@ package com.Colota.data/** Runtime state keys persisted via DatabaseHelper.saveSetting/getSetting. */object SettingsKeys {+ /** The user's intent to track, which outlives the process. Liveness is+ * [com.Colota.service.LocationForegroundService.isRunning] - never this. */const val TRACKING_ENABLED = "tracking_enabled"const val PAUSE_ZONE_NAME = "pause_zone_name"const val PAUSE_ZONE_WIFI_ACTIVE = "pause_zone_wifi_active"diff --git a/apps/mobile/android/app/src/main/java/com/colota/service/BatteryRecoveryWorker.kt b/apps/mobile/android/app/src/main/java/com/colota/service/BatteryRecoveryWorker.ktindex f22a69f9..951d3d85 100644--- a/apps/mobile/android/app/src/main/java/com/colota/service/BatteryRecoveryWorker.kt+++ b/apps/mobile/android/app/src/main/java/com/colota/service/BatteryRecoveryWorker.kt@@ -66,8 +66,9 @@ class BatteryRecoveryWorker(return Result.success()}- val alreadyTracking = db.getSetting(SettingsKeys.TRACKING_ENABLED, "false") == "true"- if (alreadyTracking) {+ // Liveness, not the intent flag: a flag left true by a service the system killed would+ // make this recovery a permanent no-op, which is the window it exists to cover.+ if (LocationForegroundService.isRunning) {// Manual start / cable-wobble race already brought tracking back.AppLogger.d(TAG, "Already tracking - skipping resume")return Result.success()diff --git a/apps/mobile/android/app/src/test/java/com/Colota/bridge/LocationServiceModuleTest.kt b/apps/mobile/android/app/src/test/java/com/Colota/bridge/LocationServiceModuleTest.ktindex 67507fbe..88ea9ca2 100644--- a/apps/mobile/android/app/src/test/java/com/Colota/bridge/LocationServiceModuleTest.kt+++ b/apps/mobile/android/app/src/test/java/com/Colota/bridge/LocationServiceModuleTest.kt@@ -5,6 +5,7 @@package com.Colota.bridge+import android.content.Intentimport android.location.Locationimport com.Colota.data.DatabaseHelperimport com.Colota.data.GeofenceHelper@@ -54,6 +55,8 @@ class LocationServiceModuleTest {every { Arguments.createMap() } returns JavaOnlyMap()mockkObject(DatabaseHelper.Companion)+ mockkObject(LocationForegroundService.Companion)+ every { LocationForegroundService.isRunning } returns truesetCompanionField("reactContextRef", WeakReference(mockContext))setCompanionField("isAppInForeground", true)@@ -65,6 +68,7 @@ class LocationServiceModuleTest {unmockkObject(AppLogger)unmockkStatic(Arguments::class)unmockkObject(DatabaseHelper.Companion)+ unmockkObject(LocationForegroundService.Companion)setCompanionField("reactContextRef", WeakReference<ReactApplicationContext>(null))setCompanionField("isAppInForeground", true)setCompanionField("activeProfileName", null)@@ -404,9 +408,9 @@ class LocationServiceModuleTest {// ========================================================================@Test- fun `triggerProfileRecheck skips when tracking disabled`() {- val (module, dbHelper) = createModuleWithDeps()- every { dbHelper.getSetting("tracking_enabled", "false") } returns "false"+ fun `triggerProfileRecheck skips when the service is not running`() {+ val (module, _) = createModuleWithDeps()+ every { LocationForegroundService.isRunning } returns falseinvokePrivate(module, "triggerProfileRecheck")@@ -414,23 +418,38 @@ class LocationServiceModuleTest {}@Test- fun `triggerProfileRecheck dispatches when tracking enabled`() {+ fun `triggerProfileRecheck dispatches when the service is running`() {+ val (module, _) = createModuleWithDeps()+ every { LocationForegroundService.isRunning } returns true++ invokePrivate(module, "triggerProfileRecheck")++ verify { module["startServiceWithAction"](LocationForegroundService.ACTION_RECHECK_PROFILES) }+ }++ /**+ * The intent flag outlives a service the system killed, so gating on it used to send a+ * lightweight action to nothing - cold-starting a service that never begins tracking.+ */+ @Test+ fun `triggerProfileRecheck skips a dead service even though the user still wants tracking`() {val (module, dbHelper) = createModuleWithDeps()every { dbHelper.getSetting("tracking_enabled", "false") } returns "true"+ every { LocationForegroundService.isRunning } returns falseinvokePrivate(module, "triggerProfileRecheck")- verify { module["startServiceWithAction"](LocationForegroundService.ACTION_RECHECK_PROFILES) }+ verify(exactly = 0) { module["startServiceWithAction"](any<String>()) }}// ========================================================================- // refreshNotificationIfTracking — only dispatches when tracking is enabled+ // refreshNotificationIfTracking — only dispatches when the service is alive// ========================================================================@Test- fun `refreshNotificationIfTracking skips when not tracking`() {- val (module, dbHelper) = createModuleWithDeps()- every { dbHelper.getSetting("tracking_enabled", "false") } returns "false"+ fun `refreshNotificationIfTracking skips when the service is not running`() {+ val (module, _) = createModuleWithDeps()+ every { LocationForegroundService.isRunning } returns falseinvokePrivate(module, "refreshNotificationIfTracking")@@ -438,15 +457,79 @@ class LocationServiceModuleTest {}@Test- fun `refreshNotificationIfTracking dispatches when tracking`() {- val (module, dbHelper) = createModuleWithDeps()- every { dbHelper.getSetting("tracking_enabled", "false") } returns "true"+ fun `refreshNotificationIfTracking dispatches when the service is running`() {+ val (module, _) = createModuleWithDeps()+ every { LocationForegroundService.isRunning } returns trueinvokePrivate(module, "refreshNotificationIfTracking")verify { module["startServiceWithAction"](LocationForegroundService.ACTION_REFRESH_NOTIFICATION) }}+ // ========================================================================+ // triggerZoneRecheck — same liveness gate+ // ========================================================================++ @Test+ fun `triggerZoneRecheck skips when the service is not running`() {+ val (module, _) = createModuleWithDeps()+ every { LocationForegroundService.isRunning } returns false++ invokePrivate(module, "triggerZoneRecheck")++ verify(exactly = 0) { module["startServiceWithAction"](any<String>()) }+ }++ @Test+ fun `triggerZoneRecheck dispatches when the service is running`() {+ val (module, _) = createModuleWithDeps()+ every { LocationForegroundService.isRunning } returns true++ invokePrivate(module, "triggerZoneRecheck")++ verify { module["startServiceWithAction"](LocationForegroundService.ACTION_RECHECK_ZONE) }+ }++ // ========================================================================+ // stopService — intent is cleared before the service goes away+ // ========================================================================++ /**+ * Written after the stop, the flag left a window where the service was already gone but the+ * user's intent still read true - long enough for a liveness check to restart what they+ * had just turned off.+ */+ @Test+ fun `stopService clears the user's intent before stopping the service`() {+ val (module, dbHelper) = createModuleWithDeps()+ mockkConstructor(Intent::class)+ try {+ module.stopService()++ verifyOrder {+ dbHelper.saveSetting("tracking_enabled", "false")+ mockContext.stopService(any())+ }+ } finally {+ unmockkConstructor(Intent::class)+ }+ }++ // ========================================================================+ // isServiceRunning+ // ========================================================================++ @Test+ fun `isServiceRunning resolves the service's own liveness flag`() {+ val (module, _) = createModuleWithDeps()+ val promise = mockk<com.facebook.react.bridge.Promise>(relaxed = true)+ every { LocationForegroundService.isRunning } returns true++ module.isServiceRunning(promise)++ verify { promise.resolve(true) }+ }+// ========================================================================// Module name// ========================================================================diff --git a/apps/mobile/android/app/src/test/java/com/Colota/service/BatteryRecoveryWorkerTest.kt b/apps/mobile/android/app/src/test/java/com/Colota/service/BatteryRecoveryWorkerTest.ktindex cac5799b..24fe0b59 100644--- a/apps/mobile/android/app/src/test/java/com/Colota/service/BatteryRecoveryWorkerTest.kt+++ b/apps/mobile/android/app/src/test/java/com/Colota/service/BatteryRecoveryWorkerTest.kt@@ -87,15 +87,37 @@ class BatteryRecoveryWorkerTest {}@Test- fun `skips resume when tracking is already active`() {+ fun `skips resume when the service is already running`() {+ db.saveSetting(SettingsKeys.STOPPED_BY_BATTERY, "true")++ mockkObject(LocationForegroundService.Companion)+ try {+ every { LocationForegroundService.isRunning } returns true++ val result = runWorker()++ assertEquals(ListenableWorker.Result.success(), result)+ assertNull("Already tracking - must not double-start", shadowOf(app).nextStartedService)+ verify(exactly = 0) { LocationServiceModule.sendTrackingStartedEvent(any()) }+ } finally {+ unmockkObject(LocationForegroundService.Companion)+ }+ }++ /**+ * A service the system killed leaves the intent flag true. Gating on that flag made this+ * recovery a permanent no-op for exactly the users it exists to rescue.+ */+ @Test+ fun `resumes when the intent flag is stale-true but the service is dead`() {db.saveSetting(SettingsKeys.STOPPED_BY_BATTERY, "true")db.saveSetting(SettingsKeys.TRACKING_ENABLED, "true")val result = runWorker()assertEquals(ListenableWorker.Result.success(), result)- assertNull("Already tracking - must not double-start", shadowOf(app).nextStartedService)- verify(exactly = 0) { LocationServiceModule.sendTrackingStartedEvent(any()) }+ assertNotNull("A dead service must still be resumed", shadowOf(app).nextStartedService)+ verify { LocationServiceModule.sendTrackingStartedEvent(any()) }}@Testdiff --git a/apps/mobile/src/services/NativeLocationService.ts b/apps/mobile/src/services/NativeLocationService.tsindex 1b1dab66..cadacd40 100644--- a/apps/mobile/src/services/NativeLocationService.ts+++ b/apps/mobile/src/services/NativeLocationService.ts@@ -120,6 +120,21 @@ class NativeLocationService {return state === "true"}+ /**+ * Whether a native service instance is alive right now.+ * Null means the answer is unknown - callers must not read that as "dead".+ */+ static async isServiceRunning(): Promise<boolean | null> {+ return this.safeExecute(+ () => {+ this.ensureModule()+ return LocationServiceModule.isServiceRunning()+ },+ null,+ "isServiceRunning failed"+ )+ }+// ============================================================================// QUEUE OPERATIONS// ============================================================================diff --git a/apps/mobile/src/services/__tests__/NativeLocationService.test.ts b/apps/mobile/src/services/__tests__/NativeLocationService.test.tsindex 878bb15f..13557f93 100644--- a/apps/mobile/src/services/__tests__/NativeLocationService.test.ts+++ b/apps/mobile/src/services/__tests__/NativeLocationService.test.ts@@ -211,6 +211,18 @@ describe("NativeLocationService", () => {})})+ describe("isServiceRunning", () => {+ it("reports the native service's own liveness", async () => {+ nativeMock.isServiceRunning.mockResolvedValueOnce(false)+ expect(await NativeLocationService.isServiceRunning()).toBe(false)+ })++ it("returns null when the bridge fails, so callers cannot mistake it for a dead service", async () => {+ nativeMock.isServiceRunning.mockRejectedValueOnce(new Error("bridge gone"))+ expect(await NativeLocationService.isServiceRunning()).toBeNull()+ })+ })+describe("getStats", () => {it("returns database stats", async () => {const stats = await NativeLocationService.getStats()