Colota - Android GPS Location tracker
Harden codebase: fix sync logic, UX feedback, battery safety, and audit issues
Max Dietrich1447dee96e0c
diff --git a/apps/mobile/android/app/src/foss/java/com/Colota/location/NativeLocationProvider.kt b/apps/mobile/android/app/src/foss/java/com/Colota/location/NativeLocationProvider.ktindex b48dad9e..554b13fb 100644--- a/apps/mobile/android/app/src/foss/java/com/Colota/location/NativeLocationProvider.kt+++ b/apps/mobile/android/app/src/foss/java/com/Colota/location/NativeLocationProvider.kt@@ -26,7 +26,7 @@ class NativeLocationProvider(context: Context) : LocationProvider {context.getSystemService(Context.LOCATION_SERVICE) as LocationManager/** Maps each callback to its GPS listener and optional network listener. */- private val listenerMap = mutableMapOf<LocationUpdateCallback, List<LocationListener>>()+ private val listenerMap = java.util.concurrent.ConcurrentHashMap<LocationUpdateCallback, List<LocationListener>>()override fun requestLocationUpdates(intervalMs: Long,diff --git a/apps/mobile/android/app/src/gms/java/com/Colota/location/GmsLocationProvider.kt b/apps/mobile/android/app/src/gms/java/com/Colota/location/GmsLocationProvider.ktindex 6a130f09..3202702e 100644--- a/apps/mobile/android/app/src/gms/java/com/Colota/location/GmsLocationProvider.kt+++ b/apps/mobile/android/app/src/gms/java/com/Colota/location/GmsLocationProvider.kt@@ -19,7 +19,7 @@ class GmsLocationProvider(context: Context) : LocationProvider {private val fusedClient: FusedLocationProviderClient =LocationServices.getFusedLocationProviderClient(context)- private val callbackMap = mutableMapOf<LocationUpdateCallback, LocationCallback>()+ private val callbackMap = java.util.concurrent.ConcurrentHashMap<LocationUpdateCallback, LocationCallback>()override fun requestLocationUpdates(intervalMs: Long,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 4d772a70..2d5f214f 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@@ -23,6 +23,7 @@ import com.facebook.react.modules.core.DeviceEventManagerModuleimport com.Colota.location.LocationProviderFactoryimport org.json.JSONObjectimport kotlinx.coroutines.*+import java.lang.ref.WeakReference/*** React Native bridge module for managing the Location Service.@@ -43,13 +44,13 @@ class LocationServiceModule(reactContext: ReactApplicationContext) :private val moduleScope = CoroutineScope(Dispatchers.IO + SupervisorJob())init {- reactContextStatic = reactContext+ reactContextRef = WeakReference(reactContext)reactContext.addLifecycleEventListener(this)}companion object {private const val TAG = "LocationServiceModule"- private var reactContextStatic: ReactApplicationContext? = null+ private var reactContextRef: WeakReference<ReactApplicationContext> = WeakReference(null)@Volatileprivate var isAppInForeground: Boolean = true@@ -59,7 +60,7 @@ class LocationServiceModule(reactContext: ReactApplicationContext) :fun sendLocationEvent(location: android.location.Location, battery: Int, batteryStatus: Int): Boolean {if (!isAppInForeground) return false- val context = reactContextStatic ?: return false+ val context = reactContextRef.get() ?: return falseif (!context.hasActiveCatalystInstance()) return falsereturn try {@@ -94,7 +95,7 @@ class LocationServiceModule(reactContext: ReactApplicationContext) :/** Fires when service stops for non-user reasons (OOM kill, system cleanup). */@JvmStaticfun sendTrackingStoppedEvent(reason: String): Boolean {- val context = reactContextStatic ?: return false+ val context = reactContextRef.get() ?: return falseif (!context.hasActiveCatalystInstance()) return falsereturn try {@@ -114,7 +115,7 @@ class LocationServiceModule(reactContext: ReactApplicationContext) :/** Only fires after 3+ consecutive sync failures — see SyncManager.startPeriodicSync(). */@JvmStaticfun sendSyncErrorEvent(message: String, queuedCount: Int): Boolean {- val context = reactContextStatic ?: return false+ val context = reactContextRef.get() ?: return falseif (!context.hasActiveCatalystInstance()) return falsereturn try {@@ -135,7 +136,7 @@ class LocationServiceModule(reactContext: ReactApplicationContext) :/** Emits pause zone entry/exit events for the JS geofence UI. */@JvmStaticfun sendPauseZoneEvent(entered: Boolean, zoneName: String?): Boolean {- val context = reactContextStatic ?: return false+ val context = reactContextRef.get() ?: return falseif (!context.hasActiveCatalystInstance()) return falsereturn try {@@ -170,7 +171,7 @@ class LocationServiceModule(reactContext: ReactApplicationContext) :override fun invalidate() {moduleScope.cancel()- reactContextStatic = null+ reactContextRef.clear()super.invalidate()}@@ -189,7 +190,7 @@ class LocationServiceModule(reactContext: ReactApplicationContext) :}@ReactMethod- fun startService(config: ReadableMap) {+ fun startService(config: ReadableMap, promise: Promise) {Log.d(TAG, "Starting Service with config")moduleScope.launch(Dispatchers.IO) {@@ -206,8 +207,10 @@ class LocationServiceModule(reactContext: ReactApplicationContext) :} else {reactApplicationContext.startService(serviceIntent)}+ promise.resolve(null)} catch (e: Exception) {Log.e(TAG, "Failed to start service", e)+ promise.reject("START_FAILED", e.message, e)}}diff --git a/apps/mobile/android/app/src/main/java/com/colota/data/DatabaseHelper.kt b/apps/mobile/android/app/src/main/java/com/colota/data/DatabaseHelper.ktindex fb3778aa..796d3f56 100644--- a/apps/mobile/android/app/src/main/java/com/colota/data/DatabaseHelper.kt+++ b/apps/mobile/android/app/src/main/java/com/colota/data/DatabaseHelper.kt@@ -249,9 +249,13 @@ class DatabaseHelper private constructor(context: Context) :}}+ private val ALLOWED_TABLES = setOf(TABLE_LOCATIONS, TABLE_QUEUE, TABLE_SETTINGS, TABLE_GEOFENCES)+fun getTableData(tableName: String, limit: Int, offset: Int): List<Map<String, Any?>> {+ require(tableName in ALLOWED_TABLES) { "Invalid table name: $tableName" }+val data = mutableListOf<Map<String, Any?>>()-+val orderBy = when(tableName) {TABLE_LOCATIONS -> "timestamp DESC"TABLE_QUEUE -> "created_at DESC"@@ -494,8 +498,12 @@ class DatabaseHelper private constructor(context: Context) :/** Reclaims unused space. Call from background thread only. */fun vacuum() {- writableDatabase.execSQL("VACUUM")- writableDatabase.execSQL("ANALYZE")+ try {+ writableDatabase.execSQL("VACUUM")+ writableDatabase.execSQL("ANALYZE")+ } catch (e: Exception) {+ Log.e(TAG, "Vacuum failed (likely concurrent access)", e)+ }}diff --git a/apps/mobile/android/app/src/main/java/com/colota/data/GeofenceHelper.kt b/apps/mobile/android/app/src/main/java/com/colota/data/GeofenceHelper.ktindex ad1267ff..fb986ee1 100644--- a/apps/mobile/android/app/src/main/java/com/colota/data/GeofenceHelper.kt+++ b/apps/mobile/android/app/src/main/java/com/colota/data/GeofenceHelper.kt@@ -98,35 +98,39 @@ class GeofenceHelper(private val context: Context) {fun getGeofencesAsArray(): WritableArray {val array = Arguments.createArray()-- dbHelper.readableDatabase.query(- DatabaseHelper.TABLE_GEOFENCES,- null, null, null, null, null,- "created_at DESC"- ).use { cursor ->- val idIdx = cursor.getColumnIndexOrThrow("id")- val nameIdx = cursor.getColumnIndexOrThrow("name")- val latIdx = cursor.getColumnIndexOrThrow("latitude")- val lonIdx = cursor.getColumnIndexOrThrow("longitude")- val radiusIdx = cursor.getColumnIndexOrThrow("radius")- val enabledIdx = cursor.getColumnIndexOrThrow("enabled")- val pauseIdx = cursor.getColumnIndexOrThrow("pause_tracking")- val createdIdx = cursor.getColumnIndexOrThrow("created_at")-- while (cursor.moveToNext()) {- array.pushMap(Arguments.createMap().apply {- putInt("id", cursor.getInt(idIdx))- putString("name", cursor.getString(nameIdx))- putDouble("lat", cursor.getDouble(latIdx))- putDouble("lon", cursor.getDouble(lonIdx))- putDouble("radius", cursor.getDouble(radiusIdx))- putBoolean("enabled", cursor.getInt(enabledIdx) == 1)- putBoolean("pauseTracking", cursor.getInt(pauseIdx) == 1)- putDouble("createdAt", cursor.getLong(createdIdx).toDouble())- })++ try {+ dbHelper.readableDatabase.query(+ DatabaseHelper.TABLE_GEOFENCES,+ null, null, null, null, null,+ "created_at DESC"+ ).use { cursor ->+ val idIdx = cursor.getColumnIndexOrThrow("id")+ val nameIdx = cursor.getColumnIndexOrThrow("name")+ val latIdx = cursor.getColumnIndexOrThrow("latitude")+ val lonIdx = cursor.getColumnIndexOrThrow("longitude")+ val radiusIdx = cursor.getColumnIndexOrThrow("radius")+ val enabledIdx = cursor.getColumnIndexOrThrow("enabled")+ val pauseIdx = cursor.getColumnIndexOrThrow("pause_tracking")+ val createdIdx = cursor.getColumnIndexOrThrow("created_at")++ while (cursor.moveToNext()) {+ array.pushMap(Arguments.createMap().apply {+ putInt("id", cursor.getInt(idIdx))+ putString("name", cursor.getString(nameIdx))+ putDouble("lat", cursor.getDouble(latIdx))+ putDouble("lon", cursor.getDouble(lonIdx))+ putDouble("radius", cursor.getDouble(radiusIdx))+ putBoolean("enabled", cursor.getInt(enabledIdx) == 1)+ putBoolean("pauseTracking", cursor.getInt(pauseIdx) == 1)+ putDouble("createdAt", cursor.getLong(createdIdx).toDouble())+ })+ }}+ } catch (e: Exception) {+ Log.e(TAG, "Failed to load geofences as array", e)}-+return array}diff --git a/apps/mobile/android/app/src/main/java/com/colota/service/LocationForegroundService.kt b/apps/mobile/android/app/src/main/java/com/colota/service/LocationForegroundService.ktindex ce0495a4..82987bd0 100644--- a/apps/mobile/android/app/src/main/java/com/colota/service/LocationForegroundService.kt+++ b/apps/mobile/android/app/src/main/java/com/colota/service/LocationForegroundService.kt@@ -44,8 +44,8 @@ class LocationForegroundService : Service() {@Volatile private var serviceScope: CoroutineScope? = null@Volatile private var locationUpdateCallback: LocationUpdateCallback? = null- private var insidePauseZone = false- private var currentZoneName: String? = null+ @Volatile private var insidePauseZone = false+ @Volatile private var currentZoneName: String? = nullprivate var lastNotificationText: String? = nullprivate var lastNotificationTime: Long = 0@@ -311,6 +311,15 @@ class LocationForegroundService : Service() {}val (battery, batteryStatus) = deviceInfoHelper.getCachedBatteryStatus()++ if (battery in 1..4 && batteryStatus == 1) {+ if (BuildConfig.DEBUG) {+ Log.d(TAG, "Battery critical ($battery%) during tracking - stopping")+ }+ stopForegroundServiceWithReason("Battery critical")+ return+ }+val timestampSec = location.time / 1000val currentFieldMap = fieldMap ?: emptyMap()@@ -455,12 +464,9 @@ class LocationForegroundService : Service() {) {val now = System.currentTimeMillis()val lastCoords = lastNotificationCoords-- // Check if this is a zone change (always update immediately)- val isZoneChange = pausedInZone != insidePauseZone || zoneName != currentZoneName-- // Apply smart filtering unless forced or zone change- if (!forceUpdate && !isZoneChange && lat != null && lon != null) {++ // Apply smart filtering unless forced (zone changes always pass forceUpdate=true)+ if (!forceUpdate && lat != null && lon != null) {// Throttle: don't update more than once per 10 secondsif ((now - lastNotificationTime) < NOTIFICATION_THROTTLE_MS) {returndiff --git a/apps/mobile/android/app/src/main/java/com/colota/service/ServiceConfig.kt b/apps/mobile/android/app/src/main/java/com/colota/service/ServiceConfig.ktindex a13199bb..279766b6 100644--- a/apps/mobile/android/app/src/main/java/com/colota/service/ServiceConfig.kt+++ b/apps/mobile/android/app/src/main/java/com/colota/service/ServiceConfig.kt@@ -35,13 +35,13 @@ data class ServiceConfig(return ServiceConfig(endpoint = saved["endpoint"] ?: "",- interval = saved["interval"]?.toLongOrNull() ?: 1000L,+ interval = saved["interval"]?.toLongOrNull() ?: 5000L,minUpdateDistance = saved["minUpdateDistance"]?.toFloatOrNull() ?: 0f,syncIntervalSeconds = saved["syncInterval"]?.toIntOrNull() ?: 0,maxRetries = saved["maxRetries"]?.toIntOrNull() ?: 5,accuracyThreshold = saved["accuracyThreshold"]?.toFloatOrNull() ?: 50.0f,- filterInaccurateLocations = saved["filterInaccurateLocations"]?.toBoolean() ?: true,- retryIntervalSeconds = saved["retryInterval"]?.toIntOrNull() ?: 300,+ filterInaccurateLocations = saved["filterInaccurateLocations"]?.toBoolean() ?: false,+ retryIntervalSeconds = saved["retryInterval"]?.toIntOrNull() ?: 30,isOfflineMode = saved["isOfflineMode"]?.toBoolean() ?: false,isWifiOnlySync = saved["isWifiOnlySync"]?.toBoolean() ?: false,fieldMap = saved["fieldMap"],diff --git a/apps/mobile/android/app/src/main/java/com/colota/sync/SyncManager.kt b/apps/mobile/android/app/src/main/java/com/colota/sync/SyncManager.ktindex 31f4f3b1..349e7769 100644--- a/apps/mobile/android/app/src/main/java/com/colota/sync/SyncManager.kt+++ b/apps/mobile/android/app/src/main/java/com/colota/sync/SyncManager.kt@@ -26,14 +26,14 @@ class SyncManager(private const val TAG = "SyncManager"}- private var endpoint: String = ""- private var syncIntervalSeconds: Int = 0- private var retryIntervalSeconds: Int = 300- private var maxRetries: Int = 5- private var isOfflineMode: Boolean = false- private var isWifiOnlySync: Boolean = false- private var authHeaders: Map<String, String> = emptyMap()- private var httpMethod: String = "POST"+ @Volatile private var endpoint: String = ""+ @Volatile private var syncIntervalSeconds: Int = 0+ @Volatile private var retryIntervalSeconds: Int = 300+ @Volatile private var maxRetries: Int = 5+ @Volatile private var isOfflineMode: Boolean = false+ @Volatile private var isWifiOnlySync: Boolean = false+ @Volatile private var authHeaders: Map<String, String> = emptyMap()+ @Volatile private var httpMethod: String = "POST"private var syncJob: Job? = null@Volatile private var lastSyncTime: Long = 0@@ -136,7 +136,7 @@ class SyncManager(// Immediate send mode (syncInterval = 0)if (syncIntervalSeconds == 0 && networkManager.isNetworkAvailable() &&!(isWifiOnlySync && !networkManager.isUnmeteredConnection())) {- Log.d(TAG, "Instant send")+ if (BuildConfig.DEBUG) Log.d(TAG, "Instant send")val success = networkManager.sendToEndpoint(payload, endpoint, authHeaders, httpMethod)if (success) {@@ -187,6 +187,7 @@ class SyncManager(private suspend fun syncQueue() = coroutineScope {var totalProcessed = 0+ var totalSucceeded = 0var batchNumber = 1while (isActive && batchNumber <= MAX_BATCHES_PER_SYNC) {@@ -246,6 +247,7 @@ class SyncManager(if (toRemove.isNotEmpty()) {dbHelper.removeBatchFromQueue(toRemove)totalProcessed += toRemove.size+ totalSucceeded += successfulIds.size}yield()@@ -260,7 +262,7 @@ class SyncManager(invalidateQueueCache()- if (totalProcessed > 0) {+ if (totalSucceeded > 0) {lastSuccessfulSyncTime = System.currentTimeMillis()}}diff --git a/apps/mobile/android/app/src/main/java/com/colota/util/TimedCache.kt b/apps/mobile/android/app/src/main/java/com/colota/util/TimedCache.ktindex 3537301a..dfc53f11 100644--- a/apps/mobile/android/app/src/main/java/com/colota/util/TimedCache.kt+++ b/apps/mobile/android/app/src/main/java/com/colota/util/TimedCache.kt@@ -18,6 +18,7 @@ class TimedCache<T>(@Volatile private var value: T? = null@Volatile private var lastCheck: Long = 0+ @Synchronizedfun get(): T {val now = System.currentTimeMillis()if (value == null || (now - lastCheck) > ttlMs) {@@ -27,6 +28,7 @@ class TimedCache<T>(return value!!}+ @Synchronizedfun invalidate() {lastCheck = 0}diff --git a/apps/mobile/src/components/features/inspector/TrackMap.tsx b/apps/mobile/src/components/features/inspector/TrackMap.tsxindex b98f424e..43e289b8 100644--- a/apps/mobile/src/components/features/inspector/TrackMap.tsx+++ b/apps/mobile/src/components/features/inspector/TrackMap.tsx@@ -262,8 +262,13 @@ export function TrackMap({ locations, selectedPoint, colors, isDark }: Props) {document.addEventListener("message", handleInternalMessage);map.on("moveend", () => {+ var centered = true;+ if (currentExtent) {+ var viewExtent = map.getView().calculateExtent(map.getSize());+ centered = ol.extent.containsExtent(viewExtent, currentExtent);+ }window.ReactNativeWebView.postMessage(- JSON.stringify({ type: "CENTERED", value: true })+ JSON.stringify({ type: "CENTERED", value: centered }));});diff --git a/apps/mobile/src/components/features/settings/SyncStrategySettings.tsx b/apps/mobile/src/components/features/settings/SyncStrategySettings.tsxindex 1a3da0c6..6b0381ee 100644--- a/apps/mobile/src/components/features/settings/SyncStrategySettings.tsx+++ b/apps/mobile/src/components/features/settings/SyncStrategySettings.tsx@@ -31,11 +31,12 @@ export function SyncStrategySettings({const [accuracyThresholdInput, setAccuracyTresholdInput] = useState(settings.accuracyThreshold.toString())const [showAdvanced, setShowAdvanced] = useState(false)- // Sync inputs with settings changes+ // Sync inputs with settings changes (e.g. preset selection)useEffect(() => {setIntervalInput(settings.interval.toString())setDistanceInput(settings.distance?.toString() || "0")- }, [settings.interval, settings.distance])+ setAccuracyTresholdInput(settings.accuracyThreshold.toString())+ }, [settings.interval, settings.distance, settings.accuracyThreshold])const handleNumericChange = useCallback((key: "interval" | "distance" | "accuracyThreshold", value: string, min: number = 0) => {@@ -46,11 +47,10 @@ export function SyncStrategySettings({const num = Number(value)if (!isNaN(num) && num >= min) {const next = { ...settings, [key]: num, syncPreset: "custom" as const }- onSettingsChange(next)onDebouncedSave(next)}},- [settings, onSettingsChange, onDebouncedSave]+ [settings, onDebouncedSave])const handleNumericBlur = useCallback(@@ -92,6 +92,7 @@ export function SyncStrategySettings({retryInterval: config.retryInterval}+ onSettingsChange(next)onImmediateSave(next)},[settings, onSettingsChange, onImmediateSave]diff --git a/apps/mobile/src/components/features/settings/__tests__/SyncStrategySettings.test.tsx b/apps/mobile/src/components/features/settings/__tests__/SyncStrategySettings.test.tsxindex 40c0d866..d2ca0398 100644--- a/apps/mobile/src/components/features/settings/__tests__/SyncStrategySettings.test.tsx+++ b/apps/mobile/src/components/features/settings/__tests__/SyncStrategySettings.test.tsx@@ -97,6 +97,14 @@ describe("SyncStrategySettings", () => {fireEvent.press(getByTestId("preset-balanced"))+ expect(mockOnSettingsChange).toHaveBeenCalledWith(+ expect.objectContaining({+ syncPreset: "balanced",+ interval: TRACKING_PRESETS.balanced.interval,+ distance: TRACKING_PRESETS.balanced.distance,+ syncInterval: TRACKING_PRESETS.balanced.syncInterval+ })+ )expect(mockOnImmediateSave).toHaveBeenCalledWith(expect.objectContaining({syncPreset: "balanced",@@ -173,7 +181,12 @@ describe("SyncStrategySettings", () => {syncPreset: "custom"}))- expect(mockOnDebouncedSave).toHaveBeenCalled()+ expect(mockOnDebouncedSave).toHaveBeenCalledWith(+ expect.objectContaining({+ syncInterval: 300,+ syncPreset: "custom"+ })+ )})})diff --git a/apps/mobile/src/contexts/TrackingProvider.tsx b/apps/mobile/src/contexts/TrackingProvider.tsxindex 2ae47ee8..cf449e84 100644--- a/apps/mobile/src/contexts/TrackingProvider.tsx+++ b/apps/mobile/src/contexts/TrackingProvider.tsx@@ -14,6 +14,7 @@ import { logger } from "../utils/logger"type TrackingContextType = {settings: SettingssetSettings: (s: Settings) => Promise<void>+ updateSettingsLocal: (s: Settings) => voidcoords: LocationCoords | nulltracking: booleanisLoading: boolean@@ -243,6 +244,7 @@ export function TrackingProvider({ children }: { children: React.ReactNode }) {() => ({settings,setSettings,+ updateSettingsLocal: setSettingsState,coords,tracking,isLoading,diff --git a/apps/mobile/src/hooks/__tests__/useAutoSave.test.ts b/apps/mobile/src/hooks/__tests__/useAutoSave.test.tsindex 9ad3b478..9eb5f79a 100644--- a/apps/mobile/src/hooks/__tests__/useAutoSave.test.ts+++ b/apps/mobile/src/hooks/__tests__/useAutoSave.test.ts@@ -73,7 +73,7 @@ describe("useAutoSave", () => {expect(saveFn2).toHaveBeenCalledTimes(1)})- it("sets saving=true during save, then schedules restart", async () => {+ it("sets saving=true during save, then restarts immediately", async () => {const saveFn = jest.fn().mockResolvedValue(undefined)const restartFn = jest.fn().mockResolvedValue(undefined)const { result } = renderHook(() => useAutoSave())@@ -86,14 +86,8 @@ describe("useAutoSave", () => {jest.advanceTimersByTime(AUTOSAVE_DEBOUNCE_MS)})- // After save completes, restart is debounced+ // After debounced save completes, restart fires immediately (no second debounce)expect(saveFn).toHaveBeenCalled()- expect(restartFn).not.toHaveBeenCalled()-- await act(async () => {- jest.advanceTimersByTime(AUTOSAVE_DEBOUNCE_MS)- })-expect(restartFn).toHaveBeenCalledTimes(1)})@@ -106,12 +100,7 @@ describe("useAutoSave", () => {result.current.debouncedSaveAndRestart(saveFn, restartFn)})- // Trigger save- await act(async () => {- jest.advanceTimersByTime(AUTOSAVE_DEBOUNCE_MS)- })-- // Trigger restart+ // Trigger save + restart (restart fires immediately after debounced save)await act(async () => {jest.advanceTimersByTime(AUTOSAVE_DEBOUNCE_MS)})@@ -152,10 +141,7 @@ describe("useAutoSave", () => {result.current.debouncedSaveAndRestart(saveFn, restartFn)})- await act(async () => {- jest.advanceTimersByTime(AUTOSAVE_DEBOUNCE_MS)- })-+ // Save + restart both fire after debounce (restart is immediate after save)await act(async () => {jest.advanceTimersByTime(AUTOSAVE_DEBOUNCE_MS)})diff --git a/apps/mobile/src/hooks/useAutoSave.ts b/apps/mobile/src/hooks/useAutoSave.tsindex f90fe789..76b715dd 100644--- a/apps/mobile/src/hooks/useAutoSave.ts+++ b/apps/mobile/src/hooks/useAutoSave.ts@@ -33,17 +33,17 @@ export function useAutoSave() {setSaving(true)try {await saveFn()- restartTimeout.set(async () => {- try {- await restartFn()- setSaveSuccess(true)- successTimeout.set(() => setSaveSuccess(false), SAVE_SUCCESS_DISPLAY_MS)- } catch (err) {- logger.error("[useAutoSave] Restart failed:", err)- } finally {- setSaving(false)- }- }, AUTOSAVE_DEBOUNCE_MS)+ // Restart immediately — input was already debounced by saveTimeout+ restartTimeout.clear()+ try {+ await restartFn()+ setSaveSuccess(true)+ successTimeout.set(() => setSaveSuccess(false), SAVE_SUCCESS_DISPLAY_MS)+ } catch (err) {+ logger.error("[useAutoSave] Restart failed:", err)+ } finally {+ setSaving(false)+ }} catch (err) {setSaving(false)logger.error("[useAutoSave] Save failed:", err)diff --git a/apps/mobile/src/screens/AuthSettingsScreen.tsx b/apps/mobile/src/screens/AuthSettingsScreen.tsxindex f3945634..f1108d67 100644--- a/apps/mobile/src/screens/AuthSettingsScreen.tsx+++ b/apps/mobile/src/screens/AuthSettingsScreen.tsx@@ -84,8 +84,14 @@ export function AuthSettingsScreen({}: ScreenProps) {const headerEntries = Object.entries(config.customHeaders)const addHeader = useCallback(() => {+ // Use a unique placeholder key to avoid overwriting existing empty entries+ let key = ""+ let i = 1+ while (key in config.customHeaders) {+ key = `Header-${i++}`+ }updateConfig({- customHeaders: { ...config.customHeaders, "": "" }+ customHeaders: { ...config.customHeaders, [key]: "" }})}, [config, updateConfig])diff --git a/apps/mobile/src/screens/ExportDataScreen.tsx b/apps/mobile/src/screens/ExportDataScreen.tsxindex 3d37cbd4..df725966 100644--- a/apps/mobile/src/screens/ExportDataScreen.tsx+++ b/apps/mobile/src/screens/ExportDataScreen.tsx@@ -58,7 +58,7 @@ export function ExportDataScreen() {const content = EXPORT_FORMATS[selectedFormat].convert(cachedData.current)setFileSize(formatBytes(getByteSize(content)))- }, [selectedFormat])+ }, [selectedFormat, stats.totalLocations])const handleExport = async (format: ExportFormat) => {if (stats.totalLocations === 0) {@@ -125,14 +125,6 @@ export function ExportDataScreen() {} catch (shareError: any) {logger.warn("[ExportDataScreen] Share error:", shareError)}-- setTimeout(async () => {- try {- await NativeLocationService.deleteFile(filePath)- } catch (err) {- logger.warn("[ExportDataScreen] Failed to cleanup temp file:", err)- }- }, 2000)} catch (error) {logger.error("[ExportDataScreen] Export failed:", error)Alert.alert("Export Failed", "Unable to export your data. Please try again.")diff --git a/apps/mobile/src/screens/SettingsScreen.tsx b/apps/mobile/src/screens/SettingsScreen.tsxindex bd7476f4..524e86b1 100644--- a/apps/mobile/src/screens/SettingsScreen.tsx+++ b/apps/mobile/src/screens/SettingsScreen.tsx@@ -8,7 +8,7 @@ import { Text, StyleSheet, Switch, View, ScrollView, TouchableOpacity } from "reimport { ScreenProps, Settings } from "../types/global"import { useTheme } from "../hooks/useTheme"import { useAutoSave } from "../hooks/useAutoSave"-import { STATS_REFRESH_FAST } from "../constants"+import { STATS_REFRESH_FAST, STATS_REFRESH_IDLE } from "../constants"import NativeLocationService from "../services/NativeLocationService"import { useTracking } from "../contexts/TrackingProvider"import { FloatingSaveIndicator } from "../components/ui/FloatingSaveIndicator"@@ -25,7 +25,7 @@ import { SyncStrategySettings } from "../components/features/settings/SyncStrate* Features auto-save, presets, and advanced customization.*/export function SettingsScreen({ navigation }: ScreenProps) {- const { settings, setSettings, restartTracking } = useTracking()+ const { settings, setSettings, updateSettingsLocal, tracking, restartTracking } = useTracking()const { mode, toggleTheme, colors } = useTheme()const { saving, saveSuccess, debouncedSaveAndRestart, immediateSaveAndRestart } = useAutoSave()@@ -52,17 +52,16 @@ export function SettingsScreen({ navigation }: ScreenProps) {}}, [])- // Poll stats every 5 seconds+ // Poll stats: 3s when tracking, 30s when idleuseEffect(() => {updateStats()- const interval = setInterval(updateStats, STATS_REFRESH_FAST)+ const interval = setInterval(updateStats, tracking ? STATS_REFRESH_FAST : STATS_REFRESH_IDLE)return () => clearInterval(interval)- }, [updateStats])+ }, [updateStats, tracking])/** Debounced save + restart for continuous changes (text input, sliders) */const handleDebouncedSave = useCallback((newSettings: Settings) => {- setSettings(newSettings)debouncedSaveAndRestart(() => setSettings(newSettings),() => restartTracking(newSettings)@@ -74,7 +73,6 @@ export function SettingsScreen({ navigation }: ScreenProps) {/** Immediate save + restart for discrete changes (toggles, presets) */const handleImmediateSave = useCallback((newSettings: Settings) => {- setSettings(newSettings)immediateSaveAndRestart(() => setSettings(newSettings),() => restartTracking(newSettings)@@ -118,7 +116,7 @@ export function SettingsScreen({ navigation }: ScreenProps) {{/* Tracking Configuration */}<SyncStrategySettingssettings={settings}- onSettingsChange={setSettings}+ onSettingsChange={updateSettingsLocal}onDebouncedSave={handleDebouncedSave}onImmediateSave={handleImmediateSave}colors={colors}diff --git a/apps/mobile/src/services/NativeLocationService.ts b/apps/mobile/src/services/NativeLocationService.tsindex bc91869a..8be250ab 100644--- a/apps/mobile/src/services/NativeLocationService.ts+++ b/apps/mobile/src/services/NativeLocationService.ts@@ -64,7 +64,8 @@ class NativeLocationService {accuracyThreshold: settings.accuracyThreshold,isOfflineMode: settings.isOfflineMode,isWifiOnlySync: settings.isWifiOnlySync,- httpMethod: settings.httpMethod+ httpMethod: settings.httpMethod,+ customFields: Object.fromEntries(settings.customFields.filter((f) => f.key).map((f) => [f.key, f.value]))}logger.debug(diff --git a/apps/mobile/src/utils/exportConverters.ts b/apps/mobile/src/utils/exportConverters.tsindex f7c22a02..0a72273c 100644--- a/apps/mobile/src/utils/exportConverters.ts+++ b/apps/mobile/src/utils/exportConverters.ts@@ -19,7 +19,17 @@ export const getByteSize = (content: string): number => {let bytes = 0for (let i = 0; i < content.length; i++) {const code = content.charCodeAt(i)- bytes += code <= 0x7f ? 1 : code <= 0x7ff ? 2 : 3+ if (code <= 0x7f) {+ bytes += 1+ } else if (code <= 0x7ff) {+ bytes += 2+ } else if (code >= 0xd800 && code <= 0xdbff) {+ // High surrogate — pair encodes a 4-byte UTF-8 character+ bytes += 4+ i++ // skip the low surrogate+ } else {+ bytes += 3+ }}return bytes}