Colota - Android GPS Location tracker
feat: add per-zone WiFi pause and geofence editor screen (#247)
Max Dietrich56fd093ee243
diff --git a/apps/docs/docs/development/architecture.md b/apps/docs/docs/development/architecture.mdindex eb1016a7..e9d329d7 100644--- a/apps/docs/docs/development/architecture.md+++ b/apps/docs/docs/development/architecture.md@@ -135,6 +135,14 @@ HTTP client. Validates endpoints, enforces HTTPS for public hosts, injects authManages pause zones using the **haversine formula** for distance calculations. Maintains an in-memory cache of geofences that invalidates on CRUD changes.+Each geofence supports three independent GPS pause modes, configured per zone:++- **Pause tracking** - Stops saving and syncing locations inside the zone. GPS continues running to detect exit.+- **WiFi pause** - Stops GPS entirely when connected to an unmetered network (WiFi/Ethernet). Implemented via `ConnectivityManager.NetworkCallback`, which fires immediately on network availability changes. An active network counter handles devices with multiple simultaneous unmetered networks - GPS only resumes once all of them are gone, after a short debounce.+- **Motionless pause** - Stops GPS after no device motion is detected for a configurable timeout. Uses the hardware motion sensor (via `MotionDetector`) to resume GPS when movement is detected again.++When both WiFi and motionless pause are enabled, GPS only resumes when both conditions clear - WiFi disconnected **and** motion detected. Changes made in the editor take effect immediately even when already inside the zone, via `applyZoneSettingsIfChanged` on the next zone recheck.+### ProfileManagerEvaluates tracking profile conditions and switches GPS settings automatically. Supports four condition types: charging, Android Auto / car mode, speed above threshold, and speed below threshold. Uses a rolling speed buffer for averaged speed readings, deactivation delays (hysteresis) to prevent rapid toggling, and priority-based resolution when multiple profiles match.diff --git a/apps/docs/docs/guides/battery-optimization.md b/apps/docs/docs/guides/battery-optimization.mdindex 50a95017..0f6b0b55 100644--- a/apps/docs/docs/guides/battery-optimization.md+++ b/apps/docs/docs/guides/battery-optimization.md@@ -19,7 +19,7 @@ Settings and tips to reduce battery usage without losing GPS fixes.1. **Increase GPS interval** - 5s to 30s saves significant battery2. **Enable accuracy filtering** - Reject poor GPS fixes to avoid unnecessary processing3. **Use batch sync** instead of instant - Reduces network usage and wake-ups-4. **Create geofences** for home/work - Stops recording locations in known zones. GPS stays active inside the zone to reliably detect when you leave+4. **Create geofences** for home/work - Stops recording locations in known zones. Enable **Pause when on WiFi** to also stop GPS entirely when connected to your home network, or **Pause when motionless** to stop GPS after sitting still for a set time5. **Enable movement threshold** - 10-50m, skip stationary updates6. **Disable battery optimization** for Colota in Android settings to prevent the OS from killing the servicediff --git a/apps/docs/docs/guides/geofencing.md b/apps/docs/docs/guides/geofencing.mdindex 780b936c..e6580f0e 100644--- a/apps/docs/docs/guides/geofencing.md+++ b/apps/docs/docs/guides/geofencing.md@@ -4,7 +4,7 @@ sidebar_position: 1# Geofencing-Create zones where location recording stops automatically. These "pause zones" stop saving and syncing locations at places you visit often. GPS stays active to detect when you leave the zone.+Create zones where location recording stops automatically. These "pause zones" stop saving and syncing locations at places you visit often. Each zone can also be configured to stop GPS entirely when on WiFi or when the device is motionless.## Use Cases@@ -16,29 +16,47 @@ Create zones where location recording stops automatically. These "pause zones" s1. Go to the **Geofences** tab2. Enter a name and radius-3. Tap the map to place the geofence-4. Enable **Pause Tracking**+3. Tap **Place Geofence**, then tap the map to place it+4. Tap the **›** arrow on any geofence to open the editor and configure pause optionsimport ScreenshotGallery from '@site/src/components/ScreenshotGallery'-<ScreenshotGallery screenshots={[ { src: "/img/screenshots/Geofences.png", label: "Geofence setup" }, ]} />+<ScreenshotGallery screenshots={[ { src: "/img/screenshots/Geofences.png", label: "Geofences" }, { src: "/img/screenshots/GeofenceEditor.png", label: "Geofence Editor" }, ]} />++## GPS Pause Options++Each geofence has independent pause settings, configured in the editor (tap **›**):++### Don't record in zone++Locations are not saved or synced while inside the zone. GPS continues running to detect when you leave. This is the default behavior.++### Pause when on WiFi or Ethernet++Stops GPS entirely when connected to an unmetered network (home WiFi, Ethernet). GPS resumes automatically when the connection is lost. Useful if you want to completely stop GPS while at home on WiFi, saving additional battery.++### Pause when motionless++Stops GPS after no device motion is detected for a configurable time (default 10 minutes). GPS resumes automatically when the device moves again. Useful for users who put their phone in airplane mode at night or sit still for long periods.++### Combined behavior++When both **WiFi** and **motionless** pause are enabled, GPS only resumes when **both** conditions clear - WiFi must be disconnected **and** motion must be detected. Either condition alone is not enough to resume.++:::tip Changes made in the editor take effect immediately, even when you are already inside the zone. :::## How It Works- Zone detection uses the Haversine formula (1-2ms per check)- When entering a pause zone, Colota keeps recording for 3.5× your tracking interval before pausing - this logs several real arrival points near the zone boundary, which backends like GeoPulse need to confirm a trip has ended- The notification shows "Paused: [Zone Name]" once the pause takes effect-- GPS continues running inside the zone to detect when you leave+- By default, GPS continues running inside the zone to detect when you leave. If **WiFi pause** or **motionless pause** is enabled, GPS stops entirely inside the zone and zone exit is detected when GPS resumes- If you leave before the entry delay completes, the delay is cancelled and tracking continues uninterrupted-- GPS stays active inside the zone to reliably detect when you leave - stationary detection is suspended inside zones so exit is never missed+- Stationary detection is suspended inside zones so GPS is never stopped by the stationary timer while zone exit needs to be detected- When exiting the zone, tracking automatically resumes- Zone checks happen every location update with minimal overhead- You can create unlimited geofence zones## Anchor Points-When you exit a pause zone, Colota saves a synthetic location at the geofence center. This gives your new trip a clean start point at the zone center rather than somewhere mid-road where GPS first locks in.--- **On exit:** An anchor point is logged at the zone center, then recording resumes--Anchor points use the geofence center coordinates (not your actual GPS position) and set accuracy to the zone radius. They are saved to the database and synced to your server like regular locations.+When you exit a pause zone, Colota saves a synthetic location at the geofence center. This gives your new trip a clean start point rather than somewhere mid-road where GPS first locks in. Anchor points use the zone radius as their accuracy value and are saved and synced like regular locations.diff --git a/apps/docs/docs/guides/offline-maps.md b/apps/docs/docs/guides/offline-maps.mdindex 7facd9b5..961e42f9 100644--- a/apps/docs/docs/guides/offline-maps.md+++ b/apps/docs/docs/guides/offline-maps.md@@ -6,6 +6,10 @@ sidebar_position: 5Download map areas to your device so the map works without an internet connection. Useful when tracking in areas with poor cell coverage - remote trails, backcountry routes, etc.+import ScreenshotGallery from '@site/src/components/ScreenshotGallery'++<ScreenshotGallery screenshots={[ { src: "/img/screenshots/OfflineMaps.png", label: "Offline Maps" }, ]} />+## Downloading an Area1. Go to **Settings > Offline Maps**diff --git a/apps/docs/docs/introduction.md b/apps/docs/docs/introduction.mdindex 93a01ada..86862b81 100644--- a/apps/docs/docs/introduction.md+++ b/apps/docs/docs/introduction.md@@ -16,7 +16,7 @@ Colota is a self-hosted GPS tracking app for Android. It sends your location to- **Scheduled Export** - Automatic daily, weekly or monthly exports to a local directory with file retention management.- **Location History** - View daily summaries, trip segmentation, calendar with activity dots and per-trip export.- **Reliable Tracking** - Foreground service, auto-start on boot, exponential backoff retry and automatic GPS pause when stationary.-- **Geofencing** - Pause zones that automatically stop recording locations.+- **Geofencing** - Pause zones that stop recording locations. Optionally stop GPS entirely when on WiFi or when the device is motionless.- **Tracking Profiles** - Automatically adjust GPS interval, distance filter and sync settings based on conditions like charging, car mode or speed.- **Flexible Sync** - Instant, batch, Wi-Fi only or offline modes.- **Display Settings** - Choose between metric and imperial units, 12h or 24h time format. Auto-detected from device locale on first use.@@ -26,7 +26,7 @@ Colota is a self-hosted GPS tracking app for Android. It sends your location to## App Screens-Colota has sixteen screens, each focused on a specific task:+Colota has seventeen screens, each focused on a specific task:| Screen | Purpose || --- | --- |@@ -34,7 +34,8 @@ Colota has sixteen screens, each focused on a specific task:| **Settings** | GPS polling interval, distance filter, sync strategy, offline mode, accuracy threshold, unit system, time format || **API Config** | Endpoint field mapping with templates for Dawarich, OwnTracks, PhoneTrack, Reitti, Traccar, or custom backends || **Auth Settings** | Endpoint authentication (None, Basic Auth, Bearer Token) and custom HTTP headers |-| **Geofences** | Create, edit, and delete pause zones on an interactive map |+| **Geofences** | Create pause zones by tapping the map, view all zones with pause option indicators |+| **Geofence Editor** | Configure pause options per zone: record pause, WiFi pause, motionless pause, and delete || **Offline Maps** | Download map areas to the device for use without an internet connection || **Tracking Profiles** | Create and manage condition-based profiles that automatically adjust tracking settings || **Profile Editor** | Configure profile name, condition trigger, GPS interval, distance filter, sync interval, priority, and deactivation delay |@@ -51,7 +52,7 @@ Colota has sixteen screens, each focused on a specific task:import ScreenshotGallery from '@site/src/components/ScreenshotGallery'-<ScreenshotGallery screenshots={[ { src: "/img/screenshots/Dashboard.png", label: "Dashboard" }, { src: "/img/screenshots/LocationHistory.png", label: "Location History" }, { src: "/img/screenshots/TripDetails.png", label: "Trip Detail" }, { src: "/img/screenshots/Trips.png", label: "Trips" }, { src: "/img/screenshots/Settings.png", label: "Settings" }, { src: "/img/screenshots/TrackingProfiles.png", label: "Tracking Profiles" }, { src: "/img/screenshots/DataManagement.png", label: "Data Management" }, { src: "/img/screenshots/ApiFieldMapping.png", label: "API Field Mapping" }, { src: "/img/screenshots/ExportData.png", label: "Export" }, { src: "/img/screenshots/AutoExport.png", label: "Auto-Export" }, { src: "/img/screenshots/Authentication.png", label: "Authentication" }, { src: "/img/screenshots/DarkMode.png", label: "Dark Mode" }, ]} />+<ScreenshotGallery screenshots={[ { src: "/img/screenshots/Dashboard.png", label: "Dashboard" }, { src: "/img/screenshots/Settings.png", label: "Settings" }, { src: "/img/screenshots/ApiFieldMapping.png", label: "API Config" }, { src: "/img/screenshots/Authentication.png", label: "Auth Settings" }, { src: "/img/screenshots/Geofences.png", label: "Geofences" }, { src: "/img/screenshots/GeofenceEditor.png", label: "Geofence Editor" }, { src: "/img/screenshots/OfflineMaps.png", label: "Offline Maps" }, { src: "/img/screenshots/TrackingProfiles.png", label: "Profile Editor" }, { src: "/img/screenshots/LocationHistory.png", label: "Location History" }, { src: "/img/screenshots/TripDetails.png", label: "Trip Detail" }, { src: "/img/screenshots/Trips.png", label: "Trips" }, { src: "/img/screenshots/ExportData.png", label: "Export" }, { src: "/img/screenshots/AutoExport.png", label: "Auto-Export" }, { src: "/img/screenshots/DataManagement.png", label: "Data Management" }, { src: "/img/screenshots/DarkMode.png", label: "Dark Mode" }, ]} />## Architecturediff --git a/apps/docs/src/pages/index.tsx b/apps/docs/src/pages/index.tsxindex 045aa934..afb3fa57 100644--- a/apps/docs/src/pages/index.tsx+++ b/apps/docs/src/pages/index.tsx@@ -99,14 +99,9 @@ function HomepageFeatures(): ReactNode {const homepageScreenshots = [{ src: "/img/screenshots/Dashboard.png", label: "Dashboard" },+ { src: "/img/screenshots/Geofences.png", label: "Geofences" },{ src: "/img/screenshots/LocationHistory.png", label: "Location History" },- { src: "/img/screenshots/TripDetails.png", label: "Trip Detail" },- { src: "/img/screenshots/Trips.png", label: "Trips" },- { src: "/img/screenshots/Settings.png", label: "Settings" },- { src: "/img/screenshots/TrackingProfiles.png", label: "Tracking Profiles" },- { src: "/img/screenshots/DataManagement.png", label: "Data Management" },- { src: "/img/screenshots/ApiFieldMapping.png", label: "API Field Mapping" },- { src: "/img/screenshots/Authentication.png", label: "Authentication" },+ { src: "/img/screenshots/TrackingProfiles.png", label: "Profile Editor" },{ src: "/img/screenshots/DarkMode.png", label: "Dark Mode" }]diff --git a/apps/docs/static/img/screenshots/GeofenceEditor.png b/apps/docs/static/img/screenshots/GeofenceEditor.pngnew file mode 100644index 00000000..e47cd38cBinary files /dev/null and b/apps/docs/static/img/screenshots/GeofenceEditor.png differdiff --git a/apps/docs/static/img/screenshots/Geofences.png b/apps/docs/static/img/screenshots/Geofences.pngindex 689f19b9..c507b060 100644Binary files a/apps/docs/static/img/screenshots/Geofences.png and b/apps/docs/static/img/screenshots/Geofences.png differdiff --git a/apps/docs/static/img/screenshots/OfflineMaps.png b/apps/docs/static/img/screenshots/OfflineMaps.pngnew file mode 100644index 00000000..be41efb9Binary files /dev/null and b/apps/docs/static/img/screenshots/OfflineMaps.png differdiff --git a/apps/mobile/App.tsx b/apps/mobile/App.tsxindex 8331b90a..e6748e75 100644--- a/apps/mobile/App.tsx+++ b/apps/mobile/App.tsx@@ -19,6 +19,7 @@ import {AuthSettingsScreen,AutoExportScreen,GeofenceScreen,+ GeofenceEditorScreen,DataManagementScreen,LocationHistoryScreen,LocationSummaryScreen,@@ -70,6 +71,11 @@ const SCREEN_CONFIG = [component: GeofenceScreen,title: "Geofences"},+ {+ name: "Geofence Editor",+ component: GeofenceEditorScreen,+ title: "Geofence Editor"+ },{name: "Location History",component: LocationHistoryScreen,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 82105c62..bfcbdeb0 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@@ -620,14 +620,17 @@ class LocationServiceModule(reactContext: ReactApplicationContext) :*/@ReactMethodfun createGeofence(- name: String,- lat: Double,- lon: Double,- radius: Double,- pause: Boolean,+ name: String,+ lat: Double,+ lon: Double,+ radius: Double,+ pause: Boolean,+ pauseOnWifi: Boolean,+ pauseOnMotionless: Boolean,+ motionlessTimeoutMinutes: Int,promise: Promise- ) = executeAsync(promise) {- val result = geofenceHelper.insertGeofence(name, lat, lon, radius, pause)+ ) = executeAsync(promise) {+ val result = geofenceHelper.insertGeofence(name, lat, lon, radius, pause, pauseOnWifi, pauseOnMotionless, motionlessTimeoutMinutes)if (result > 0) {geofenceHelper.invalidateCache()triggerZoneRecheck()@@ -646,18 +649,21 @@ class LocationServiceModule(reactContext: ReactApplicationContext) :@ReactMethodfun updateGeofence(- id: Int,- name: String?,- lat: Double?,- lon: Double?,- radius: Double?,- enabled: Boolean?,- pause: Boolean?,+ id: Int,+ name: String?,+ lat: Double?,+ lon: Double?,+ radius: Double?,+ enabled: Boolean?,+ pause: Boolean?,+ pauseOnWifi: Boolean?,+ pauseOnMotionless: Boolean?,+ motionlessTimeoutMinutes: Int?,promise: Promise- ) = executeAsync(promise) {- val result = geofenceHelper.updateGeofence(id, name, lat, lon, radius, enabled, pause)+ ) = executeAsync(promise) {+ val result = geofenceHelper.updateGeofence(id, name, lat, lon, radius, enabled, pause, pauseOnWifi, pauseOnMotionless, motionlessTimeoutMinutes)if (result) {- geofenceHelper.invalidateCache()+ geofenceHelper.invalidateCache()triggerZoneRecheck()}resultdiff --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 93ede042..5dbd6d4c 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@@ -32,7 +32,7 @@ class DatabaseHelper private constructor(context: Context) :companion object {private const val DATABASE_NAME = "Colota.db"- private const val DATABASE_VERSION = 3+ private const val DATABASE_VERSION = 4const val TABLE_LOCATIONS = "locations"const val TABLE_QUEUE = "queue"@@ -115,6 +115,9 @@ class DatabaseHelper private constructor(context: Context) :radius REAL NOT NULL,enabled INTEGER DEFAULT 1,pause_tracking INTEGER DEFAULT 1,+ pause_on_wifi INTEGER DEFAULT 0,+ pause_on_motionless INTEGER DEFAULT 0,+ motionless_timeout_minutes INTEGER DEFAULT 10,notify_enter INTEGER DEFAULT 0,notify_exit INTEGER DEFAULT 0,created_at INTEGER NOT NULL@@ -218,6 +221,11 @@ class DatabaseHelper private constructor(context: Context) :// Mark existing locations not in queue as sent (accurate for pre-offline-mode users)db.execSQL("UPDATE $TABLE_LOCATIONS SET sent = 1 WHERE id NOT IN (SELECT location_id FROM $TABLE_QUEUE)")}+ if (oldVersion < 4) {+ db.execSQL("ALTER TABLE $TABLE_GEOFENCES ADD COLUMN pause_on_wifi INTEGER NOT NULL DEFAULT 0")+ db.execSQL("ALTER TABLE $TABLE_GEOFENCES ADD COLUMN pause_on_motionless INTEGER NOT NULL DEFAULT 0")+ db.execSQL("ALTER TABLE $TABLE_GEOFENCES ADD COLUMN motionless_timeout_minutes INTEGER NOT NULL DEFAULT 10")+ }}override fun onOpen(db: SQLiteDatabase) {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 e16f0ca1..63355477 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@@ -24,7 +24,10 @@ class GeofenceHelper(private val context: Context) {val name: String,val lat: Double,val lon: Double,- val radius: Double+ val radius: Double,+ val pauseOnWifi: Boolean = false,+ val pauseOnMotionless: Boolean = false,+ val motionlessTimeoutMinutes: Int = 10)companion object {@@ -49,6 +52,9 @@ class GeofenceHelper(private val context: Context) {}}+ fun getGeofenceByName(name: String): CachedGeofence? =+ geofenceCache.get().find { it.name == name }+fun getPauseZone(location: Location): CachedGeofence? {val fences = getGeofences()val match = fences.find {@@ -73,7 +79,7 @@ class GeofenceHelper(private val context: Context) {val fences = mutableListOf<CachedGeofence>()dbHelper.readableDatabase.query(DatabaseHelper.TABLE_GEOFENCES,- arrayOf("name", "latitude", "longitude", "radius"),+ arrayOf("name", "latitude", "longitude", "radius", "pause_on_wifi", "pause_on_motionless", "motionless_timeout_minutes"),"enabled = 1 AND pause_tracking = 1",null, null, null, null).use { cursor ->@@ -81,13 +87,19 @@ class GeofenceHelper(private val context: Context) {val latIdx = cursor.getColumnIndexOrThrow("latitude")val lonIdx = cursor.getColumnIndexOrThrow("longitude")val radIdx = cursor.getColumnIndexOrThrow("radius")+ val wifiIdx = cursor.getColumnIndexOrThrow("pause_on_wifi")+ val motionlessIdx = cursor.getColumnIndexOrThrow("pause_on_motionless")+ val timeoutIdx = cursor.getColumnIndexOrThrow("motionless_timeout_minutes")while (cursor.moveToNext()) {fences.add(CachedGeofence(cursor.getString(nameIdx),cursor.getDouble(latIdx),cursor.getDouble(lonIdx),- cursor.getDouble(radIdx)+ cursor.getDouble(radIdx),+ cursor.getInt(wifiIdx) == 1,+ cursor.getInt(motionlessIdx) == 1,+ cursor.getInt(timeoutIdx)))}}@@ -126,6 +138,9 @@ class GeofenceHelper(private val context: Context) {putDouble("radius", cursor.getDouble(radiusIdx))putBoolean("enabled", cursor.getInt(enabledIdx) == 1)putBoolean("pauseTracking", cursor.getInt(pauseIdx) == 1)+ putBoolean("pauseOnWifi", cursor.getInt(cursor.getColumnIndexOrThrow("pause_on_wifi")) == 1)+ putBoolean("pauseOnMotionless", cursor.getInt(cursor.getColumnIndexOrThrow("pause_on_motionless")) == 1)+ putInt("motionlessTimeoutMinutes", cursor.getInt(cursor.getColumnIndexOrThrow("motionless_timeout_minutes")))putDouble("createdAt", cursor.getLong(createdIdx).toDouble())})}@@ -141,11 +156,14 @@ class GeofenceHelper(private val context: Context) {* Inserts a new geofence into the database.*/fun insertGeofence(- name: String,- lat: Double,- lon: Double,- rad: Double,- pause: Boolean+ name: String,+ lat: Double,+ lon: Double,+ rad: Double,+ pause: Boolean,+ pauseOnWifi: Boolean = false,+ pauseOnMotionless: Boolean = false,+ motionlessTimeoutMinutes: Int = 10): Int {val values = ContentValues().apply {put("name", name)@@ -154,6 +172,9 @@ class GeofenceHelper(private val context: Context) {put("radius", rad)put("enabled", 1)put("pause_tracking", if (pause) 1 else 0)+ put("pause_on_wifi", if (pauseOnWifi) 1 else 0)+ put("pause_on_motionless", if (pauseOnMotionless) 1 else 0)+ put("motionless_timeout_minutes", motionlessTimeoutMinutes)put("created_at", System.currentTimeMillis() / 1000)}@@ -166,13 +187,16 @@ class GeofenceHelper(private val context: Context) {* Updates geofence with only provided fields.*/fun updateGeofence(- id: Int,- name: String?,- lat: Double?,- lon: Double?,- rad: Double?,- en: Boolean?,- pause: Boolean?+ id: Int,+ name: String?,+ lat: Double?,+ lon: Double?,+ rad: Double?,+ en: Boolean?,+ pause: Boolean?,+ pauseOnWifi: Boolean? = null,+ pauseOnMotionless: Boolean? = null,+ motionlessTimeoutMinutes: Int? = null): Boolean {val values = ContentValues().apply {name?.let { put("name", it) }@@ -181,6 +205,9 @@ class GeofenceHelper(private val context: Context) {rad?.let { put("radius", it) }en?.let { put("enabled", if (it) 1 else 0) }pause?.let { put("pause_tracking", if (it) 1 else 0) }+ pauseOnWifi?.let { put("pause_on_wifi", if (it) 1 else 0) }+ pauseOnMotionless?.let { put("pause_on_motionless", if (it) 1 else 0) }+ motionlessTimeoutMinutes?.let { put("motionless_timeout_minutes", it) }}if (values.size() == 0) return falsediff --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 3e604213..991f9b8b 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@@ -6,6 +6,10 @@package com.Colota.serviceimport android.app.*+import android.net.ConnectivityManager+import android.net.Network+import android.net.NetworkCapabilities+import android.net.NetworkRequestimport com.Colota.bridge.LocationServiceModuleimport com.Colota.util.AppLoggerimport com.Colota.data.DatabaseHelper@@ -50,6 +54,13 @@ class LocationForegroundService : Service() {@Volatile private var isStationary = false@Volatile private var motionDetector: MotionDetector? = null@Volatile private var insidePauseZone = false+ @Volatile private var isWifiPaused = false+ // Accessed exclusively on the main thread - @Volatile not needed and would be misleading+ private var unmeteredNetworkCount = 0+ @Volatile private var wifiCallback: ConnectivityManager.NetworkCallback? = null+ @Volatile private var wifiResumeJob: Job? = null+ @Volatile private var isMotionlessPaused = false+ @Volatile private var motionlessJob: Job? = null@Volatile private var currentZoneName: String? = null@Volatile private var currentZoneGeofence: GeofenceHelper.CachedGeofence? = null@Volatile private var lastKnownLocation: android.location.Location? = null@@ -68,6 +79,8 @@ class LocationForegroundService : Service() {private const val STATIONARY_TIMEOUT_MS = 60_000L/** Multiplier applied to the tracking interval for the geofence entry delay. */private const val ENTRY_DELAY_MULTIPLIER = 3.5+ /** Debounce before resuming GPS after unmetered network is lost (ms). */+ private const val WIFI_RESUME_DEBOUNCE_MS = 15_000Lconst val ACTION_MANUAL_FLUSH = "com.Colota.ACTION_MANUAL_FLUSH"const val ACTION_RECHECK_ZONE = "com.Colota.RECHECK_PAUSE_ZONE"const val ACTION_REFRESH_NOTIFICATION = "com.Colota.REFRESH_NOTIFICATION"@@ -145,7 +158,19 @@ class LocationForegroundService : Service() {if (!savedZone.isNullOrBlank()) {insidePauseZone = truecurrentZoneName = savedZone+ val restoredGeofence = geofenceHelper.getGeofenceByName(savedZone)+ currentZoneGeofence = restoredGeofenceAppLogger.d(TAG, "Restored pause zone state: $savedZone")+ if (restoredGeofence?.pauseOnWifi == true) {+ // registerWifiPause() also sets isWifiPaused if currently on unmetered network,+ // which prevents setupLocationUpdates() from starting GPS unnecessarily.+ registerWifiPause()+ }+ if (savedSettings["pause_zone_motionless_active"]?.toBoolean() == true) {+ isMotionlessPaused = true+ motionDetector?.arm()+ AppLogger.d(TAG, "Restored motionless pause state")+ }}}@@ -234,6 +259,8 @@ class LocationForegroundService : Service() {entryDelayJob?.cancel()entryDelayJob = nullpendingPauseZone = null+ unregisterWifiPause()+ cancelMotionlessCountdown()conditionMonitor.stop()stopLocationUpdates()syncManager.stopPeriodicSync()@@ -248,6 +275,8 @@ class LocationForegroundService : Service() {override fun onBind(intent: Intent?): IBinder? = nullprivate fun setupLocationUpdates() {+ if (isWifiPaused || isMotionlessPaused) return // GPS intentionally stopped by a zone pause hold+val callback = object : LocationUpdateCallback {override fun onLocationUpdate(location: android.location.Location) {handleLocationUpdate(location)@@ -333,10 +362,10 @@ class LocationForegroundService : Service() {private fun recheckZoneWithLocation(location: android.location.Location) {val zone = geofenceHelper.getPauseZone(location)- applyZoneTransition(zone)- // Same zone - refresh notification coords+ // Already inside this zone - refresh settings in case they changed via editorif (zone != null && insidePauseZone && zone.name == currentZoneName) {+ applyZoneSettingsIfChanged(zone)updateNotification(lat = location.latitude,lon = location.longitude,@@ -344,7 +373,12 @@ class LocationForegroundService : Service() {zoneName = currentZoneName,forceUpdate = true)- } else if (zone == null && !insidePauseZone && pendingPauseZone == null) {+ return+ }++ applyZoneTransition(zone)++ if (zone == null && !insidePauseZone && pendingPauseZone == null) {updateNotification(location.latitude,location.longitude,@@ -353,6 +387,36 @@ class LocationForegroundService : Service() {}}+ /**+ * Re-applies WiFi/motionless pause settings from a freshly loaded zone object.+ * Called on RECHECK when already inside the zone so editor changes take effect immediately.+ */+ private fun applyZoneSettingsIfChanged(zone: GeofenceHelper.CachedGeofence) {+ val timeoutChanged = currentZoneGeofence?.motionlessTimeoutMinutes != zone.motionlessTimeoutMinutes+ currentZoneGeofence = zone++ if (zone.pauseOnWifi && wifiCallback == null) {+ registerWifiPause()+ } else if (!zone.pauseOnWifi) {+ if (isWifiPaused) {+ isWifiPaused = false+ maybeResumeGps()+ }+ unregisterWifiPause()+ }++ if (zone.pauseOnMotionless && !isMotionlessPaused && (motionlessJob == null || timeoutChanged)) {+ if (timeoutChanged) cancelMotionlessCountdown()+ startMotionlessCountdown(zone.motionlessTimeoutMinutes)+ } else if (!zone.pauseOnMotionless) {+ cancelMotionlessCountdown()+ if (isMotionlessPaused) {+ clearMotionlessPauseState()+ maybeResumeGps()+ }+ }+ }+/*** Applies zone entry/exit state transitions common to both live location updates* and manual zone rechecks. Returns the anchor [Job] if a zone exit was triggered.@@ -401,7 +465,6 @@ class LocationForegroundService : Service() {return}-applySpeedFallback(location)// Evaluated before the distance filter so stationary detection works regardless@@ -535,6 +598,9 @@ class LocationForegroundService : Service() {LocationServiceModule.sendPauseZoneEvent(true, geofence.name)+ if (geofence.pauseOnWifi) registerWifiPause()+ if (geofence.pauseOnMotionless) startMotionlessCountdown(geofence.motionlessTimeoutMinutes)+AppLogger.d(TAG, "Entered pause zone: ${geofence.name}")}@@ -547,9 +613,18 @@ class LocationForegroundService : Service() {currentZoneName = nullcurrentZoneGeofence = nulldbHelper.saveSetting("pause_zone_name", "")+ val wasWifiPaused = isWifiPaused+ val wasMotionlessPaused = isMotionlessPaused+ isWifiPaused = false+ unregisterWifiPause()+ cancelMotionlessCountdown()+ clearMotionlessPauseState()val anchorJob = exitedGeofence?.let { saveAnchorPoint(it) }+ // Resume GPS if it was stopped by any zone pause hold+ if (wasWifiPaused || wasMotionlessPaused) setupLocationUpdates()+val loc = lastKnownLocationupdateNotification(lat = loc?.latitude, lon = loc?.longitude, forceUpdate = true)@@ -559,6 +634,144 @@ class LocationForegroundService : Service() {return anchorJob}+ // ── WiFi pause ────────────────────────────────────────────────────────++ /**+ * Registers a [ConnectivityManager.NetworkCallback] to monitor unmetered network+ * availability (WiFi/Ethernet) while inside a pause zone with [pauseOnWifi] enabled.+ * GPS is stopped immediately if already on an unmetered network, and resumed+ * (after a [WIFI_RESUME_DEBOUNCE_MS] debounce) when the network is lost.+ *+ * Must only be called from the main thread. Callbacks are delivered on the main thread.+ */+ private fun registerWifiPause() {+ unregisterWifiPause() // clean up any stale callback++ val cm = getSystemService(CONNECTIVITY_SERVICE) as ConnectivityManager+ val request = NetworkRequest.Builder()+ .addCapability(NetworkCapabilities.NET_CAPABILITY_NOT_METERED)+ .build()++ val callback = object : ConnectivityManager.NetworkCallback() {+ override fun onAvailable(network: Network) {+ wifiResumeJob?.cancel()+ wifiResumeJob = null+ unmeteredNetworkCount+++ if (!isWifiPaused) {+ isWifiPaused = true+ stopLocationUpdates()+ updateNotification(forceUpdate = true)+ AppLogger.i(TAG, "Unmetered network available - WiFi pause active (networks=$unmeteredNetworkCount)")+ }+ }++ override fun onLost(network: Network) {+ unmeteredNetworkCount = maxOf(0, unmeteredNetworkCount - 1)+ if (!isWifiPaused || unmeteredNetworkCount > 0) return+ AppLogger.i(TAG, "Unmetered network lost - resuming GPS in ${WIFI_RESUME_DEBOUNCE_MS / 1000}s")+ wifiResumeJob?.cancel()+ wifiResumeJob = serviceScope?.launch {+ delay(WIFI_RESUME_DEBOUNCE_MS)+ withContext(Dispatchers.Main) {+ if (isWifiPaused && unmeteredNetworkCount == 0) {+ isWifiPaused = false+ maybeResumeGps()+ AppLogger.i(TAG, "GPS resumed after unmetered network lost")+ }+ }+ }+ }+ }++ try {+ cm.registerNetworkCallback(request, callback, Handler(Looper.getMainLooper()))+ wifiCallback = callback+ // onAvailable fires immediately for already-active networks, so no manual initial check needed+ } catch (e: Exception) {+ AppLogger.e(TAG, "Failed to register network callback", e)+ }+ }++ private fun unregisterWifiPause() {+ wifiResumeJob?.cancel()+ wifiResumeJob = null+ unmeteredNetworkCount = 0+ val cb = wifiCallback ?: return+ wifiCallback = null+ try {+ val cm = getSystemService(CONNECTIVITY_SERVICE) as ConnectivityManager+ cm.unregisterNetworkCallback(cb)+ } catch (_: Exception) {}+ }++ // ── Motionless pause ──────────────────────────────────────────────────++ /**+ * Starts the motionless timeout countdown for a zone with [pauseOnMotionless] enabled.+ * When the countdown completes without significant motion, GPS is stopped and the+ * motion sensor is armed to resume it when the device moves again.+ */+ private fun startMotionlessCountdown(timeoutMinutes: Int) {+ motionlessJob?.cancel()+ motionlessJob = serviceScope?.launch {+ delay(timeoutMinutes * 60_000L)+ withContext(Dispatchers.Main) {+ motionlessJob = null+ if (insidePauseZone && !isMotionlessPaused) {+ isMotionlessPaused = true+ dbHelper.saveSetting("pause_zone_motionless_active", "true")+ stopLocationUpdates()+ motionDetector?.arm()+ updateNotification(forceUpdate = true)+ AppLogger.i(TAG, "Motionless timeout reached - GPS paused, motion sensor armed")+ }+ }+ }+ }++ private fun cancelMotionlessCountdown() {+ motionlessJob?.cancel()+ motionlessJob = null+ }++ private fun clearMotionlessPauseState() {+ isMotionlessPaused = false+ dbHelper.saveSetting("pause_zone_motionless_active", "false")+ motionDetector?.disarm()+ }++ /**+ * Resumes GPS after motion is detected in a motionless-paused zone.+ * Re-arms the countdown so the zone can pause again if device becomes stationary again.+ */+ private fun resumeFromMotionlessPause() {+ clearMotionlessPauseState()+ val geofence = currentZoneGeofence+ maybeResumeGps()+ // Restart countdown so the zone can pause again if device becomes stationary+ if (geofence?.pauseOnMotionless == true) {+ startMotionlessCountdown(geofence.motionlessTimeoutMinutes)+ }+ AppLogger.i(TAG, "Motion detected in pause zone - motionless hold cleared")+ }++ /**+ * Resumes GPS only if no pause holds are active.+ * Use this instead of calling [setupLocationUpdates] directly in WiFi/motionless resume paths.+ */+ private fun maybeResumeGps() {+ val geofence = currentZoneGeofence ?: run { setupLocationUpdates(); updateNotification(forceUpdate = true); return }+ val wifiHold = geofence.pauseOnWifi && isWifiPaused+ val motionHold = geofence.pauseOnMotionless && isMotionlessPaused+ if (!wifiHold && !motionHold) {+ AppLogger.i(TAG, "GPS resumed - all pause holds cleared")+ setupLocationUpdates()+ updateNotification(forceUpdate = true)+ } else {+ AppLogger.i(TAG, "GPS still held: wifi=$wifiHold motionless=$motionHold")+ }+ }+/** Logs a synthetic location at the geofence center on zone exit to give the departing trip a clean start point. */private fun saveAnchorPoint(geofence: GeofenceHelper.CachedGeofence): Job? {if (!::config.isInitialized) {@@ -629,7 +842,9 @@ class LocationForegroundService : Service() {activeProfileName = profileManager.getActiveProfileName(),forceUpdate = forceUpdate,isOfflineMode = offline,- isStationary = isStationary+ isStationary = isStationary,+ isWifiPaused = isWifiPaused,+ isMotionlessPaused = isMotionlessPaused)}@@ -644,6 +859,7 @@ class LocationForegroundService : Service() {LocationServiceModule.sendTrackingStoppedEvent(reason)dbHelper.saveSetting("tracking_enabled", "false")dbHelper.saveSetting("pause_zone_name", "")+ dbHelper.saveSetting("pause_zone_motionless_active", "false")stopForeground(Service.STOP_FOREGROUND_DETACH)@@ -700,8 +916,7 @@ class LocationForegroundService : Service() {AppLogger.i(TAG, "Device stationary - pausing active GPS, arming motion sensor")// Stop active GPS but keep the service running- locationUpdateCallback?.let { locationProvider.removeLocationUpdates(it) }- locationUpdateCallback = null+ stopLocationUpdates()motionDetector?.arm()@@ -715,6 +930,10 @@ class LocationForegroundService : Service() {/** Called by MotionDetector when the device starts moving again. */private fun onMotionDetected() {+ if (isMotionlessPaused) {+ resumeFromMotionlessPause()+ return+ }if (!isStationary) returnAppLogger.i(TAG, "Motion detected - resuming active GPS")resumeFromStationary()diff --git a/apps/mobile/android/app/src/main/java/com/colota/service/NotificationHelper.kt b/apps/mobile/android/app/src/main/java/com/colota/service/NotificationHelper.ktindex de3242c5..457d6284 100644--- a/apps/mobile/android/app/src/main/java/com/colota/service/NotificationHelper.kt+++ b/apps/mobile/android/app/src/main/java/com/colota/service/NotificationHelper.kt@@ -106,9 +106,18 @@ class NotificationHelper(queuedCount: Int,lastSyncTime: Long,isOfflineMode: Boolean = false,- isStationary: Boolean = false+ isStationary: Boolean = false,+ isWifiPaused: Boolean = false,+ isMotionlessPaused: Boolean = false): String = when {- isPaused -> "Paused: ${zoneName ?: "Unknown"}"+ isPaused -> {+ val zone = zoneName ?: "Unknown"+ when {+ isWifiPaused -> "Paused: $zone \u00b7 WiFi"+ isMotionlessPaused -> "Paused: $zone \u00b7 Motionless"+ else -> "Paused: $zone"+ }+ }isStationary -> {val coords = if (lat != null && lon != null) String.format(Locale.US, "%.5f, %.5f", lat, lon) else ""if (coords.isNotEmpty()) "Stationary - $coords" else "Stationary - GPS paused"@@ -168,7 +177,9 @@ class NotificationHelper(activeProfileName: String? = null,forceUpdate: Boolean = false,isOfflineMode: Boolean = false,- isStationary: Boolean = false+ isStationary: Boolean = false,+ isWifiPaused: Boolean = false,+ isMotionlessPaused: Boolean = false): Boolean {val now = System.currentTimeMillis()@@ -194,11 +205,12 @@ class NotificationHelper(lastCoords = Pair(lat, lon)}- val statusText = buildStatusText(isPaused, zoneName, lat, lon, queuedCount, lastSyncTime, isOfflineMode, isStationary)+ val statusText = buildStatusText(isPaused, zoneName, lat, lon, queuedCount, lastSyncTime, isOfflineMode, isStationary, isWifiPaused, isMotionlessPaused)- // Dedup: skip if notification text hasn't changed+ // Dedup: skip if notification text hasn't changed (bypass on forceUpdate so state-change+ // notifications always reach Android even if text appears identical)val cacheKey = "$statusText-$queuedCount-$activeProfileName"- if (cacheKey == lastText) return false+ if (!forceUpdate && cacheKey == lastText) return falselastText = cacheKeylastQueuedCount = queuedCountdiff --git a/apps/mobile/android/app/src/test/java/com/Colota/data/DatabaseHelperSQLiteTest.kt b/apps/mobile/android/app/src/test/java/com/Colota/data/DatabaseHelperSQLiteTest.ktindex fbfc7116..10b8c340 100644--- a/apps/mobile/android/app/src/test/java/com/Colota/data/DatabaseHelperSQLiteTest.kt+++ b/apps/mobile/android/app/src/test/java/com/Colota/data/DatabaseHelperSQLiteTest.kt@@ -25,6 +25,21 @@ import io.mockk.*@RunWith(RobolectricTestRunner::class)class DatabaseHelperSQLiteTest {+ private val V3_GEOFENCES_SCHEMA = """+ CREATE TABLE ${DatabaseHelper.TABLE_GEOFENCES} (+ id INTEGER PRIMARY KEY AUTOINCREMENT,+ name TEXT NOT NULL,+ latitude REAL NOT NULL,+ longitude REAL NOT NULL,+ radius REAL NOT NULL,+ enabled INTEGER DEFAULT 1,+ pause_tracking INTEGER DEFAULT 1,+ notify_enter INTEGER DEFAULT 0,+ notify_exit INTEGER DEFAULT 0,+ created_at INTEGER NOT NULL+ )+ """+private lateinit var db: DatabaseHelper@Before@@ -98,12 +113,15 @@ class DatabaseHelperSQLiteTest {fun `onUpgrade from v1 creates profiles table and adds sent column`() {val rawDb = db.writableDatabase- // Simulate v1 state: no profiles table, no sent column+ // Simulate v1 state: no profiles table, no sent column, no pause_on_wifi on geofencesrawDb.execSQL("DROP TABLE IF EXISTS ${DatabaseHelper.TABLE_PROFILES}")rawDb.execSQL("DROP INDEX IF EXISTS idx_profiles_enabled")// Recreate locations table without sent column to simulate v1 schemarawDb.execSQL("DROP TABLE IF EXISTS ${DatabaseHelper.TABLE_QUEUE}")rawDb.execSQL("DROP TABLE IF EXISTS ${DatabaseHelper.TABLE_LOCATIONS}")+ // Recreate geofences table without pause_on_wifi to simulate v1 schema+ rawDb.execSQL("DROP TABLE IF EXISTS ${DatabaseHelper.TABLE_GEOFENCES}")+ rawDb.execSQL(V3_GEOFENCES_SCHEMA)rawDb.execSQL("""CREATE TABLE ${DatabaseHelper.TABLE_LOCATIONS} (id INTEGER PRIMARY KEY AUTOINCREMENT,@@ -133,7 +151,7 @@ class DatabaseHelperSQLiteTest {""")// Run full upgrade from v1- db.onUpgrade(rawDb, 1, 3)+ db.onUpgrade(rawDb, 1, 4)// Verify profiles table was createdval tables = queryTableNames()@@ -163,12 +181,28 @@ class DatabaseHelperSQLiteTest {val rawDb = db.writableDatabase// Running upgrade on current version should be safe (no-op)- db.onUpgrade(rawDb, 3, 3)+ db.onUpgrade(rawDb, 4, 4)val tables = queryTableNames()assertTrue(tables.contains("tracking_profiles"))}+ @Test+ fun `onUpgrade from v3 adds pause_on_wifi column to geofences`() {+ val rawDb = db.writableDatabase++ // Simulate v3 state: geofences table without pause_on_wifi+ rawDb.execSQL("DROP TABLE IF EXISTS ${DatabaseHelper.TABLE_GEOFENCES}")+ rawDb.execSQL(V3_GEOFENCES_SCHEMA)++ db.onUpgrade(rawDb, 3, 4)++ val columns = queryColumnNames(DatabaseHelper.TABLE_GEOFENCES)+ assertTrue(columns.contains("pause_on_wifi"))+ assertTrue(columns.contains("pause_on_motionless"))+ assertTrue(columns.contains("motionless_timeout_minutes"))+ }+// ========================================================================// WAL mode and pragmas// ========================================================================diff --git a/apps/mobile/android/app/src/test/java/com/Colota/data/GeofenceHelperTest.kt b/apps/mobile/android/app/src/test/java/com/Colota/data/GeofenceHelperTest.ktindex 160a2a0e..2de2d3a5 100644--- a/apps/mobile/android/app/src/test/java/com/Colota/data/GeofenceHelperTest.kt+++ b/apps/mobile/android/app/src/test/java/com/Colota/data/GeofenceHelperTest.kt@@ -1,10 +1,46 @@package com.Colota.data+import androidx.test.core.app.ApplicationProvider+import com.Colota.util.AppLogger+import io.mockk.*+import org.junit.Afterimport org.junit.Assert.*+import org.junit.Beforeimport org.junit.Test+import org.junit.runner.RunWith+import org.robolectric.RobolectricTestRunner+@RunWith(RobolectricTestRunner::class)class GeofenceHelperTest {+ private lateinit var helper: GeofenceHelper+ private lateinit var db: DatabaseHelper++ @Before+ fun setUp() {+ resetSingleton()+ db = DatabaseHelper.getInstance(ApplicationProvider.getApplicationContext())+ helper = GeofenceHelper(ApplicationProvider.getApplicationContext())+ mockkObject(AppLogger)+ every { AppLogger.d(any(), any()) } just Runs+ every { AppLogger.i(any(), any()) } just Runs+ every { AppLogger.w(any(), any()) } just Runs+ every { AppLogger.e(any(), any(), any()) } just Runs+ }++ @After+ fun tearDown() {+ db.close()+ resetSingleton()+ unmockkObject(AppLogger)+ }++ private fun resetSingleton() {+ val field = DatabaseHelper::class.java.getDeclaredField("INSTANCE")+ field.isAccessible = true+ field.set(null, null)+ }+// Known reference distances (verified against online Haversine calculators):// Berlin (52.52, 13.405) → Munich (48.1351, 11.582) ≈ 504 km// New York (40.7128, -74.006) → London (51.5074, -0.1278) ≈ 5,570 km@@ -97,4 +133,77 @@ class GeofenceHelperTest {// Berlin to Munich (~504 km) with 1 km radius — should be rejected by bounding boxassertFalse(GeofenceHelper.isWithinRadius(52.52, 13.405, 48.1351, 11.582, 1000.0))}++ // =========================================================================+ // getGeofenceByName+ // =========================================================================++ @Test+ fun `getGeofenceByName returns matching geofence`() {+ helper.insertGeofence("Home", 52.5, 13.4, 150.0, pause = true)++ val result = helper.getGeofenceByName("Home")++ assertNotNull(result)+ assertEquals("Home", result!!.name)+ assertEquals(52.5, result.lat, 0.001)+ assertEquals(13.4, result.lon, 0.001)+ assertEquals(150.0, result.radius, 0.001)+ }++ @Test+ fun `getGeofenceByName returns null for unknown name`() {+ assertNull(helper.getGeofenceByName("Unknown"))+ }++ @Test+ fun `getGeofenceByName returns correct pauseOnWifi value`() {+ helper.insertGeofence("Home", 52.5, 13.4, 150.0, pause = true, pauseOnWifi = true)++ val result = helper.getGeofenceByName("Home")++ assertNotNull(result)+ assertTrue(result!!.pauseOnWifi)+ }++ @Test+ fun `getGeofenceByName returns correct pauseOnMotionless and timeout`() {+ helper.insertGeofence("Home", 52.5, 13.4, 150.0, pause = true, pauseOnMotionless = true, motionlessTimeoutMinutes = 5)++ val result = helper.getGeofenceByName("Home")++ assertNotNull(result)+ assertTrue(result!!.pauseOnMotionless)+ assertEquals(5, result.motionlessTimeoutMinutes)+ }++ @Test+ fun `getGeofenceByName returns null when zone is disabled`() {+ helper.insertGeofence("Home", 52.5, 13.4, 150.0, pause = true)+ val id = db.readableDatabase.query("geofences", arrayOf("id"), "name = ?", arrayOf("Home"), null, null, null).use {+ it.moveToFirst(); it.getInt(0)+ }+ helper.updateGeofence(id, en = false, name = null, lat = null, lon = null, rad = null, pause = null)+ helper.invalidateCache()++ assertNull(helper.getGeofenceByName("Home"))+ }++ @Test+ fun `getGeofenceByName returns null when pause_tracking is off`() {+ helper.insertGeofence("Home", 52.5, 13.4, 150.0, pause = false)++ assertNull(helper.getGeofenceByName("Home"))+ }++ @Test+ fun `getGeofenceByName returns first match when multiple zones exist`() {+ helper.insertGeofence("Home", 52.5, 13.4, 150.0, pause = true)+ helper.insertGeofence("Office", 48.1, 11.5, 200.0, pause = true)++ val result = helper.getGeofenceByName("Office")++ assertNotNull(result)+ assertEquals("Office", result!!.name)+ }}diff --git a/apps/mobile/android/app/src/test/java/com/Colota/service/LocationForegroundServiceTest.kt b/apps/mobile/android/app/src/test/java/com/Colota/service/LocationForegroundServiceTest.ktindex 51d35254..54533fba 100644--- a/apps/mobile/android/app/src/test/java/com/Colota/service/LocationForegroundServiceTest.kt+++ b/apps/mobile/android/app/src/test/java/com/Colota/service/LocationForegroundServiceTest.kt@@ -1281,6 +1281,361 @@ class LocationForegroundServiceTest {verify(exactly = 0) { LocationServiceModule.sendProfileSwitchEvent(any(), any()) }}+ // =========================================================================+ // enterPauseZone - pause flag registration+ // =========================================================================++ @Test+ fun `enterPauseZone with pauseOnWifi registers wifi callback`() {+ val wifiGeofence = geofence("Home", 52.50, 13.40, 150.0, pauseOnWifi = true)+ coEvery { service["registerWifiPause"]() } returns Unit++ invokeEnterPauseZone(wifiGeofence)++ verify { service["registerWifiPause"]() }+ }++ @Test+ fun `enterPauseZone without pauseOnWifi skips wifi callback`() {+ coEvery { service["registerWifiPause"]() } returns Unit++ invokeEnterPauseZone(homeGeofence)++ verify(exactly = 0) { service["registerWifiPause"]() }+ }++ @Test+ fun `enterPauseZone with pauseOnMotionless starts countdown`() {+ val motionlessGeofence = geofence("Home", 52.50, 13.40, 150.0, pauseOnMotionless = true, motionlessTimeoutMinutes = 5)+ coEvery { service["startMotionlessCountdown"](any<Int>()) } returns Unit++ invokeEnterPauseZone(motionlessGeofence)++ verify { service["startMotionlessCountdown"](5) }+ }++ @Test+ fun `enterPauseZone without pauseOnMotionless skips countdown`() {+ coEvery { service["startMotionlessCountdown"](any<Int>()) } returns Unit++ invokeEnterPauseZone(homeGeofence)++ verify(exactly = 0) { service["startMotionlessCountdown"](any<Int>()) }+ }++ // =========================================================================+ // exitPauseZone - pause state cleanup+ // =========================================================================++ @Test+ fun `exitPauseZone saves pause_zone_motionless_active false`() {+ setField("insidePauseZone", true)+ setField("currentZoneGeofence", homeGeofence)++ invokeExitPauseZone()++ verify { dbHelper.saveSetting("pause_zone_motionless_active", "false") }+ }++ @Test+ fun `exitPauseZone with isWifiPaused resumes GPS`() {+ setField("insidePauseZone", true)+ setField("currentZoneGeofence", homeGeofence)+ setField("isWifiPaused", true)++ invokeExitPauseZone()++ verify { locationProvider.requestLocationUpdates(any(), any(), any(), any()) }+ }++ @Test+ fun `exitPauseZone with isMotionlessPaused resumes GPS`() {+ setField("insidePauseZone", true)+ setField("currentZoneGeofence", homeGeofence)+ setField("isMotionlessPaused", true)++ invokeExitPauseZone()++ verify { locationProvider.requestLocationUpdates(any(), any(), any(), any()) }+ }++ @Test+ fun `exitPauseZone without pause holds does not resume GPS`() {+ setField("insidePauseZone", true)+ setField("currentZoneGeofence", homeGeofence)+ setField("isWifiPaused", false)+ setField("isMotionlessPaused", false)++ invokeExitPauseZone()++ verify(exactly = 0) { locationProvider.requestLocationUpdates(any(), any(), any(), any()) }+ }++ // =========================================================================+ // startMotionlessCountdown+ // =========================================================================++ @Test+ fun `startMotionlessCountdown pauses GPS after timeout`() = testScope.runTest {+ val motionDetector = mockk<MotionDetector>(relaxed = true)+ setField("motionDetector", motionDetector)+ setField("insidePauseZone", true)++ invokeStartMotionlessCountdown(1)+ advanceTimeBy(60_001L)++ assertTrue(getField<Boolean>("isMotionlessPaused"))+ verify { dbHelper.saveSetting("pause_zone_motionless_active", "true") }+ verify { motionDetector.arm() }+ }++ @Test+ fun `startMotionlessCountdown does not pause when zone exited before timeout`() = testScope.runTest {+ val motionDetector = mockk<MotionDetector>(relaxed = true)+ setField("motionDetector", motionDetector)+ setField("insidePauseZone", false)++ invokeStartMotionlessCountdown(1)+ advanceTimeBy(60_001L)++ assertFalse(getField<Boolean>("isMotionlessPaused"))+ verify(exactly = 0) { motionDetector.arm() }+ }++ @Test+ fun `startMotionlessCountdown does not pause when already motionless paused`() = testScope.runTest {+ val motionDetector = mockk<MotionDetector>(relaxed = true)+ setField("motionDetector", motionDetector)+ setField("insidePauseZone", true)+ setField("isMotionlessPaused", true)++ invokeStartMotionlessCountdown(1)+ advanceTimeBy(60_001L)++ // arm should not be called a second time+ verify(exactly = 0) { motionDetector.arm() }+ }++ // =========================================================================+ // resumeFromMotionlessPause+ // =========================================================================++ @Test+ fun `resumeFromMotionlessPause clears state and saves to DB`() = testScope.runTest {+ val motionDetector = mockk<MotionDetector>(relaxed = true)+ setField("motionDetector", motionDetector)+ setField("isMotionlessPaused", true)+ setField("currentZoneGeofence", homeGeofence)++ invokeResumeFromMotionlessPause()++ assertFalse(getField<Boolean>("isMotionlessPaused"))+ verify { dbHelper.saveSetting("pause_zone_motionless_active", "false") }+ verify { motionDetector.disarm() }+ }++ @Test+ fun `resumeFromMotionlessPause resumes GPS when no wifi hold active`() = testScope.runTest {+ val motionDetector = mockk<MotionDetector>(relaxed = true)+ setField("motionDetector", motionDetector)+ setField("isMotionlessPaused", true)+ setField("isWifiPaused", false)+ setField("currentZoneGeofence", geofence("Home", 52.50, 13.40, 150.0, pauseOnMotionless = true))++ invokeResumeFromMotionlessPause()++ verify { locationProvider.requestLocationUpdates(any(), any(), any(), any()) }+ }++ @Test+ fun `resumeFromMotionlessPause does not resume GPS when wifi hold still active`() = testScope.runTest {+ val motionDetector = mockk<MotionDetector>(relaxed = true)+ setField("motionDetector", motionDetector)+ setField("isMotionlessPaused", true)+ setField("isWifiPaused", true)+ setField("currentZoneGeofence", geofence("Home", 52.50, 13.40, 150.0, pauseOnWifi = true, pauseOnMotionless = true))++ invokeResumeFromMotionlessPause()++ verify(exactly = 0) { locationProvider.requestLocationUpdates(any(), any(), any(), any()) }+ }++ @Test+ fun `resumeFromMotionlessPause restarts countdown when zone has pauseOnMotionless`() = testScope.runTest {+ val motionDetector = mockk<MotionDetector>(relaxed = true)+ setField("motionDetector", motionDetector)+ setField("isMotionlessPaused", true)+ val motionlessGeofence = geofence("Home", 52.50, 13.40, 150.0, pauseOnMotionless = true, motionlessTimeoutMinutes = 3)+ setField("currentZoneGeofence", motionlessGeofence)+ coEvery { service["startMotionlessCountdown"](any<Int>()) } returns Unit++ invokeResumeFromMotionlessPause()++ verify { service["startMotionlessCountdown"](3) }+ }++ // =========================================================================+ // onMotionDetected - motionless pause path+ // =========================================================================++ @Test+ fun `onMotionDetected resumes from motionless pause when isMotionlessPaused`() = testScope.runTest {+ val motionDetector = mockk<MotionDetector>(relaxed = true)+ setField("motionDetector", motionDetector)+ setField("isMotionlessPaused", true)+ setField("insidePauseZone", true)+ setField("currentZoneGeofence", homeGeofence)++ invokeOnMotionDetected()++ assertFalse(getField<Boolean>("isMotionlessPaused"))+ verify { dbHelper.saveSetting("pause_zone_motionless_active", "false") }+ }++ @Test+ fun `onMotionDetected motionless path takes priority over stationary`() = testScope.runTest {+ val motionDetector = mockk<MotionDetector>(relaxed = true)+ setField("motionDetector", motionDetector)+ setField("isMotionlessPaused", true)+ setField("isStationary", true)+ setField("currentZoneGeofence", homeGeofence)++ invokeOnMotionDetected()++ // Motionless path fires, not stationary path+ assertFalse(getField<Boolean>("isMotionlessPaused"))+ assertTrue(getField<Boolean>("isStationary")) // stationary unchanged+ }++ // =========================================================================+ // maybeResumeGps - dual hold logic+ // =========================================================================++ @Test+ fun `maybeResumeGps resumes GPS when no holds active`() = testScope.runTest {+ setField("currentZoneGeofence", geofence("Home", 52.50, 13.40, 150.0, pauseOnWifi = true, pauseOnMotionless = true))+ setField("isWifiPaused", false)+ setField("isMotionlessPaused", false)++ invokeMaybeResumeGps()++ verify { locationProvider.requestLocationUpdates(any(), any(), any(), any()) }+ }++ @Test+ fun `maybeResumeGps blocked when wifi hold active`() = testScope.runTest {+ setField("currentZoneGeofence", geofence("Home", 52.50, 13.40, 150.0, pauseOnWifi = true))+ setField("isWifiPaused", true)+ setField("isMotionlessPaused", false)++ invokeMaybeResumeGps()++ verify(exactly = 0) { locationProvider.requestLocationUpdates(any(), any(), any(), any()) }+ }++ @Test+ fun `maybeResumeGps blocked when motionless hold active`() = testScope.runTest {+ setField("currentZoneGeofence", geofence("Home", 52.50, 13.40, 150.0, pauseOnMotionless = true))+ setField("isWifiPaused", false)+ setField("isMotionlessPaused", true)++ invokeMaybeResumeGps()++ verify(exactly = 0) { locationProvider.requestLocationUpdates(any(), any(), any(), any()) }+ }++ @Test+ fun `maybeResumeGps resumes when currentZoneGeofence is null`() = testScope.runTest {+ setField("currentZoneGeofence", null)++ invokeMaybeResumeGps()++ verify { locationProvider.requestLocationUpdates(any(), any(), any(), any()) }+ }++ // =========================================================================+ // applyZoneSettingsIfChanged+ // =========================================================================++ @Test+ fun `applyZoneSettingsIfChanged enables wifi callback when pauseOnWifi toggled on`() {+ setField("currentZoneGeofence", homeGeofence) // pauseOnWifi=false+ coEvery { service["registerWifiPause"]() } returns Unit+ val updatedGeofence = geofence("Home", 52.50, 13.40, 150.0, pauseOnWifi = true)++ invokeApplyZoneSettingsIfChanged(updatedGeofence)++ verify { service["registerWifiPause"]() }+ }++ @Test+ fun `applyZoneSettingsIfChanged disables wifi hold and resumes GPS`() {+ val wifiGeofence = geofence("Home", 52.50, 13.40, 150.0, pauseOnWifi = true)+ setField("currentZoneGeofence", wifiGeofence)+ setField("isWifiPaused", true)++ invokeApplyZoneSettingsIfChanged(homeGeofence) // pauseOnWifi=false++ assertFalse(getField<Boolean>("isWifiPaused"))+ verify { locationProvider.requestLocationUpdates(any(), any(), any(), any()) }+ }++ @Test+ fun `applyZoneSettingsIfChanged disables motionless hold and resumes GPS`() {+ val motionlessGeofence = geofence("Home", 52.50, 13.40, 150.0, pauseOnMotionless = true)+ val motionDetector = mockk<MotionDetector>(relaxed = true)+ setField("motionDetector", motionDetector)+ setField("currentZoneGeofence", motionlessGeofence)+ setField("isMotionlessPaused", true)++ invokeApplyZoneSettingsIfChanged(homeGeofence) // pauseOnMotionless=false++ assertFalse(getField<Boolean>("isMotionlessPaused"))+ verify { dbHelper.saveSetting("pause_zone_motionless_active", "false") }+ verify { locationProvider.requestLocationUpdates(any(), any(), any(), any()) }+ }++ @Test+ fun `applyZoneSettingsIfChanged starts countdown when pauseOnMotionless toggled on`() {+ setField("currentZoneGeofence", homeGeofence) // pauseOnMotionless=false+ coEvery { service["startMotionlessCountdown"](any<Int>()) } returns Unit+ val updatedGeofence = geofence("Home", 52.50, 13.40, 150.0, pauseOnMotionless = true, motionlessTimeoutMinutes = 7)++ invokeApplyZoneSettingsIfChanged(updatedGeofence)++ verify { service["startMotionlessCountdown"](7) }+ }++ @Test+ fun `applyZoneSettingsIfChanged restarts countdown when timeout changes`() {+ val originalGeofence = geofence("Home", 52.50, 13.40, 150.0, pauseOnMotionless = true, motionlessTimeoutMinutes = 10)+ setField("currentZoneGeofence", originalGeofence)+ setField("motionlessJob", mockk<Job>(relaxed = true))+ coEvery { service["cancelMotionlessCountdown"]() } returns Unit+ coEvery { service["startMotionlessCountdown"](any<Int>()) } returns Unit+ val updatedGeofence = geofence("Home", 52.50, 13.40, 150.0, pauseOnMotionless = true, motionlessTimeoutMinutes = 3)++ invokeApplyZoneSettingsIfChanged(updatedGeofence)++ verifyOrder {+ service["cancelMotionlessCountdown"]()+ service["startMotionlessCountdown"](3)+ }+ }++ @Test+ fun `applyZoneSettingsIfChanged does not restart countdown when timeout unchanged`() {+ val originalGeofence = geofence("Home", 52.50, 13.40, 150.0, pauseOnMotionless = true, motionlessTimeoutMinutes = 10)+ setField("currentZoneGeofence", originalGeofence)+ setField("motionlessJob", mockk<Job>(relaxed = true))+ coEvery { service["startMotionlessCountdown"](any<Int>()) } returns Unit+ val updatedGeofence = geofence("Home", 52.50, 13.40, 150.0, pauseOnMotionless = true, motionlessTimeoutMinutes = 10)++ invokeApplyZoneSettingsIfChanged(updatedGeofence)++ verify(exactly = 0) { service["startMotionlessCountdown"](any<Int>()) }+ }+// =========================================================================// Helpers - invoke private methods via reflection// =========================================================================@@ -1598,8 +1953,41 @@ class LocationForegroundServiceTest {method.invoke(service)}- private fun geofence(name: String, lat: Double = 52.52, lon: Double = 13.405, radius: Double = 100.0) =- GeofenceHelper.CachedGeofence(name, lat, lon, radius)+ private fun invokeStartMotionlessCountdown(timeoutMinutes: Int) {+ val method = LocationForegroundService::class.java.getDeclaredMethod("startMotionlessCountdown", Int::class.java)+ method.isAccessible = true+ method.invoke(service, timeoutMinutes)+ }++ private fun invokeResumeFromMotionlessPause() {+ val method = LocationForegroundService::class.java.getDeclaredMethod("resumeFromMotionlessPause")+ method.isAccessible = true+ method.invoke(service)+ }++ private fun invokeMaybeResumeGps() {+ val method = LocationForegroundService::class.java.getDeclaredMethod("maybeResumeGps")+ method.isAccessible = true+ method.invoke(service)+ }++ private fun invokeApplyZoneSettingsIfChanged(zone: GeofenceHelper.CachedGeofence) {+ val method = LocationForegroundService::class.java.getDeclaredMethod(+ "applyZoneSettingsIfChanged", GeofenceHelper.CachedGeofence::class.java+ )+ method.isAccessible = true+ method.invoke(service, zone)+ }++ private fun geofence(+ name: String,+ lat: Double = 52.52,+ lon: Double = 13.405,+ radius: Double = 100.0,+ pauseOnWifi: Boolean = false,+ pauseOnMotionless: Boolean = false,+ motionlessTimeoutMinutes: Int = 10+ ) = GeofenceHelper.CachedGeofence(name, lat, lon, radius, pauseOnWifi, pauseOnMotionless, motionlessTimeoutMinutes)private val homeGeofence = geofence("Home", 52.50, 13.40, 150.0)private val officeGeofence = geofence("Office", 48.14, 11.58, 200.0)diff --git a/apps/mobile/android/app/src/test/java/com/Colota/service/NotificationHelperTest.kt b/apps/mobile/android/app/src/test/java/com/Colota/service/NotificationHelperTest.ktindex cacdb201..7c184f69 100644--- a/apps/mobile/android/app/src/test/java/com/Colota/service/NotificationHelperTest.kt+++ b/apps/mobile/android/app/src/test/java/com/Colota/service/NotificationHelperTest.kt@@ -82,6 +82,30 @@ class NotificationHelperTest {assertEquals("Paused: Unknown", helper.buildStatusText(true, null, 52.0, 13.0, 0, 0L))}+ @Test+ fun `status text shows WiFi suffix when wifi paused`() {+ assertEquals(+ "Paused: Home \u00b7 WiFi",+ helper.buildStatusText(true, "Home", 52.0, 13.0, 0, 0L, isWifiPaused = true)+ )+ }++ @Test+ fun `status text shows Motionless suffix when motionless paused`() {+ assertEquals(+ "Paused: Home \u00b7 Motionless",+ helper.buildStatusText(true, "Home", 52.0, 13.0, 0, 0L, isMotionlessPaused = true)+ )+ }++ @Test+ fun `status text WiFi takes priority over motionless when both active`() {+ assertEquals(+ "Paused: Home \u00b7 WiFi",+ helper.buildStatusText(true, "Home", 52.0, 13.0, 0, 0L, isWifiPaused = true, isMotionlessPaused = true)+ )+ }+@Testfun `status text shows coordinates when tracking normally`() {assertEquals("52.51630, 13.37770", helper.buildStatusText(false, null, 52.51630, 13.37770, 0, 0L))@@ -185,9 +209,15 @@ class NotificationHelperTest {// --- Deduplication (via update()) ---@Test- fun `same state is deduplicated on second update`() {+ fun `same state is deduplicated on second non-forced update`() {+ assertTrue(helper.update(lat = 52.52, lon = 13.405, forceUpdate = true))+ assertFalse(helper.update(lat = 52.52, lon = 13.405, forceUpdate = false))+ }++ @Test+ fun `forceUpdate bypasses dedup`() {+ assertTrue(helper.update(lat = 52.52, lon = 13.405, forceUpdate = true))assertTrue(helper.update(lat = 52.52, lon = 13.405, forceUpdate = true))- assertFalse(helper.update(lat = 52.52, lon = 13.405, forceUpdate = true))}@Test@@ -249,6 +279,17 @@ class NotificationHelperTest {assertEquals("Paused: Home", text)}+ @Test+ fun `buildStatusText WiFi suffix shown with stationary also active`() {+ val text = helper.buildStatusText(+ isPaused = true, zoneName = "Home",+ lat = 52.52, lon = 13.405,+ queuedCount = 0, lastSyncTime = 0L,+ isStationary = true, isWifiPaused = true+ )+ assertEquals("Paused: Home \u00b7 WiFi", text)+ }+// --- Reflection helper ---private fun setField(name: String, value: Any?) {diff --git a/apps/mobile/src/components/features/map/__tests__/mapUtils.test.ts b/apps/mobile/src/components/features/map/__tests__/mapUtils.test.tsindex 2b07ef80..6d067f77 100644--- a/apps/mobile/src/components/features/map/__tests__/mapUtils.test.ts+++ b/apps/mobile/src/components/features/map/__tests__/mapUtils.test.ts@@ -251,7 +251,10 @@ describe("buildGeofencesGeoJSON", () => {lon: 13.405,radius: 200,enabled: true,- pauseTracking: true+ pauseTracking: true,+ pauseOnWifi: false,+ pauseOnMotionless: false,+ motionlessTimeoutMinutes: 10}it("returns empty collections for no geofences", () => {diff --git a/apps/mobile/src/screens/GeofenceEditorScreen.tsx b/apps/mobile/src/screens/GeofenceEditorScreen.tsxnew file mode 100644index 00000000..9fddb3da--- /dev/null+++ b/apps/mobile/src/screens/GeofenceEditorScreen.tsx@@ -0,0 +1,300 @@+/**+ * Copyright (C) 2026 Max Dietrich+ * Licensed under the GNU AGPLv3. See LICENSE in the project root for details.+ */++import React, { useState, useEffect, useCallback, useRef, useMemo } from "react"+import { View, Text, StyleSheet, ScrollView, Switch, TextInput, DeviceEventEmitter } from "react-native"+import { useTheme } from "../hooks/useTheme"+import NativeLocationService from "../services/NativeLocationService"+import { showAlert, showConfirm } from "../services/modalService"+import { fonts } from "../styles/typography"+import { Container, SectionTitle, Card, SettingRow, Button } from "../components"+import { Check, Trash2 } from "lucide-react-native"+import { logger } from "../utils/logger"+import { shortDistanceUnit, inputToMeters, metersToInput } from "../utils/geo"++export function GeofenceEditorScreen({ navigation, route }: any) {+ const { colors } = useTheme()+ const geofenceId = route?.params?.geofenceId as number | undefined+ const isEditing = !!geofenceId++ const [name, setName] = useState<string>(route?.params?.name ?? "")+ const initialRadius = route?.params?.radius ?? inputToMeters(50)+ const [radiusStr, setRadiusStr] = useState(String(metersToInput(initialRadius)))+ const [radius, setRadius] = useState<number>(initialRadius)+ const [pauseTracking, setPauseTracking] = useState(true)+ const [pauseOnWifi, setPauseOnWifi] = useState(false)+ const [pauseOnMotionless, setPauseOnMotionless] = useState(false)+ const [motionlessTimeoutMinutes, setMotionlessTimeoutMinutes] = useState(10)+ const [motionlessTimeoutStr, setMotionlessTimeoutStr] = useState("10")+ const [saving, setSaving] = useState(false)++ const savedState = useRef({+ name: route?.params?.name ?? ("" as string),+ radius: (route?.params?.radius ?? inputToMeters(50)) as number,+ pauseTracking: true,+ pauseOnWifi: false,+ pauseOnMotionless: false,+ motionlessTimeoutMinutes: 10+ })++ const hasChanges = useMemo(() => {+ const s = savedState.current+ return (+ name !== s.name ||+ radius !== s.radius ||+ pauseTracking !== s.pauseTracking ||+ pauseOnWifi !== s.pauseOnWifi ||+ pauseOnMotionless !== s.pauseOnMotionless ||+ motionlessTimeoutMinutes !== s.motionlessTimeoutMinutes+ )+ }, [name, radius, pauseTracking, pauseOnWifi, pauseOnMotionless, motionlessTimeoutMinutes])++ useEffect(() => {+ if (!geofenceId) return++ NativeLocationService.getGeofences()+ .then((geofences) => {+ const existing = geofences.find((g) => g.id === geofenceId)+ if (existing) {+ setName(existing.name)+ setRadiusStr(String(metersToInput(existing.radius)))+ setRadius(existing.radius)+ setPauseTracking(existing.pauseTracking)+ setPauseOnWifi(existing.pauseOnWifi)+ setPauseOnMotionless(existing.pauseOnMotionless)+ setMotionlessTimeoutMinutes(existing.motionlessTimeoutMinutes)+ setMotionlessTimeoutStr(String(existing.motionlessTimeoutMinutes))+ savedState.current = {+ name: existing.name,+ radius: existing.radius,+ pauseTracking: existing.pauseTracking,+ pauseOnWifi: existing.pauseOnWifi,+ pauseOnMotionless: existing.pauseOnMotionless,+ motionlessTimeoutMinutes: existing.motionlessTimeoutMinutes+ }+ }+ })+ .catch((err) => {+ logger.error("[GeofenceEditor] Failed to load geofence:", err)+ showAlert("Error", "Failed to load geofence data.", "error")+ navigation.goBack()+ })+ }, [geofenceId, navigation])++ const handleRadiusChange = useCallback((val: string) => {+ setRadiusStr(val)+ const num = Number(val)+ if (!isNaN(num) && num > 0) setRadius(inputToMeters(num))+ }, [])++ const handleTimeoutChange = useCallback((val: string) => {+ setMotionlessTimeoutStr(val)+ const num = parseInt(val, 10)+ if (!isNaN(num) && num >= 1) setMotionlessTimeoutMinutes(num)+ }, [])++ const handleSave = useCallback(async () => {+ if (!name.trim()) {+ showAlert("Missing Name", "Please enter a name.", "warning")+ return+ }+ if (radius <= 0) {+ showAlert("Invalid Radius", "Please enter a valid radius.", "warning")+ return+ }++ setSaving(true)+ try {+ if (isEditing && geofenceId) {+ await NativeLocationService.updateGeofence({+ id: geofenceId,+ name: name.trim(),+ radius,+ pauseTracking,+ pauseOnWifi,+ pauseOnMotionless,+ motionlessTimeoutMinutes+ })+ } else {+ const lat = route?.params?.lat as number+ const lon = route?.params?.lon as number+ await NativeLocationService.createGeofence({+ name: name.trim(),+ lat,+ lon,+ radius,+ enabled: true,+ pauseTracking,+ pauseOnWifi,+ pauseOnMotionless,+ motionlessTimeoutMinutes+ })+ }+ DeviceEventEmitter.emit("geofenceUpdated")+ navigation.goBack()+ } catch (err) {+ logger.error("[GeofenceEditor] Save failed:", err)+ showAlert("Error", "Failed to save geofence.", "error")+ } finally {+ setSaving(false)+ }+ }, [+ name,+ radius,+ pauseTracking,+ pauseOnWifi,+ pauseOnMotionless,+ motionlessTimeoutMinutes,+ isEditing,+ geofenceId,+ navigation,+ route+ ])++ const handleDelete = useCallback(async () => {+ if (!geofenceId) return+ const confirmed = await showConfirm({+ title: "Delete Geofence",+ message: `Delete "${name}"?`,+ confirmText: "Delete",+ destructive: true+ })+ if (!confirmed) return+ try {+ await NativeLocationService.deleteGeofence(geofenceId)+ DeviceEventEmitter.emit("geofenceUpdated")+ navigation.goBack()+ } catch (err) {+ logger.error("[GeofenceEditor] Delete failed:", err)+ showAlert("Error", "Failed to delete geofence.", "error")+ }+ }, [geofenceId, name, navigation])++ const inputStyle = [+ styles.input,+ { backgroundColor: colors.background, color: colors.text, borderColor: colors.border }+ ]++ return (+ <Container>+ <ScrollView contentContainerStyle={styles.content} showsVerticalScrollIndicator={false}>+ <SectionTitle>General</SectionTitle>+ <Card style={styles.card}>+ <SettingRow label="Name">+ <TextInput+ testID="geofence-name-input"+ style={[inputStyle, styles.nameInput]}+ value={name}+ onChangeText={setName}+ placeholder="Home, Work..."+ placeholderTextColor={colors.placeholder}+ />+ </SettingRow>+ <SettingRow label={`Radius (${shortDistanceUnit()})`}>+ <TextInput+ testID="geofence-radius-input"+ style={[inputStyle, styles.numInput]}+ value={radiusStr}+ onChangeText={handleRadiusChange}+ placeholder="50"+ placeholderTextColor={colors.placeholder}+ keyboardType="numeric"+ />+ </SettingRow>+ </Card>++ <SectionTitle>GPS Pause Options</SectionTitle>+ <Card style={styles.card}>+ <SettingRow label="Don't record in zone" hint="Locations are not saved while inside this zone">+ <Switch+ testID="pause-tracking-toggle"+ value={pauseTracking}+ onValueChange={setPauseTracking}+ trackColor={{ false: colors.border, true: colors.warning + "80" }}+ thumbColor={pauseTracking ? colors.warning : colors.border}+ />+ </SettingRow>++ <SettingRow label="Pause when on WiFi or Ethernet" hint="Stop GPS when connected to an unmetered network">+ <Switch+ testID="pause-wifi-toggle"+ value={pauseOnWifi}+ onValueChange={setPauseOnWifi}+ trackColor={{ false: colors.border, true: colors.primary + "80" }}+ thumbColor={pauseOnWifi ? colors.primary : colors.border}+ />+ </SettingRow>++ <SettingRow label="Pause when motionless" hint="Stop GPS after no device motion is detected for a set time">+ <Switch+ testID="pause-motionless-toggle"+ value={pauseOnMotionless}+ onValueChange={setPauseOnMotionless}+ trackColor={{ false: colors.border, true: colors.primary + "80" }}+ thumbColor={pauseOnMotionless ? colors.primary : colors.border}+ />+ </SettingRow>++ {pauseOnMotionless && (+ <SettingRow+ label="Motionless timeout (min)"+ hint="GPS pauses after this many minutes without motion. Resumes automatically when the device moves again."+ >+ <TextInput+ testID="motionless-timeout-input"+ style={[inputStyle, styles.numInput]}+ value={motionlessTimeoutStr}+ onChangeText={handleTimeoutChange}+ placeholder="10"+ placeholderTextColor={colors.placeholder}+ keyboardType="numeric"+ />+ </SettingRow>+ )}++ {pauseOnWifi && pauseOnMotionless && (+ <View style={[styles.combinedNote, { borderTopColor: colors.border }]}>+ <Text style={[styles.combinedNoteText, { color: colors.textSecondary }]}>+ GPS resumes only when both WiFi is disconnected and motion is detected+ </Text>+ </View>+ )}+ </Card>++ <Button+ title={saving ? "Saving..." : "Save Geofence"}+ onPress={handleSave}+ disabled={saving || (isEditing && !hasChanges)}+ icon={Check}+ />+ {isEditing && <Button title="Delete Geofence" onPress={handleDelete} variant="danger" icon={Trash2} />}+ </ScrollView>+ </Container>+ )+}++const styles = StyleSheet.create({+ content: { padding: 20, paddingBottom: 40 },+ card: { marginBottom: 16 },+ input: {+ padding: 10,+ borderWidth: 1.5,+ borderRadius: 8,+ fontSize: 15+ },+ nameInput: { flex: 1 },+ numInput: { width: 80, textAlign: "center" },+ combinedNote: {+ marginTop: 8,+ paddingTop: 12,+ borderTopWidth: StyleSheet.hairlineWidth+ },+ combinedNoteText: {+ fontSize: 12,+ ...fonts.regular,+ lineHeight: 17,+ fontStyle: "italic"+ }+})diff --git a/apps/mobile/src/screens/GeofenceScreen.tsx b/apps/mobile/src/screens/GeofenceScreen.tsxindex a5de19ea..602651c9 100644--- a/apps/mobile/src/screens/GeofenceScreen.tsx+++ b/apps/mobile/src/screens/GeofenceScreen.tsx@@ -4,14 +4,14 @@*/import React, { useState, useEffect, useRef, useMemo, useCallback } from "react"-import { View, Text, StyleSheet, TextInput, Pressable, FlatList, Switch, DeviceEventEmitter } from "react-native"+import { View, Text, StyleSheet, TextInput, Pressable, FlatList, DeviceEventEmitter } from "react-native"import { useTheme } from "../hooks/useTheme"import NativeLocationService from "../services/NativeLocationService"-import { showAlert, showConfirm } from "../services/modalService"+import { showAlert } from "../services/modalService"import { Geofence, ScreenProps } from "../types/global"import { useTracking, useCoords } from "../contexts/TrackingProvider"import { fonts } from "../styles/typography"-import { X } from "lucide-react-native"+import { ChevronRight, Wifi, PersonStanding } from "lucide-react-native"import { Container, SectionTitle, Card } from "../components"import {DEFAULT_MAP_ZOOM,@@ -28,7 +28,7 @@ import { UserLocationOverlay } from "../components/features/map/UserLocationOverimport { logger } from "../utils/logger"import { formatShortDistance, shortDistanceUnit, inputToMeters } from "../utils/geo"-export function GeofenceScreen({}: ScreenProps) {+export function GeofenceScreen({ navigation }: ScreenProps) {const { tracking } = useTracking()const coords = useCoords()const { colors } = useTheme()@@ -101,9 +101,12 @@ export function GeofenceScreen({}: ScreenProps) {}checkPauseZone()- const listener = DeviceEventEmitter.addListener("geofenceUpdated", checkPauseZone)+ const listener = DeviceEventEmitter.addListener("geofenceUpdated", () => {+ checkPauseZone()+ loadGeofences()+ })return () => listener.remove()- }, [])+ }, [loadGeofences])// Auto-center camera when position changes (ref avoids overriding setCamera zoom)useEffect(() => {@@ -115,25 +118,27 @@ export function GeofenceScreen({}: ScreenProps) {const handleMapPress = useCallback(async (pressCoords: { latitude: number; longitude: number }) => {if (!placingGeofence) return-+ setPlacingGeofence(false)try {await NativeLocationService.createGeofence({- name: newName,+ name: newName.trim(),lat: pressCoords.latitude,lon: pressCoords.longitude,radius: inputToMeters(Number(newRadius)),enabled: true,- pauseTracking: true+ pauseTracking: true,+ pauseOnWifi: false,+ pauseOnMotionless: false,+ motionlessTimeoutMinutes: 10})-- setNewName("")- setNewRadius("50")- setPlacingGeofence(false)await loadGeofences()DeviceEventEmitter.emit("geofenceUpdated")- } catch {+ } catch (err) {+ logger.error("[GeofenceScreen] Failed to create geofence:", err)showAlert("Error", "Failed to create geofence.", "error")}+ setNewName("")+ setNewRadius("50")},[placingGeofence, newName, newRadius, loadGeofences])@@ -173,23 +178,6 @@ export function GeofenceScreen({}: ScreenProps) {}}, [])- const togglePause = useCallback(- async (id: number, value: boolean) => {- try {- await NativeLocationService.updateGeofence({- id,- pauseTracking: value- })- await loadGeofences()- DeviceEventEmitter.emit("geofenceUpdated")- await NativeLocationService.recheckZoneSettings()- } catch {- showAlert("Error", "Failed to update geofence.", "error")- }- },- [loadGeofences]- )-const handleZoomToGeofence = useCallback((item: Geofence) => {if (!mapRef.current?.camera) return@@ -204,28 +192,6 @@ export function GeofenceScreen({}: ScreenProps) {)}, [])- const handleDelete = useCallback(- async (item: Geofence) => {- const confirmed = await showConfirm({- title: "Delete Geofence",- message: `Delete "${item.name}"?`,- confirmText: "Delete",- destructive: true- })-- if (!confirmed) return-- try {- await NativeLocationService.deleteGeofence(item.id!)- await loadGeofences()- DeviceEventEmitter.emit("geofenceUpdated")- } catch {- showAlert("Error", "Failed to delete geofence.", "error")- }- },- [loadGeofences]- )-// Geofence GeoJSONconst geofenceData = useMemo(() => buildGeofencesGeoJSON(geofences, colors), [geofences, colors])@@ -243,42 +209,26 @@ export function GeofenceScreen({}: ScreenProps) {onPress={() => handleZoomToGeofence(item)}><Text style={[styles.name, { color: colors.text }]}>{item.name}</Text>- <Text style={[styles.radius, { color: colors.textSecondary }]}>- {formatShortDistance(item.radius)} radius- </Text>- </Pressable>-- <View style={styles.actions}>- <View style={styles.pauseSwitch}>- <Text style={[styles.pauseLabel, { color: colors.textSecondary }]}>Pause</Text>- <Switch- testID={`pause-geofence-${item.id}`}- value={item.pauseTracking}- onValueChange={(val) => togglePause(item.id!, val)}- trackColor={{- false: colors.border,- true: colors.warning + "80"- }}- thumbColor={item.pauseTracking ? colors.warning : colors.border}- />+ <View style={styles.radiusRow}>+ <Text style={[styles.radius, { color: colors.textSecondary }]}>+ {formatShortDistance(item.radius)} radius+ </Text>+ {item.pauseOnWifi && <Wifi size={12} color={colors.textSecondary} />}+ {item.pauseOnMotionless && <PersonStanding size={12} color={colors.textSecondary} />}</View>+ </Pressable>- <Pressable- testID={`delete-geofence-${item.id}`}- onPress={() => handleDelete(item)}- style={({ pressed }) => [- styles.deleteBtn,- { backgroundColor: colors.error + "15" },- pressed && { opacity: colors.pressedOpacity }- ]}- >- <X size={16} color={colors.error} />- </Pressable>- </View>+ <Pressable+ testID={`edit-geofence-${item.id}`}+ onPress={() => navigation.navigate("Geofence Editor", { geofenceId: item.id })}+ style={({ pressed }) => [pressed && { opacity: colors.pressedOpacity }]}+ >+ <ChevronRight size={20} color={colors.textSecondary} />+ </Pressable></View></Card>),- [colors, handleDelete, togglePause, handleZoomToGeofence]+ [colors, handleZoomToGeofence, navigation])return (@@ -431,22 +381,8 @@ const styles = StyleSheet.create({},info: { flex: 1, marginRight: 12 },name: { fontSize: 15, ...fonts.semiBold, marginBottom: 2 },+ radiusRow: { flexDirection: "row", alignItems: "center", gap: 4 },radius: { fontSize: 12 },- actions: { flexDirection: "row", alignItems: "center", gap: 12 },- pauseSwitch: { flexDirection: "row", alignItems: "center", gap: 6 },- pauseLabel: {- fontSize: 11,- ...fonts.semiBold,- textTransform: "uppercase",- letterSpacing: 0.3- },- deleteBtn: {- width: 32,- height: 32,- borderRadius: 16,- alignItems: "center",- justifyContent: "center"- },empty: { alignItems: "center", paddingVertical: 40 },emptyText: { fontSize: 15, ...fonts.semiBold, marginBottom: 6 },emptyHint: {diff --git a/apps/mobile/src/screens/__tests__/GeofenceEditorScreen.test.tsx b/apps/mobile/src/screens/__tests__/GeofenceEditorScreen.test.tsxnew file mode 100644index 00000000..4ef3bfe7--- /dev/null+++ b/apps/mobile/src/screens/__tests__/GeofenceEditorScreen.test.tsx@@ -0,0 +1,264 @@+/**+ * Copyright (C) 2026 Max Dietrich+ * Licensed under the GNU AGPLv3. See LICENSE in the project root for details.+ */++import React from "react"+import { render, fireEvent, waitFor } from "@testing-library/react-native"+import { Geofence } from "../../types/global"++// --- Mocks ---++const mockGetGeofences = jest.fn()+const mockUpdateGeofence = jest.fn().mockResolvedValue(true)+const mockDeleteGeofence = jest.fn().mockResolvedValue(true)++jest.mock("../../services/NativeLocationService", () => ({+ __esModule: true,+ default: {+ getGeofences: (...args: any[]) => mockGetGeofences(...args),+ updateGeofence: (...args: any[]) => mockUpdateGeofence(...args),+ deleteGeofence: (...args: any[]) => mockDeleteGeofence(...args)+ }+}))++const mockShowAlert = jest.fn()+const mockShowConfirm = jest.fn().mockResolvedValue(true)++jest.mock("../../services/modalService", () => ({+ showAlert: (...args: any[]) => mockShowAlert(...args),+ showConfirm: (...args: any[]) => mockShowConfirm(...args)+}))++jest.mock("react-native/Libraries/EventEmitter/NativeEventEmitter")++jest.mock("../../hooks/useTheme", () => ({+ useTheme: () => ({+ colors: {+ primary: "#0d9488",+ primaryDark: "#0d9488",+ border: "#e5e7eb",+ text: "#000",+ textSecondary: "#6b7280",+ textDisabled: "#d1d5db",+ textLight: "#9ca3af",+ textOnPrimary: "#fff",+ background: "#fff",+ card: "#fff",+ error: "#ef4444",+ warning: "#f59e0b",+ success: "#22c55e",+ placeholder: "#9ca3af",+ borderRadius: 12,+ pressedOpacity: 0.7+ }+ })+}))++jest.mock("../../utils/geo", () => ({+ shortDistanceUnit: () => "m",+ metersToInput: (v: number) => v,+ inputToMeters: (v: number) => v+}))++jest.mock("../../utils/logger", () => ({+ logger: { debug: jest.fn(), error: jest.fn(), warn: jest.fn(), info: jest.fn() }+}))++jest.mock("../../components", () => {+ const R = require("react")+ const { View, Text, Pressable } = require("react-native")+ return {+ Container: ({ children }: any) => R.createElement(View, null, children),+ SectionTitle: ({ children }: any) => R.createElement(Text, null, children),+ Card: ({ children }: any) => R.createElement(View, null, children),+ SettingRow: ({ label, children }: any) => R.createElement(View, null, R.createElement(Text, null, label), children),+ Button: ({ title, onPress, disabled }: any) =>+ R.createElement(+ Pressable,+ {+ onPress,+ testID: `btn-${title.replace(/\s+/g, "-").toLowerCase()}`,+ accessibilityState: { disabled: !!disabled }+ },+ R.createElement(Text, null, title)+ )+ }+})++jest.mock("lucide-react-native", () => {+ const R = require("react")+ const { Text } = require("react-native")+ return {+ Check: (props: any) => R.createElement(Text, props, "Check"),+ Trash2: (props: any) => R.createElement(Text, props, "Trash2")+ }+})++const mockGoBack = jest.fn()+const mockNavigation = { goBack: mockGoBack }++const mockExistingGeofence: Geofence = {+ id: 1,+ name: "Home",+ lat: 48.1,+ lon: 11.5,+ radius: 100,+ enabled: true,+ pauseTracking: true,+ pauseOnWifi: false,+ pauseOnMotionless: false,+ motionlessTimeoutMinutes: 10+}++import { GeofenceEditorScreen } from "../GeofenceEditorScreen"++// --- Tests ---++describe("GeofenceEditorScreen", () => {+ beforeEach(() => {+ jest.clearAllMocks()+ mockGetGeofences.mockResolvedValue([mockExistingGeofence])+ mockShowConfirm.mockResolvedValue(true)+ mockDeleteGeofence.mockResolvedValue(true)+ mockUpdateGeofence.mockResolvedValue(true)+ })++ function renderEdit(geofenceId = 1) {+ return render(<GeofenceEditorScreen navigation={mockNavigation as any} route={{ params: { geofenceId } }} />)+ }++ function renderNew() {+ return render(+ <GeofenceEditorScreen+ navigation={mockNavigation as any}+ route={{ params: { lat: 48.1, lon: 11.5, name: "New Zone", radius: 50 } }}+ />+ )+ }++ // --- Save button state ---++ it("save button is disabled when editing with no changes", async () => {+ const { getByTestId } = renderEdit()++ await waitFor(() => {+ expect(getByTestId("btn-save-geofence")).toBeTruthy()+ })++ expect(getByTestId("btn-save-geofence").props.accessibilityState.disabled).toBe(true)+ })++ it("save button enables after name change", async () => {+ const { getByTestId, getByDisplayValue } = renderEdit()++ await waitFor(() => {+ expect(getByDisplayValue("Home")).toBeTruthy()+ })++ fireEvent.changeText(getByDisplayValue("Home"), "Home Updated")++ await waitFor(() => {+ expect(getByTestId("btn-save-geofence").props.accessibilityState.disabled).toBe(false)+ })+ })++ it("save button enables after toggling WiFi pause", async () => {+ const { getByTestId } = renderEdit()++ await waitFor(() => {+ expect(getByTestId("pause-wifi-toggle")).toBeTruthy()+ })++ fireEvent(getByTestId("pause-wifi-toggle"), "onValueChange", true)++ await waitFor(() => {+ expect(getByTestId("btn-save-geofence").props.accessibilityState.disabled).toBe(false)+ })+ })++ it("save button is always enabled for new geofence", async () => {+ const { getByTestId } = renderNew()++ await waitFor(() => {+ expect(getByTestId("btn-save-geofence")).toBeTruthy()+ })++ expect(getByTestId("btn-save-geofence").props.accessibilityState.disabled).toBe(false)+ })++ // --- Delete button ---++ it("delete button is shown when editing", async () => {+ const { getByTestId } = renderEdit()++ await waitFor(() => {+ expect(getByTestId("btn-delete-geofence")).toBeTruthy()+ })+ })++ it("delete button is not shown for new geofence", async () => {+ const { queryByTestId } = renderNew()++ await waitFor(() => {+ expect(queryByTestId("btn-delete-geofence")).toBeNull()+ })+ })++ it("delete shows confirmation dialog", async () => {+ mockShowConfirm.mockResolvedValue(false)+ const { getByTestId } = renderEdit()++ await waitFor(() => {+ expect(getByTestId("btn-delete-geofence")).toBeTruthy()+ })++ fireEvent.press(getByTestId("btn-delete-geofence"))++ await waitFor(() => {+ expect(mockShowConfirm).toHaveBeenCalledWith(+ expect.objectContaining({+ title: "Delete Geofence",+ message: 'Delete "Home"?',+ confirmText: "Delete",+ destructive: true+ })+ )+ })++ expect(mockDeleteGeofence).not.toHaveBeenCalled()+ })++ it("calls deleteGeofence and navigates back after confirmation", async () => {+ const { getByTestId } = renderEdit()++ await waitFor(() => {+ expect(getByTestId("btn-delete-geofence")).toBeTruthy()+ })++ fireEvent.press(getByTestId("btn-delete-geofence"))++ await waitFor(() => {+ expect(mockDeleteGeofence).toHaveBeenCalledWith(1)+ expect(mockGoBack).toHaveBeenCalled()+ })+ })++ // --- Save flow ---++ it("calls updateGeofence with changed values on save", async () => {+ const { getByTestId, getByDisplayValue } = renderEdit()++ await waitFor(() => {+ expect(getByDisplayValue("Home")).toBeTruthy()+ })++ fireEvent.changeText(getByDisplayValue("Home"), "Home Renamed")+ fireEvent.press(getByTestId("btn-save-geofence"))++ await waitFor(() => {+ expect(mockUpdateGeofence).toHaveBeenCalledWith(expect.objectContaining({ id: 1, name: "Home Renamed" }))+ expect(mockGoBack).toHaveBeenCalled()+ })+ })+})diff --git a/apps/mobile/src/screens/__tests__/GeofenceScreen.test.tsx b/apps/mobile/src/screens/__tests__/GeofenceScreen.test.tsxindex 662fb13b..a59a7d78 100644--- a/apps/mobile/src/screens/__tests__/GeofenceScreen.test.tsx+++ b/apps/mobile/src/screens/__tests__/GeofenceScreen.test.tsx@@ -83,11 +83,9 @@ jest.mock("../../services/NativeLocationService", () => ({}))const mockShowAlert = jest.fn()-const mockShowConfirm = jest.fn().mockResolvedValue(true)jest.mock("../../services/modalService", () => ({- showAlert: (...args: any[]) => mockShowAlert(...args),- showConfirm: (...args: any[]) => mockShowConfirm(...args)+ showAlert: (...args: any[]) => mockShowAlert(...args)}))jest.mock("../../components/features/map/ColotaMapView", () => {@@ -144,8 +142,9 @@ jest.mock("lucide-react-native", () => {const R = require("react")const { Text } = require("react-native")return {- X: (props: any) => R.createElement(Text, props, "X"),- WifiOff: (props: any) => R.createElement(Text, props, "WifiOff")+ ChevronRight: (props: any) => R.createElement(Text, props, "ChevronRight"),+ Wifi: (props: any) => R.createElement(Text, props, "Wifi"),+ PersonStanding: (props: any) => R.createElement(Text, props, "PersonStanding")}})@@ -171,7 +170,10 @@ const mockGeofences: Geofence[] = [lon: 11.5,radius: 100,enabled: true,- pauseTracking: true+ pauseTracking: true,+ pauseOnWifi: false,+ pauseOnMotionless: false,+ motionlessTimeoutMinutes: 10},{id: 2,@@ -180,7 +182,10 @@ const mockGeofences: Geofence[] = [lon: 11.6,radius: 200,enabled: true,- pauseTracking: false+ pauseTracking: false,+ pauseOnWifi: false,+ pauseOnMotionless: false,+ motionlessTimeoutMinutes: 10}]@@ -190,7 +195,6 @@ describe("GeofenceScreen", () => {beforeEach(() => {jest.clearAllMocks()mockGetGeofences.mockResolvedValue([])- mockShowConfirm.mockResolvedValue(true)})function renderScreen() {@@ -259,72 +263,18 @@ describe("GeofenceScreen", () => {expect(getByText("Tap Map to Place...")).toBeTruthy()})- it("toggles pause tracking on a geofence", async () => {+ it("tapping ChevronRight navigates to editor with geofence id", async () => {mockGetGeofences.mockResolvedValue(mockGeofences)+ const mockNavigate = jest.fn()- const { getAllByRole } = renderScreen()+ const { getAllByText } = render(<GeofenceScreen navigation={{ navigate: mockNavigate } as any} />)await waitFor(() => {- expect(getAllByRole("switch").length).toBeGreaterThanOrEqual(2)+ expect(getAllByText("ChevronRight").length).toBeGreaterThanOrEqual(1)})- const switches = getAllByRole("switch")- // The second geofence (Office) has pauseTracking: false, toggle it on- fireEvent(switches[1], "onValueChange", true)+ fireEvent.press(getAllByText("ChevronRight")[0])- await waitFor(() => {- expect(mockUpdateGeofence).toHaveBeenCalledWith({ id: 2, pauseTracking: true })- })-- await waitFor(() => {- expect(mockRecheckZoneSettings).toHaveBeenCalled()- })- })-- it("shows delete confirmation dialog", async () => {- mockGetGeofences.mockResolvedValue(mockGeofences)- mockShowConfirm.mockResolvedValue(false)-- const { getAllByText } = renderScreen()-- await waitFor(() => {- expect(getAllByText("X").length).toBeGreaterThanOrEqual(1)- })-- // Press the first delete button (X icon)- fireEvent.press(getAllByText("X")[0])-- await waitFor(() => {- expect(mockShowConfirm).toHaveBeenCalledWith(- expect.objectContaining({- title: "Delete Geofence",- message: 'Delete "Home"?',- confirmText: "Delete",- destructive: true- })- )- })- })-- it("deletes geofence after confirmation", async () => {- mockGetGeofences.mockResolvedValue(mockGeofences)- mockShowConfirm.mockResolvedValue(true)-- const { getAllByText } = renderScreen()-- await waitFor(() => {- expect(getAllByText("X").length).toBeGreaterThanOrEqual(1)- })-- // Press the first delete button (X icon)- fireEvent.press(getAllByText("X")[0])-- await waitFor(() => {- expect(mockShowConfirm).toHaveBeenCalled()- })-- await waitFor(() => {- expect(mockDeleteGeofence).toHaveBeenCalledWith(1)- })+ expect(mockNavigate).toHaveBeenCalledWith("Geofence Editor", { geofenceId: 1 })})})diff --git a/apps/mobile/src/screens/index.ts b/apps/mobile/src/screens/index.tsindex 9c266cc0..9420ae0e 100644--- a/apps/mobile/src/screens/index.ts+++ b/apps/mobile/src/screens/index.ts@@ -10,6 +10,7 @@ export { DashboardScreen } from "./DashboardScreen"export { DataManagementScreen } from "./DataManagementScreen"export { ExportDataScreen } from "./ExportDataScreen"export { GeofenceScreen } from "./GeofenceScreen"+export { GeofenceEditorScreen } from "./GeofenceEditorScreen"export { LocationHistoryScreen } from "./LocationInspectorScreen"export { LocationSummaryScreen } from "./LocationSummaryScreen"export { SettingsScreen } from "./SettingsScreen"diff --git a/apps/mobile/src/services/NativeLocationService.ts b/apps/mobile/src/services/NativeLocationService.tsindex 34ba1319..2d6dda20 100644--- a/apps/mobile/src/services/NativeLocationService.ts+++ b/apps/mobile/src/services/NativeLocationService.ts@@ -292,7 +292,10 @@ class NativeLocationService {geofence.lat,geofence.lon,geofence.radius,- geofence.pauseTracking+ geofence.pauseTracking,+ geofence.pauseOnWifi ?? false,+ geofence.pauseOnMotionless ?? false,+ geofence.motionlessTimeoutMinutes ?? 10)}@@ -314,7 +317,10 @@ class NativeLocationService {update.lon ?? null,update.radius ?? null,update.enabled ?? null,- update.pauseTracking ?? null+ update.pauseTracking ?? null,+ update.pauseOnWifi ?? null,+ update.pauseOnMotionless ?? null,+ update.motionlessTimeoutMinutes ?? null)}diff --git a/apps/mobile/src/services/__tests__/NativeLocationService.test.ts b/apps/mobile/src/services/__tests__/NativeLocationService.test.tsindex d8540230..de1a328d 100644--- a/apps/mobile/src/services/__tests__/NativeLocationService.test.ts+++ b/apps/mobile/src/services/__tests__/NativeLocationService.test.ts@@ -297,10 +297,13 @@ describe("NativeLocationService", () => {lon: 11.5,radius: 100,enabled: true,- pauseTracking: true+ pauseTracking: true,+ pauseOnWifi: false,+ pauseOnMotionless: false,+ motionlessTimeoutMinutes: 10})- expect(nativeMock.createGeofence).toHaveBeenCalledWith("Home", 48.1, 11.5, 100, true)+ expect(nativeMock.createGeofence).toHaveBeenCalledWith("Home", 48.1, 11.5, 100, true, false, false, 10)})it("deleteGeofence passes id", async () => {diff --git a/apps/mobile/src/types/global.ts b/apps/mobile/src/types/global.tsindex 08bb2404..18052107 100644--- a/apps/mobile/src/types/global.ts+++ b/apps/mobile/src/types/global.ts@@ -38,6 +38,9 @@ export interface Geofence {radius: numberenabled: booleanpauseTracking: boolean+ pauseOnWifi: boolean+ pauseOnMotionless: boolean+ motionlessTimeoutMinutes: numbercreatedAt?: number}diff --git a/screenshots/mobile/original/DataList.png b/screenshots/mobile/original/DataList.pngdeleted file mode 100644index 89de9aec..00000000Binary files a/screenshots/mobile/original/DataList.png and /dev/null differdiff --git a/screenshots/mobile/original/GeofenceEditor.png b/screenshots/mobile/original/GeofenceEditor.pngnew file mode 100644index 00000000..e47cd38cBinary files /dev/null and b/screenshots/mobile/original/GeofenceEditor.png differdiff --git a/screenshots/mobile/original/Geofences.png b/screenshots/mobile/original/Geofences.pngnew file mode 100644index 00000000..c507b060Binary files /dev/null and b/screenshots/mobile/original/Geofences.png differdiff --git a/screenshots/mobile/original/OfflineMaps.png b/screenshots/mobile/original/OfflineMaps.pngnew file mode 100644index 00000000..be41efb9Binary files /dev/null and b/screenshots/mobile/original/OfflineMaps.png differ