Colota - Android GPS Location tracker
feat(profiles): add per-profile activation delay (#435)
Max Dietriche1b80c721537
diff --git a/apps/docs/docs/guides/deep-link-setup.md b/apps/docs/docs/guides/deep-link-setup.mdindex fc7bdc75..3340ff1d 100644--- a/apps/docs/docs/guides/deep-link-setup.md+++ b/apps/docs/docs/guides/deep-link-setup.md@@ -92,7 +92,8 @@ Each entry in the `profiles` array describes one [tracking profile](tracking-pro| `condition.type` | string | (required) | `charging`, `android_auto`, `speed_above`, `speed_below`, or `stationary` || `condition.speedThreshold` | number | - | Required for `speed_above` / `speed_below`. Speed in m/s (divide km/h by 3.6) || `priority` | number | `10` | Higher value wins when multiple profiles match |-| `deactivationDelay` | number | `60` | Seconds to keep the profile active after the condition stops matching |+| `activationDelay` | number | `0` (stationary: `60`) | Seconds the condition must keep matching before the profile is applied (0 = immediate). For `stationary`, how long the device must be still before activating |+| `deactivationDelay` | number | `60` (stationary: `0`) | Seconds to keep the profile active after the condition stops matching. Stationary resumes instantly via the motion sensor || `enabled` | boolean | `true` | Profile is active on import |Imported profiles are appended by default. When both profiles and geofences are present the same "Replace ... with the same name" toggle on the import screen also deletes existing profiles whose names match before creating the incoming ones.diff --git a/apps/docs/docs/guides/tracking-profiles.md b/apps/docs/docs/guides/tracking-profiles.mdindex b4c4eebe..b5b50b98 100644--- a/apps/docs/docs/guides/tracking-profiles.md+++ b/apps/docs/docs/guides/tracking-profiles.md@@ -58,10 +58,13 @@ Each profile overrides the default tracking configuration with:- **Distance Filter** - Minimum movement required between updates (meters)- **Sync Interval** - How often to sync with the server (Instant, 1 min, 5 min, 15 min, or Custom)- **Priority** - Determines which profile wins when multiple conditions match simultaneously (higher = wins)+- **Activation Delay** - How long the condition must keep matching before the profile is applied (seconds, default 0 = immediate). Prevents activating on brief spikes, e.g. a momentary speed reading. For the Stationary condition it instead sets how long the device must be still before the profile activates (default 60s).- **Deactivation Delay** - How long to wait after the condition stops matching before reverting to default settings (seconds). Prevents rapid toggling when conditions fluctuate.When creating a new profile, GPS interval, distance filter, and sync interval are pre-filled with your current values from main Settings. Each field also shows a hint with the default value for reference.+**Choosing delay values:** together the two delays make a profile "sticky" - hard to switch on by accident, hard to switch off by accident. Clean on/off signals like Charging and Android Auto want activation 0 (switch the instant you plug in or connect) plus a small deactivation delay so a brief disconnect or cable wiggle does not drop you. Noisy signals like speed want both: an activation delay to ignore short spikes (a Driving profile won't trigger from one GPS glitch while you walk) and a longer deactivation delay to ride through red lights, traffic and tunnels without flapping. Rule of thumb: if a profile keeps flickering on and off, raise the delays; if it reacts too slowly, lower them. Tracking never stops during either wait - you stay on your defaults through an activation delay, and on the profile through a deactivation delay.+## PriorityWhen multiple conditions match at the same time, the profile with the highest priority wins.@@ -74,12 +77,12 @@ If you use both a Speed Below and a Stationary profile, give Stationary the high## Example Configurations-| Profile | Condition | Interval | Distance | Priority | Use case |-| ---------- | ------------------ | -------- | -------- | -------- | ------------------------------ |-| Stationary | Stationary | 1800s | 0m | 40 | Heartbeat while not moving |-| Driving | Car Mode | 10s | 1m | 30 | Detailed route while driving |-| Walking | Speed Below 8 km/h | 60s | 2m | 20 | Battery-friendly on foot |-| Charging | Charging | 15s | 0m | 10 | High accuracy while plugged in |+| Profile | Condition | Interval | Distance | Priority | Activation | Deactivation | Use case |+| --- | --- | --- | --- | --- | --- | --- | --- |+| Stationary | Stationary | 1800s | 0m | 40 | 60s | n/a | Heartbeat while not moving |+| Driving | Car Mode | 10s | 1m | 30 | 0s | 30s | Detailed route while driving |+| Walking | Speed Below 8 km/h | 60s | 2m | 20 | 20s | 45s | Battery-friendly on foot |+| Charging | Charging | 15s | 0m | 10 | 0s | 30s | High accuracy while plugged in |Note that Stationary has the highest priority so it takes over from Walking when you stop. Charging has the lowest priority so a more specific profile (e.g. Driving) wins when both match.@@ -87,6 +90,7 @@ Note that Stationary has the highest priority so it takes over from Walking when- When tracking starts, all enabled profiles are evaluated against current conditions- The highest-priority matching profile's settings override the defaults+- If a profile has an activation delay, its condition must keep matching for that long before it is applied; if the condition drops first, or a higher-priority profile takes over, the activation is cancelled- When the condition no longer matches, a deactivation delay timer starts- If the condition matches again before the delay expires, the timer is cancelled- After the delay expires, settings revert to the defaults configured in the Settings screendiff --git a/apps/docs/src/components/DeepLinkGenerator.tsx b/apps/docs/src/components/DeepLinkGenerator.tsxindex 49db07ee..33952942 100644--- a/apps/docs/src/components/DeepLinkGenerator.tsx+++ b/apps/docs/src/components/DeepLinkGenerator.tsx@@ -29,6 +29,7 @@ interface ProfileRow {distance: stringsyncInterval: stringpriority: string+ activationDelay: stringdeactivationDelay: stringenabled: boolean}@@ -196,16 +197,21 @@ export default function DeepLinkGenerator() {condition.speedThreshold = Number(p.speedKmh) / 3.6}- pfs.push({+ const entry: Record<string, unknown> = {name: p.name,condition,interval: Number(p.interval),distance: Number(p.distance),syncInterval: Number(p.syncInterval),priority: p.priority ? Number(p.priority) : 10,- deactivationDelay: p.deactivationDelay ? Number(p.deactivationDelay) : 60,enabled: p.enabled- })+ }+ // Stationary hides the delay inputs; omit them so the app applies its own defaults (60 / 0)+ if (p.conditionType !== "stationary") {+ entry.activationDelay = p.activationDelay ? Number(p.activationDelay) : 0+ entry.deactivationDelay = p.deactivationDelay ? Number(p.deactivationDelay) : 60+ }+ pfs.push(entry)}if (pfs.length > 0) obj.profiles = pfs@@ -346,6 +352,7 @@ export default function DeepLinkGenerator() {distance: "0",syncInterval: "0",priority: "10",+ activationDelay: "0",deactivationDelay: "60",enabled: true}@@ -879,6 +886,19 @@ export default function DeepLinkGenerator() {onChange={(e) => updateProfile(i, "syncInterval", e.target.value)}/></div>+ {!isStationary && (+ <div className={styles.field}>+ <label className={styles.label}>Activation delay (sec)</label>+ <input+ className={styles.input}+ type="number"+ min="0"+ placeholder="0"+ value={p.activationDelay}+ onChange={(e) => updateProfile(i, "activationDelay", e.target.value)}+ />+ </div>+ )}{!isStationary && (<div className={styles.field}><label className={styles.label}>Deactivation delay (sec)</label>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 d8a52c7c..fa39e85b 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@@ -603,6 +603,7 @@ class LocationServiceModule(reactContext: ReactApplicationContext) :speedThreshold = if (config.hasKey("speedThreshold") && !config.isNull("speedThreshold"))config.getDouble("speedThreshold").toFloat() else null,deactivationDelaySeconds = config.getInt("deactivationDelaySeconds"),+ activationDelaySeconds = config.getInt("activationDelaySeconds"),)afterProfileMutation(id > 0)id@@ -622,6 +623,7 @@ class LocationServiceModule(reactContext: ReactApplicationContext) :config.getDouble("speedThreshold").toFloat() else null,hasSpeedThreshold = config.hasKey("speedThreshold"),deactivationDelaySeconds = config.getIntOrNull("deactivationDelaySeconds"),+ activationDelaySeconds = config.getIntOrNull("activationDelaySeconds"),enabled = config.getBooleanOrNull("enabled"),)afterProfileMutation(changed)diff --git a/apps/mobile/android/app/src/main/java/com/colota/data/DatabaseHelper.kt b/apps/mobile/android/app/src/main/java/com/colota/data/DatabaseHelper.ktindex 570d4c53..a7b75f2b 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 {const val DATABASE_NAME = "Colota.db"- const val DATABASE_VERSION = 5+ const val DATABASE_VERSION = 6const val TABLE_LOCATIONS = "locations"const val TABLE_QUEUE = "queue"@@ -49,6 +49,25 @@ class DatabaseHelper private constructor(context: Context) :private const val TRIP_GAP_SECONDS = 900L // 15 min, matches JS segmentTripsprivate const val CREATE_PROFILES_TABLE = """+ CREATE TABLE IF NOT EXISTS $TABLE_PROFILES (+ id INTEGER PRIMARY KEY AUTOINCREMENT,+ name TEXT NOT NULL,+ interval_ms INTEGER NOT NULL,+ min_update_distance REAL NOT NULL,+ sync_interval_seconds INTEGER NOT NULL,+ priority INTEGER NOT NULL DEFAULT 0,+ condition_type TEXT NOT NULL,+ speed_threshold REAL,+ deactivation_delay_seconds INTEGER NOT NULL DEFAULT 30,+ activation_delay_seconds INTEGER NOT NULL DEFAULT 0,+ enabled INTEGER NOT NULL DEFAULT 1,+ created_at INTEGER NOT NULL+ )+ """+ // Profiles table as introduced in v2, before activation_delay_seconds (added by the v6+ // migration). Frozen on purpose: the < 2 migration must create this older shape so the v6+ // ALTER adds the column without colliding. onCreate uses the latest CREATE_PROFILES_TABLE.+ private const val CREATE_PROFILES_TABLE_V2 = """CREATE TABLE IF NOT EXISTS $TABLE_PROFILES (id INTEGER PRIMARY KEY AUTOINCREMENT,name TEXT NOT NULL,@@ -188,7 +207,7 @@ class DatabaseHelper private constructor(context: Context) :private fun applyMigrations(db: SQLiteDatabase, oldVersion: Int, newVersion: Int) {AppLogger.i(TAG, "Migrating database from v$oldVersion to v$newVersion")if (oldVersion < 2) {- db.execSQL(CREATE_PROFILES_TABLE)+ db.execSQL(CREATE_PROFILES_TABLE_V2)db.execSQL(CREATE_PROFILES_INDEX)}if (oldVersion < 3) {@@ -210,6 +229,12 @@ class DatabaseHelper private constructor(context: Context) :db.execSQL("ALTER TABLE $TABLE_GEOFENCES ADD COLUMN heartbeat_enabled INTEGER NOT NULL DEFAULT 0")db.execSQL("ALTER TABLE $TABLE_GEOFENCES ADD COLUMN heartbeat_interval_minutes INTEGER NOT NULL DEFAULT 15")}+ if (oldVersion < 6) {+ db.execSQL("ALTER TABLE $TABLE_PROFILES ADD COLUMN activation_delay_seconds INTEGER NOT NULL DEFAULT 0")+ // Stationary profiles existed before this column with a fixed 60s detection window;+ // backfill that value so they keep behaving the same now that it is a stored field.+ db.execSQL("UPDATE $TABLE_PROFILES SET activation_delay_seconds = 60 WHERE condition_type = 'stationary'")+ }}@JvmStaticdiff --git a/apps/mobile/android/app/src/main/java/com/colota/data/ProfileHelper.kt b/apps/mobile/android/app/src/main/java/com/colota/data/ProfileHelper.ktindex f5b72626..4c24c3b6 100644--- a/apps/mobile/android/app/src/main/java/com/colota/data/ProfileHelper.kt+++ b/apps/mobile/android/app/src/main/java/com/colota/data/ProfileHelper.kt@@ -29,6 +29,7 @@ class ProfileHelper(private val context: Context) {val conditionType: String,val speedThreshold: Float?,val deactivationDelaySeconds: Int,+ val activationDelaySeconds: Int,)companion object {@@ -51,6 +52,7 @@ class ProfileHelper(private val context: Context) {"id", "name", "interval_ms", "min_update_distance","sync_interval_seconds", "priority", "condition_type","speed_threshold", "deactivation_delay_seconds",+ "activation_delay_seconds",),"enabled = 1",null, null, null,@@ -65,6 +67,7 @@ class ProfileHelper(private val context: Context) {val conditionIdx = cursor.getColumnIndexOrThrow("condition_type")val speedIdx = cursor.getColumnIndexOrThrow("speed_threshold")val delayIdx = cursor.getColumnIndexOrThrow("deactivation_delay_seconds")+ val activationDelayIdx = cursor.getColumnIndexOrThrow("activation_delay_seconds")while (cursor.moveToNext()) {profiles.add(CachedProfile(@@ -77,6 +80,7 @@ class ProfileHelper(private val context: Context) {conditionType = cursor.getString(conditionIdx),speedThreshold = if (cursor.isNull(speedIdx)) null else cursor.getFloat(speedIdx),deactivationDelaySeconds = cursor.getInt(delayIdx),+ activationDelaySeconds = cursor.getInt(activationDelayIdx),))}}@@ -105,6 +109,7 @@ class ProfileHelper(private val context: Context) {val conditionIdx = cursor.getColumnIndexOrThrow("condition_type")val speedIdx = cursor.getColumnIndexOrThrow("speed_threshold")val delayIdx = cursor.getColumnIndexOrThrow("deactivation_delay_seconds")+ val activationDelayIdx = cursor.getColumnIndexOrThrow("activation_delay_seconds")val enabledIdx = cursor.getColumnIndexOrThrow("enabled")val createdIdx = cursor.getColumnIndexOrThrow("created_at")@@ -123,6 +128,7 @@ class ProfileHelper(private val context: Context) {putDouble("speedThreshold", cursor.getFloat(speedIdx).toDouble())}putInt("deactivationDelaySeconds", cursor.getInt(delayIdx))+ putInt("activationDelaySeconds", cursor.getInt(activationDelayIdx))putBoolean("enabled", cursor.getInt(enabledIdx) == 1)putDouble("createdAt", cursor.getLong(createdIdx).toDouble())})@@ -144,6 +150,7 @@ class ProfileHelper(private val context: Context) {conditionType: String,speedThreshold: Float?,deactivationDelaySeconds: Int,+ activationDelaySeconds: Int,): Int {val values = ContentValues().apply {put("name", name)@@ -154,6 +161,7 @@ class ProfileHelper(private val context: Context) {put("condition_type", conditionType)if (speedThreshold != null) put("speed_threshold", speedThreshold) else putNull("speed_threshold")put("deactivation_delay_seconds", deactivationDelaySeconds)+ put("activation_delay_seconds", activationDelaySeconds)put("enabled", 1)put("created_at", System.currentTimeMillis() / 1000)}@@ -179,6 +187,7 @@ class ProfileHelper(private val context: Context) {speedThreshold: Float? = null,hasSpeedThreshold: Boolean = false,deactivationDelaySeconds: Int? = null,+ activationDelaySeconds: Int? = null,enabled: Boolean? = null,): Boolean {val values = ContentValues().apply {@@ -192,6 +201,7 @@ class ProfileHelper(private val context: Context) {if (speedThreshold != null) put("speed_threshold", speedThreshold) else putNull("speed_threshold")}deactivationDelaySeconds?.let { put("deactivation_delay_seconds", it) }+ activationDelaySeconds?.let { put("activation_delay_seconds", it) }enabled?.let { put("enabled", if (it) 1 else 0) }}diff --git a/apps/mobile/android/app/src/main/java/com/colota/service/ProfileConstants.kt b/apps/mobile/android/app/src/main/java/com/colota/service/ProfileConstants.ktindex cb4d2c9f..cd8af4e9 100644--- a/apps/mobile/android/app/src/main/java/com/colota/service/ProfileConstants.kt+++ b/apps/mobile/android/app/src/main/java/com/colota/service/ProfileConstants.kt@@ -28,5 +28,4 @@ object ProfileConstants {const val SPEED_BUFFER_SIZE = 5const val MIN_INTERVAL_MS = 1000Lconst val STATIONARY_SPEED_THRESHOLD = 0.3f- const val STATIONARY_TIMEOUT_MS = 60_000L}diff --git a/apps/mobile/android/app/src/main/java/com/colota/service/ProfileManager.kt b/apps/mobile/android/app/src/main/java/com/colota/service/ProfileManager.ktindex f1a61dd4..b816b728 100644--- a/apps/mobile/android/app/src/main/java/com/colota/service/ProfileManager.kt+++ b/apps/mobile/android/app/src/main/java/com/colota/service/ProfileManager.kt@@ -49,6 +49,8 @@ class ProfileManager(@Volatile private var activeProfile: ProfileHelper.CachedProfile? = null// Accessed only inside @Synchronized methods — the intrinsic lock covers visibility.private var deactivationJob: Job? = null+ private var activationJob: Job? = null+ private var pendingActivationProfileId: Int? = null// Condition flags: written from broadcast callbacks, each write immediately followed by// @Synchronized evaluate() which reads them. @Volatile makes the write visible to readers@@ -122,6 +124,10 @@ class ProfileManager(deactivateToDefault()}+ if (pendingActivationProfileId != null && profiles.none { it.id == pendingActivationProfileId }) {+ cancelActivation()+ }+if (profiles.isEmpty()) {return}@@ -135,6 +141,7 @@ class ProfileManager(cancelDeactivation()if (activeProfile?.id == matchingProfile.id) {+ cancelActivation()// Same profile still matches — re-apply only if config changedval active = activeProfile!!if (active.intervalMs != matchingProfile.intervalMs ||@@ -145,14 +152,29 @@ class ProfileManager(return}- // Different profile or new activation- activateProfile(matchingProfile)+ // Stationary spends its activation delay reaching the stationary state, so it+ // applies immediately here; the generic delay would double-count it.+ val activationDelay =+ if (matchingProfile.conditionType == ProfileConstants.CONDITION_STATIONARY) 0+ else matchingProfile.activationDelaySeconds+ if (activationDelay <= 0) {+ cancelActivation()+ activateProfile(matchingProfile)+ } else {+ scheduleActivation(matchingProfile)+ }}// No profile matches — schedule deactivation if one was activeactiveProfile != null -> {+ cancelActivation()scheduleDeactivation(activeProfile!!)}++ // Pending activation's condition dropped before its delay elapsed+ else -> {+ cancelActivation()+ }}}@@ -250,6 +272,47 @@ class ProfileManager(deactivationJob = null}+ private fun scheduleActivation(profile: ProfileHelper.CachedProfile) {+ if (activationJob?.isActive == true && pendingActivationProfileId == profile.id) return++ cancelActivation()+ pendingActivationProfileId = profile.id+ val scheduledProfileId = profile.id+ activationJob = scope.launch {+ delay(profile.activationDelaySeconds * 1000L)+ ensureActive()+ activateIfStillMatching(scheduledProfileId)+ }++ AppLogger.d(TAG, "Scheduled activation of '${profile.name}' in ${profile.activationDelaySeconds}s")+ }++ /**+ * Called from the activation coroutine. Re-resolves the highest-priority match+ * under the lock and activates only if the scheduled profile is still the winner —+ * the condition may have lapsed or a higher-priority profile may have arrived+ * during the delay.+ */+ @Synchronized+ private fun activateIfStillMatching(scheduledProfileId: Int) {+ // Superseded by a newer activation between the delay and the lock: leave its+ // job/pending fields intact rather than orphaning the newer timer.+ if (pendingActivationProfileId != scheduledProfileId) return+ activationJob = null+ pendingActivationProfileId = null++ val matching = profileHelper.getEnabledProfiles().firstOrNull { matchesCondition(it) }+ if (matching?.id != scheduledProfileId) return+ if (activeProfile?.id == scheduledProfileId) return+ activateProfile(matching)+ }++ private fun cancelActivation() {+ activationJob?.cancel()+ activationJob = null+ pendingActivationProfileId = null+ }+private fun evaluateStationaryState(location: android.location.Location) {if (ProfileConstants.CONDITION_STATIONARY !in getNeededConditionTypes()) return@@ -267,16 +330,25 @@ class ProfileManager(}if (!isStationary && stationaryJob?.isActive != true) {+ val timeoutMs = stationaryTimeoutMs()stationaryJob = scope.launch {- delay(ProfileConstants.STATIONARY_TIMEOUT_MS)+ delay(timeoutMs)isStationary = trueonStationaryChanged?.invoke(true)- AppLogger.d(TAG, "Device stationary (speed below threshold for ${ProfileConstants.STATIONARY_TIMEOUT_MS / 1000}s)")+ AppLogger.d(TAG, "Device stationary (speed below threshold for ${timeoutMs / 1000}s)")evaluate()}}}+ // Stationary detection window = the profile's activation delay (the "still for this long" time).+ private fun stationaryTimeoutMs(): Long {+ val seconds = profileHelper.getEnabledProfiles()+ .firstOrNull { it.conditionType == ProfileConstants.CONDITION_STATIONARY }+ ?.activationDelaySeconds ?: 0+ return seconds * 1000L+ }+private fun deactivateToDefault() {val previousProfile = activeProfile ?: returnactiveProfile = nulldiff --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 0124a5a5..c5af5d3e 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@@ -16,6 +16,7 @@ import org.junit.runner.RunWithimport org.robolectric.RobolectricTestRunnerimport com.Colota.util.AppLoggerimport io.mockk.*+import java.io.File/*** SQLite integration tests for DatabaseHelper using Robolectric.@@ -90,6 +91,102 @@ class DatabaseHelperSQLiteTest {assertEquals("custom", settings["apiTemplate"])}+ @Test+ fun `tracking_profiles table includes activation_delay_seconds column`() {+ val columns = queryColumnNames("tracking_profiles")+ assertTrue(columns.contains("activation_delay_seconds"))+ }++ // ========================================================================+ // Migration v5 -> v6: activation_delay_seconds+ // ========================================================================++ @Test+ fun `migration from v5 backfills activation_delay_seconds (stationary 60, others 0)`() {+ // Seed a v5-schema candidate DB (tracking_profiles without the activation column)+ val candidate = File.createTempFile("candidate-v5", ".db").also { it.delete() }+ SQLiteDatabase.openOrCreateDatabase(candidate, null).use { old ->+ old.execSQL(+ """+ CREATE TABLE tracking_profiles (+ id INTEGER PRIMARY KEY AUTOINCREMENT,+ name TEXT NOT NULL,+ interval_ms INTEGER NOT NULL,+ min_update_distance REAL NOT NULL,+ sync_interval_seconds INTEGER NOT NULL,+ priority INTEGER NOT NULL DEFAULT 0,+ condition_type TEXT NOT NULL,+ speed_threshold REAL,+ deactivation_delay_seconds INTEGER NOT NULL DEFAULT 30,+ enabled INTEGER NOT NULL DEFAULT 1,+ created_at INTEGER NOT NULL+ )+ """.trimIndent()+ )+ old.execSQL(+ """+ INSERT INTO tracking_profiles+ (name, interval_ms, min_update_distance, sync_interval_seconds,+ priority, condition_type, deactivation_delay_seconds, created_at)+ VALUES ('Charging', 10000, 0, 0, 10, 'charging', 60, 0),+ ('Parked', 1800000, 0, 0, 40, 'stationary', 0, 0)+ """.trimIndent()+ )+ old.version = 5+ }++ DatabaseHelper.migrateCandidate(candidate)++ SQLiteDatabase.openDatabase(candidate.absolutePath, null, SQLiteDatabase.OPEN_READONLY).use { migrated ->+ assertEquals(6, migrated.version)+ migrated.rawQuery(+ "SELECT name, activation_delay_seconds FROM tracking_profiles",+ null+ ).use { cursor ->+ val byName = mutableMapOf<String, Int>()+ while (cursor.moveToNext()) {+ byName[cursor.getString(0)] = cursor.getInt(1)+ }+ // Non-stationary keeps the column default (instant); stationary is backfilled to its 60s window+ assertEquals(0, byName["Charging"])+ assertEquals(60, byName["Parked"])+ }+ }++ candidate.delete()+ }++ @Test+ fun `migration from v1 creates profiles then adds activation_delay_seconds without colliding`() {+ // v1 predates the profiles table, so the < 2 migration creates it; the v6 migration then+ // ALTERs in activation_delay_seconds. The two must not double-add the column.+ val candidate = File.createTempFile("candidate-v1", ".db").also { it.delete() }+ SQLiteDatabase.openOrCreateDatabase(candidate, null).use { old ->+ // v1 schema: locations without `sent`, geofences without the v4/v5 columns, no profiles+ old.execSQL("CREATE TABLE locations (id INTEGER PRIMARY KEY AUTOINCREMENT, latitude REAL NOT NULL, longitude REAL NOT NULL, accuracy INTEGER, altitude INTEGER, speed INTEGER, bearing REAL, battery INTEGER, battery_status INTEGER, timestamp INTEGER NOT NULL, endpoint TEXT, created_at INTEGER NOT NULL)")+ old.execSQL("CREATE TABLE queue (id INTEGER PRIMARY KEY AUTOINCREMENT, location_id INTEGER NOT NULL, payload TEXT NOT NULL, retry_count INTEGER DEFAULT 0, last_error TEXT, created_at INTEGER NOT NULL)")+ old.execSQL("CREATE TABLE settings (key TEXT PRIMARY KEY, value TEXT NOT NULL)")+ old.execSQL("CREATE 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)")+ old.version = 1+ }++ // Must not throw (regression guard: the frozen v2 create must omit activation_delay_seconds)+ DatabaseHelper.migrateCandidate(candidate)++ SQLiteDatabase.openDatabase(candidate.absolutePath, null, SQLiteDatabase.OPEN_READONLY).use { migrated ->+ assertEquals(6, migrated.version)+ migrated.rawQuery("PRAGMA table_info(tracking_profiles)", null).use { cursor ->+ val cols = mutableSetOf<String>()+ while (cursor.moveToNext()) {+ cols.add(cursor.getString(cursor.getColumnIndexOrThrow("name")))+ }+ assertTrue(cols.contains("activation_delay_seconds"))+ }+ }++ candidate.delete()+ }+// ========================================================================// WAL mode and pragmas// ========================================================================diff --git a/apps/mobile/android/app/src/test/java/com/Colota/data/ProfileHelperTest.kt b/apps/mobile/android/app/src/test/java/com/Colota/data/ProfileHelperTest.ktindex 8451d521..8a3fadd9 100644--- a/apps/mobile/android/app/src/test/java/com/Colota/data/ProfileHelperTest.kt+++ b/apps/mobile/android/app/src/test/java/com/Colota/data/ProfileHelperTest.kt@@ -61,7 +61,8 @@ class ProfileHelperTest {val columns = listOf("id", "name", "interval_ms", "min_update_distance","sync_interval_seconds", "priority", "condition_type",- "speed_threshold", "deactivation_delay_seconds", "enabled", "created_at"+ "speed_threshold", "deactivation_delay_seconds", "activation_delay_seconds",+ "enabled", "created_at")for ((idx, col) in columns.withIndex()) {@@ -218,6 +219,46 @@ class ProfileHelperTest {assertEquals("speed_above", profiles[0].conditionType)}+ @Test+ fun `getEnabledProfiles reads activation delay`() {+ val cursor = mockCursorWithProfiles(listOf(+ mapOf(+ "id" to 1, "name" to "Fast", "interval_ms" to 2000L,+ "min_update_distance" to 0f, "sync_interval_seconds" to 0,+ "priority" to 15, "condition_type" to "speed_above",+ "speed_threshold" to 13.89f, "deactivation_delay_seconds" to 30,+ "activation_delay_seconds" to 12+ )+ ))++ every { mockDb.query(any(), any(), eq("enabled = 1"), any(), any(), any(), any()) } returns cursor++ val helper = ProfileHelper(mockk(relaxed = true))+ val profiles = helper.getEnabledProfiles()++ assertEquals(1, profiles.size)+ assertEquals(12, profiles[0].activationDelaySeconds)+ }++ @Test+ fun `getEnabledProfiles defaults activation delay to zero when column is zero`() {+ val cursor = mockCursorWithProfiles(listOf(+ mapOf(+ "id" to 1, "name" to "Charging", "interval_ms" to 10000L,+ "min_update_distance" to 0f, "sync_interval_seconds" to 0,+ "priority" to 10, "condition_type" to "charging",+ "speed_threshold" to null, "deactivation_delay_seconds" to 60+ )+ ))++ every { mockDb.query(any(), any(), eq("enabled = 1"), any(), any(), any(), any()) } returns cursor++ val helper = ProfileHelper(mockk(relaxed = true))+ val profiles = helper.getEnabledProfiles()++ assertEquals(0, profiles[0].activationDelaySeconds)+ }+@Testfun `deleteProfile calls database delete`() {every { mockDb.delete(any(), any(), any()) } returns 1diff --git a/apps/mobile/android/app/src/test/java/com/Colota/service/ProfileManagerTest.kt b/apps/mobile/android/app/src/test/java/com/Colota/service/ProfileManagerTest.ktindex 6f0c7831..56f4eb2d 100644--- a/apps/mobile/android/app/src/test/java/com/Colota/service/ProfileManagerTest.kt+++ b/apps/mobile/android/app/src/test/java/com/Colota/service/ProfileManagerTest.kt@@ -53,7 +53,8 @@ class ProfileManagerTest {name: String = "Charging",intervalMs: Long = 10000,priority: Int = 10,- deactivationDelay: Int = 60+ deactivationDelay: Int = 60,+ activationDelay: Int = 0) = ProfileHelper.CachedProfile(id = id,name = name,@@ -63,14 +64,16 @@ class ProfileManagerTest {priority = priority,conditionType = ProfileConstants.CONDITION_CHARGING,speedThreshold = null,- deactivationDelaySeconds = deactivationDelay+ deactivationDelaySeconds = deactivationDelay,+ activationDelaySeconds = activationDelay)private fun carModeProfile(id: Int = 2,name: String = "Car Mode",intervalMs: Long = 3000,- priority: Int = 20+ priority: Int = 20,+ activationDelay: Int = 0) = ProfileHelper.CachedProfile(id = id,name = name,@@ -80,13 +83,15 @@ class ProfileManagerTest {priority = priority,conditionType = ProfileConstants.CONDITION_ANDROID_AUTO,speedThreshold = null,- deactivationDelaySeconds = 30+ deactivationDelaySeconds = 30,+ activationDelaySeconds = activationDelay)private fun speedAboveProfile(id: Int = 3,threshold: Float = 13.89f, // ~50 km/h- priority: Int = 15+ priority: Int = 15,+ activationDelay: Int = 0) = ProfileHelper.CachedProfile(id = id,name = "Fast",@@ -96,13 +101,15 @@ class ProfileManagerTest {priority = priority,conditionType = ProfileConstants.CONDITION_SPEED_ABOVE,speedThreshold = threshold,- deactivationDelaySeconds = 30+ deactivationDelaySeconds = 30,+ activationDelaySeconds = activationDelay)private fun speedBelowProfile(id: Int = 4,threshold: Float = 5.56f, // ~20 km/h- priority: Int = 5+ priority: Int = 5,+ activationDelay: Int = 0) = ProfileHelper.CachedProfile(id = id,name = "Slow",@@ -112,7 +119,8 @@ class ProfileManagerTest {priority = priority,conditionType = ProfileConstants.CONDITION_SPEED_BELOW,speedThreshold = threshold,- deactivationDelaySeconds = 60+ deactivationDelaySeconds = 60,+ activationDelaySeconds = activationDelay)private fun mockLocation(speed: Float, hasSpeed: Boolean = true): Location {@@ -340,6 +348,155 @@ class ProfileManagerTest {assertEquals("Charging", switchedProfileName)}+ // --- Activation delay ---++ @Test+ fun `activates immediately when activation delay is zero`() = runTest {+ val profile = chargingProfile(activationDelay = 0)+ every { profileHelper.getEnabledProfiles() } returns listOf(profile)++ val manager = createManager()+ manager.onChargingStateChanged(true)++ assertEquals("Charging", switchedProfileName)+ assertEquals(1, switchCount)+ }++ @Test+ fun `does not activate until activation delay elapses`() = testScope.runTest {+ val profile = chargingProfile(activationDelay = 10)+ every { profileHelper.getEnabledProfiles() } returns listOf(profile)++ val manager = createManager()++ // Condition starts matching — profile must NOT apply yet+ manager.onChargingStateChanged(true)+ assertNull(switchedProfileName)+ assertEquals(0, switchCount)++ // Still within the delay window+ advanceTimeBy(9_000)+ assertNull(switchedProfileName)++ // Past the delay — now it applies+ advanceTimeBy(2_000)+ assertEquals("Charging", switchedProfileName)+ assertEquals(1, switchCount)+ }++ @Test+ fun `cancels pending activation when condition stops before delay elapses`() = testScope.runTest {+ val profile = chargingProfile(activationDelay = 30)+ every { profileHelper.getEnabledProfiles() } returns listOf(profile)++ val manager = createManager()++ // Transient spike: condition matches then drops within the delay+ manager.onChargingStateChanged(true)+ advanceTimeBy(10_000)+ manager.onChargingStateChanged(false)++ // Well past the original delay — must never have activated+ advanceTimeBy(60_000)+ assertNull(switchedProfileName)+ assertEquals(0, switchCount)+ }++ @Test+ fun `higher priority profile replaces a pending activation`() = testScope.runTest {+ val charging = chargingProfile(id = 1, priority = 5, activationDelay = 30)+ val carMode = carModeProfile(id = 2, priority = 20, activationDelay = 5)+ every { profileHelper.getEnabledProfiles() } returns listOf(carMode, charging)++ val manager = createManager()++ // Charging starts -> charging activation pending (30s)+ manager.onChargingStateChanged(true)+ advanceTimeBy(10_000)+ assertNull(switchedProfileName)++ // Car mode (higher priority) starts -> its 5s activation replaces the pending charging one+ manager.onCarModeStateChanged(true)+ advanceTimeBy(6_000)+ assertEquals("Car Mode", switchedProfileName)+ assertEquals(1, switchCount)++ // The superseded charging activation must never fire+ advanceTimeBy(60_000)+ assertEquals("Car Mode", switchedProfileName)+ assertEquals(1, switchCount)+ }++ @Test+ fun `pending activation does not fire if profile is disabled during the delay`() = testScope.runTest {+ val profile = chargingProfile(activationDelay = 30)+ every { profileHelper.getEnabledProfiles() } returns listOf(profile)++ val manager = createManager()+ manager.onChargingStateChanged(true)+ advanceTimeBy(10_000)++ // Profile disabled mid-delay+ every { profileHelper.getEnabledProfiles() } returns emptyList()+ manager.invalidateProfiles()+ manager.evaluate()++ advanceTimeBy(60_000)+ assertNull(switchedProfileName)+ assertEquals(0, switchCount)+ }++ @Test+ fun `active profile is retained while a higher-priority activation is pending and then cancelled`() = testScope.runTest {+ val charging = chargingProfile(id = 1, priority = 5, activationDelay = 0)+ val carMode = carModeProfile(id = 2, priority = 20, activationDelay = 30)+ every { profileHelper.getEnabledProfiles() } returns listOf(carMode, charging)++ val manager = createManager()++ // Charging applies immediately (delay 0)+ manager.onChargingStateChanged(true)+ assertEquals("Charging", switchedProfileName)+ assertEquals(1, switchCount)++ // Car mode starts -> pending activation; charging stays applied during the wait+ manager.onCarModeStateChanged(true)+ advanceTimeBy(10_000)+ assertEquals("Charging", switchedProfileName)++ // Car mode drops before its delay -> charging remains the match, pending activation cancelled+ manager.onCarModeStateChanged(false)+ advanceTimeBy(60_000)+ assertEquals("Charging", switchedProfileName)+ assertEquals(1, switchCount)+ }++ @Test+ fun `repeated evaluation while the condition holds does not restart the activation timer`() = testScope.runTest {+ val profile = chargingProfile(activationDelay = 30)+ every { profileHelper.getEnabledProfiles() } returns listOf(profile)++ val manager = createManager()++ // Condition starts matching -> 30s activation pending+ manager.onChargingStateChanged(true)++ // Re-evaluate repeatedly while the condition keeps holding (mimics the stream of+ // location updates / broadcasts in production). Each call must hit the already-pending+ // guard, NOT reset the timer — otherwise the profile would never activate under load.+ advanceTimeBy(10_000)+ manager.evaluate()+ advanceTimeBy(10_000)+ manager.evaluate()+ advanceTimeBy(9_000) // 29s elapsed — still inside the ORIGINAL window+ assertNull(switchedProfileName)++ // Crossing the original 30s deadline fires, proving the timer was never pushed out+ advanceTimeBy(2_000) // 31s elapsed+ assertEquals("Charging", switchedProfileName)+ assertEquals(1, switchCount)+ }+// --- Config change detection ---@Test@@ -512,7 +669,8 @@ class ProfileManagerTest {name: String = "Stationary",intervalMs: Long = 30000,priority: Int = 10,- deactivationDelay: Int = 30+ deactivationDelay: Int = 30,+ activationDelay: Int = 60) = ProfileHelper.CachedProfile(id = id,name = name,@@ -522,7 +680,8 @@ class ProfileManagerTest {priority = priority,conditionType = ProfileConstants.CONDITION_STATIONARY,speedThreshold = null,- deactivationDelaySeconds = deactivationDelay+ deactivationDelaySeconds = deactivationDelay,+ activationDelaySeconds = activationDelay)@Test@@ -537,12 +696,44 @@ class ProfileManagerTest {assertEquals(0, switchCount)// Advance past stationary timeout- advanceTimeBy(ProfileConstants.STATIONARY_TIMEOUT_MS + 100)+ advanceTimeBy(60_000L + 100)assertEquals("Stationary", switchedProfileName)assertEquals(30000L, switchedInterval)}+ @Test+ fun `stationary profile uses its activation delay as the detection timeout`() = testScope.runTest {+ val profile = stationaryProfile(activationDelay = 30)+ every { profileHelper.getEnabledProfiles() } returns listOf(profile)++ val manager = createManager()+ manager.onLocationUpdate(mockLocation(0.1f))++ // Not stationary before the configured 30s+ advanceTimeBy(29_000)+ assertNull(switchedProfileName)+ assertFalse(manager.isStationary)++ // Becomes stationary at its own window, not the built-in 60s+ advanceTimeBy(2_000)+ assertEquals("Stationary", switchedProfileName)+ assertTrue(manager.isStationary)+ }++ @Test+ fun `stationary profile with zero activation delay activates immediately`() = testScope.runTest {+ val profile = stationaryProfile(activationDelay = 0)+ every { profileHelper.getEnabledProfiles() } returns listOf(profile)++ val manager = createManager()+ manager.onLocationUpdate(mockLocation(0.1f))++ // 0 = no stillness window, same as every other delay: instant+ advanceTimeBy(100)+ assertEquals("Stationary", switchedProfileName)+ }+@Testfun `does not activate stationary profile when speed above threshold`() = testScope.runTest {val profile = stationaryProfile()@@ -551,7 +742,7 @@ class ProfileManagerTest {val manager = createManager()repeat(5) { manager.onLocationUpdate(mockLocation(5f)) }- advanceTimeBy(ProfileConstants.STATIONARY_TIMEOUT_MS + 100)+ advanceTimeBy(60_000L + 100)assertNull(switchedProfileName)}@@ -568,7 +759,7 @@ class ProfileManagerTest {// Become stationarymanager.onLocationUpdate(mockLocation(0.1f))- advanceTimeBy(ProfileConstants.STATIONARY_TIMEOUT_MS + 100)+ advanceTimeBy(60_000L + 100)assertEquals("Stationary", switchedProfileName)// Start moving@@ -608,7 +799,7 @@ class ProfileManagerTest {// Location without speed datamanager.onLocationUpdate(mockLocation(0f, hasSpeed = false))- advanceTimeBy(ProfileConstants.STATIONARY_TIMEOUT_MS + 100)+ advanceTimeBy(60_000L + 100)assertEquals("Stationary", switchedProfileName)}@@ -622,7 +813,7 @@ class ProfileManagerTest {assertFalse(manager.isStationary)manager.onLocationUpdate(mockLocation(0.1f))- advanceTimeBy(ProfileConstants.STATIONARY_TIMEOUT_MS + 100)+ advanceTimeBy(60_000L + 100)assertTrue(manager.isStationary)manager.onLocationUpdate(mockLocation(5f))@@ -637,7 +828,7 @@ class ProfileManagerTest {val manager = createManager()manager.onLocationUpdate(mockLocation(0.1f))- advanceTimeBy(ProfileConstants.STATIONARY_TIMEOUT_MS + 100)+ advanceTimeBy(60_000L + 100)assertEquals(true, lastStationaryCallback)manager.onLocationUpdate(mockLocation(5f))@@ -656,7 +847,7 @@ class ProfileManagerTest {// Become stationarymanager.onLocationUpdate(mockLocation(0.1f))- advanceTimeBy(ProfileConstants.STATIONARY_TIMEOUT_MS + 100)+ advanceTimeBy(60_000L + 100)assertEquals("Stationary", switchedProfileName)assertTrue(manager.isStationary)@@ -692,7 +883,7 @@ class ProfileManagerTest {// Become stationary firstmanager.onLocationUpdate(mockLocation(0.1f))- advanceTimeBy(ProfileConstants.STATIONARY_TIMEOUT_MS + 100)+ advanceTimeBy(60_000L + 100)assertEquals("Stationary", switchedProfileName)// Start charging - higher priority should take over@@ -713,7 +904,7 @@ class ProfileManagerTest {// Become stationarymanager.onLocationUpdate(mockLocation(0.1f))- advanceTimeBy(ProfileConstants.STATIONARY_TIMEOUT_MS + 100)+ advanceTimeBy(60_000L + 100)assertTrue(manager.isStationary)// Start charging - charging wins@@ -735,7 +926,7 @@ class ProfileManagerTest {// Feed slow locations - should not start stationary timermanager.onLocationUpdate(mockLocation(0.1f))- advanceTimeBy(ProfileConstants.STATIONARY_TIMEOUT_MS + 100)+ advanceTimeBy(60_000L + 100)assertFalse(manager.isStationary)}@@ -826,7 +1017,8 @@ class ProfileManagerTest {priority = 10,conditionType = "unknown_condition",speedThreshold = null,- deactivationDelaySeconds = 30+ deactivationDelaySeconds = 30,+ activationDelaySeconds = 0)every { profileHelper.getEnabledProfiles() } returns listOf(profile)diff --git a/apps/mobile/src/constants/index.ts b/apps/mobile/src/constants/index.tsindex 691ad1c5..0f45967b 100644--- a/apps/mobile/src/constants/index.ts+++ b/apps/mobile/src/constants/index.ts@@ -75,6 +75,18 @@ export const PROFILE_CONDITIONS: {}]+// Per-condition default switch delays (seconds). Stationary enters via a stillness window+// (activation) and exits instantly via the hardware motion sensor (deactivation 0); every+// other condition is the inverse. Single source of truth for both the editor and import.+export function defaultProfileDelays(conditionType: ProfileConditionType): {+ activationDelay: number+ deactivationDelay: number+} {+ return conditionType === "stationary"+ ? { activationDelay: 60, deactivationDelay: 0 }+ : { activationDelay: 0, deactivationDelay: 60 }+}+// Sync Intervalexport const SYNC_INTERVAL_PRESETS: readonly number[] = [0, 60, 300, 900]diff --git a/apps/mobile/src/screens/ProfileEditorScreen.tsx b/apps/mobile/src/screens/ProfileEditorScreen.tsxindex 9680f4e3..ee98b316 100644--- a/apps/mobile/src/screens/ProfileEditorScreen.tsx+++ b/apps/mobile/src/screens/ProfileEditorScreen.tsx@@ -20,7 +20,8 @@ import {PROFILE_CONDITIONS,SYNC_INTERVAL_PRESETS,SYNC_INTERVAL_LABELS,- STATIONARY_MAX_INTERVAL_SECONDS+ STATIONARY_MAX_INTERVAL_SECONDS,+ defaultProfileDelays} from "../constants"import type { RootScreenProps } from "../types/navigation"@@ -43,7 +44,7 @@ export function ProfileEditorScreen({ navigation, route }: RootScreenProps<"ProfsyncInterval: settings.syncInterval,priority: 10,condition: { type: "charging" },- deactivationDelay: 60,+ ...defaultProfileDelays("charging"),enabled: true})const [speedKmh, setSpeedKmh] = useState("30")@@ -53,6 +54,7 @@ export function ProfileEditorScreen({ navigation, route }: RootScreenProps<"Profconst [intervalStr, setIntervalStr] = useState(String(settings.interval))const [distanceStr, setDistanceStr] = useState(String(metersToInput(settings.distance)))const [priorityStr, setPriorityStr] = useState("10")+ const [activationDelayStr, setActivationDelayStr] = useState("0")const [delayStr, setDelayStr] = useState("60")const [syncIntervalStr, setSyncIntervalStr] = useState(String(settings.syncInterval))@@ -70,12 +72,14 @@ export function ProfileEditorScreen({ navigation, route }: RootScreenProps<"ProfsyncInterval: existing.syncInterval,priority: existing.priority,condition: existing.condition,+ activationDelay: existing.activationDelay,deactivationDelay: existing.deactivationDelay,enabled: existing.enabled})setIntervalStr(String(existing.interval))setDistanceStr(String(metersToInput(existing.distance)))setPriorityStr(String(existing.priority))+ setActivationDelayStr(String(existing.activationDelay))setDelayStr(String(existing.deactivationDelay))setSyncIntervalStr(String(existing.syncInterval))if (existing.condition.speedThreshold) {@@ -105,18 +109,22 @@ export function ProfileEditorScreen({ navigation, route }: RootScreenProps<"Profconst setConditionType = useCallback((type: ProfileConditionType) => {const isSpeed = type === "speed_above" || type === "speed_below"- const newDelay = type === "stationary" ? 0 : 60+ const { activationDelay: defaultActivation, deactivationDelay: defaultDeactivation } = defaultProfileDelays(type)setProfile((prev) => ({...prev,- deactivationDelay: prev.condition.type !== type ? newDelay : prev.deactivationDelay,+ deactivationDelay: prev.condition.type !== type ? defaultDeactivation : prev.deactivationDelay,+ activationDelay: prev.condition.type !== type ? defaultActivation : prev.activationDelay,condition: {type,...(isSpeed ? { speedThreshold: Number(speedKmh) / MS_TO_KMH } : {})}}))- if (type === "stationary") setDelayStr("0")+ if (profile.condition.type !== type) {+ setDelayStr(String(defaultDeactivation))+ setActivationDelayStr(String(defaultActivation))+ }},- [speedKmh]+ [speedKmh, profile.condition.type])const handleSpeedChange = useCallback((val: string) => {@@ -393,23 +401,49 @@ export function ProfileEditorScreen({ navigation, route }: RootScreenProps<"Prof)}</Card>- {profile.condition.type === "stationary" ? (- <>- <SectionTitle style={styles.sectionGap}>Deactivation</SectionTitle>- <Card>- <Text style={[styles.conditionHint, { color: colors.textLight }]}>- Activates after ~60s without movement. Resumes instantly via the hardware motion sensor when the device- moves.- </Text>- </Card>- </>- ) : (- <>- <SectionTitle style={styles.sectionGap}>Deactivation</SectionTitle>- <Card>+ <SectionTitle style={styles.sectionGap}>Switching</SectionTitle>+ <Card>+ {profile.condition.type === "stationary" ? (+ <SettingRow+ label="Activation Delay"+ hint="How long the device must be still before this profile activates. Resumes instantly via the hardware motion sensor when you move again."+ >+ <View style={styles.inputWithUnit}>+ <TextInput+ style={inputStyle}+ keyboardType="numeric"+ value={activationDelayStr}+ onChangeText={(val) => handleNumericChange(setActivationDelayStr, "activationDelay", val, 0)}+ placeholder="60"+ placeholderTextColor={colors.placeholder}+ />+ <Text style={[styles.unit, { color: colors.textSecondary }]}>sec</Text>+ </View>+ </SettingRow>+ ) : (+ <>+ <SettingRow+ label="Activation Delay"+ hint="How long the condition must hold before this profile takes over. Avoids switching on brief, temporary changes. 0 = instant."+ >+ <View style={styles.inputWithUnit}>+ <TextInput+ style={inputStyle}+ keyboardType="numeric"+ value={activationDelayStr}+ onChangeText={(val) => handleNumericChange(setActivationDelayStr, "activationDelay", val, 0)}+ placeholder="0"+ placeholderTextColor={colors.placeholder}+ />+ <Text style={[styles.unit, { color: colors.textSecondary }]}>sec</Text>+ </View>+ </SettingRow>++ <Divider />+<SettingRowlabel="Deactivation Delay"- hint="Wait before reverting to default settings after the condition stops matching. Prevents rapid switching."+ hint="How long after the condition stops before reverting to your defaults. Prevents rapid back-and-forth switching."><View style={styles.inputWithUnit}><TextInput@@ -423,9 +457,9 @@ export function ProfileEditorScreen({ navigation, route }: RootScreenProps<"Prof<Text style={[styles.unit, { color: colors.textSecondary }]}>sec</Text></View></SettingRow>- </Card>- </>- )}+ </>+ )}+ </Card>{/* Save Button */}<Pressable@@ -487,7 +521,6 @@ const styles = StyleSheet.create({},conditionLabel: { fontSize: 13, ...fonts.semiBold },conditionDesc: { fontSize: 11, ...fonts.regular, textAlign: "center" },- conditionHint: { fontSize: 13, ...fonts.regular, paddingHorizontal: 16, paddingVertical: 12 },syncLabelRow: { marginBottom: 8 },settingLabel: { fontSize: 16, ...fonts.semiBold, marginBottom: 2 },settingHint: { fontSize: 13, ...fonts.regular, lineHeight: 18 },diff --git a/apps/mobile/src/screens/SetupImportScreen.tsx b/apps/mobile/src/screens/SetupImportScreen.tsxindex b6cfd1a0..856cee9c 100644--- a/apps/mobile/src/screens/SetupImportScreen.tsx+++ b/apps/mobile/src/screens/SetupImportScreen.tsx@@ -11,7 +11,7 @@ import { Container, Card, Button, SectionTitle } from "../components"import { fonts } from "../styles/typography"import { CircleAlert, CircleCheck, Import } from "lucide-react-native"import SettingsService from "../services/SettingsService"-import { OVERLAND_BATCH_MIN, OVERLAND_BATCH_MAX } from "../constants"+import { OVERLAND_BATCH_MIN, OVERLAND_BATCH_MAX, defaultProfileDelays } from "../constants"import { isEndpointAllowed } from "../utils/settingsValidation"import NativeLocationService from "../services/NativeLocationService"import { showAlert } from "../services/modalService"@@ -361,14 +361,19 @@ function validateConfig(raw: unknown): ValidationResult {? { type: condType, speedThreshold: condRaw.speedThreshold as number }: { type: condType }+ const delays = defaultProfileDelays(condType)profiles.push({name: p.name,interval: p.interval,distance: p.distance,syncInterval: p.syncInterval,priority: typeof p.priority === "number" ? p.priority : 10,+ activationDelay:+ typeof p.activationDelay === "number" && p.activationDelay >= 0 ? p.activationDelay : delays.activationDelay,deactivationDelay:- typeof p.deactivationDelay === "number" && p.deactivationDelay >= 0 ? p.deactivationDelay : 60,+ typeof p.deactivationDelay === "number" && p.deactivationDelay >= 0+ ? p.deactivationDelay+ : delays.deactivationDelay,enabled: typeof p.enabled === "boolean" ? p.enabled : true,condition})diff --git a/apps/mobile/src/screens/__tests__/ProfileEditorScreen.test.tsx b/apps/mobile/src/screens/__tests__/ProfileEditorScreen.test.tsxindex a9e9d21a..f84fb317 100644--- a/apps/mobile/src/screens/__tests__/ProfileEditorScreen.test.tsx+++ b/apps/mobile/src/screens/__tests__/ProfileEditorScreen.test.tsx@@ -13,6 +13,7 @@ const mockProfiles: TrackingProfile[] = [syncInterval: 60,priority: 15,condition: { type: "speed_above", speedThreshold: 13.89 },+ activationDelay: 12,deactivationDelay: 30,enabled: true}@@ -147,10 +148,11 @@ describe("ProfileEditorScreen", () => {})it("pre-fills fields with main settings values", () => {- const { getByDisplayValue } = renderNewProfile()+ const { getByDisplayValue, getAllByDisplayValue } = renderNewProfile()expect(getByDisplayValue("5")).toBeTruthy() // interval from settings- expect(getByDisplayValue("0")).toBeTruthy() // distance from settings+ // distance from settings is 0; activation delay also defaults to 0+ expect(getAllByDisplayValue("0").length).toBeGreaterThan(0)})it("shows default hints from main settings", () => {@@ -314,6 +316,36 @@ describe("ProfileEditorScreen", () => {expect(queryByText("Speed Threshold (km/h)")).toBeNull()})+ // --- Activation delay ---++ it("shows activation delay for all conditions, and deactivation delay only for non-stationary", () => {+ const { getByText, queryByText } = renderNewProfile()++ // Charging: both delays+ expect(getByText("Activation Delay")).toBeTruthy()+ expect(getByText("Deactivation Delay")).toBeTruthy()++ // Stationary: activation delay only (deactivation is instant via the motion sensor)+ fireEvent.press(getByText("Stationary"))+ expect(getByText("Activation Delay")).toBeTruthy()+ expect(queryByText("Deactivation Delay")).toBeNull()+ })++ it("defaults stationary activation delay to 60", () => {+ const { getByText, getByDisplayValue } = renderNewProfile()++ fireEvent.press(getByText("Stationary"))+ expect(getByDisplayValue("60")).toBeTruthy()+ })++ it("loads existing activation delay in edit mode", async () => {+ const { getByDisplayValue } = renderEditProfile()++ await waitFor(() => {+ expect(getByDisplayValue("12")).toBeTruthy()+ })+ })+// --- Numeric input ---it("updates interval via numeric input", () => {@@ -376,6 +408,7 @@ describe("ProfileEditorScreen", () => {syncInterval: 0,priority: 10,condition: { type: "stationary" },+ activationDelay: 0,deactivationDelay: 0,enabled: true}diff --git a/apps/mobile/src/screens/__tests__/SetupImportScreen.test.tsx b/apps/mobile/src/screens/__tests__/SetupImportScreen.test.tsxindex 388d037e..33d446e2 100644--- a/apps/mobile/src/screens/__tests__/SetupImportScreen.test.tsx+++ b/apps/mobile/src/screens/__tests__/SetupImportScreen.test.tsx@@ -503,6 +503,7 @@ describe("SetupImportScreen", () => {distance: 5,syncInterval: 60,priority: 20,+ activationDelay: 5,deactivationDelay: 30,enabled: true,condition: { type: "speed_above", speedThreshold: 8.33 }@@ -567,6 +568,7 @@ describe("SetupImportScreen", () => {distance: 5,syncInterval: 60,priority: 20,+ activationDelay: 5,deactivationDelay: 30,enabled: true,condition: { type: "speed_above", speedThreshold: 8.33 }@@ -592,6 +594,7 @@ describe("SetupImportScreen", () => {expect.objectContaining({name: "Charging",priority: 10,+ activationDelay: 0,deactivationDelay: 60,enabled: true,condition: { type: "charging" }diff --git a/apps/mobile/src/screens/__tests__/TrackingProfilesScreen.test.tsx b/apps/mobile/src/screens/__tests__/TrackingProfilesScreen.test.tsxindex 45e815ff..76955f94 100644--- a/apps/mobile/src/screens/__tests__/TrackingProfilesScreen.test.tsx+++ b/apps/mobile/src/screens/__tests__/TrackingProfilesScreen.test.tsx@@ -14,6 +14,7 @@ const mockProfiles: TrackingProfile[] = [syncInterval: 0,priority: 10,condition: { type: "charging" },+ activationDelay: 0,deactivationDelay: 60,enabled: true},@@ -25,6 +26,7 @@ const mockProfiles: TrackingProfile[] = [syncInterval: 60,priority: 20,condition: { type: "speed_above", speedThreshold: 13.89 },+ activationDelay: 15,deactivationDelay: 30,enabled: false}@@ -322,6 +324,7 @@ describe("TrackingProfilesScreen", () => {syncInterval: 0,priority: 10,condition: { type: "charging" },+ activationDelay: 0,deactivationDelay: 60,enabled: true})diff --git a/apps/mobile/src/services/NativeLocationService.ts b/apps/mobile/src/services/NativeLocationService.tsindex d9d1b051..50e926f4 100644--- a/apps/mobile/src/services/NativeLocationService.ts+++ b/apps/mobile/src/services/NativeLocationService.ts@@ -409,6 +409,7 @@ class NativeLocationService {type: p.conditionType,...(p.speedThreshold != null ? { speedThreshold: p.speedThreshold } : {})},+ activationDelay: p.activationDelaySeconds,deactivationDelay: p.deactivationDelaySeconds,enabled: p.enabled,createdAt: p.createdAt@@ -430,7 +431,8 @@ class NativeLocationService {priority: profile.priority,conditionType: profile.condition.type,speedThreshold: profile.condition.speedThreshold ?? null,- deactivationDelaySeconds: profile.deactivationDelay+ deactivationDelaySeconds: profile.deactivationDelay,+ activationDelaySeconds: profile.activationDelay})}@@ -452,6 +454,7 @@ class NativeLocationService {config.speedThreshold = update.condition.speedThreshold ?? null}if (update.deactivationDelay !== undefined) config.deactivationDelaySeconds = update.deactivationDelay+ if (update.activationDelay !== undefined) config.activationDelaySeconds = update.activationDelayif (update.enabled !== undefined) config.enabled = update.enabledreturn LocationServiceModule.updateProfile(config)diff --git a/apps/mobile/src/types/global.ts b/apps/mobile/src/types/global.tsindex ab3e87c0..e0c368b0 100644--- a/apps/mobile/src/types/global.ts+++ b/apps/mobile/src/types/global.ts@@ -401,6 +401,8 @@ export interface TrackingProfile {priority: number/** The condition that activates this profile */condition: ProfileCondition+ /** Seconds the condition must hold continuously before the profile activates (0 = immediate) */+ activationDelay: number/** Seconds to wait before deactivating after condition stops matching */deactivationDelay: number/** Whether this profile is enabled */