Colota - Android GPS Location tracker
fix(app): restart a dead tracking service when the app comes to the foreground (#607)
Max Dietrich52b33efe459a
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 e2cde643..e59e9fc8 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@@ -298,6 +298,15 @@ class LocationServiceModule(reactContext: ReactApplicationContext) :fun startService(config: ReadableMap, promise: Promise) {AppLogger.d(TAG, "Starting Service with config")+ // JS logging never reaches the exported log, so record here that this start is a+ // recovery - otherwise a report of "it stopped recording" shows the restart but+ // never says the service had died while the user still wanted tracking.+ if (!LocationForegroundService.isRunning &&+ dbHelper.getSetting(SettingsKeys.TRACKING_ENABLED, "false") == "true"+ ) {+ AppLogger.w(TAG, "Starting a service that died while tracking was on")+ }+val serviceConfig = ServiceConfig.fromReadableMap(config, dbHelper)val serviceIntent = Intent(reactApplicationContext, LocationForegroundService::class.java)serviceConfig.toIntent(serviceIntent)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 88ea9ca2..56f42072 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@@ -515,6 +515,44 @@ class LocationServiceModuleTest {}}+ // ========================================================================+ // startService — records a recovery start in the native log+ // ========================================================================++ /**+ * The JS reconciler's own logging never reaches the exported log, so this line is the+ * only evidence a report will carry that the service had died while tracking was on.+ */+ @Test+ fun `startService records that it is reviving a service which died while tracking was on`() {+ val (module, dbHelper) = createModuleWithDeps()+ every { LocationForegroundService.isRunning } returns false+ every { dbHelper.getSetting("tracking_enabled", "false") } returns "true"+ mockkConstructor(Intent::class)+ try {+ module.startService(JavaOnlyMap(), mockk(relaxed = true))++ verify { AppLogger.w(any(), "Starting a service that died while tracking was on") }+ } finally {+ unmockkConstructor(Intent::class)+ }+ }++ @Test+ fun `startService stays quiet on an ordinary user start`() {+ val (module, dbHelper) = createModuleWithDeps()+ every { LocationForegroundService.isRunning } returns false+ every { dbHelper.getSetting("tracking_enabled", "false") } returns "false"+ mockkConstructor(Intent::class)+ try {+ module.startService(JavaOnlyMap(), mockk(relaxed = true))++ verify(exactly = 0) { AppLogger.w(any(), "Starting a service that died while tracking was on") }+ } finally {+ unmockkConstructor(Intent::class)+ }+ }+// ========================================================================// isServiceRunning// ========================================================================diff --git a/apps/mobile/src/contexts/TrackingProvider.tsx b/apps/mobile/src/contexts/TrackingProvider.tsxindex efc1079e..52453804 100644--- a/apps/mobile/src/contexts/TrackingProvider.tsx+++ b/apps/mobile/src/contexts/TrackingProvider.tsx@@ -180,7 +180,9 @@ export function TrackingProvider({ children }: { children: React.ReactNode }) {}logger.debug("[TrackingContext] Re-syncing UI with active background service")- internalReconnect()+ // Pass the settings we just parsed: the hook's ref still holds the defaults until+ // the next render, and a restart from here would start the service configured wrong.+ internalReconnect(mergedSettings)// Restore active profile name from the running serviceconst profileName = await NativeLocationService.getActiveProfileName()diff --git a/apps/mobile/src/hooks/__tests__/useLocationTracking.test.ts b/apps/mobile/src/hooks/__tests__/useLocationTracking.test.tsindex 5975e545..518f79a3 100644--- a/apps/mobile/src/hooks/__tests__/useLocationTracking.test.ts+++ b/apps/mobile/src/hooks/__tests__/useLocationTracking.test.ts@@ -12,18 +12,22 @@ const mockStart = jest.fn().mockResolvedValue(undefined)const mockStop = jest.fn()const mockGetMostRecentLocation = jest.fn().mockResolvedValue(null)const mockIsTrackingActive = jest.fn().mockResolvedValue(false)+const mockIsServiceRunning = jest.fn().mockResolvedValue(true)jest.mock("../../services/NativeLocationService", () => ({start: (...args: any[]) => mockStart(...args),stop: (...args: any[]) => mockStop(...args),getMostRecentLocation: (...args: any[]) => mockGetMostRecentLocation(...args),- isTrackingActive: (...args: any[]) => mockIsTrackingActive(...args)+ isTrackingActive: (...args: any[]) => mockIsTrackingActive(...args),+ isServiceRunning: (...args: any[]) => mockIsServiceRunning(...args)}))// Mock permissionsconst mockEnsurePermissions = jest.fn().mockResolvedValue(true)+const mockCheckPermissions = jest.fn().mockResolvedValue({ location: true, background: true, notifications: true })jest.mock("../../services/LocationServicePermission", () => ({- ensurePermissions: (...args: any[]) => mockEnsurePermissions(...args)+ ensurePermissions: (...args: any[]) => mockEnsurePermissions(...args),+ checkPermissions: (...args: any[]) => mockCheckPermissions(...args)}))// Mock NativeEventEmitter as a class@@ -43,8 +47,13 @@ import { useLocationTracking } from "../useLocationTracking"beforeEach(() => {jest.clearAllMocks()+ // clearAllMocks keeps implementations, so restore the defaults each test explicitly overrides+ mockIsTrackingActive.mockResolvedValue(false)+ mockIsServiceRunning.mockResolvedValue(true)+ mockCheckPermissions.mockResolvedValue({ location: true, background: true, notifications: true })jest.spyOn(console, "log").mockImplementation()jest.spyOn(console, "error").mockImplementation()+ jest.spyOn(console, "warn").mockImplementation()})afterEach(() => {@@ -241,6 +250,21 @@ describe("useLocationTracking", () => {expect(result.current.tracking).toBe(true)})++ // Hydration reads settings from SQLite and reconnects in the same pass, before the hook's+ // settings ref has caught up - restarting on the ref would configure the service from defaults.+ it("restarts a dead service with the settings it was handed, not the stale ref", async () => {+ mockIsServiceRunning.mockResolvedValue(false)+ const stored = { ...DEFAULT_SETTINGS, interval: 42 }++ const { result } = renderHook(() => useLocationTracking(DEFAULT_SETTINGS))++ await act(async () => {+ await result.current.reconnect(stored)+ })++ expect(mockStart).toHaveBeenCalledWith(expect.objectContaining({ interval: 42 }))+ })})describe("AppState foreground sync", () => {@@ -315,6 +339,121 @@ describe("useLocationTracking", () => {expect(result.current.coords?.latitude).toBe(48.1)})+ /**+ * The #444 case: the user still wants tracking and the UI still shows it, but Android killed+ * the service. Nothing recorded until the user noticed and toggled Stop/Start by hand.+ */+ it("restarts the service when tracking is on but the service died", async () => {+ mockIsTrackingActive.mockResolvedValue(true)+ mockIsServiceRunning.mockResolvedValue(true)+ mockGetMostRecentLocation.mockResolvedValue(null)++ const { result } = renderHook(() => useLocationTracking(DEFAULT_SETTINGS))++ await act(async () => {+ await result.current.startTracking(DEFAULT_SETTINGS)+ })+ expect(mockStart).toHaveBeenCalledTimes(1)++ mockIsServiceRunning.mockResolvedValue(false)+ await act(async () => {+ await appStateCallback("active")+ })++ expect(mockStart).toHaveBeenCalledTimes(2)+ // A resume must never replay the disclosure or the battery/notification dialogs+ expect(mockEnsurePermissions).toHaveBeenCalledTimes(1)+ expect(result.current.tracking).toBe(true)+ })++ it("reconnects and restarts when the service died while the app was closed", async () => {+ mockIsTrackingActive.mockResolvedValue(true)+ mockIsServiceRunning.mockResolvedValue(false)+ mockGetMostRecentLocation.mockResolvedValue(null)++ const { result } = renderHook(() => useLocationTracking(DEFAULT_SETTINGS))++ await act(async () => {+ await appStateCallback("active")+ })++ expect(mockStart).toHaveBeenCalledTimes(1)+ expect(mockEnsurePermissions).not.toHaveBeenCalled()+ expect(result.current.tracking).toBe(true)+ })++ it("leaves a live service alone", async () => {+ mockIsTrackingActive.mockResolvedValue(true)+ mockIsServiceRunning.mockResolvedValue(true)+ mockGetMostRecentLocation.mockResolvedValue(null)++ const { result } = renderHook(() => useLocationTracking(DEFAULT_SETTINGS))++ await act(async () => {+ await result.current.startTracking(DEFAULT_SETTINGS)+ })++ await act(async () => {+ await appStateCallback("active")+ })++ expect(mockStart).toHaveBeenCalledTimes(1)+ expect(result.current.tracking).toBe(true)+ })++ // A bridge failure says nothing about the service - restarting on it would double-start.+ /**+ * Hydration and the foreground handler both reconcile on app open. Without a guard both+ * observe the service still down while the first start is in flight, and the service gets+ * a second onStartCommand it never needed. Caught on a device, not by the single-path tests.+ */+ it("starts a dead service only once when both reconcile paths fire together", async () => {+ mockIsTrackingActive.mockResolvedValue(true)+ mockIsServiceRunning.mockResolvedValue(false)+ mockGetMostRecentLocation.mockResolvedValue(null)++ const { result } = renderHook(() => useLocationTracking(DEFAULT_SETTINGS))++ await act(async () => {+ await Promise.all([result.current.reconnect(DEFAULT_SETTINGS), appStateCallback("active")])+ })++ expect(mockStart).toHaveBeenCalledTimes(1)+ })++ it("does not restart when liveness is unknown", async () => {+ mockIsTrackingActive.mockResolvedValue(true)+ mockIsServiceRunning.mockResolvedValue(null)+ mockGetMostRecentLocation.mockResolvedValue(null)++ const { result } = renderHook(() => useLocationTracking(DEFAULT_SETTINGS))++ await act(async () => {+ await result.current.startTracking(DEFAULT_SETTINGS)+ })++ await act(async () => {+ await appStateCallback("active")+ })++ expect(mockStart).toHaveBeenCalledTimes(1)+ })++ it("does not restart a dead service when location permission is gone", async () => {+ mockIsTrackingActive.mockResolvedValue(true)+ mockIsServiceRunning.mockResolvedValue(false)+ mockCheckPermissions.mockResolvedValue({ location: false, background: false, notifications: true })+ mockGetMostRecentLocation.mockResolvedValue(null)++ renderHook(() => useLocationTracking(DEFAULT_SETTINGS))++ await act(async () => {+ await appStateCallback("active")+ })++ expect(mockStart).not.toHaveBeenCalled()+ })+it("does nothing when transitioning to background", async () => {const { result } = renderHook(() => useLocationTracking(DEFAULT_SETTINGS))diff --git a/apps/mobile/src/hooks/useLocationTracking.ts b/apps/mobile/src/hooks/useLocationTracking.tsindex e4562c43..7212edd6 100644--- a/apps/mobile/src/hooks/useLocationTracking.ts+++ b/apps/mobile/src/hooks/useLocationTracking.ts@@ -8,7 +8,7 @@ import { AppState, NativeEventEmitter, NativeModules } from "react-native"import NativeLocationService from "../services/NativeLocationService"import { showAlert } from "../services/modalService"import { LocationCoords, Settings, LocationTrackingResult } from "../types/global"-import { ensurePermissions } from "../services/LocationServicePermission"+import { ensurePermissions, checkPermissions } from "../services/LocationServicePermission"import { SERVICE_RESTART_DELAY_MS, RESTART_DEBOUNCE_MS } from "../constants"import { logger } from "../utils/logger"@@ -39,6 +39,7 @@ export function useLocationTracking(settings: Settings): LocationTrackingResultconst settingsRef = useRef<Settings>(settings)const isTrackingRef = useRef(false)const restartingRef = useRef(false)+ const revivingRef = useRef(false)const restartQueuedRef = useRef(false)const listenerRef = useRef<any>(null)@@ -251,11 +252,43 @@ export function useLocationTracking(settings: Settings): LocationTrackingResult)/**- * Reconnects React state to an already-running native service.+ * Restarts the service when the user wants tracking but no service is alive.+ *+ * Deliberately skips ensurePermissions: the disclosure is already gated on the location+ * grants, but the notification request and the battery-exemption dialog are not, so+ * reusing it would pop system dialogs every time the app is foregrounded.+ */+ const reviveIfDead = useCallback(async (startSettings: Settings) => {+ // Hydration and the foreground handler both reach here on app open, and both would see+ // the service still down while the first start is in flight.+ if (revivingRef.current) return+ revivingRef.current = true++ try {+ const running = await NativeLocationService.isServiceRunning()+ if (running !== false) return // null = unknown, not dead++ const perms = await checkPermissions()+ if (!perms.location) {+ logger.warn("[useLocationTracking] Service is dead but location permission is gone, not restarting")+ return+ }++ logger.warn("[useLocationTracking] Tracking is on but the service is not running - restarting")+ await NativeLocationService.start(startSettings)+ } catch (error) {+ logger.error("[useLocationTracking] Restart of a dead service failed:", error)+ } finally {+ revivingRef.current = false+ }+ }, [])++ /**+ * Reconnects React state to a native service that should be running.* Used after app restart when tracking_enabled is true in the DB.- * Does NOT request permissions or restart the service.+ * Does NOT request permissions, but does restart the service if it died.*/- const reconnect = useCallback(async () => {+ const reconnect = useCallback(async (startSettings?: Settings) => {if (isTrackingRef.current) {logger.debug("[useLocationTracking] Already tracking, skip reconnect")return@@ -264,6 +297,8 @@ export function useLocationTracking(settings: Settings): LocationTrackingResultlogger.debug("[useLocationTracking] Reconnecting to active service")setTracking(true)+ await reviveIfDead(startSettings ?? settingsRef.current)+try {const latest = await NativeLocationService.getMostRecentLocation()if (latest) {@@ -282,12 +317,12 @@ export function useLocationTracking(settings: Settings): LocationTrackingResult} catch (err) {logger.error("[useLocationTracking] Failed to fetch location on reconnect:", err)}- }, [])+ }, [reviveIfDead])/*** Syncs tracking state and coords when app returns to foreground.* Detects external start/stop (e.g. app shortcuts) by comparing UI state- * against the DB's tracking_enabled flag.+ * against the DB's tracking_enabled flag, and restarts a service the system killed.*/useEffect(() => {const subscription = AppState.addEventListener("change", async (nextState) => {@@ -309,7 +344,10 @@ export function useLocationTracking(settings: Settings): LocationTrackingResult}setTracking(false)} else if (isTrackingRef.current && serviceActive) {- // Already in sync - refresh coords since events are suppressed while backgrounded+ // Intent and UI agree, but the service itself may have been killed meanwhile+ await reviveIfDead(settingsRef.current)++ // Refresh coords since events are suppressed while backgroundedNativeLocationService.getMostRecentLocation().then((latest) => {if (latest) {@@ -333,7 +371,7 @@ export function useLocationTracking(settings: Settings): LocationTrackingResult})return () => subscription.remove()- }, [reconnect])+ }, [reconnect, reviveIfDead])/*** Cleanup on unmountdiff --git a/apps/mobile/src/types/global.ts b/apps/mobile/src/types/global.tsindex 1549993a..aa38e6bf 100644--- a/apps/mobile/src/types/global.ts+++ b/apps/mobile/src/types/global.ts@@ -61,7 +61,7 @@ export interface LocationTrackingResult {startTracking: (overrideSettings?: Settings) => Promise<void>stopTracking: () => voidrestartTracking: (newSettings?: Settings) => Promise<void>- reconnect: () => Promise<void>+ reconnect: (settings?: Settings) => Promise<void>settings: Settings}