Colota - Android GPS Location tracker
feat(platform): sync state, bridge methods and the tokens beneath the screens (#847)
Max Dietrichb9b0f5a5709d
diff --git a/apps/docs/docs/development/architecture.md b/apps/docs/docs/development/architecture.mdindex d7f3fea9..3687eaa9 100644--- a/apps/docs/docs/development/architecture.md+++ b/apps/docs/docs/development/architecture.md@@ -61,7 +61,7 @@ Three React Native bridge modules are registered by `LocationServicePackage`: `LThe primary React Native bridge module (exposed as `"LocationServiceModule"`). Handles all JS-to-native communication for:- Service control (`startService`, `stopService`)-- Database queries (`getStats`, `getTableData`, `getLocationsByDateRange`, `getDaysWithData`, `getDailyStats`)+- Database queries (`getStats`, `getTableData`, `getLocationsByDateRange`, `getDaysWithData`, `getDailyStats`, `countOlderThan`, `countUnsentOlderThan`)- Geofence CRUD operations- Settings persistence- Device info, file operations, authentication@@ -71,7 +71,8 @@ Emits events back to JavaScript:- `onLocationUpdate` - new GPS fix received- `onTrackingStopped` - service stopped (user action or OOM kill)- `onSyncError` - 3+ consecutive sync failures-- `onSyncProgress` - batch sync progress updates with `{sent, failed, total}`+- `onSyncProgress` - batch sync progress updates with `{sent, failed, total}`, plus `remaining` on the one event that ends a pass. A pass caps at `MAX_BATCHES_PER_SYNC`, so `sent + failed` reaching `total` does not mean the queue is empty+- `onDatabaseCompacted` - the detached `VACUUM` after a bulk delete has finished, with `{success}`, so a size read before it is known to be stale- `onPauseZoneChange` - entered or exited a geofence pause zone- `onProfileSwitch` - a tracking profile was activated or deactivated- `onAutoExportComplete` - auto-export finished with `{success, fileName, rowCount, error}`@@ -82,12 +83,13 @@ Second React Native bridge module (exposed as `"BackupServiceModule"`). Owns the- `pickBackupDestination` / `pickBackupSource` - launches the Storage Access Framework picker (`ACTION_CREATE_DOCUMENT` / `ACTION_OPEN_DOCUMENT`); a single in-flight picker is enforced via a 5-minute timeout.- `createBackup(uri, password)` - validates password strength, claims an operation mutex, runs `BackupBuilder` against a cacheDir-staged file, then atomically copies into the SAF destination. Stops promotion to a foreground service when finished.-- `restoreBackup(uri, password)` - cancels the location service and any auto-export work, polls until both stop, runs `BackupRestorer`, then forces `tracking_enabled=false` so the destination device doesn't auto-resume. Its `finally` re-arms the auto-export alarm from whichever DB is live, because `pauseAllDbWriters` cancelled it whether or not the restore went through, and starts tracking again through `TrackingControl.start` when the restore failed before it replaced the database. A failure raised after the swap (`SECRETS_PARTIAL`) leaves tracking off like a success does, because the live DB is then the backup's.+- `describeBackup(uri, password)` - reads the archive's `manifest.json` and stops there, returning `createdAt`, `appVersion`, `appBuild` and `schemaDb`. It claims the same operation mutex but starts no foreground service, pauses no writers and extracts nothing, so a wrong password costs a retry rather than a stopped recording. The manifest is the first entry the builder writes, so the read costs one key derivation and the first chunk. A schema newer than the installed app is refused here, before any destructive control is offered.+- `restoreBackup(uri, password)` - cancels the location service and any auto-export work, polls until both stop, then runs `BackupRestorer`. Its `finally` writes `tracking_enabled=false` whenever the database was replaced, success or failure, so the destination device doesn't auto-resume; the write sits in the `finally` and not the try because a throw after the swap would otherwise leave the flag as the archive carried it and recording could resume at the next revive. The same `finally` re-arms the auto-export alarm from whichever DB is live, because `pauseAllDbWriters` cancelled it whether or not the restore went through, and starts tracking again through `TrackingControl.start` when the restore failed before it replaced the database. Any failure raised after the swap that is not `SECRETS_PARTIAL` is reported to JS as `E_BACKUP_RESTORED_INCOMPLETE`, because a caller cannot otherwise tell from the code whether the swap already happened, and that answer decides whether it reloads the bundle.- `applyRestore` - JS calls this after the success dialog is dismissed; it triggers `reactHost.reload()` so all modules re-read state from the restored DB.Both `createBackup` and `restoreBackup` await `BackupOrphanCleanup.awaitComplete()` before claiming the operation mutex, ensuring the launch-time orphan sweeper can't race active operations.-Errors are surfaced to JS as `E_BACKUP_<ERROR_NAME>` codes that map onto the `BackupError` enum (`WRONG_PASSWORD`, `BAD_MAGIC`, `UNSUPPORTED_VERSION`, `UNSUPPORTED_KDF`, `UNSUPPORTED_SCHEMA`, `MISSING_ENTRY`, `INTEGRITY_FAIL`, `TRUNCATED`, `TAMPERED`, `SECRETS_PARTIAL`).+Errors are surfaced to JS as `E_BACKUP_<ERROR_NAME>` codes that map onto the `BackupError` enum (`WRONG_PASSWORD`, `BAD_MAGIC`, `UNSUPPORTED_VERSION`, `UNSUPPORTED_KDF`, `UNSUPPORTED_SCHEMA`, `MISSING_ENTRY`, `INTEGRITY_FAIL`, `MIGRATION_FAILED`, `NO_SPACE`, `TRUNCATED`, `TAMPERED`, `SECRETS_PARTIAL`), plus `E_BACKUP_RESTORED_INCOMPLETE`, which is not an enum member but the code a post-swap failure is reported under.### Backup Pipeline@@ -98,7 +100,7 @@ Native-only modules in `backup/` package. The on-disk format is documented in `B| `BackupCrypto` | Chunked AES-256-GCM encrypt/decrypt keyed by Argon2id. Each chunk binds the file header into its GCM AAD so any header tamper invalidates the first tag. Argon2 is deferred until the first ciphertext chunk arrives so wrong-password rejection costs no key derivation. || `BackupFormat` | On-disk layout constants, `BackupHeader` data class, `BackupError` enum, and `BackupException`. 76-byte header (magic, format version, KDF id, KDF params, 32-byte salt, 8-byte nonce prefix, chunk size, reserved) followed by length-prefixed ciphertext chunks and an end-marker + chunk-count footer. || `BackupBuilder` | Snapshots the SQLite database via `DatabaseHelper.snapshotTo` (uses `VACUUM INTO` on API 30+, file-copy with WAL checkpoint as fallback), runs `quick_check`, extracts secrets via `SecureStorageHelper.exportPlaintextForBackup()`, deflates everything into a zip, then streams it through `BackupCrypto.encrypt`. Picks Argon2 memory by `ActivityManager.isLowRamDevice` (32 MiB / 64 MiB). |-| `BackupRestorer` | Decrypts the file via a `PipedInputStream` into a `ZipInputStream`, extracts entries to a temp dir with bounded reads (zip-bomb defense), validates the manifest schema version, runs `PRAGMA integrity_check` on the candidate DB, calls `DatabaseHelper.migrateCandidate` to run any required migrations on the candidate, then atomically swaps the live DB via `DatabaseHelper.replaceLiveDatabase`, then re-imports secrets. A failed secrets commit is surfaced as `SECRETS_PARTIAL` so the UI can prompt the user to re-enter credentials. |+| `BackupRestorer` | Decrypts the file via a `PipedInputStream` into a `ZipInputStream`, extracts entries to a temp dir with bounded reads (zip-bomb defense), validates the manifest schema version, runs `PRAGMA integrity_check` on the candidate DB, calls `DatabaseHelper.migrateCandidate` to run any required migrations on the candidate, then atomically swaps the live DB via `DatabaseHelper.replaceLiveDatabase`, then re-imports secrets. A migration that fails raises `MIGRATION_FAILED` rather than `INTEGRITY_FAIL`, because the archive is intact and it is this app's reading of it that failed. A failed secrets commit is surfaced as `SECRETS_PARTIAL` so the UI can prompt the user to re-enter credentials. `describe(input, password)` is the read-only half behind `describeBackup`: it stops at `manifest.json` and extracts nothing. || `BackupForegroundService` | Notification-only foreground service shown during long backups/restores. Uses `FOREGROUND_SERVICE_TYPE_DATA_SYNC`. Holds no work itself - the actual encryption stays in `BackupServiceModule`'s coroutine so the password `CharArray` lives only on the heap, not in service state. || `BackupOrphanCleanup` | Singleton kicked off from `MainApplication.onCreate` on a daemon thread. Sweeps `cacheDir/backup_temp`, `cacheDir/restore_temp`, `cacheDir/pending_backup.colota`, and `<dbDir>/Colota.db.incoming` left behind by a process death mid-operation. Exposes a `CompletableDeferred` so `BackupServiceModule` can await completion before claiming the operation mutex. || `PasswordStrength` | Mirror of the JS-side `passwordStrength.ts`. Enforces the 12-character floor and ~50-bit entropy floor; sequential runs and `<4` distinct chars cap the score. |@@ -123,7 +125,7 @@ Native-only modules in the `importer/` package. Format-specific parsers all retu| Module | Purpose || --- | --- || `LocationImporter` | Orchestrator. Detects format from the sniff (XML root for GPX/KML, JSON top-level keys for GeoJSON / Google Timeline, CSV header for CSV), dispatches to the per-format parser, runs streaming **merge-walk dedup** against an ASC-ordered DB cursor (no existing-key `HashSet` is materialised - memory is O(1) on top of the parsed-rows list, so the dedup scales to multi-million-row user histories without OOM). On commit, the recovery path writes `sent = 1` and skips the queue; the migration path (`asQueued=true`) builds payloads via the live `PayloadBuilder` against a synthetic `android.location.Location` so the import path can't drift from the live tracking path. |-| `GeoJsonParser` | Streaming `android.util.JsonReader`-based parser for a `FeatureCollection` of `Point` features (scalar properties) or Colota's columnar `MultiPoint` features (per-point attributes as parallel arrays, including `note` / `battery_status`), zipped by index. Tolerates foreign shapes - any feature without a recognised time / non-Point-or-MultiPoint geometry is counted as invalid and dropped, but parsing continues. |+| `GeoJsonParser` | Streaming `android.util.JsonReader`-based parser for a `FeatureCollection` of `Point` features (scalar properties) or the columnar `MultiPoint` features Colota exported in 1.12.0 through 1.16.0 (per-point attributes as parallel arrays, including `note` / `battery_status`), zipped by index. The MultiPoint reader is permanent: such a file can be the last copy of data since deleted from the device. The writer emits Point features only. Tolerates foreign shapes - any feature without a recognised time / non-Point-or-MultiPoint geometry is counted as invalid and dropped, but parsing continues. || `GoogleTimelineParser` | Handles both Google Timeline schemas in a single pass: legacy Takeout (`locations[].latitudeE7/longitudeE7/timestampMs`) and the new on-device export (`semanticSegments[].timelinePath[]` + `rawSignals[].position` with degree-suffix coord strings). Visit/activity inferences are intentionally skipped. || `GpxParser` | `XmlPullParser`-based. Collects `<wpt>` + `<rtept>` + `<trkpt>` uniformly into the flat locations table. Recognises Garmin's nested `TrackPointExtension` wrapper so sport-watch metadata (speed, course) lands on the row. || `KmlParser` | `XmlPullParser`-based. Reads `Placemark/Point/coordinates` (KML's `lon,lat[,alt]` order, flipped back internally) with `TimeStamp/when`. `LineString`-only Placemarks are dropped + counted as invalid since the KML schema doesn't carry per-vertex timestamps. |@@ -155,16 +157,9 @@ An Android foreground service that runs continuously for GPS tracking. Manages:- Stationary detection - slows GPS to the profile's interval after 60s of fixes without movement; resume is driven by the shared `MotionStateDetector` (accelerometer variance, with SIG_MOTION as a fast-path for sharp wake events). It keeps working inside a pause zone and during an entry delay, since fixes reach `ProfileManager` before the in-zone drop; only a hold that stops the stream can prevent a verdict.- Queuing data for server sync-**Alarms go through a receiver, not the service.** Each scheduler targets a `BroadcastReceiver`-that then starts the service. That keeps the PendingIntent a plain explicit broadcast, and the-foreground-service start runs inside the alarm's temporary allowlist window.+**Alarms go through a receiver, not the service.** Each scheduler targets a `BroadcastReceiver` that then starts the service. That keeps the PendingIntent a plain explicit broadcast, and the foreground-service start runs inside the alarm's temporary allowlist window.-**Intent vs liveness.** The `tracking_enabled` setting records that the user wants tracking and-deliberately survives process death and reboot. Whether a service exists right now is-`LocationForegroundService.isRunning`. Anything asking "is tracking alive" must read `isRunning`,-because a service the system killed leaves the flag true. Recovery is layered: the app reconciles-the two whenever it reaches the foreground, and `TrackingWatchdogScheduler` covers the window while-the app stays closed.+**Intent vs liveness.** The `tracking_enabled` setting records that the user wants tracking and deliberately survives process death and reboot. Whether a service exists right now is `LocationForegroundService.isRunning`. Anything asking "is tracking alive" must read `isRunning`, because a service the system killed leaves the flag true. Recovery is layered: the app reconciles the two whenever it reaches the foreground, and `TrackingWatchdogScheduler` covers the window while the app stays closed. Reconciling can also drop the intent rather than honour it: a revoked location permission means no service can be started again, so the foreground reconciler clears the flag and the watchdog stops re-arming itself.### NotificationHelper@@ -256,7 +251,7 @@ The stationary condition is decided by the fixes and never by a timer. `evaluate### ProfileHelper-Database access layer for tracking profiles and trip events. Maintains a `TimedCache` of enabled profiles (30s TTL) and provides CRUD operations plus trip event logging.+Database access layer for tracking profiles and trip events. Maintains a `TimedCache` of enabled profiles (30s TTL) ordered by priority then id, so equal priorities go to the older profile, and provides CRUD operations plus trip event logging.### ConditionMonitor@@ -290,7 +285,7 @@ For backups, two `internal` methods support the export/import flow without expos| `PayloadBuilder` | Builds outgoing JSON payloads (field-mapped, Overland batch envelope, Traccar JSON) and extracts envelope custom fields || `ServiceConfig` | Centralized configuration data class || `TimedCache` | Generic TTL cache used for queue count, device info, profiles, and network state |-| `BuildConfigModule` | Exposes build constants (SDK versions, app version) to JS |+| `BuildConfigModule` | Exposes the version name, version code, flavor and device language to JS, plus `getSystemPalette` - the Android 12+ wallpaper tonal steps as `#RRGGBB` hex, null below API 31 || `AppLogger` | Centralized logger - always active, all tags prefixed with `Colota.` for logcat filtering || `AutoExportWorker` | WorkManager `CoroutineWorker` enqueued by `AutoExportAlarmReceiver` - performs the export (chunked writes to a per-run temp file, foreground service, retries, retention cleanup), verifies the copy by bytes written and re-arms the next alarm in `finally` || `AutoExportAlarmReceiver` | Broadcast receiver fired by AlarmManager at the configured time - hands off to `AutoExportWorker` because the receiver's 10s budget can't run an export |@@ -307,31 +302,34 @@ For backups, two `internal` methods support the export/import flow without expos| Screen | Purpose || --- | --- |-| `DashboardScreen` | Live map with tracking controls, coordinates, database stats, geofence and profile status |-| `SettingsScreen` | Hub with stats card and navigation to Connection, Tracking & Sync, API Field Mapping, Tracking Profiles, Appearance and data/about screens |-| `ConnectionScreen` | Server endpoint URL, offline mode toggle and connection test |+| `DashboardScreen` | Full-bleed map with no header. One banner slot under the status inset for a missing permission, location services off or a critical battery, and a docked card over the bottom edge: the tracking state line, the interval row (fix cadence and sync cadence, from the active profile or from settings; a zero sync interval reads as instant) and the server row. The Start/Stop pill and the Route toggle float above the dock. Nothing polls: it reads on focus and takes the rest from events |+| `SettingsScreen` | The hub, a tab of five grouped lists: Tracking (Connection, Tracking & sync, Tracking profiles), Display, Data, Help and About. Two rows carry live state through the derivation their target screen opens with (`serverState.describeServer`, `profileRow.profileStateLabel`); every other sub is a stored value, an on-disk fact or the nouns inside the screen, computed by `utils/settingsRow` |+| `ConnectionScreen` | The server hub: a sync state line from `utils/serverState`, offline mode, the endpoint (saved on blur), Test connection, and rows to Request format, Authentication and Client certificate || `TrackingSyncScreen` | GPS interval, distance filter, accuracy threshold and sync strategy preset |-| `AppearanceScreen` | Light/dark theme, unit system, time format and custom map tile URLs (light and dark) |-| `ApiSettingsScreen` | Endpoint URL, HTTP method, field mapping with backend templates |-| `AuthSettingsScreen` | Authentication method (None, Basic Auth, Bearer Token) and custom HTTP headers, with a link row to mTLS Settings |-| `MtlsSettingsScreen` | Client certificate (PKCS12 import + Android Keystore storage) and Trusted Server CA management |-| `GeofenceScreen` | Create, edit, and delete pause zones on an interactive map |-| `GeofenceEditorScreen` | Configure a zone: name, radius, record pause, WiFi pause, motionless pause and timeout, stationary heartbeat |-| `TrackingProfilesScreen` | List and manage condition-based tracking profiles |-| `ProfileEditorScreen` | Create/edit a profile's name, condition, GPS settings, priority, and deactivation delay |-| `LocationInspectorScreen` | Calendar day picker with activity dots, map tab with trip-colored tracks, trips tab with trip cards, per-trip and multi-select export and multi-select delete |-| `TripDetailScreen` | Full trip view with dedicated map, stats grid, speed and elevation profile charts, per-trip export, and per-trip delete |-| `LocationSummaryScreen` | Aggregated stats for selectable periods (week/month/30 days) with daily breakdown and tap-to-inspect navigation |+| `AppearanceScreen` | Theme, wallpaper colors on Android 12 and up, unit system, time format and custom map tile URLs (light and dark, refused unless they parse as an http or https URL) |+| `ApiSettingsScreen` | Route **Request Format**. Backend template as a row opening the picker, HTTP method and Dawarich mode as radio rows, and the field mapping |+| `BackendTemplateScreen` | The eight backend templates as radio rows, each stating what it sends, returning the choice with `popTo` and `merge`. Eight options that each need a sentence do not fit inline on a form screen |+| `AuthSettingsScreen` | Authentication method as a radio group (None, Basic auth, Bearer token) with never-echoed secrets, and custom HTTP headers |+| `MtlsSettingsScreen` | Client certificate (device store pick or PKCS12 import into the Android Keystore) and the trusted server CA, each with a state line from `utils/certificateState` |+| `GeofenceScreen` | Pause zones as rows over a map. Create geofence opens the editor on an empty draft; deletion happens there |+| `GeofenceEditorScreen` | Every property of a zone: name, radius, location, record pause, WiFi pause, motionless pause and timeout, stationary heartbeat |+| `PlaceZoneScreen` | Picks a zone coordinate on a map with the radius drawn live, returning it to the editor with `popTo` and `merge` |+| `TrackingProfilesScreen` | One card: a state line naming the profile in force (or what applies instead), then a row per profile in evaluation order reading as a rule, each with its enabled switch |+| `ProfileEditorScreen` | The rule as a live sentence, then Condition, Profile (name, priority), Tracking while active and Switching, with inline validation and a Save button |+| `LocationHistoryScreen` | One day at a time: a day header (chevrons, title opening the calendar dialog, ledger caption) over Map, Trips and Data lenses. Map docks a card over the track: the trip rows as legend, the tapped point (split, delete, note) or the empty day's next step. Trips is one card of trip rows; long-press turns the header into a contextual action bar for export, merge and delete. Data is a frozen-time table whose row tap opens the point on the map. Export of the day and the summary live in the header |+| `TripDetailScreen` | A trip stepper (swatch, name, date and times) over the trip's map, where a tapped point docks its card for split and note; a ledger of distance, duration, speed, points and elevation, then the speed and elevation charts; export and delete in the header |+| `LocationSummaryScreen` | A period stepper (week or month) over a ledger of distance, trips, active days and average, and the period's days as rows that open the day in Location History; each period is read from the daily stats on its own, since a year or all time would walk every row || `ExportLocationsScreen` | Export all tracked locations via native streaming converters as CSV, GeoJSON, GPX, or KML || `ImportLocationsScreen` | Import external location files (GeoJSON, Google Timeline legacy + new, GPX, KML, CSV) with auto format detection, dedup preview, and recovery vs migration (queue-for-sync) commit choice || `AutoExportScreen` | Configure scheduled auto-export: directory, format, frequency, time of day, weekday or day-of-month, export range and file retention |-| `OfflineMapsScreen` | Download and manage offline map areas - interactive bounding box picker, size estimate, progress tracking, and area deletion |-| `DataManagementScreen` | Clear sent history, delete old data, vacuum database, sync controls |+| `OfflineMapsScreen` | Download and manage offline map areas - the viewport as the bounding box with a live estimate, one download at a time with progress the screen picks up again on return, re-download and delete, a Map style changed mark |+| `DataManagementScreen` | Database ledger, manual flush, compaction, deletes by sync state or age || `BackupRestoreScreen` | Create or restore a password-encrypted `.colota` archive of all data, with strength meter and no-recovery confirmation || `SetupImportScreen` | Confirmation screen for `colota://setup` deep link imports || `ShareSetupScreen` | Bundles selected config categories into a `colota://setup` link to share; credentials opt-in |-| `ActivityLogScreen` | In-app log viewer with level filtering, search, and export |-| `AboutScreen` | App version, device info, links to repository and privacy policy |+| `LoggingScreen` | Records a log file and saves it as one file: capture state, the toggle, and the save and delete actions, which are absent while the file is empty |+| `LogPreviewScreen` | Reads the recorded file, or the system log while recording is off. Newest first, search, and a single-select severity floor whose chips carry their own counts |+| `AboutScreen` | The app's icon and name over the version with its build code, then the privacy policy, licence and source links and the copyright notice; map credits stay on the map's own dialog |### Services@@ -352,10 +350,11 @@ The app uses [MapLibre GL Native](https://github.com/maplibre/maplibre-react-nat| Component | Purpose || --- | --- || `ColotaMapView` | Shared base map component wrapping MapLibre's `MapView` with OpenFreeMap vector tiles, dark mode style transformation, custom compass, and attribution |-| `DashboardMap` | Live tracking map with user marker, accuracy circle, today's track overlay with toggle button, geofence polygons with labels, auto-center, and center button |-| `TrackMap` | Location history map with trip-colored track segments, tappable point markers with detail popups, fit-to-track bounds, and trip legend |-| `CalendarPicker` | Day picker with month navigation, dot indicators for days with data, and daily distance/count display |-| `TripList` | Segmented trip cards with distance, duration, avg speed, elevation gain/loss. Per-trip share icon plus a long-press contextual action bar for multi-select export and delete |+| `DashboardMap` | Live tracking map with user marker, accuracy circle, today's track (its visibility is the screen's Route toggle, the map only draws it), geofence polygons with labels, follow-me until the user pans, then a centre button in the disc column. Frames the last known fix, or the zones when there is none |+| `TrackMap` | Location history map: trip-colored track segments over a casing layer, a focused trip drawn wider while the rest dim, 48 dp point hitboxes, fit-to-day and fit-to-trip bounds. Selection and focus are props; it draws no popup or legend |+| `CalendarPicker` | Day, month and year panes inside `DayPickerModal`, dot indicators for days with data, per-day stats spoken by the cell |+| `LocationTable` | The day's points newest first with a frozen time column beside a horizontally scrolling pane; a Sync column when an endpoint is set; a row tap opens the point on the map |+| `TripList` | One card of `TripRow`s (swatch, number, time range, distance, duration, speed) with controlled selection: long-press enters, tap toggles; the screen owns the action bar, export, merge and delete || `GeofenceLayers` | Shared geofence rendering (fill polygons, stroke outlines, labels) used by DashboardMap and GeofenceScreen || `UserLocationOverlay` | User position dot with accuracy circle, used by DashboardMap and GeofenceScreen || `MapCenterButton` | Reusable button overlay to re-center the map |@@ -365,11 +364,13 @@ The app uses [MapLibre GL Native](https://github.com/maplibre/maplibre-react-nat| Export | Purpose || --- | --- || `createOfflinePack` | Creates a MapLibre offline pack for a bounding box at z8-14 |-| `loadOfflineAreas` | Fetches all stored packs from MapLibre's `OfflineManager` and returns status info (size, complete, active) |+| `loadOfflineAreas` | Fetches all stored packs from MapLibre's `OfflineManager` and returns status info (size, complete, active) and each pack's bounds |+| `subscribeOfflinePack` | Re-attaches progress and error listeners to a pack native reports active and returns its status. Never call it on an inactive pack: observing one re-activates it |+| `pruneOfflineAreaBounds` | Drops sidecar entries whose pack is gone, in one write || `deleteOfflineArea` | Unsubscribes, pauses, and deletes a pack; resets the tile database when the last pack is removed to reclaim OS storage || `willExceedTileLimit` | Estimates whether an area would hit the 100k-tile cap before downloading || `estimateSizeLabel` / `estimateSizeBytes` | Pre-download size estimates using per-zoom tile counting and per-tile byte averages |-| `loadOfflineAreaBounds` / `saveOfflineAreaBounds` / `removeOfflineAreaBounds` | Persist area metadata (center, radius) to the native SQLite settings table |+| `loadOfflineAreaBounds` / `saveOfflineAreaBounds` / `removeOfflineAreaBounds` | Persist area metadata (style URL and completion time; the extent comes from the pack) to the native SQLite settings table |Supporting utilities in `mapUtils.ts`:@@ -388,28 +389,30 @@ Supporting utilities in `mapUtils.ts`:| Utility | Purpose || --- | --- |-| `logger` | Environment-aware logging - suppresses debug/info console output in production via `__DEV__`, always logs warn/error to console. All levels are always captured in a ring buffer (2000 entries) for the Logging screen |+| `logger` | Environment-aware logging - suppresses debug/info console output in production via `__DEV__`, always logs warn/error to console. All levels are always captured in a ring buffer (`MAX_BUFFER_SIZE`, 2000 entries) which the Logging screen previews and `logExport.buildAppLog` formats into `AppFileLogger`'s own line shape for the exported file |+| `logExport` | Parses native log lines into `MergedLogEntry` and builds the two halves of an export. A line matching neither the file nor the logcat shape is a continuation and inherits the time and level of the line above it, so a stack trace filters and sorts with the throw it belongs to. `buildExportHeader` writes the version, flavor, device and capture window; `buildAppLog` writes the ring buffer with an `APP_LOG_COVERAGE` marker at its first line, because the buffer spans one process while the recorded file spans restarts |+| `LogExportMerger` (Kotlin, `util/`) | Interleaves the app log into the recorded segments by timestamp while streaming them to the SAF document, so an export is one timeline and never holds a multi-megabyte file in memory. The merge is native because the segments are copied natively and the bridge only hands JS a capped tail of them, so a JS-side merge would truncate the file it completes || `geo` | Haversine distance, speed/distance/duration/time formatting with configurable unit system (metric/imperial) and time format (12h/24h), auto-detected from locale on first use || `exportConverters` | Export-format metadata (labels, icons, extensions, MIME types) for the export UI. Serialization itself is native - see `ExportConverters.kt` || `trips` | Trip segmentation via time-gap detection (15-min threshold), dropping segments whose bounding box spans under 100 m so stationary heartbeat runs do not become trips, plus distance computation, trip stats (avg speed, elevation gain/loss), and trip color assignment. Elevation is smoothed over a time window before accumulating, since raw altitude swings between fixes overstate the climb. Manual `trip_boundary_overrides` take priority over the gap threshold, and a segment abutting a forced split is exempt from the 100 m filter so an explicit edit is never silently dropped. `getDailyStats` in `DatabaseHelper.kt` mirrors all of this for the calendar and summary |-| `queueStatus` | Maps sync queue size to color indicators for the dashboard |+| `dashboardState` | Pure functions behind the Dashboard: `pickBannerCondition` ranks the one banner slot (location grant, background grant while tracking, location services, battery), `describeState` turns tracking, pause and fix state into the dock's state line, `intervalText` and `formatLastFix` || `settingsValidation` | URL validation and security checks for endpoint configuration |### Hooks-| Hook | Purpose |-| --------------------- | ---------------------------------------------------------------------------------------- |+| Hook | Purpose |+| --- | --- || `useLocationTracking` | Manages the foreground service lifecycle, native event subscriptions, and location state. On app foreground it reconciles the user's intent against real service liveness and restarts a service that died |-| `useTheme` | Provides theme colors, mode, and toggle from ThemeProvider context |-| `useAutoSave` | Debounced auto-save pattern for settings screens |-| `useTimeout` | Managed timeout with automatic cleanup on unmount |+| `useTheme` | Provides theme colors, mode, and toggle from ThemeProvider context |+| `useAutoSave` | Debounced auto-save pattern for settings screens |+| `useTimeout` | Managed timeout with automatic cleanup on unmount |### State ManagementThe app uses React Context for global state:- **ThemeProvider** - Light/dark theme with system preference sync-- **TrackingProvider** - Single source of truth for tracking state, coordinates, settings, and active profile name. Hydrates from SQLite on mount, restores the active profile from the running service on reconnect, and persists changes back through `SettingsService`.+- **TrackingProvider** - Single source of truth for tracking state, coordinates, settings and the active profile's name and id. Hydrates from SQLite on mount, restores the active profile's name and id from the running service on reconnect, and persists changes back through `SettingsService`.### Data Flowdiff --git a/apps/docs/docs/development/permissions.md b/apps/docs/docs/development/permissions.mdindex 53263461..9f1d5f6c 100644--- a/apps/docs/docs/development/permissions.md+++ b/apps/docs/docs/development/permissions.md@@ -35,7 +35,7 @@ When you start tracking for the first time, Colota requests permissions in sequeOnly the two location permissions are required. The app does not request anything until you tap "Start Tracking".-The **Local Network Permission** (Android 17+) is not part of this sequence. It is requested separately when you use **Test Connection** with a local/private server endpoint.+The **Local Network Permission** (Android 17+) is not part of this sequence. It is requested separately when you use **Test connection** with a local/private server endpoint.## Detailed Explanations@@ -91,7 +91,7 @@ On Android 13 and later, apps need this permission before they can show notificaandroid.permission.ACCESS_LOCAL_NETWORK```-Starting with Android 17, apps need this permission to connect to devices on the local network. Colota requests it when you use **Test Connection** with a private/local endpoint - this includes IP addresses (e.g. `192.168.x.x`, `10.x.x.x`, `172.16-31.x.x`, `100.64.x.x`) and hostnames that resolve to private IPs via DNS (e.g. `server.local`). Loopback addresses (`localhost` / `127.0.0.1`) do not require this permission. If your server is a public HTTPS endpoint, this permission is never requested.+Starting with Android 17, apps need this permission to connect to devices on the local network. Colota requests it when you use **Test connection** with a private/local endpoint - this includes IP addresses (e.g. `192.168.x.x`, `10.x.x.x`, `172.16-31.x.x`, `100.64.x.x`) and hostnames that resolve to private IPs via DNS (e.g. `server.local`). Loopback addresses (`localhost` / `127.0.0.1`) do not require this permission. If your server is a public HTTPS endpoint, this permission is never requested.:::note[Android 16]@@ -117,4 +117,4 @@ Lets Colota briefly hold the CPU awake when a heartbeat alarm fires during Doze.## Revoking Permissions-You can revoke any permission at any time through Android Settings → Apps → Colota → Permissions. Revoking location permissions will stop tracking. Other permissions can be toggled without affecting the core tracking functionality.+You can revoke any permission at any time through Android Settings → Apps → Colota → Permissions. Revoking a location permission stops the tracking service, and Colota turns the tracking toggle off the next time you open the app. Other permissions can be toggled without affecting the core tracking functionality.diff --git a/apps/mobile/android/app/build.gradle b/apps/mobile/android/app/build.gradleindex 32ef734c..b0c88f43 100644--- a/apps/mobile/android/app/build.gradle+++ b/apps/mobile/android/app/build.gradle@@ -97,13 +97,6 @@ android {versionCode 49versionName "1.17.0"- // Strip Build IDs for reproducible builds (IzzyOnDroid/F-Droid)- externalNativeBuild {- cmake {- arguments "-DCMAKE_SHARED_LINKER_FLAGS=-Wl,--build-id=none"- }- }-// Expose build config to the modulebuildConfigField "int", "MIN_SDK_VERSION", "${rootProject.ext.minSdkVersion}"buildConfigField "int", "TARGET_SDK_VERSION", "${rootProject.ext.targetSdkVersion}"@@ -111,6 +104,14 @@ android {buildConfigField "String", "BUILD_TOOLS_VERSION", "\"${rootProject.ext.buildToolsVersion}\""buildConfigField "String", "KOTLIN_VERSION", "\"${rootProject.ext.kotlinVersion}\""buildConfigField "String", "NDK_VERSION", "\"${rootProject.ext.ndkVersion}\""++ // Strip Build IDs for reproducible builds (IzzyOnDroid/F-Droid)+ externalNativeBuild {+ cmake {+ arguments "-DCMAKE_SHARED_LINKER_FLAGS=-Wl,--build-id=none"+ }+ }+}signingConfigs {diff --git a/apps/mobile/android/app/src/main/java/com/colota/backup/BackupFormat.kt b/apps/mobile/android/app/src/main/java/com/colota/backup/BackupFormat.ktindex 8e6c6760..6600e450 100644--- a/apps/mobile/android/app/src/main/java/com/colota/backup/BackupFormat.kt+++ b/apps/mobile/android/app/src/main/java/com/colota/backup/BackupFormat.kt@@ -117,6 +117,10 @@ enum class BackupError {TRUNCATED,TAMPERED,WRONG_PASSWORD,+ // The archive is intact; this app's own migration of it failed.+ MIGRATION_FAILED,+ // Restore ran out of room before the swap. Nothing was replaced.+ NO_SPACE,// DB swapped successfully but secrets commit failed; user must re-enter credentials.SECRETS_PARTIAL,}diff --git a/apps/mobile/android/app/src/main/java/com/colota/backup/BackupRestorer.kt b/apps/mobile/android/app/src/main/java/com/colota/backup/BackupRestorer.ktindex 0dca34ad..d30317a7 100644--- a/apps/mobile/android/app/src/main/java/com/colota/backup/BackupRestorer.kt+++ b/apps/mobile/android/app/src/main/java/com/colota/backup/BackupRestorer.kt@@ -55,7 +55,7 @@ class BackupRestorer @JvmOverloads constructor(} catch (e: IllegalStateException) {throw BackupException(BackupError.UNSUPPORTED_SCHEMA, e.message ?: "Migration refused", e)} catch (e: Exception) {- throw BackupException(BackupError.INTEGRITY_FAIL, "Schema migration failed: ${e.message}", e)+ throw BackupException(BackupError.MIGRATION_FAILED, "Schema migration failed: ${e.message}", e)}val secretsMap = extracted.secrets?.let { parseSecrets(it) }@@ -78,6 +78,61 @@ class BackupRestorer @JvmOverloads constructor(}}+ /**+ * The manifest and nothing else. It is the first entry the builder writes, so reading it costs+ * one key derivation and the first chunk, and the archive is never extracted.+ */+ fun describe(input: InputStream, password: CharArray): JSONObject {+ val pipedOut = PipedOutputStream()+ val pipedIn = PipedInputStream(pipedOut, 1024 * 1024)+ var decryptError: Throwable? = null++ val decryptThread = Thread({+ try {+ pipedOut.use { crypto.decrypt(input, it, password) }+ } catch (t: Throwable) {+ decryptError = t+ try { pipedOut.close() } catch (_: Exception) {}+ }+ }, "BackupDescribeDecryptor").apply { isDaemon = true }+ decryptThread.start()++ val bytes = try {+ ZipInputStream(pipedIn).use { zip ->+ var found: ByteArray? = null+ var entry = zip.nextEntry+ while (entry != null && found == null) {+ if (!entry.isDirectory && entry.name == MANIFEST_ENTRY) {+ found = readBoundedZipEntry(zip, MANIFEST_ENTRY, MAX_MANIFEST_BYTES)+ }+ if (found == null) entry = zip.nextEntry+ }+ found+ }+ } catch (e: Exception) {+ // Closing the pipe early makes the decryptor throw, so its error only counts if it came first.+ decryptThread.join()+ decryptError?.let { throw it }+ throw e+ }++ // Not joined on the happy path: the reader stops at the first entry and the writer is a+ // daemon blocked on a closed pipe, which a join would wait out for the rest of the archive.+ decryptError?.let { throw it }+ val manifestBytes = bytes ?: throw BackupException(BackupError.MISSING_ENTRY, MANIFEST_ENTRY)++ val manifest = JSONObject(String(manifestBytes, Charsets.UTF_8))+ val backupSchema = manifest.optJSONObject("schema")?.optInt("db", -1) ?: -1+ if (backupSchema > DatabaseHelper.DATABASE_VERSION) {+ throw BackupException(+ BackupError.UNSUPPORTED_SCHEMA,+ "Backup schema $backupSchema is newer than installed app schema " ++ "${DatabaseHelper.DATABASE_VERSION}; upgrade Colota first."+ )+ }+ return manifest+ }+private fun decryptAndExtract(input: InputStream,password: CharArray,diff --git a/apps/mobile/android/app/src/main/java/com/colota/bridge/BackupServiceModule.kt b/apps/mobile/android/app/src/main/java/com/colota/bridge/BackupServiceModule.ktindex 114278b4..e3e49231 100644--- a/apps/mobile/android/app/src/main/java/com/colota/bridge/BackupServiceModule.kt+++ b/apps/mobile/android/app/src/main/java/com/colota/bridge/BackupServiceModule.kt@@ -169,7 +169,7 @@ class BackupServiceModule(reactContext: ReactApplicationContext) :val resolver = reactApplicationContext.contentResolverresolver.openOutputStream(uri, "wt")?.use { safOut ->pendingFile.inputStream().use { it.copyTo(safOut) }- } ?: throw IllegalStateException("Could not open output stream for $uriString")+ } ?: throw IllegalStateException("Could not write to the file you chose. Pick a different location and try again.")promise.resolve(true)} catch (e: Exception) {@@ -191,6 +191,47 @@ class BackupServiceModule(reactContext: ReactApplicationContext) :}}+ /**+ * Reads the manifest and stops. No foreground service, no writer pause, nothing extracted, so a+ * wrong password costs a retry rather than a stopped recording.+ */+ @ReactMethod+ fun describeBackup(uriString: String, passwordCodes: ReadableArray, promise: Promise) {+ val passwordChars = readableArrayToCharArray(passwordCodes)+ if (passwordChars.isEmpty()) {+ promise.reject("E_PASSWORD_EMPTY", "Password is required")+ return+ }+ scope.launch {+ BackupOrphanCleanup.awaitComplete()+ if (!operationMutex.tryLock()) {+ Arrays.fill(passwordChars, 0.toChar())+ promise.reject("E_BUSY", "Another backup or restore is in progress")+ return@launch+ }+ try {+ val uri = Uri.parse(uriString)+ val input = reactApplicationContext.contentResolver.openInputStream(uri)+ ?: throw IllegalStateException("Could not open the file you chose.")+ val manifest = input.use { BackupRestorer(reactApplicationContext).describe(it, passwordChars) }+ promise.resolve(+ Arguments.createMap().apply {+ putString("createdAt", manifest.optString("createdAt", ""))+ putString("appVersion", manifest.optString("appVersion", ""))+ putInt("appBuild", manifest.optInt("appBuild", 0))+ putInt("schemaDb", manifest.optJSONObject("schema")?.optInt("db", -1) ?: -1)+ }+ )+ } catch (e: Exception) {+ AppLogger.e(TAG, "describeBackup failed", e)+ promise.reject(errorCode(e), e.message ?: "Could not read the backup", e)+ } finally {+ Arrays.fill(passwordChars, 0.toChar())+ operationMutex.unlock()+ }+ }+ }+@ReactMethodfun restoreBackup(uriString: String, passwordCodes: ReadableArray, promise: Promise) {val passwordChars = readableArrayToCharArray(passwordCodes)@@ -226,16 +267,18 @@ class BackupServiceModule(reactContext: ReactApplicationContext) :// Swap is done; clear the writer block so the post-restore saveSetting can land on the new DB.DatabaseHelper.setRestoreInProgress(false)- // Don't silently resume tracking on the destination device.- DatabaseHelper.getInstance(reactApplicationContext)- .saveSetting(SettingsKeys.TRACKING_ENABLED, "false")-promise.resolve(true)} catch (e: Exception) {- // The swap happens inside restore(); SECRETS_PARTIAL is the only failure raised after it.if (e is BackupException && e.error == BackupError.SECRETS_PARTIAL) dbReplaced = trueAppLogger.e(TAG, "restoreBackup failed", e)- promise.reject(errorCode(e), e.message ?: "Restore failed", e)+ // A caller cannot tell from an ordinary code whether the swap already happened, and+ // the answer decides whether it reloads the bundle.+ val code = if (dbReplaced && !(e is BackupException && e.error == BackupError.SECRETS_PARTIAL)) {+ "E_BACKUP_RESTORED_INCOMPLETE"+ } else {+ errorCode(e)+ }+ promise.reject(code, e.message ?: "Restore failed", e)} finally {Arrays.fill(passwordChars, 0.toChar())BackupForegroundService.stop(reactApplicationContext)@@ -247,6 +290,16 @@ class BackupServiceModule(reactContext: ReactApplicationContext) :AppLogger.w(TAG, "scheduleNext failed after restore: ${e.message}")}// Once the database is the backup's, the destination-device rule applies and tracking stays off.+ // In the finally, not the try: a throw after the swap would otherwise leave the flag+ // as the archive carried it and recording could resume at the next revive.+ if (dbReplaced) {+ try {+ DatabaseHelper.getInstance(reactApplicationContext)+ .saveSetting(SettingsKeys.TRACKING_ENABLED, "false")+ } catch (e: Exception) {+ AppLogger.w(TAG, "Could not clear tracking_enabled after restore: ${e.message}")+ }+ }// Not in the catch: every saveSetting here is gated until the finally clears restoreInProgress.if (!dbReplaced && trackingWasEnabled) {try {@@ -334,7 +387,8 @@ class BackupServiceModule(reactContext: ReactApplicationContext) :if (available < needed) {val neededMb = needed / (1024 * 1024)val availableMb = available / (1024 * 1024)- throw IllegalStateException(+ throw BackupException(+ BackupError.NO_SPACE,"Not enough free space for restore. Need ~${neededMb} MB, have ${availableMb} MB.")}diff --git a/apps/mobile/android/app/src/main/java/com/colota/bridge/BuildConfigModule.kt b/apps/mobile/android/app/src/main/java/com/colota/bridge/BuildConfigModule.ktindex 49f10c65..8b9aa7ba 100644--- a/apps/mobile/android/app/src/main/java/com/colota/bridge/BuildConfigModule.kt+++ b/apps/mobile/android/app/src/main/java/com/colota/bridge/BuildConfigModule.kt@@ -2,12 +2,16 @@* Copyright (C) 2026 Max Dietrich* Licensed under the GNU AGPLv3. See LICENSE in the project root for details.*/-+package com.Colota.bridge+import android.os.Build+import com.facebook.react.bridge.Arguments+import com.facebook.react.bridge.Promiseimport com.facebook.react.bridge.ReactApplicationContextimport com.Colota.BuildConfigimport com.facebook.react.bridge.ReactContextBaseJavaModule+import com.facebook.react.bridge.ReactMethodimport java.util.Localeclass BuildConfigModule(reactContext: ReactApplicationContext) :@@ -17,16 +21,59 @@ class BuildConfigModule(reactContext: ReactApplicationContext) :override fun getConstants(): Map<String, Any> {return mapOf(+ "VERSION_NAME" to BuildConfig.VERSION_NAME,+ "VERSION_CODE" to BuildConfig.VERSION_CODE,+ "FLAVOR" to BuildConfig.FLAVOR,"MIN_SDK_VERSION" to BuildConfig.MIN_SDK_VERSION,"TARGET_SDK_VERSION" to BuildConfig.TARGET_SDK_VERSION,"BUILD_TOOLS_VERSION" to BuildConfig.BUILD_TOOLS_VERSION,"COMPILE_SDK_VERSION" to BuildConfig.COMPILE_SDK_VERSION,"KOTLIN_VERSION" to BuildConfig.KOTLIN_VERSION,"NDK_VERSION" to BuildConfig.NDK_VERSION,- "VERSION_NAME" to BuildConfig.VERSION_NAME,- "VERSION_CODE" to BuildConfig.VERSION_CODE,- "FLAVOR" to BuildConfig.FLAVOR,"APP_LANGUAGE" to Locale.getDefault().toLanguageTag())}-}\ No newline at end of file++ /**+ * The wallpaper-derived tonal steps the theme reads, as `#RRGGBB`. Null below API 31, where+ * the framework has no such palette. Hex rather than PlatformColor: the theme concatenates+ * alpha onto its colours as strings, which an opaque colour object cannot do.+ */+ @ReactMethod+ fun getSystemPalette(promise: Promise) {+ if (Build.VERSION.SDK_INT < Build.VERSION_CODES.S) {+ promise.resolve(null)+ return+ }+ val palette = Arguments.createMap()+ for ((name, resId) in systemPaletteIds()) {+ val color = reactApplicationContext.getColor(resId)+ palette.putString(name, String.format(Locale.US, "#%06X", color and 0xFFFFFF))+ }+ promise.resolve(palette)+ }++ private fun systemPaletteIds(): List<Pair<String, Int>> = listOf(+ "accent1_100" to android.R.color.system_accent1_100,+ "accent1_200" to android.R.color.system_accent1_200,+ "accent1_300" to android.R.color.system_accent1_300,+ "accent1_600" to android.R.color.system_accent1_600,+ "accent1_700" to android.R.color.system_accent1_700,+ "accent1_800" to android.R.color.system_accent1_800,+ "accent1_900" to android.R.color.system_accent1_900,+ "neutral1_0" to android.R.color.system_neutral1_0,+ "neutral1_50" to android.R.color.system_neutral1_50,+ "neutral1_600" to android.R.color.system_neutral1_600,+ "neutral1_700" to android.R.color.system_neutral1_700,+ "neutral1_800" to android.R.color.system_neutral1_800,+ "neutral1_900" to android.R.color.system_neutral1_900,+ "neutral2_100" to android.R.color.system_neutral2_100,+ "neutral2_200" to android.R.color.system_neutral2_200,+ "neutral2_300" to android.R.color.system_neutral2_300,+ "neutral2_400" to android.R.color.system_neutral2_400,+ "neutral2_500" to android.R.color.system_neutral2_500,+ "neutral2_600" to android.R.color.system_neutral2_600,+ "neutral2_700" to android.R.color.system_neutral2_700,+ "neutral2_800" to android.R.color.system_neutral2_800+ )+}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 739324fb..4242eb48 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@@ -24,14 +24,17 @@ import com.Colota.service.getDoubleOrNullimport com.Colota.service.getIntOrNullimport com.Colota.service.getStringOrNullimport com.Colota.service.getBooleanOrNull+import com.Colota.sync.SyncStateimport com.Colota.sync.NetworkManagerimport com.Colota.sync.UrlSafetyimport com.Colota.util.DeviceInfoHelperimport com.Colota.export.AutoExportConfigimport com.Colota.export.AutoExportScheduler+import com.Colota.export.AutoExportWorkerimport com.Colota.export.ExportConvertersimport com.Colota.util.AppFileLoggerimport com.Colota.util.FileOperations+import com.Colota.util.LogExportMergerimport com.Colota.util.AppLoggerimport com.Colota.util.SecureStorageHelperimport com.facebook.react.bridge.Arguments@@ -113,6 +116,9 @@ class LocationServiceModule(reactContext: ReactApplicationContext) :companion object {private const val TAG = "LocationServiceModule"+ /** A debug flag outside Settings, so it goes through saveSetting and no ServiceConfig parser. */+ private const val SETTING_LOG_STARTED_AT = "debugFileLoggingStartedAt"+/** JS config key -> secure storage key mapping for saveAuthConfig. */private val AUTH_CONFIG_KEYS = listOf("authType" to SecureStorageHelper.KEY_AUTH_TYPE,@@ -130,6 +136,9 @@ class LocationServiceModule(reactContext: ReactApplicationContext) :@Volatileprivate var activeProfileName: String? = null+ @Volatile+ private var activeProfileId: Int? = null+private inline fun emit(event: String, build: WritableMap.() -> Unit): Boolean {val context = reactContextRef.get() ?: return falseif (!context.hasActiveCatalystInstance()) return false@@ -182,6 +191,7 @@ class LocationServiceModule(reactContext: ReactApplicationContext) :@JvmStaticfun sendProfileSwitchEvent(profileName: String?, profileId: Int?): Boolean {activeProfileName = profileName+ activeProfileId = profileIdreturn emit("onProfileSwitch") {if (profileName != null) putString("profileName", profileName) else putNull("profileName")if (profileId != null) putInt("profileId", profileId) else putNull("profileId")@@ -189,12 +199,19 @@ class LocationServiceModule(reactContext: ReactApplicationContext) :}}+ /** The detached rewrite after a bulk delete has finished, so any size read before it is stale. */@JvmStatic- fun sendSyncProgressEvent(sent: Int, failed: Int, total: Int): Boolean =+ fun sendDatabaseCompactedEvent(success: Boolean): Boolean =+ emit("onDatabaseCompacted") { putBoolean("success", success) }++ /** `remaining` is present only on the event that ends a pass, and is what says the pass ended. */+ @JvmStatic+ fun sendSyncProgressEvent(sent: Int, failed: Int, total: Int, remaining: Int? = null): Boolean =emit("onSyncProgress") {putInt("sent", sent)putInt("failed", failed)putInt("total", total)+ if (remaining != null) putInt("remaining", remaining)}@JvmStatic@@ -347,6 +364,8 @@ class LocationServiceModule(reactContext: ReactApplicationContext) :putInt("total", stats.total)putInt("today", stats.today)putDouble("databaseSizeMB", dbHelper.getDatabaseSizeMB())+ putDouble("lastSyncTime", SyncState.lastSuccessTime.toDouble())+ putString("lastSyncError", SyncState.lastSyncError)}}@@ -401,15 +420,6 @@ class LocationServiceModule(reactContext: ReactApplicationContext) :}}- @ReactMethod- fun insertDummyData(promise: Promise) {- if (!BuildConfig.DEBUG) {- promise.reject("ERR_NOT_DEBUG", "insertDummyData is only available in debug builds")- return- }- executeAsync(promise) { DebugSeedData.insertDummyData(dbHelper) }- }-@ReactMethodfun manualFlush(promise: Promise) {try {@@ -441,9 +451,32 @@ class LocationServiceModule(reactContext: ReactApplicationContext) :deleteThenVacuum(refresh = true) { dbHelper.deleteOlderThan(days) }}+ @ReactMethod+ fun insertDummyData(promise: Promise) {+ if (!BuildConfig.DEBUG) {+ promise.reject("ERR_NOT_DEBUG", "insertDummyData is only available in debug builds")+ return+ }+ executeAsync(promise) { DebugSeedData.insertDummyData(dbHelper) }+ }++ @ReactMethod+ fun countOlderThan(days: Int, promise: Promise) = executeAsync(promise) {+ val counted = dbHelper.countOlderThan(days)+ Arguments.createMap().apply {+ putInt("total", counted.total)+ putDouble("cutoffSeconds", counted.cutoffSeconds.toDouble())+ }+ }++ @ReactMethod+ fun countUnsentOlderThan(days: Int, promise: Promise) = executeAsync(promise) {+ dbHelper.countUnsentOlderThan(days)+ }+@ReactMethodfun deleteLocationsInRange(startTs: Double, endTs: Double, promise: Promise) = executeAsync(promise) {- deleteThenVacuum(refresh = true) { dbHelper.deleteInRange(startTs.toLong(), endTs.toLong()) }+ deleteWithoutVacuum { dbHelper.deleteInRange(startTs.toLong(), endTs.toLong()) }}@ReactMethod@@ -455,17 +488,25 @@ class LocationServiceModule(reactContext: ReactApplicationContext) :val end = r.getDouble("end").toLong()pairs.add(start to end)}- deleteThenVacuum(refresh = true) { dbHelper.deleteInRanges(pairs) }+ deleteWithoutVacuum { dbHelper.deleteInRanges(pairs) }}@ReactMethodfun deleteLocationsByIds(ids: ReadableArray, promise: Promise) = executeAsync(promise) {val locationIds = (0 until ids.size()).map { ids.getDouble(it).toLong() }- val deleted = dbHelper.deleteLocations(locationIds)+ deleteWithoutVacuum { dbHelper.deleteLocations(locationIds) }+ }++ /**+ * Editing a track, not maintaining a database: a point or a trip is a few rows out of millions,+ * and the delete gets repeated. Rewriting the whole file each time holds the one write+ * connection for minutes and stalls the recording service. Compact database is the deliberate+ * rewrite, and its figure is what the user watches move.+ */+ private fun deleteWithoutVacuum(delete: () -> Int): Int {+ val deleted = delete()if (deleted > 0) refreshNotificationIfTracking()- // No vacuum here: a few rows are not worth rewriting the database, and this delete gets- // repeated. Data Management has an explicit Vacuum action.- deleted+ return deleted}@ReactMethod@@ -494,9 +535,11 @@ class LocationServiceModule(reactContext: ReactApplicationContext) :}@ReactMethod- fun vacuumDatabase(promise: Promise) = executeAsync(promise) {- dbHelper.vacuum()- true+ fun vacuumDatabase(promise: Promise) = executeAsync(promise) {+ // Rejecting is what lets the caller say the database was busy. Resolving regardless made a+ // failure look like a rewrite that found nothing to release.+ if (!dbHelper.vacuum()) throw IllegalStateException("The database was busy")+ true}private fun triggerZoneRecheck() {@@ -530,11 +573,20 @@ class LocationServiceModule(reactContext: ReactApplicationContext) :triggerProfileRecheck()}- /** delete() runs inline; vacuum is fire-and-forget so callers return immediately. */+ /**+ * For the bulk deletes on Data management only: rare, deliberate, and asked for by someone who+ * just said to remove a large share of the table. delete() runs inline; vacuum is+ * fire-and-forget so callers return immediately.+ */private fun deleteThenVacuum(refresh: Boolean = false, delete: () -> Int): Int {val deleted = delete()if (refresh) refreshNotificationIfTracking()- moduleScope.launch(Dispatchers.IO) { dbHelper.vacuum() }+ // The rewrite runs detached so the delete returns at once, which leaves the file its old+ // size for as long as it takes. The event is how a caller learns the size it read is stale.+ moduleScope.launch(Dispatchers.IO) {+ val ok = dbHelper.vacuum()+ sendDatabaseCompactedEvent(ok)+ }return deleted}@@ -693,7 +745,15 @@ class LocationServiceModule(reactContext: ReactApplicationContext) :@ReactMethodfun getActiveProfile(promise: Promise) {- promise.resolve(activeProfileName)+ val name = activeProfileName+ if (name == null) {+ promise.resolve(null)+ return+ }+ promise.resolve(Arguments.createMap().apply {+ putString("name", name)+ activeProfileId?.let { putInt("id", it) } ?: putNull("id")+ })}@ReactMethod@@ -924,7 +984,13 @@ class LocationServiceModule(reactContext: ReactApplicationContext) :@ReactMethodfun setFileLoggingEnabled(enabled: Boolean, promise: Promise) = executeAsync(promise) {+ val was = AppFileLogger.isEnabled()dbHelper.saveSetting("debugFileLoggingEnabled", if (enabled) "true" else "false")+ // The arming edge only: a re-enable that was already on must not reset the window.+ if (enabled && !was) {+ dbHelper.saveSetting(SETTING_LOG_STARTED_AT, System.currentTimeMillis().toString())+ }+ if (!enabled) dbHelper.saveSetting(SETTING_LOG_STARTED_AT, "")AppFileLogger.setEnabled(enabled)null}@@ -932,6 +998,11 @@ class LocationServiceModule(reactContext: ReactApplicationContext) :@ReactMethodfun clearFileLog(promise: Promise) = executeAsync(promise) {AppFileLogger.clear()+ // The window described bytes that no longer exist.+ dbHelper.saveSetting(+ SETTING_LOG_STARTED_AT,+ if (AppFileLogger.isEnabled()) System.currentTimeMillis().toString() else ""+ )null}@@ -941,7 +1012,12 @@ class LocationServiceModule(reactContext: ReactApplicationContext) :}@ReactMethod- fun exportFileLogToUri(treeUriString: String, promise: Promise) = executeAsync(promise) {+ fun exportFileLogToUri(+ treeUriString: String,+ header: String,+ appLog: String,+ promise: Promise,+ ) = executeAsync(promise) {AppFileLogger.flushNow()// Oldest segment first so the exported file reads chronologically.val sources = AppFileLogger.logFiles()@@ -958,14 +1034,17 @@ class LocationServiceModule(reactContext: ReactApplicationContext) :?: throw Exception("Could not create document in selected directory")reactApplicationContext.contentResolver.openOutputStream(doc.uri)?.use { output ->- for (source in sources) {- source.inputStream().use { input -> input.copyTo(output) }+ output.write(header.toByteArray())+ output.bufferedWriter().let { writer ->+ LogExportMerger.merge(sources, appLog, writer)+ writer.flush()}} ?: throw Exception("Could not open output stream")doc.uri.toString()}+// =========================================================================// AUTO-EXPORT// =========================================================================@@ -1040,6 +1119,7 @@ class LocationServiceModule(reactContext: ReactApplicationContext) :Arguments.createMap().apply {putBoolean("enabled", config.enabled)+ putBoolean("running", AutoExportWorker.isRunning)putString("format", config.format)putString("interval", config.interval)putString("uri", config.uri)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 088aacaf..e5bd775d 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@@ -874,12 +874,45 @@ class DatabaseHelper private constructor(context: Context) :return out}+ /** The boundary a retention age names, in seconds. The preview and the delete must share it or they drift. */+ /**+ * The boundary a retention age names, snapped to the start of that local day. A rolling instant+ * would move between the count and the delete the user then confirms, so the delete would take+ * slightly more than the confirmation named. Snapped, the boundary holds still, and the date the+ * confirmation prints is the whole of what goes.+ */+ private fun cutoffFor(days: Int): Long =+ LocalDate.now().minusDays(days.toLong()).atStartOfDay(ZoneId.systemDefault()).toEpochSecond()+fun deleteOlderThan(days: Int): Int {requireNotRestoring()- val cutoff = (System.currentTimeMillis() - days.toLong() * 24 * 60 * 60 * 1000) / 1000- return writableDatabase.delete(TABLE_LOCATIONS, "timestamp < ?", arrayOf(cutoff.toString()))+ return writableDatabase.delete(TABLE_LOCATIONS, "timestamp < ?", arrayOf(cutoffFor(days).toString()))}+ /** What `deleteOlderThan(days)` would take, and the boundary it would take it at. */+ data class OlderThan(val total: Int, val cutoffSeconds: Long)++ /** Cheap: the timestamp index answers this without reading the table. Safe to call as the user types. */+ fun countOlderThan(days: Int): OlderThan {+ requireNotRestoring()+ val cutoff = cutoffFor(days)+ return OlderThan(countWhereOlder("", arrayOf(cutoff.toString())), cutoff)+ }++ /**+ * Expensive: `sent` is not in any index, so this reads every matching row. Call it once, when a+ * delete is actually pressed, never on the way to one.+ */+ fun countUnsentOlderThan(days: Int): Int {+ requireNotRestoring()+ return countWhereOlder(" AND sent = 0", arrayOf(cutoffFor(days).toString()))+ }++ private fun countWhereOlder(extra: String, args: Array<String>): Int =+ readableDatabase.rawQuery("SELECT COUNT(*) FROM $TABLE_LOCATIONS WHERE timestamp < ?$extra", args).use {+ if (it.moveToFirst()) it.getInt(0) else 0+ }+fun deleteInRange(startTs: Long, endTs: Long): Int {requireNotRestoring()return writableDatabase.delete(@@ -912,15 +945,18 @@ class DatabaseHelper private constructor(context: Context) :}/** Reclaims unused space. Call from background thread only. */- fun vacuum() {+ /** False when the rewrite did not happen, so a caller cannot report a failure as nothing to release. */+ fun vacuum(): Boolean {requireNotRestoring()AppLogger.d(TAG, "Starting VACUUM + ANALYZE")- try {+ return try {writableDatabase.execSQL("VACUUM")writableDatabase.execSQL("ANALYZE")AppLogger.d(TAG, "VACUUM + ANALYZE completed")+ true} catch (e: Exception) {AppLogger.e(TAG, "Vacuum failed (likely concurrent access)", e)+ false}}diff --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 4c24c3b6..8eaaeb29 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@@ -56,7 +56,7 @@ class ProfileHelper(private val context: Context) {),"enabled = 1",null, null, null,- "priority DESC"+ "priority DESC, id ASC").use { cursor ->val idIdx = cursor.getColumnIndexOrThrow("id")val nameIdx = cursor.getColumnIndexOrThrow("name")@@ -98,7 +98,7 @@ class ProfileHelper(private val context: Context) {dbHelper.readableDatabase.query(DatabaseHelper.TABLE_PROFILES,null, null, null, null, null,- "priority DESC"+ "priority DESC, id ASC").use { cursor ->val idIdx = cursor.getColumnIndexOrThrow("id")val nameIdx = cursor.getColumnIndexOrThrow("name")diff --git a/apps/mobile/android/app/src/main/java/com/colota/export/AutoExportScheduler.kt b/apps/mobile/android/app/src/main/java/com/colota/export/AutoExportScheduler.ktindex c9fdc5eb..f277b3a6 100644--- a/apps/mobile/android/app/src/main/java/com/colota/export/AutoExportScheduler.kt+++ b/apps/mobile/android/app/src/main/java/com/colota/export/AutoExportScheduler.kt@@ -10,6 +10,7 @@ import android.app.PendingIntentimport android.content.Contextimport android.content.Intentimport androidx.annotation.WorkerThread+import androidx.work.ExistingWorkPolicyimport androidx.work.OneTimeWorkRequestBuilderimport androidx.work.WorkManagerimport com.Colota.data.DatabaseHelper@@ -55,7 +56,8 @@ object AutoExportScheduler {val request = OneTimeWorkRequestBuilder<AutoExportWorker>().addTag(IMMEDIATE_WORK_TAG).build()- WorkManager.getInstance(context.applicationContext).enqueue(request)+ WorkManager.getInstance(context.applicationContext)+ .enqueueUniqueWork(IMMEDIATE_WORK_TAG, ExistingWorkPolicy.KEEP, request)AppLogger.i(TAG, "Enqueued immediate auto-export")}diff --git a/apps/mobile/android/app/src/main/java/com/colota/export/AutoExportWorker.kt b/apps/mobile/android/app/src/main/java/com/colota/export/AutoExportWorker.ktindex f33edb63..4c5f0f73 100644--- a/apps/mobile/android/app/src/main/java/com/colota/export/AutoExportWorker.kt+++ b/apps/mobile/android/app/src/main/java/com/colota/export/AutoExportWorker.kt@@ -98,13 +98,14 @@ class AutoExportWorker(val db = DatabaseHelper.getInstance(appContext)val config = AutoExportConfig.from(db)- if (!config.enabled) {+ if (!config.enabled && !isManualRun) {AppLogger.d(TAG, "Auto-export is disabled, skipping")return Result.success()}if (config.uri == null) {AppLogger.e(TAG, "No export directory configured")+ if (isManualRun) LocationServiceModule.sendAutoExportEvent(false, null, 0, "No export directory configured")return Result.failure()}@@ -163,6 +164,7 @@ class AutoExportWorker(AppLogger.i(TAG, "No locations to export")showNotification("Auto-Export", "No new locations to export.")cleanupOldExports(dirUri, config)+ if (isManualRun) LocationServiceModule.sendAutoExportEvent(true, null, 0, null)return Result.success()}diff --git a/apps/mobile/android/app/src/main/java/com/colota/export/ExportConverters.kt b/apps/mobile/android/app/src/main/java/com/colota/export/ExportConverters.ktindex 9fdc8a1c..d22dea35 100644--- a/apps/mobile/android/app/src/main/java/com/colota/export/ExportConverters.kt+++ b/apps/mobile/android/app/src/main/java/com/colota/export/ExportConverters.kt@@ -47,49 +47,6 @@ class KmlCoordsCollector(cacheDir: File) : AutoCloseable {}}-/** Spools the property columns to temp files (they trail the coords in the JSON) so large exports stay O(1) memory, like [KmlCoordsCollector]. */-class GeoJsonColumnSpooler(cacheDir: File, private val columns: List<String>) : AutoCloseable {- // Per-instance name so two exports in the same dir don't share temp files.- private val files = columns.associateWith { File(cacheDir, "geojson_col_${System.identityHashCode(this)}_$it.txt") }- private val writers = files.mapValues { BufferedWriter(FileWriter(it.value)) }- var count = 0- private set-- /** `tokens`: pre-formatted JSON values, one per column in [columns] order. */- fun addRow(tokens: List<String>) {- columns.forEachIndexed { i, name ->- val w = writers.getValue(name)- w.write(tokens[i])- w.newLine()- }- count++- }-- fun writeProperties(w: Writer) {- writers.values.forEach { it.close() }- columns.forEachIndexed { idx, name ->- // Stream each token straight to the output (like KmlCoordsCollector.writeTo) rather than- // building the whole column string first, so peak memory is one token, not one column.- w.write(" \"$name\": [")- var first = true- BufferedReader(FileReader(files.getValue(name))).use { reader ->- reader.forEachLine { line ->- if (!first) w.write(", ")- w.write(line)- first = false- }- }- w.write("]")- w.write(if (idx < columns.size - 1) ",\n" else "\n")- }- }-- override fun close() {- writers.values.forEach { try { it.close() } catch (_: Exception) {} }- files.values.forEach { it.delete() }- }-}-object ExportConverters {const val PAGE_SIZE = 10_000@@ -373,45 +330,43 @@ object ExportConverters {override fun writeFooter(w: Writer, sink: AutoCloseable?) {}}- // The whole export is one MultiPoint feature: coords stream inline while the property columns- // (parallel arrays, index-aligned to coords) spool to disk and splice in at the footer, keeping memory O(1).+ /**+ * One Point feature per location, which is what every GIS reads. The whole export used to be a+ * single MultiPoint feature with the properties as parallel arrays: legal GeoJSON, but only+ * Colota's own parser understood it. GDAL reports such a file as one feature with every+ * attribute an opaque JSON string, and refuses it outright past `OGR_GEOJSON_MAX_OBJ_SIZE`,+ * which defaults to 200 MB and a full database exceeds.+ *+ * A self-contained feature also streams more simply than the columnar shape did: nothing has to+ * spool to disk and splice in at the footer, and memory stays O(1) without a side channel.+ */private object GeoJsonFormat : FormatWriter(".geojson", "application/geo+json") {- private val COLUMNS = listOf("accuracy", "altitude", "speed", "bearing", "battery", "battery_status", "note", "time")-- override fun newSideChannel(cacheDir: File): AutoCloseable = GeoJsonColumnSpooler(cacheDir, COLUMNS)-override fun writeHeader(w: Writer) {w.write("{\n \"type\": \"FeatureCollection\",\n \"features\": [")}override fun writeRow(w: Writer, row: ExportRow, globalIndex: Int, sink: AutoCloseable?) {- val coord = "[${jsNum(row.lon)}, ${jsNum(row.lat)}]"- if (globalIndex == 0) {- w.write("\n {\n \"type\": \"Feature\",\n \"geometry\": {\n \"type\": \"MultiPoint\",\n \"coordinates\": [\n $coord")- } else {- w.write(",\n $coord")+ if (globalIndex > 0) w.write(",")+ w.write("\n {\n \"type\": \"Feature\",\n \"geometry\": {\n \"type\": \"Point\",")+ w.write("\n \"coordinates\": [${jsNum(row.lon)}, ${jsNum(row.lat)}]\n },")+ w.write("\n \"properties\": {")+ // A null property is omitted rather than written, so a reader gets no field instead of a+ // null one, and the file loses the columns that are empty for most rows.+ val props = mutableListOf<String>()+ fun put(key: String, value: String) {+ if (value != "null") props.add("\"$key\": $value")}- // Order must match COLUMNS.- (sink as? GeoJsonColumnSpooler)?.addRow(listOf(- jsonValue(row.accuracy),- jsonValue(row.altitude),- jsonValue(row.speed),- jsonValue(row.bearing),- jsonValue(row.battery),- jsonValue(batteryStatusLabel(row.batteryStatus)),- jsonValue(row.note),- "\"${isoTime(row.ts)}\"",- ))+ put("time", "\"${isoTime(row.ts)}\"")+ put("accuracy", jsonValue(row.accuracy))+ put("altitude", jsonValue(row.altitude))+ put("speed", jsonValue(row.speed))+ put("bearing", jsonValue(row.bearing))+ put("battery", jsonValue(row.battery))+ put("battery_status", jsonValue(batteryStatusLabel(row.batteryStatus)))+ put("note", jsonValue(row.note))+ w.write(props.joinToString(", ", "\n ", "\n }\n }"))}override fun writeFooter(w: Writer, sink: AutoCloseable?) {- val spool = sink as? GeoJsonColumnSpooler- if (spool == null || spool.count == 0) {- // No points: keep it a valid, empty FeatureCollection rather than an empty MultiPoint.- w.write("]\n}\n")- return- }- w.write("\n ]\n },\n \"properties\": {\n")- spool.writeProperties(w)- w.write(" }\n }\n ]\n}\n")+ w.write("\n ]\n}\n")}}@@ -676,37 +631,39 @@ object ExportConverters {return sb.toString()}- // One MultiPoint feature per trip. In-memory (not spooled like the flat export) is fine - trips are day-sized.+ /**+ * One Point feature per location, carrying the trip number it belongs to, so a GIS can colour+ * or filter by trip. The columnar MultiPoint this replaced put every attribute of a whole trip+ * into one feature, which reads back as a single unqueryable row.+ */private fun tripsToGeoJson(trips: List<TripExport>): String {val features = ArrayList<String>()for (trip in trips) {- if (trip.rows.isEmpty()) continue- val coords = trip.rows.joinToString(",\n ") {- "[${numOrZero(it["longitude"])}, ${numOrZero(it["latitude"])}]"+ for (row in trip.rows) {+ val props = mutableListOf("\"trip\": ${trip.index}", "\"time\": \"${isoTime(rowTs(row))}\"")+ fun put(key: String, value: String) {+ if (value != "null") props.add("\"$key\": $value")+ }+ put("accuracy", jsonNum(row["accuracy"]))+ put("altitude", jsonNum(row["altitude"]))+ put("speed", jsonNum(row["speed"]))+ put("bearing", jsonNum(row["bearing"]))+ put("battery", jsonNum(row["battery"]))+ put("battery_status", jsonValue(batteryStatusLabel(row["battery_status"])))+ put("note", jsonValue(row["note"]))+ features.add(+ " {\n" ++ " \"type\": \"Feature\",\n" ++ " \"geometry\": {\n" ++ " \"type\": \"Point\",\n" ++ " \"coordinates\": [${numOrZero(row["longitude"])}, ${numOrZero(row["latitude"])}]\n" ++ " },\n" ++ " \"properties\": {\n" ++ " ${props.joinToString(", ")}\n" ++ " }\n" ++ " }"+ )}- fun col(transform: (Map<String, Any?>) -> String) = trip.rows.joinToString(", ", transform = transform)- features.add(- " {\n" +- " \"type\": \"Feature\",\n" +- " \"geometry\": {\n" +- " \"type\": \"MultiPoint\",\n" +- " \"coordinates\": [\n" +- " $coords\n" +- " ]\n" +- " },\n" +- " \"properties\": {\n" +- " \"trip\": ${trip.index},\n" +- " \"accuracy\": [${col { jsonNum(it["accuracy"]) }}],\n" +- " \"altitude\": [${col { jsonNum(it["altitude"]) }}],\n" +- " \"speed\": [${col { jsonNum(it["speed"]) }}],\n" +- " \"bearing\": [${col { jsonNum(it["bearing"]) }}],\n" +- " \"battery\": [${col { jsonNum(it["battery"]) }}],\n" +- " \"battery_status\": [${col { jsonValue(batteryStatusLabel(it["battery_status"])) }}],\n" +- " \"note\": [${col { jsonValue(it["note"]) }}],\n" +- " \"time\": [${col { "\"${isoTime(rowTs(it))}\"" }}]\n" +- " }\n" +- " }"- )}val featuresBlock = if (features.isEmpty()) "[]" else "[\n${features.joinToString(",\n")}\n ]"return "{\n \"type\": \"FeatureCollection\",\n \"features\": $featuresBlock\n}"diff --git a/apps/mobile/android/app/src/main/java/com/colota/importer/GeoJsonParser.kt b/apps/mobile/android/app/src/main/java/com/colota/importer/GeoJsonParser.ktindex 0c1290dd..7d150d5f 100644--- a/apps/mobile/android/app/src/main/java/com/colota/importer/GeoJsonParser.kt+++ b/apps/mobile/android/app/src/main/java/com/colota/importer/GeoJsonParser.kt@@ -10,8 +10,17 @@ import android.util.JsonTokenimport java.io.InputStreamimport java.util.concurrent.atomic.AtomicBoolean-/** Streaming GeoJSON parser. Reads Point (scalar props) or MultiPoint (columnar, parallel-array- * props) features from a FeatureCollection; other geometries are counted invalid and skipped. */+/**+ * Streaming GeoJSON parser over a FeatureCollection. Other geometries are counted invalid and skipped.+ *+ * Two shapes are read, and both are permanent:+ * - Point with scalar properties, which is what every tool writes and what Colota now exports.+ * - MultiPoint with parallel-array properties, index-aligned to the coordinates. Only Colota ever+ * wrote that, in 1.12.0 through 1.16.0, and the docs of the day called GeoJSON the format to back+ * up with. Such a file can be the last copy of data since deleted from the device, so this reader+ * does not get removed. It costs one branch: a scalar becomes a single-element list, so both+ * shapes run through the same zip-by-index loop below.+ */object GeoJsonParser {fun parse(diff --git a/apps/mobile/android/app/src/main/java/com/colota/sync/NetworkManager.kt b/apps/mobile/android/app/src/main/java/com/colota/sync/NetworkManager.ktindex 6aff5a2f..c3792205 100644--- a/apps/mobile/android/app/src/main/java/com/colota/sync/NetworkManager.kt+++ b/apps/mobile/android/app/src/main/java/com/colota/sync/NetworkManager.kt@@ -412,11 +412,11 @@ class NetworkManager(private val context: Context) {return when {isServerNotTrusted ->- "Server certificate is not trusted (self-signed or unknown CA). Import the server's CA via mTLS Settings, or use a publicly-trusted certificate."+ "Server certificate is not trusted (self-signed or unknown CA). Import the server's CA under Connection > Client certificate, or use a publicly trusted certificate."isClientRejected && hasClientCert ->"Server rejected the client certificate. Common causes: cert signed by wrong CA, cert expired, or cert revoked."isClientRejected && !hasClientCert ->- "Server requires a client certificate (mTLS) but none is configured. Import a .p12 in Auth Settings."+ "Server requires a client certificate (mutual TLS) but none is configured. Add one under Connection > Client certificate."else ->"TLS handshake failed: ${e.message ?: e.javaClass.simpleName}"}diff --git a/apps/mobile/android/app/src/main/java/com/colota/sync/SyncManager.kt b/apps/mobile/android/app/src/main/java/com/colota/sync/SyncManager.ktindex 592a480e..8a74b553 100644--- a/apps/mobile/android/app/src/main/java/com/colota/sync/SyncManager.kt+++ b/apps/mobile/android/app/src/main/java/com/colota/sync/SyncManager.kt@@ -44,6 +44,12 @@ class SyncManager(@Volatile private var lastSyncTime: Long = 0@Volatile var lastSuccessfulSyncTime: Long = 0private set++ private fun markSuccess() {+ val now = System.currentTimeMillis()+ lastSuccessfulSyncTime = now+ SyncState.recordSuccess(now)+ }@Volatile private var syncInitialized = false@Volatile private var consecutiveFailures = 0@@ -52,6 +58,9 @@ class SyncManager(/** One pass at a time: two passes fetch the same oldest rows and post each of them twice. */private val syncMutex = Mutex()+ /** Set while a manual flush waits on [syncMutex]; the running pass reports to its screen, which gives up on silence. */+ @Volatile private var waitingFlushTotal: Int? = null+/** Queue rows an instant send is posting; a pass skips them instead of posting them a second time. */private val instantInFlight: MutableSet<Long> = ConcurrentHashMap.newKeySet()@@ -120,6 +129,7 @@ class SyncManager(if (errorMessage != null) {consecutiveFailures++if (consecutiveFailures >= 3) {+ SyncState.recordError(AppLogger.maskSensitiveUrlValues(errorMessage))LocationServiceModule.sendSyncErrorEvent("$errorMessage ($consecutiveFailures consecutive failures)",getCachedQueuedCount()@@ -139,13 +149,28 @@ class SyncManager(}suspend fun manualFlush() {- if (endpoint.isNotBlank()) {- if (syncMutex.isLocked) AppLogger.d(TAG, "Manual flush waiting for the running sync")+ if (endpoint.isBlank()) return+ if (syncMutex.isLocked) AppLogger.d(TAG, "Manual flush waiting for the running sync")+ waitingFlushTotal = dbHelper.getQueuedCount()+ var total = 0+ var pass = SyncPass(0, 0)+ try {syncMutex.withLock {- val total = dbHelper.getQueuedCount()+ waitingFlushTotal = null+ total = dbHelper.getQueuedCount()AppLogger.d(TAG, "Manual flush started: $total items in queue")- syncQueue { sent, failed -> LocationServiceModule.sendSyncProgressEvent(sent, failed, total) }+ pass = syncQueue { sent, failed -> LocationServiceModule.sendSyncProgressEvent(sent, failed, total) }}+ } finally {+ waitingFlushTotal = null+ // A pass caps at MAX_BATCHES_PER_SYNC and stops when a batch moves nothing, so the+ // running count need not reach the queue it started with. Only this event ends the pass,+ // and a throw or a cancellation, even one while waiting for the lock, must still send it or+ // the caller waits out its own timeout and reports a failure over an upload that worked.+ // The totals come from the pass, not from the last progress tick.+ invalidateQueueCache()+ val remaining = runCatching { dbHelper.getQueuedCount() }.getOrDefault(total - pass.sent)+ LocationServiceModule.sendSyncProgressEvent(pass.sent, pass.failed, total, remaining)}}@@ -180,7 +205,7 @@ class SyncManager(dbHelper.markLocationsSent(listOf(locationId))dbHelper.removeFromQueueByLocationId(locationId)invalidateQueueCache()- lastSuccessfulSyncTime = System.currentTimeMillis()+ markSuccess()} else {dbHelper.incrementRetryCount(queueId, "Send failed")}@@ -219,7 +244,7 @@ class SyncManager(// A pass that only skipped rows an instant send was still posting did not failval success = countAfter < countBefore || countAfter == 0 || (pass.sent + pass.failed == 0 && pass.skippedInFlight > 0)if (success && countAfter == 0) {- lastSuccessfulSyncTime = System.currentTimeMillis()+ markSuccess()}return success@@ -239,6 +264,9 @@ class SyncManager(delay(backoffSeconds * 1000L)}+ /** What one pass moved. It caps at [MAX_BATCHES_PER_SYNC], so it need not empty the queue. */+ data class SyncPass(val sent: Int, val failed: Int, val skippedInFlight: Int = 0)+private suspend fun syncQueue(onProgress: ((sent: Int, failed: Int) -> Unit)? = null): SyncPass = coroutineScope {// Snapshot volatile config so it stays consistent for the entire sync passval currentEndpoint = endpoint@@ -252,6 +280,12 @@ class SyncManager(var skippedInFlight = 0var batchNumber = 1+ // Every chunk reports, sent or not: silence reads as a dead service and frees Sync Now mid-pass+ fun reportProgress() {+ if (onProgress != null) onProgress(totalSucceeded, totalFailed)+ else waitingFlushTotal?.let { LocationServiceModule.sendSyncProgressEvent(totalSucceeded, totalFailed, it) }+ }+while (isActive && batchNumber <= MAX_BATCHES_PER_SYNC) {val fetchSize = if (currentApiFormat == ApiFormat.OVERLAND_BATCH) currentBatchSize else 50val fetched = dbHelper.getQueuedLocations(fetchSize)@@ -274,7 +308,7 @@ class SyncManager(totalProcessed += result.processedtotalSucceeded += result.processedtotalFailed += result.failed- if (result.processed > 0) onProgress?.invoke(totalSucceeded, totalFailed)+ reportProgress()if (result.stop) {AppLogger.d(TAG, "Sync pass aborted by transport failure")break@@ -318,8 +352,8 @@ class SyncManager(totalProcessed += successfulIds.sizetotalSucceeded += successfulIds.size- onProgress?.invoke(totalSucceeded, totalFailed)}+ reportProgress()yield()}@@ -341,14 +375,12 @@ class SyncManager(invalidateQueueCache()if (totalSucceeded > 0) {- lastSuccessfulSyncTime = System.currentTimeMillis()+ markSuccess()}SyncPass(totalSucceeded, totalFailed, skippedInFlight)}- data class SyncPass(val sent: Int, val failed: Int, val skippedInFlight: Int = 0)-private data class BatchSendResult(val processed: Int, val failed: Int, val stop: Boolean)/**diff --git a/apps/mobile/android/app/src/main/java/com/colota/sync/SyncState.kt b/apps/mobile/android/app/src/main/java/com/colota/sync/SyncState.ktnew file mode 100644index 00000000..90e37c96--- /dev/null+++ b/apps/mobile/android/app/src/main/java/com/colota/sync/SyncState.kt@@ -0,0 +1,33 @@+/**+ * Copyright (C) 2026 Max Dietrich+ * Licensed under the GNU AGPLv3. See LICENSE in the project root for details.+ */++package com.Colota.sync++/**+ * What the last sync passes learned, readable from the bridge without a handle on the service's+ * SyncManager: the time of the last success and the masked message of the last failure that+ * crossed the consecutive-failure gate, cleared on the next success.+ */+object SyncState {+ @Volatile var lastSuccessTime: Long = 0L+ private set++ @Volatile var lastSyncError: String = ""+ private set++ fun recordSuccess(timeMs: Long) {+ lastSuccessTime = timeMs+ lastSyncError = ""+ }++ fun recordError(message: String) {+ lastSyncError = message+ }++ fun reset() {+ lastSuccessTime = 0L+ lastSyncError = ""+ }+}diff --git a/apps/mobile/android/app/src/main/java/com/colota/util/LogExportMerger.kt b/apps/mobile/android/app/src/main/java/com/colota/util/LogExportMerger.ktnew file mode 100644index 00000000..a3cabc61--- /dev/null+++ b/apps/mobile/android/app/src/main/java/com/colota/util/LogExportMerger.kt@@ -0,0 +1,56 @@+/*+ * Copyright (C) 2026 Max Dietrich+ * Licensed under the GNU AGPLv3. See LICENSE in the project root for details.+ */++package com.Colota.util++import java.io.File+import java.io.Writer++/**+ * Interleaves the JS ring buffer into the recorded log segments by timestamp while streaming them.+ *+ * The merge belongs here and not in JS because `getNativeLogs` only hands JS a capped tail of the+ * segments, so a JS-side merge would truncate the file it is meant to complete. Only the app log is+ * buffered, and the ring buffer bounds it.+ */+object LogExportMerger {++ /** "yyyy-MM-dd HH:mm:ss.SSS", the fixed prefix AppFileLogger writes on every line it owns. */+ private const val STAMP_LENGTH = 23++ fun merge(sources: List<File>, appLog: String, writer: Writer) {+ val pending = ArrayDeque(if (appLog.isEmpty()) emptyList() else appLog.trimEnd('\n').split("\n"))++ for (source in sources) {+ source.bufferedReader().use { reader ->+ reader.forEachLine { line ->+ val stamp = stampOf(line)+ if (stamp != null) drainUpTo(stamp, pending, writer)+ writer.appendLine(line)+ }+ }+ }++ // Everything written since the last flush, which has no recorded line to sort against.+ while (pending.isNotEmpty()) writer.appendLine(pending.removeFirst())+ }++ private fun drainUpTo(stamp: String, pending: ArrayDeque<String>, writer: Writer) {+ while (true) {+ val head = pending.firstOrNull() ?: return+ // Unplaceable without a stamp, so it waits for the tail rather than jumping ahead.+ val headStamp = stampOf(head) ?: return+ if (headStamp > stamp) return+ writer.appendLine(pending.removeFirst())+ }+ }++ /** Null for a continuation, so a stack frame stays under the line that threw it. */+ fun stampOf(line: String): String? {+ if (line.length < STAMP_LENGTH) return null+ if (line[4] != '-' || line[7] != '-' || line[10] != ' ' || line[13] != ':' || line[16] != ':') return null+ return line.substring(0, STAMP_LENGTH)+ }+}diff --git a/apps/mobile/android/app/src/test/java/com/Colota/backup/BackupRestorerTest.kt b/apps/mobile/android/app/src/test/java/com/Colota/backup/BackupRestorerTest.ktindex e7f40cc8..fc23c995 100644--- a/apps/mobile/android/app/src/test/java/com/Colota/backup/BackupRestorerTest.kt+++ b/apps/mobile/android/app/src/test/java/com/Colota/backup/BackupRestorerTest.kt@@ -86,6 +86,36 @@ class BackupRestorerTest {assertEquals("dark", DatabaseHelper.getInstance(context).getSetting("themeMode"))}+ @Test+ fun `describe reads the manifest and replaces nothing`() {+ seedDatabase(latPrefix = 51.0)+ val backup = backupBytes()+ val before = countLocations()++ val manifest = restorer.describe(ByteArrayInputStream(backup), password)++ assertEquals(DatabaseHelper.DATABASE_VERSION, manifest.getJSONObject("schema").getInt("db"))+ assertTrue(manifest.getString("createdAt").isNotEmpty())+ assertEquals(before, countLocations())+ }++ // A wrong password has to fail here, before anything is stopped or swapped.+ @Test+ fun `describe rejects a wrong password and leaves the database untouched`() {+ seedDatabase(latPrefix = 51.0)+ val backup = backupBytes()+ val before = countLocations()++ try {+ restorer.describe(ByteArrayInputStream(backup), "not-the-password".toCharArray())+ fail("expected a wrong password to be rejected")+ } catch (e: BackupException) {+ assertEquals(BackupError.WRONG_PASSWORD, e.error)+ }++ assertEquals(before, countLocations())+ }+@Testfun `restore re-imports secrets via SecureStorageHelper`() {seedDatabase(latPrefix = 51.0)diff --git a/apps/mobile/android/app/src/test/java/com/Colota/bridge/BuildConfigModuleTest.kt b/apps/mobile/android/app/src/test/java/com/Colota/bridge/BuildConfigModuleTest.ktnew file mode 100644index 00000000..9542cf67--- /dev/null+++ b/apps/mobile/android/app/src/test/java/com/Colota/bridge/BuildConfigModuleTest.kt@@ -0,0 +1,94 @@+/**+ * Copyright (C) 2026 Max Dietrich+ * Licensed under the GNU AGPLv3. See LICENSE in the project root for details.+ */++package com.Colota.bridge++import android.content.Context+import androidx.test.core.app.ApplicationProvider+import com.facebook.react.bridge.Arguments+import com.facebook.react.bridge.BridgeReactContext+import com.facebook.react.bridge.JavaOnlyMap+import com.facebook.react.bridge.Promise+import com.facebook.react.bridge.WritableMap+import io.mockk.every+import io.mockk.mockk+import io.mockk.mockkStatic+import io.mockk.unmockkStatic+import org.junit.After+import org.junit.Assert.assertEquals+import org.junit.Assert.assertNull+import org.junit.Assert.assertTrue+import org.junit.Before+import org.junit.Test+import org.junit.runner.RunWith+import org.robolectric.RobolectricTestRunner+import org.robolectric.annotation.Config++@RunWith(RobolectricTestRunner::class)+class BuildConfigModuleTest {++ private lateinit var module: BuildConfigModule+ private var resolved: Any? = NOT_SETTLED++ // The theme reads exactly these steps. One dropped here is an undefined colour in a style prop+ // on the JS side, so the set is asserted rather than sampled.+ private val expectedSteps = setOf(+ "accent1_100", "accent1_200", "accent1_300", "accent1_600", "accent1_700", "accent1_800",+ "accent1_900",+ "neutral1_0", "neutral1_50", "neutral1_600", "neutral1_700", "neutral1_800", "neutral1_900",+ "neutral2_100", "neutral2_200", "neutral2_300", "neutral2_400", "neutral2_500",+ "neutral2_600", "neutral2_700", "neutral2_800"+ )++ @Before+ fun setUp() {+ // WritableNativeMap needs the RN native lib, which no unit test has.+ mockkStatic(Arguments::class)+ every { Arguments.createMap() } answers { JavaOnlyMap() }+ val context: Context = ApplicationProvider.getApplicationContext()+ module = BuildConfigModule(BridgeReactContext(context))+ resolved = NOT_SETTLED+ }++ @After+ fun tearDown() {+ unmockkStatic(Arguments::class)+ }++ @Test+ fun `resolves every tonal step the theme reads`() {+ module.getSystemPalette(capturingPromise())++ assertEquals(expectedSteps, (resolved as WritableMap).toHashMap().keys)+ }++ @Test+ fun `resolves opaque six-digit hex, because the theme appends its own alpha`() {+ module.getSystemPalette(capturingPromise())++ for ((step, value) in (resolved as WritableMap).toHashMap()) {+ assertTrue("$step is $value", Regex("^#[0-9A-F]{6}$").matches(value as String))+ }+ }++ @Test+ @Config(sdk = [30])+ fun `resolves null below API 31, where the framework has no wallpaper palette`() {+ module.getSystemPalette(capturingPromise())++ assertNull(resolved)+ }++ private fun capturingPromise(): Promise {+ val promise = mockk<Promise>()+ every { promise.resolve(any()) } answers { resolved = firstArg<Any?>() }+ return promise+ }++ private companion object {+ // Distinguishes "resolved with null" from "never settled", which assertNull cannot.+ val NOT_SETTLED = Any()+ }+}diff --git a/apps/mobile/android/app/src/test/java/com/Colota/bridge/LocationServiceModuleTest.kt b/apps/mobile/android/app/src/test/java/com/Colota/bridge/LocationServiceModuleTest.ktindex 7507e6b7..9e77013e 100644--- a/apps/mobile/android/app/src/test/java/com/Colota/bridge/LocationServiceModuleTest.kt+++ b/apps/mobile/android/app/src/test/java/com/Colota/bridge/LocationServiceModuleTest.kt@@ -5,7 +5,9 @@package com.Colota.bridge+import android.content.Contextimport android.content.Intent+import android.net.ConnectivityManagerimport android.location.Locationimport com.Colota.data.DatabaseHelperimport com.Colota.data.GeofenceHelper@@ -13,9 +15,13 @@ import com.Colota.data.ProfileHelperimport com.Colota.service.LocationForegroundServiceimport com.Colota.service.TrackingWatchdogSchedulerimport com.Colota.util.AppLogger+import com.Colota.util.SecureStorageHelperimport com.Colota.util.DeviceInfoHelperimport com.facebook.react.bridge.Arguments+import com.facebook.react.bridge.JavaOnlyArrayimport com.facebook.react.bridge.JavaOnlyMap+import com.facebook.react.bridge.Promise+import com.facebook.react.bridge.WritableMapimport com.facebook.react.bridge.ReactApplicationContextimport com.facebook.react.modules.core.DeviceEventManagerModuleimport io.mockk.*@@ -24,6 +30,8 @@ import org.junit.Assert.*import org.junit.Beforeimport org.junit.Testimport java.lang.ref.WeakReference+import java.util.concurrent.CountDownLatch+import java.util.concurrent.TimeUnit/*** Tests for LocationServiceModule:@@ -53,9 +61,18 @@ class LocationServiceModuleTest {every { AppLogger.e(any(), any(), any()) } just RunsmockkStatic(Arguments::class)- every { Arguments.createMap() } returns JavaOnlyMap()+ // A fresh map per call. One shared instance makes every emitted payload look identical, so+ // an assertion about what one event carries silently reads what a later one wrote.+ every { Arguments.createMap() } answers { JavaOnlyMap() }++ // NetworkManager casts this in a field initialiser, and a relaxed mock hands back an Object.+ every { mockContext.getSystemService(Context.CONNECTIVITY_SERVICE) } returns mockk<ConnectivityManager>(relaxed = true)mockkObject(DatabaseHelper.Companion)+ // The module builds one in a field initialiser, and it opens an encrypted keystore a plain+ // JVM has no keys for, so constructing the module needs this stubbed.+ mockkObject(SecureStorageHelper.Companion)+ every { SecureStorageHelper.getInstance(any()) } returns mockk(relaxed = true)mockkObject(LocationForegroundService.Companion)every { LocationForegroundService.isRunning } returns true@@ -68,6 +85,7 @@ class LocationServiceModuleTest {setCompanionField("reactContextRef", WeakReference(mockContext))setCompanionField("isAppInForeground", true)setCompanionField("activeProfileName", null)+ setCompanionField("activeProfileId", null)}@After@@ -75,11 +93,13 @@ class LocationServiceModuleTest {unmockkObject(AppLogger)unmockkStatic(Arguments::class)unmockkObject(DatabaseHelper.Companion)+ unmockkObject(SecureStorageHelper.Companion)unmockkObject(LocationForegroundService.Companion)unmockkObject(TrackingWatchdogScheduler)setCompanionField("reactContextRef", WeakReference<ReactApplicationContext>(null))setCompanionField("isAppInForeground", true)setCompanionField("activeProfileName", null)+ setCompanionField("activeProfileId", null)}// ========================================================================@@ -162,16 +182,19 @@ class LocationServiceModuleTest {// ========================================================================@Test- fun `sendProfileSwitchEvent updates activeProfileName`() {+ fun `sendProfileSwitchEvent keeps the active name and id for a reconnecting UI`() {LocationServiceModule.sendProfileSwitchEvent("Charging", 1)assertEquals("Charging", getCompanionField("activeProfileName"))+ assertEquals(1, getCompanionField("activeProfileId"))}@Test- fun `sendProfileSwitchEvent clears activeProfileName on deactivation`() {+ fun `sendProfileSwitchEvent clears the name and id on deactivation`() {setCompanionField("activeProfileName", "Charging")+ setCompanionField("activeProfileId", 1)LocationServiceModule.sendProfileSwitchEvent(null, null)assertNull(getCompanionField("activeProfileName"))+ assertNull(getCompanionField("activeProfileId"))}@Test@@ -204,6 +227,25 @@ class LocationServiceModuleTest {verify { mockEmitter.emit("onSyncProgress", any()) }}+ /**+ * `remaining` is the whole completion contract. A pass caps at MAX_BATCHES_PER_SYNC, so the+ * running count need not reach the queue it started with, and a tick carrying the key would end+ * the caller's flush on the first batch.+ */+ @Test+ fun `a progress tick carries no remaining, and only the event that ends a pass does`() {+ val payloads = mutableListOf<WritableMap>()+ every { mockEmitter.emit("onSyncProgress", capture(payloads)) } just Runs++ LocationServiceModule.sendSyncProgressEvent(50, 0, 412)+ LocationServiceModule.sendSyncProgressEvent(500, 3, 503, 120)++ assertFalse(payloads[0].hasKey("remaining"))+ assertTrue(payloads[1].hasKey("remaining"))+ assertEquals(120, payloads[1].getInt("remaining"))+ assertEquals(3, payloads[1].getInt("failed"))+ }+@Testfun `sendSyncProgressEvent returns false when no context`() {setCompanionField("reactContextRef", WeakReference<ReactApplicationContext>(null))@@ -586,7 +628,7 @@ class LocationServiceModuleTest {}// ========================================================================- // getActiveProfile reads companion activeProfileName+ // getActiveProfile reads the companion's active name and id// ========================================================================@Test@@ -598,11 +640,15 @@ class LocationServiceModuleTest {}@Test- fun `getActiveProfile resolves profile name when active`() {+ fun `getActiveProfile resolves the name and id when active, so the UI can show the profile's interval after a restart`() {setCompanionField("activeProfileName", "Charging")+ setCompanionField("activeProfileId", 3)val promise = mockk<com.facebook.react.bridge.Promise>(relaxed = true)createModule().getActiveProfile(promise)- verify { promise.resolve("Charging") }+ val map = slot<JavaOnlyMap>()+ verify { promise.resolve(capture(map)) }+ assertEquals("Charging", map.captured.getString("name"))+ assertEquals(3, map.captured.getInt("id"))}// ========================================================================@@ -681,6 +727,94 @@ class LocationServiceModuleTest {throw NoSuchFieldException(name)}+ // ========================================================================+ // Which deletes rewrite the database+ // ========================================================================++ /**+ * A track edit is a few rows out of millions and gets repeated, so it must not trigger a full+ * rewrite: VACUUM holds the one write connection for minutes and stalls the recording service.+ * The bulk deletes on Data management are rare and asked for, so they still do.+ */+ @Test+ fun `deleting a trip does not rewrite the database`() {+ val db = stubDatabase()+ every { db.deleteInRange(any(), any()) } returns 120++ awaitPromise { promise -> LocationServiceModule(mockContext).deleteLocationsInRange(1000.0, 2000.0, promise) }++ verify(exactly = 1) { db.deleteInRange(1000L, 2000L) }+ assertNoVacuum(db)+ }++ @Test+ fun `deleting selected trips does not rewrite the database`() {+ val db = stubDatabase()+ every { db.deleteInRanges(any()) } returns 40+ val ranges = JavaOnlyArray().apply {+ pushMap(JavaOnlyMap().apply {+ putDouble("start", 10.0)+ putDouble("end", 20.0)+ })+ }++ awaitPromise { promise -> LocationServiceModule(mockContext).deleteLocationsInRanges(ranges, promise) }++ verify(exactly = 1) { db.deleteInRanges(listOf(10L to 20L)) }+ assertNoVacuum(db)+ }++ @Test+ fun `deleting single points does not rewrite the database`() {+ val db = stubDatabase()+ every { db.deleteLocations(any()) } returns 1+ val ids = JavaOnlyArray().apply { pushDouble(7.0) }++ awaitPromise { promise -> LocationServiceModule(mockContext).deleteLocationsByIds(ids, promise) }++ verify(exactly = 1) { db.deleteLocations(listOf(7L)) }+ assertNoVacuum(db)+ }++ @Test+ fun `a bulk delete on Data management still rewrites the database`() {+ val db = stubDatabase()+ every { db.deleteOlderThan(any()) } returns 9000++ awaitPromise { promise -> LocationServiceModule(mockContext).deleteOlderThan(90, promise) }++ verify(exactly = 1) { db.deleteOlderThan(90) }+ // Fire-and-forget on its own coroutine, so the promise resolves before it runs.+ verify(timeout = 5000, exactly = 1) { db.vacuum() }+ }++ /**+ * The rewrite runs on a detached coroutine, so the promise can settle before it would have+ * started. Proving it never runs means giving it the chance and then checking.+ */+ private fun assertNoVacuum(db: DatabaseHelper) {+ Thread.sleep(200)+ verify(exactly = 0) { db.vacuum() }+ }++ private fun stubDatabase(): DatabaseHelper {+ val db = mockk<DatabaseHelper>(relaxed = true)+ every { DatabaseHelper.getInstance(any()) } returns db+ return db+ }++ /** The bridge resolves on its own coroutine, so a test has to wait for the promise, not the call. */+ private fun awaitPromise(call: (Promise) -> Unit) {+ val latch = CountDownLatch(1)+ val promise = mockk<Promise>(relaxed = true)+ every { promise.resolve(any()) } answers { latch.countDown() }+ every { promise.reject(any<String>(), any<String>(), any<Throwable>()) } answers { latch.countDown() }++ call(promise)++ assertTrue("the bridge never settled its promise", latch.await(5, TimeUnit.SECONDS))+ }+private fun getField(obj: Any, name: String): Any? {val field = obj.javaClass.getDeclaredField(name)field.isAccessible = truediff --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 e836b87e..01cc5826 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@@ -145,6 +145,8 @@ class DatabaseHelperSQLiteTest {DatabaseHelper.migrateCandidate(candidate)SQLiteDatabase.openDatabase(candidate.absolutePath, null, SQLiteDatabase.OPEN_READONLY).use { migrated ->+ // A literal on purpose: migrateCandidate stamps the constant, so comparing against it+ // passes for any value and stops forcing a migration arm when the version moves.assertEquals(7, migrated.version)// migrateCandidate stamps the version unconditionally, so the version alone proves// nothing about the v7 step. This is the restore-an-older-backup path.@@ -184,6 +186,8 @@ class DatabaseHelperSQLiteTest {DatabaseHelper.migrateCandidate(candidate)SQLiteDatabase.openDatabase(candidate.absolutePath, null, SQLiteDatabase.OPEN_READONLY).use { migrated ->+ // A literal on purpose: migrateCandidate stamps the constant, so comparing against it+ // passes for any value and stops forcing a migration arm when the version moves.assertEquals(7, migrated.version)assertMigratedTableExists(migrated, DatabaseHelper.TABLE_BOUNDARY_OVERRIDES)migrated.rawQuery("PRAGMA table_info(locations)", null).use { locCursor ->@@ -1168,6 +1172,79 @@ class DatabaseHelperSQLiteTest {assertEquals(53.0, remaining[0]["latitude"] as Double, 0.001)}+ @Test+ fun `countOlderThan counts exactly what deleteOlderThan then removes, so a preview cannot promise a wrong number`() {+ val now = System.currentTimeMillis() / 1000+ // Rows sitting on the boundary and one second either side, so a shift of one day or a flip+ // between < and <= moves the two figures apart instead of leaving both unchanged.+ val cutoff = db.countOlderThan(7).cutoffSeconds+ db.saveLocation(latitude = 52.0, longitude = 13.0, timestamp = cutoff - 1)+ db.saveLocation(latitude = 52.1, longitude = 13.1, timestamp = cutoff)+ db.saveLocation(latitude = 52.2, longitude = 13.2, timestamp = cutoff + 1)+ db.saveLocation(latitude = 53.0, longitude = 14.0, timestamp = now)++ val predicted = db.countOlderThan(7).total+ val deleted = db.deleteOlderThan(7)++ assertEquals(predicted, deleted)+ // Only the row strictly before the boundary goes; the one on it stays.+ assertEquals(1, deleted)+ }++ @Test+ fun `the boundary holds still across a dwell, so a confirmation cannot name less than the delete takes`() {+ val first = db.countOlderThan(30).cutoffSeconds++ Thread.sleep(20)++ assertEquals(first, db.countOlderThan(30).cutoffSeconds)+ }++ @Test+ fun `countUnsentOlderThan reports how many matches were never uploaded, since no copy of those survives`() {+ val now = System.currentTimeMillis() / 1000+ val sentId = db.saveLocation(latitude = 52.0, longitude = 13.0, timestamp = now - 86400 * 10)+ db.saveLocation(latitude = 52.1, longitude = 13.1, timestamp = now - 86400 * 9)+ db.markLocationsSent(listOf(sentId))++ assertEquals(2, db.countOlderThan(7).total)+ assertEquals(1, db.countUnsentOlderThan(7))+ }++ @Test+ fun `countOlderThan is zero on an empty window rather than reporting a phantom match`() {+ db.saveLocation(latitude = 53.0, longitude = 14.0, timestamp = System.currentTimeMillis() / 1000)++ assertEquals(0, db.countOlderThan(7).total)+ assertEquals(0, db.countUnsentOlderThan(7))+ }++ @Test+ fun `countOlderThan reports the boundary it counted at, so the confirmation cannot name a different one`() {+ val now = System.currentTimeMillis() / 1000+ db.saveLocation(latitude = 52.0, longitude = 13.0, timestamp = now - 86400 * 10)++ val counted = db.countOlderThan(7)++ // Every row it counted sits before the boundary it reports.+ assertEquals(1, counted.total)+ assertTrue(counted.cutoffSeconds <= now - 86400 * 7)+ assertTrue(counted.cutoffSeconds > now - 86400 * 8)+ }++ @Test+ fun `getStats agrees with the table on how many rows have been uploaded`() {+ val sentId = db.saveLocation(latitude = 52.0, longitude = 13.0, timestamp = 1000L)+ db.saveLocation(latitude = 52.1, longitude = 13.1, timestamp = 2000L)+ db.saveLocation(latitude = 52.2, longitude = 13.2, timestamp = 3000L)+ db.markLocationsSent(listOf(sentId))++ val stats = db.getStats()++ assertEquals(3, stats.total)+ assertEquals(1, stats.sent)+ }+// ========================================================================// deleteInRange// ========================================================================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 8a3fadd9..477bf72a 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@@ -109,6 +109,17 @@ class ProfileHelperTest {return cursor}+ @Test+ fun `getEnabledProfiles asks for priority then id, so equal priorities go to the older profile`() {+ val cursor = mockCursorWithProfiles(emptyList())+ val order = slot<String>()+ every { mockDb.query(any(), any(), eq("enabled = 1"), any(), any(), any(), capture(order)) } returns cursor++ ProfileHelper(mockk(relaxed = true)).getEnabledProfiles()++ assertEquals("priority DESC, id ASC", order.captured)+ }+@Testfun `getEnabledProfiles returns profiles from database`() {val cursor = mockCursorWithProfiles(listOf(diff --git a/apps/mobile/android/app/src/test/java/com/Colota/export/AutoExportSchedulerTest.kt b/apps/mobile/android/app/src/test/java/com/Colota/export/AutoExportSchedulerTest.ktindex dd6b56b0..5f50f44c 100644--- a/apps/mobile/android/app/src/test/java/com/Colota/export/AutoExportSchedulerTest.kt+++ b/apps/mobile/android/app/src/test/java/com/Colota/export/AutoExportSchedulerTest.kt@@ -114,6 +114,16 @@ class AutoExportSchedulerTest {assertEquals(WorkInfo.State.CANCELLED, wm.getWorkInfosByTag(AutoExportWorker::class.java.name).get().single().state)}+ @Test+ fun `a second Export now while one is queued does not enqueue a second run`() {+ // Each run writes its own file, so a double tap produced two exports a second apart.+ AutoExportScheduler.runNow(context)+ AutoExportScheduler.runNow(context)++ val wm = WorkManager.getInstance(context)+ assertEquals(1, wm.getWorkInfosByTag(AutoExportWorker::class.java.name).get().size)+ }+@Testfun `the alarm receiver re-arms the alarm before enqueuing so a failed enqueue cannot end the schedule`() {mockkObject(AutoExportScheduler)diff --git a/apps/mobile/android/app/src/test/java/com/Colota/export/AutoExportWorkerRunTest.kt b/apps/mobile/android/app/src/test/java/com/Colota/export/AutoExportWorkerRunTest.ktindex 0cb35373..cbde6385 100644--- a/apps/mobile/android/app/src/test/java/com/Colota/export/AutoExportWorkerRunTest.kt+++ b/apps/mobile/android/app/src/test/java/com/Colota/export/AutoExportWorkerRunTest.kt@@ -125,4 +125,29 @@ class AutoExportWorkerRunTest {assertTrue("expected the verification error, got ${config.lastError}", config.lastError!!.contains("Export verification failed"))verify { createdDoc.delete() }}++ @Test+ fun `Export now exports while auto-export is switched off`() {+ // The screen offers Export now whenever a directory is set, and the enabled flag is the+ // schedule's, so the button used to return success without writing anything.+ db.saveSetting("autoExportEnabled", "false")++ val result = runWorker()++ assertTrue("expected success, got $result", result is ListenableWorker.Result.Success)+ val csv = written.toString(Charsets.UTF_8.name())+ assertTrue("expected rows to be written", csv.contains("1700000500"))+ assertEquals(200, AutoExportConfig.from(db).lastRowCount)+ }++ @Test+ fun `a scheduled run still skips while auto-export is switched off`() {+ db.saveSetting("autoExportEnabled", "false")++ val worker = TestListenableWorkerBuilder<AutoExportWorker>(context).build()+ val result = runBlocking { worker.doWork() }++ assertTrue("expected success, got $result", result is ListenableWorker.Result.Success)+ assertEquals("", written.toString(Charsets.UTF_8.name()))+ }}diff --git a/apps/mobile/android/app/src/test/java/com/Colota/export/ExportConvertersTest.kt b/apps/mobile/android/app/src/test/java/com/Colota/export/ExportConvertersTest.ktindex b4426607..102a6606 100644--- a/apps/mobile/android/app/src/test/java/com/Colota/export/ExportConvertersTest.kt+++ b/apps/mobile/android/app/src/test/java/com/Colota/export/ExportConvertersTest.kt@@ -2,6 +2,7 @@ package com.Colota.exportimport org.junit.Assert.*import org.junit.Rule+import org.json.JSONObjectimport org.junit.Testimport org.junit.rules.TemporaryFolderimport java.io.StringWriter@@ -104,38 +105,130 @@ class ExportConvertersTest {// --- GeoJSON ---+ /**+ * RFC 7946 conformance, checked by parsing rather than by matching strings. The old writer's+ * defect was invisible to a `contains` assertion, because the file it produced was legal JSON+ * and legal GeoJSON: it broke no rule here, it just put 2.5 million points in one feature. So+ * this validates the grammar and the sibling tests validate the shape a reader needs.+ */+ private fun assertRfc7946(json: String, expectedFeatures: Int) {+ val root = JSONObject(json)+ // Section 3.3: a FeatureCollection has type and a features array.+ assertEquals("FeatureCollection", root.getString("type"))+ val features = root.getJSONArray("features")+ assertEquals(expectedFeatures, features.length())+ for (i in 0 until features.length()) {+ val feature = features.getJSONObject(i)+ // Section 3.2: type, a geometry member and a properties member.+ assertEquals("Feature", feature.getString("type"))+ assertTrue("feature $i has no properties member", feature.has("properties"))+ feature.getJSONObject("properties")+ val geometry = feature.getJSONObject("geometry")+ assertEquals("Point", geometry.getString("type"))+ // Section 3.1.1: a position is an array of at least two numbers, longitude first.+ val position = geometry.getJSONArray("coordinates")+ assertTrue("position needs two or more numbers", position.length() >= 2)+ val lon = position.getDouble(0)+ val lat = position.getDouble(1)+ // Section 4: the CRS is WGS 84, so these are the valid ranges. Swapping the pair puts a+ // German longitude of 11 where a latitude belongs, which stays inside both ranges and is+ // why the order is asserted against known fixture values elsewhere too.+ assertTrue("longitude $lon out of range", lon >= -180.0 && lon <= 180.0)+ assertTrue("latitude $lat out of range", lat >= -90.0 && lat <= 90.0)+ assertFalse("a position must not carry NaN", lon.isNaN() || lat.isNaN())+ }+ }++ // Proves the validator bites. The shape Colota wrote until 1.16.0 is legal GeoJSON, so the+ // rejection comes from the Point assertion, not from the grammar. The importer still reads it.+ @Test+ fun `the RFC check rejects the columnar MultiPoint Colota wrote until 1_16_0`() {+ val legacy = """+ {"type":"FeatureCollection","features":[{"type":"Feature",+ "geometry":{"type":"MultiPoint","coordinates":[[13.4,52.5],[13.41,52.51]]},+ "properties":{"accuracy":[10,15],"time":["2023-11-14T22:13:20.000Z","2023-11-14T22:14:20.000Z"]}}]}+ """.trimIndent()+ // It parses as JSON and satisfies RFC 7946 on its own terms, which is exactly why a+ // string-matching test never caught it.+ JSONObject(legacy)+ val failure = runCatching { assertRfc7946(legacy, 2) }.exceptionOrNull()+ assertTrue("the validator must reject a single columnar feature", failure is AssertionError)+ }++ @Test+ fun `convert GeoJSON conforms to RFC 7946`() {+ assertRfc7946(ExportConverters.convert("geojson", sampleRows), sampleRows.size)+ }++ @Test+ fun `convertTrips GeoJSON conforms to RFC 7946`() {+ assertRfc7946(ExportConverters.convertTrips("geojson", tripFixture), 4)+ }++ @Test+ fun `an empty GeoJSON export is still a valid FeatureCollection`() {+ assertRfc7946(streamToString("geojson", emptyList()), 0)+ }++ @Test+ fun `a streamed GeoJSON export conforms to RFC 7946 across chunk boundaries`() {+ val streamed = streamToString("geojson", emptyList(), chunks = listOf(listOf(sampleRows[0]), listOf(sampleRows[1])))+ assertRfc7946(streamed, 2)+ }++ // A row with only a position and a time still has to produce a valid feature.+ @Test+ fun `a sparse row still conforms to RFC 7946`() {+ val sparse = listOf(mapOf<String, Any?>("latitude" to 52.0, "longitude" to 13.0, "timestamp" to 1700000000L))+ assertRfc7946(ExportConverters.convert("geojson", sparse), 1)+ }++ /**+ * The contract a GIS reads, not the shape this writer happens to produce. Attributes belong to+ * features, so one feature for the whole export gives QGIS a single unqueryable row, and past+ * `OGR_GEOJSON_MAX_OBJ_SIZE` (200 MB by default) GDAL refuses the file outright.+ */@Test- fun `convert GeoJSON produces a single columnar MultiPoint feature`() {+ fun `convert GeoJSON produces one Point feature per location`() {val json = ExportConverters.convert("geojson", sampleRows)assertTrue(json.contains("\"type\": \"FeatureCollection\""))- assertTrue(json.contains("\"type\": \"Feature\""))- assertTrue(json.contains("\"type\": \"MultiPoint\""))- // Exactly one Feature for the whole export (columnar), not one per point.- assertEquals(1, Regex("\"type\": \"Feature\"").findAll(json).count())- assertFalse(json.contains("\"type\": \"Point\""))+ assertEquals(sampleRows.size, Regex("\"type\": \"Feature\"").findAll(json).count())+ assertEquals(sampleRows.size, Regex("\"type\": \"Point\"").findAll(json).count())+ assertFalse(json.contains("MultiPoint"))}@Test- fun `convert GeoJSON contains coordinates in lon-lat order`() {+ fun `convert GeoJSON writes properties as scalars, so a reader gets typed columns`() {val json = ExportConverters.convert("geojson", sampleRows)- assertTrue(json.contains("[13.405, 52.52]"))- assertTrue(json.contains("[2.3522, 48.8566]"))+ assertTrue(json.contains("\"accuracy\": 10"))+ assertTrue(json.contains("\"accuracy\": 15"))+ assertTrue(json.contains("\"speed\": 1.2"))+ // A parallel array is what made every attribute an opaque JSON string in GDAL.+ assertFalse(json.contains("\"accuracy\": ["))+ assertFalse(json.contains("\"time\": ["))+ }++ // Omitted, not null: a reader gets no field rather than an empty one, and the column that is+ // empty for most rows costs nothing.+ @Test+ fun `convert GeoJSON omits a property the row does not carry`() {+ val json = ExportConverters.convert("geojson", sampleRows)+ assertFalse(json.contains("\"note\": null"))+ assertFalse(json.contains("null"))}@Test- fun `convert GeoJSON emits properties as parallel arrays aligned to coordinates`() {+ fun `convert GeoJSON contains coordinates in lon-lat order`() {val json = ExportConverters.convert("geojson", sampleRows)- assertTrue(json.contains("\"accuracy\": [10, 15]"))- assertTrue(json.contains("\"speed\": [1.2, 0.5]"))- assertTrue(json.contains("\"battery\": [85, 72]"))- assertTrue(json.contains("\"time\": [\""))+ assertTrue(json.contains("[13.405, 52.52]"))+ assertTrue(json.contains("[2.3522, 48.8566]"))}@Test- fun `convert GeoJSON keeps a single point as a MultiPoint`() {+ fun `convert GeoJSON writes one point as one feature, not a collection of one`() {val json = ExportConverters.convert("geojson", listOf(sampleRows[0]))- assertTrue(json.contains("\"type\": \"MultiPoint\""))- assertTrue(json.contains("\"accuracy\": [10]")) // length-1 array, not a scalar+ assertEquals(1, Regex("\"type\": \"Point\"").findAll(json).count())+ assertTrue(json.contains("\"accuracy\": 10"))}// --- GPX ---@@ -204,10 +297,11 @@ class ExportConvertersTest {}@Test- fun `GeoJSON JSON-escapes the note and emits null when absent`() {+ fun `GeoJSON JSON-escapes the note and omits it when absent`() {val json = ExportConverters.convert("geojson", noteRows)assertTrue(json.contains("\\\"big\\\""))- assertTrue(json.contains(", null]")) // the note column ends with null for the second point+ // One feature carries a note, the other has no note member at all.+ assertEquals(1, Regex("\"note\":").findAll(json).count())}@Test@@ -364,10 +458,10 @@ class ExportConvertersTest {assertTrue(csvLines[2].startsWith("1,"))val geojsonResult = streamToString("geojson", emptyList(), chunks = listOf(chunk1, chunk2))- // Both chunks fold into one MultiPoint feature.+ // A chunk boundary is invisible in the output: two rows, two features, whichever chunk they came in.assertTrue(geojsonResult.contains("[13.405, 52.52]"))assertTrue(geojsonResult.contains("[2.3522, 48.8566]"))- assertEquals(1, Regex("\"type\": \"Feature\"").findAll(geojsonResult).count())+ assertEquals(2, Regex("\"type\": \"Feature\"").findAll(geojsonResult).count())val gpxResult = streamToString("gpx", emptyList(), chunks = listOf(chunk1, chunk2))assertTrue(gpxResult.contains("lat=\"52.520000\""))@@ -391,8 +485,8 @@ class ExportConvertersTest {val geojsonResult = streamToString("geojson", emptyList())assertTrue(geojsonResult.contains("FeatureCollection"))- assertTrue("empty export is an empty FeatureCollection, not an empty MultiPoint", geojsonResult.contains("\"features\": []"))- assertFalse(geojsonResult.contains("MultiPoint"))+ assertTrue("an empty export is a FeatureCollection with no features", geojsonResult.contains("\"features\": ["))+ assertEquals(0, Regex("\"type\": \"Feature\"").findAll(geojsonResult).count())}@Test@@ -414,8 +508,8 @@ class ExportConvertersTest {val csv = ExportConverters.convert("csv", sampleRows)assertTrue(csv.lines()[1].endsWith(",Charging,")) // battery_status label, then empty note (last column)val gj = ExportConverters.convert("geojson", sampleRows)- assertTrue(gj.contains("\"bearing\": [180")) // whole double -> no trailing ".0"- assertTrue(gj.contains("\"battery_status\": [\"Charging\""))+ assertTrue(gj.contains("\"bearing\": 180")) // whole double -> no trailing ".0"+ assertTrue(gj.contains("\"battery_status\": \"Charging\""))val gpx = ExportConverters.convert("gpx", sampleRows)assertTrue(gpx.contains("<bearing>180</bearing>"))assertTrue(gpx.contains("<battery_status>Charging</battery_status>"))@@ -480,7 +574,7 @@ class ExportConvertersTest {assertTrue(csv.contains("\"deer, \"\"big\"\" <antlers>\""))val gj = ExportConverters.convertTrips("geojson", trips)assertTrue(gj.contains("\\\"big\\\""))- assertTrue(gj.contains(", null]")) // the note column ends with null for the second point+ assertEquals(1, Regex("\"note\":").findAll(gj).count())val gpx = ExportConverters.convertTrips("gpx", trips)assertTrue(gpx.contains("<note>deer, "big" <antlers></note>"))assertTrue(gpx.contains("<note></note>"))diff --git a/apps/mobile/android/app/src/test/java/com/Colota/importer/GeoJsonParserTest.kt b/apps/mobile/android/app/src/test/java/com/Colota/importer/GeoJsonParserTest.ktindex d8b73590..605720b8 100644--- a/apps/mobile/android/app/src/test/java/com/Colota/importer/GeoJsonParserTest.kt+++ b/apps/mobile/android/app/src/test/java/com/Colota/importer/GeoJsonParserTest.kt@@ -84,6 +84,8 @@ class GeoJsonParserTest {}@Test+ // The shape Colota wrote in 1.12.0 through 1.16.0. Not deprecated: such a file can be the last+ // copy of data since deleted, so this stays readable and this test is what keeps it that way.fun `parses a columnar MultiPoint feature into one row per point`() {val json = """{@@ -189,7 +191,7 @@ class GeoJsonParserTest {}@Test- fun `round-trips a single-point export (still a MultiPoint) back into one row`() {+ fun `round-trips an export back into one row per point`() {val rows = listOf(mapOf<String, Any?>("latitude" to 40.0, "longitude" to -3.0, "timestamp" to 1_700_000_000L,@@ -198,7 +200,7 @@ class GeoJsonParserTest {)val json = ExportConverters.convert("geojson", rows)- assertTrue("a single point must still export as a MultiPoint", json.contains("\"MultiPoint\""))+ assertTrue("the export is Point features, which is what a GIS reads", json.contains("\"Point\""))val result = GeoJsonParser.parse(json.byteInputStream(), cancelled, nowSec)assertEquals(0, result.invalid)diff --git a/apps/mobile/android/app/src/test/java/com/Colota/service/ConditionMonitorTest.kt b/apps/mobile/android/app/src/test/java/com/Colota/service/ConditionMonitorTest.ktindex e3c2f3e5..65feecd6 100644--- a/apps/mobile/android/app/src/test/java/com/Colota/service/ConditionMonitorTest.kt+++ b/apps/mobile/android/app/src/test/java/com/Colota/service/ConditionMonitorTest.kt@@ -284,8 +284,8 @@ class ConditionMonitorTest {monitor.stop()- // Should complete without crash — observer null check returns early- // (observer is non-null but connection is null → returns early after observer check)+ // Nothing was posted to the main looper, because there is no LiveData to remove from.+ verify(exactly = 0) { mockHandler.post(any()) }}// ========================================================================diff --git a/apps/mobile/android/app/src/test/java/com/Colota/sync/SyncManagerTest.kt b/apps/mobile/android/app/src/test/java/com/Colota/sync/SyncManagerTest.ktindex 7e14b165..03b979e5 100644--- a/apps/mobile/android/app/src/test/java/com/Colota/sync/SyncManagerTest.kt+++ b/apps/mobile/android/app/src/test/java/com/Colota/sync/SyncManagerTest.kt@@ -430,6 +430,29 @@ class SyncManagerTest {assertTrue(syncManager.lastSuccessfulSyncTime > 0)}+ @Test+ fun `queueAndSend records the success where the bridge reads it and clears a stale error`() = scope.runTest {+ SyncState.reset()+ SyncState.recordError("HTTP 401 Unauthorized")+ syncManager.updateConfig(+ endpoint = "https://example.com",+ syncIntervalSeconds = 0,+ retryIntervalSeconds = 30,+ isOfflineMode = false,+ syncCondition = "any",+ syncSsid = "",+ authHeaders = emptyMap()+ )+ coEvery { networkManager.isNetworkAvailable() } returns true+ coEvery { networkManager.sendToEndpoint(any(), any(), any(), any()) } returns true++ syncManager.queueAndSend(1L, JSONObject().put("lat", 52.0))++ assertEquals(syncManager.lastSuccessfulSyncTime, SyncState.lastSuccessTime)+ assertEquals("", SyncState.lastSyncError)+ SyncState.reset()+ }+// --- manualFlush ---@Test@@ -1234,22 +1257,6 @@ class SyncManagerTest {verify(exactly = 0) { dbHelper.removeBatchFromQueue(match { it.contains(1L) }) }}- // ========================================================================- // Helpers- // ========================================================================-- @Suppress("UNCHECKED_CAST")- private suspend fun callApplyBackoffDelay() {- val method = SyncManager::class.java.getDeclaredMethod(- "applyBackoffDelay",- Continuation::class.java- )- method.isAccessible = true- kotlin.coroutines.intrinsics.suspendCoroutineUninterceptedOrReturn<Unit> { cont ->- method.invoke(syncManager, cont)- }- }-// ========================================================================// One sender at a time// ========================================================================@@ -1326,6 +1333,91 @@ class SyncManagerTest {verify(exactly = 0) { dbHelper.removeFromQueueByLocationId(500L) }}+ @Test+ fun `a manual flush reports progress after a chunk that sent nothing`() = scope.runTest {+ mockkObject(LocationServiceModule.Companion)+ every { LocationServiceModule.sendSyncProgressEvent(any(), any(), any(), any()) } returns true+ syncManager.updateConfig(+ endpoint = "https://example.com",+ syncIntervalSeconds = 0,+ retryIntervalSeconds = 30,+ isOfflineMode = false,+ syncCondition = "any",+ syncSsid = "",+ authHeaders = emptyMap()+ )+ fakeQueue(10)+ coEvery { networkManager.sendToEndpoint(any(), any(), any(), any(), any()) } returns false++ syncManager.manualFlush()++ // Sync Now frees its button after a silence, so a pass that only fails must still report+ verify { LocationServiceModule.sendSyncProgressEvent(0, 10, 10, null) }++ unmockkObject(LocationServiceModule.Companion)+ }++ @Test+ fun `batch path reports progress after a batch that sent nothing`() = scope.runTest {+ mockkObject(LocationServiceModule.Companion)+ every { LocationServiceModule.sendSyncProgressEvent(any(), any(), any(), any()) } returns true+ syncManager.updateConfig(+ endpoint = "https://dawarich.example/api/v1/overland/batches",+ syncIntervalSeconds = 300,+ retryIntervalSeconds = 30,+ isOfflineMode = false,+ syncCondition = "any",+ syncSsid = "",+ authHeaders = emptyMap(),+ apiFormat = ApiFormat.OVERLAND_BATCH,+ overlandBatchSize = 50+ )+ val items = (1L..50L).map {+ QueuedLocation(it, it + 100, """{"lat":52.0,"lon":13.0,"tst":1700000000}""", 0)+ }+ every { dbHelper.getQueuedLocations(50) } returns items+ every { dbHelper.getQueuedCount() } returns 50+ coEvery { networkManager.sendBatchToEndpoint(any(), any(), any(), any()) } returns BatchResult.NetworkError++ syncManager.manualFlush()++ // Sync Now frees its button after a silence, so a batch that only fails must still report+ verify { LocationServiceModule.sendSyncProgressEvent(0, 50, 50, null) }++ unmockkObject(LocationServiceModule.Companion)+ }++ @Test+ fun `a manual flush waiting on a periodic pass hears that pass report`() = scope.runTest {+ mockkObject(LocationServiceModule.Companion)+ every { LocationServiceModule.sendSyncProgressEvent(any(), any(), any(), any()) } returns true+ syncManager.updateConfig(+ endpoint = "https://example.com",+ syncIntervalSeconds = 1,+ retryIntervalSeconds = 1,+ isOfflineMode = false,+ syncCondition = "any",+ syncSsid = "",+ authHeaders = emptyMap()+ )+ coEvery { networkManager.isNetworkAvailable() } returns true+ fakeQueue(20)+ coEvery { networkManager.sendToEndpoint(any(), any(), any(), any(), any()) } coAnswers { delay(1_500); true }++ syncManager.startPeriodicSync()+ advanceTimeBy(1_200)+ launch { syncManager.manualFlush() }+ advanceTimeBy(1_400)++ // The periodic pass has no screen of its own, but the waiting flush does and would give up on silence+ verify { LocationServiceModule.sendSyncProgressEvent(10, 0, 20, null) }+ // Only the periodic pass has posted so far, so the event can only be its report+ coVerify(exactly = 20) { networkManager.sendToEndpoint(any(), any(), any(), any(), any()) }++ syncManager.stopPeriodicSync()+ unmockkObject(LocationServiceModule.Companion)+ }+@Testfun `a slow instant send does not hold back the next fix`() = scope.runTest {syncManager.updateConfig(@@ -1377,6 +1469,35 @@ class SyncManagerTest {}}+ @Test+ fun `a manual flush cancelled while it waits still sends its ending event`() = scope.runTest {+ mockkObject(LocationServiceModule.Companion)+ every { LocationServiceModule.sendSyncProgressEvent(any(), any(), any(), any()) } returns true+ syncManager.updateConfig(+ endpoint = "https://example.com",+ syncIntervalSeconds = 0,+ retryIntervalSeconds = 30,+ isOfflineMode = false,+ syncCondition = "any",+ syncSsid = "",+ authHeaders = emptyMap()+ )+ fakeQueue(20)+ coEvery { networkManager.sendToEndpoint(any(), any(), any(), any(), any()) } coAnswers { delay(1_500); true }++ launch { syncManager.manualFlush() }+ val waiting = launch { syncManager.manualFlush() }+ advanceTimeBy(100)+ waiting.cancel()+ advanceTimeBy(100)++ // Sync Now waits for this event, so a flush stopped before it got the lock must still send one+ verify { LocationServiceModule.sendSyncProgressEvent(0, 0, 0, 20) }++ advanceUntilIdle()+ unmockkObject(LocationServiceModule.Companion)+ }+@Testfun `a tick that finds only a row an instant send is posting counts no failure`() = scope.runTest {syncManager.updateConfig(@@ -1401,6 +1522,22 @@ class SyncManagerTest {coVerify(exactly = 1) { networkManager.sendToEndpoint(any(), any(), any(), any(), any()) }}+ // ========================================================================+ // Helpers+ // ========================================================================++ @Suppress("UNCHECKED_CAST")+ private suspend fun callApplyBackoffDelay() {+ val method = SyncManager::class.java.getDeclaredMethod(+ "applyBackoffDelay",+ Continuation::class.java+ )+ method.isAccessible = true+ kotlin.coroutines.intrinsics.suspendCoroutineUninterceptedOrReturn<Unit> { cont ->+ method.invoke(syncManager, cont)+ }+ }+/** Rows leave only when a pass or an instant send removes them, so two senders running together see the same rows. */private fun fakeQueue(size: Int) {val queue = (1L..size.toLong()).map { QueuedLocation(it, it + 100, """{"lat":52.0}""", 0) }.toMutableList()diff --git a/apps/mobile/android/app/src/test/java/com/Colota/sync/SyncStateTest.kt b/apps/mobile/android/app/src/test/java/com/Colota/sync/SyncStateTest.ktnew file mode 100644index 00000000..f082cf72--- /dev/null+++ b/apps/mobile/android/app/src/test/java/com/Colota/sync/SyncStateTest.kt@@ -0,0 +1,28 @@+package com.Colota.sync++import org.junit.After+import org.junit.Assert.assertEquals+import org.junit.Test++class SyncStateTest {+ @After+ fun tearDown() = SyncState.reset()++ @Test+ fun `a success stamps the time and clears the last error, so a recovered server reads as synced`() {+ SyncState.recordError("HTTP 401 Unauthorized")+ SyncState.recordSuccess(1_700_000_000_000L)++ assertEquals(1_700_000_000_000L, SyncState.lastSuccessTime)+ assertEquals("", SyncState.lastSyncError)+ }++ @Test+ fun `an error keeps the last success time, so the caption can still say when it last worked`() {+ SyncState.recordSuccess(1_700_000_000_000L)+ SyncState.recordError("Sync failed")++ assertEquals(1_700_000_000_000L, SyncState.lastSuccessTime)+ assertEquals("Sync failed", SyncState.lastSyncError)+ }+}diff --git a/apps/mobile/android/app/src/test/java/com/Colota/util/LogExportMergerTest.kt b/apps/mobile/android/app/src/test/java/com/Colota/util/LogExportMergerTest.ktnew file mode 100644index 00000000..04722a42--- /dev/null+++ b/apps/mobile/android/app/src/test/java/com/Colota/util/LogExportMergerTest.kt@@ -0,0 +1,119 @@+package com.Colota.util++import org.junit.Assert.assertEquals+import org.junit.Assert.assertNull+import org.junit.Rule+import org.junit.Test+import org.junit.rules.TemporaryFolder+import java.io.File+import java.io.StringWriter++class LogExportMergerTest {++ @get:Rule+ val temp = TemporaryFolder()++ private fun segment(name: String, vararg lines: String): File =+ temp.newFile(name).apply { writeText(lines.joinToString("\n") + "\n") }++ private fun merged(sources: List<File>, appLog: String): List<String> {+ val writer = StringWriter()+ LogExportMerger.merge(sources, appLog, writer)+ return writer.toString().trimEnd('\n').split("\n").filter { it.isNotEmpty() }+ }++ /** One timeline, or a maintainer cross-references a Kotlin stream against a JS stream by hand. */+ @Test+ fun `app log lines land between the recorded lines they happened between`() {+ val recorded = segment(+ "seg1.log",+ "2026-09-09 09:00:00.000 INFO/Service: started",+ "2026-09-09 09:00:10.000 INFO/Service: fix received"+ )+ val appLog = "2026-09-09 09:00:05.000 WARN/JS: endpoint unreachable\n"++ val out = merged(listOf(recorded), appLog)++ assertEquals(3, out.size)+ assertEquals("2026-09-09 09:00:00.000 INFO/Service: started", out[0])+ assertEquals("2026-09-09 09:00:05.000 WARN/JS: endpoint unreachable", out[1])+ assertEquals("2026-09-09 09:00:10.000 INFO/Service: fix received", out[2])+ }++ /** The buffer is written up to the export while the file was flushed earlier, so this is normal. */+ @Test+ fun `app log lines after the last recorded line are still written`() {+ val recorded = segment("seg1.log", "2026-09-09 09:00:00.000 INFO/Service: started")+ val appLog = "2026-09-09 09:30:00.000 INFO/JS: screen opened\n"++ val out = merged(listOf(recorded), appLog)++ assertEquals(2, out.size)+ assertEquals("2026-09-09 09:30:00.000 INFO/JS: screen opened", out[1])+ }++ /** Oldest segment first, so the exported file reads in the order the events happened. */+ @Test+ fun `segments are walked in the order they are given`() {+ val older = segment("seg1.log", "2026-09-09 08:00:00.000 INFO/Service: yesterday's tail")+ val newer = segment("seg2.log", "2026-09-09 10:00:00.000 INFO/Service: today")+ val appLog = "2026-09-09 09:00:00.000 INFO/JS: between the two\n"++ val out = merged(listOf(older, newer), appLog)++ assertEquals("2026-09-09 08:00:00.000 INFO/Service: yesterday's tail", out[0])+ assertEquals("2026-09-09 09:00:00.000 INFO/JS: between the two", out[1])+ assertEquals("2026-09-09 10:00:00.000 INFO/Service: today", out[2])+ }++ /** Placing a stack frame by timestamp tears the trace off the line that threw it. */+ @Test+ fun `a continuation stays with the line it belongs to`() {+ val recorded = segment(+ "seg1.log",+ "2026-09-09 09:00:00.000 ERROR/Sync: network error",+ "\tat com.Colota.sync.NetworkManager.run(NetworkManager.kt:88)",+ "\tat com.Colota.sync.SyncManager.flush(SyncManager.kt:214)",+ "2026-09-09 09:00:20.000 INFO/Service: recovered"+ )+ val appLog = "2026-09-09 09:00:10.000 WARN/JS: retry scheduled\n"++ val out = merged(listOf(recorded), appLog)++ assertEquals("2026-09-09 09:00:00.000 ERROR/Sync: network error", out[0])+ assertEquals("\tat com.Colota.sync.NetworkManager.run(NetworkManager.kt:88)", out[1])+ assertEquals("\tat com.Colota.sync.SyncManager.flush(SyncManager.kt:214)", out[2])+ assertEquals("2026-09-09 09:00:10.000 WARN/JS: retry scheduled", out[3])+ }++ @Test+ fun `an empty app log leaves the recorded file byte for byte`() {+ val recorded = segment(+ "seg1.log",+ "2026-09-09 09:00:00.000 INFO/Service: started",+ "2026-09-09 09:00:10.000 INFO/Service: fix received"+ )++ val out = merged(listOf(recorded), "")++ assertEquals(2, out.size)+ assertEquals("2026-09-09 09:00:00.000 INFO/Service: started", out[0])+ }++ /** Nothing recorded is the fresh-capture case; the app log is still worth handing over. */+ @Test+ fun `an app log with no segments is written on its own`() {+ val out = merged(emptyList(), "2026-09-09 09:00:00.000 INFO/JS: only source\n")++ assertEquals(1, out.size)+ assertEquals("2026-09-09 09:00:00.000 INFO/JS: only source", out[0])+ }++ @Test+ fun `only a full stamp counts as one`() {+ assertEquals("2026-09-09 09:00:00.000", LogExportMerger.stampOf("2026-09-09 09:00:00.000 INFO/Tag: msg"))+ assertNull(LogExportMerger.stampOf("\tat com.Colota.Foo.bar(Foo.kt:1)"))+ assertNull(LogExportMerger.stampOf("short"))+ assertNull(LogExportMerger.stampOf("2026/09/09 09:00:00.000 INFO/Tag: msg"))+ }+}diff --git a/apps/mobile/android/app/src/test/resources/golden/export/trip.geojson b/apps/mobile/android/app/src/test/resources/golden/export/trip.geojsonindex 2bf35765..8142858b 100644--- a/apps/mobile/android/app/src/test/resources/golden/export/trip.geojson+++ b/apps/mobile/android/app/src/test/resources/golden/export/trip.geojson@@ -4,43 +4,41 @@{"type": "Feature","geometry": {- "type": "MultiPoint",- "coordinates": [- [11.576124, 48.137154],- [11.577003, 48.138001]- ]+ "type": "Point",+ "coordinates": [11.576124, 48.137154]},"properties": {- "trip": 1,- "accuracy": [8.5, 12],- "altitude": [520.2, 525],- "speed": [1.4, 2],- "bearing": [270.5, 275],- "battery": [91, 90],- "battery_status": ["Charging", "Full"],- "note": [null, null],- "time": ["2023-11-14T22:13:20.000Z", "2023-11-14T22:14:20.000Z"]+ "trip": 1, "time": "2023-11-14T22:13:20.000Z", "accuracy": 8.5, "altitude": 520.2, "speed": 1.4, "bearing": 270.5, "battery": 91, "battery_status": "Charging"}},{"type": "Feature","geometry": {- "type": "MultiPoint",- "coordinates": [- [11.58, 48.14],- [11.5811, 48.1405]- ]+ "type": "Point",+ "coordinates": [11.577003, 48.138001]},"properties": {- "trip": 2,- "accuracy": [5, 6.2],- "altitude": [530, 0],- "speed": [3, 0],- "bearing": [10, 0],- "battery": [88, 87],- "battery_status": ["Unplugged/Discharging", "Unknown"],- "note": [null, null],- "time": ["2023-11-14T22:30:00.000Z", "2023-11-14T22:31:00.000Z"]+ "trip": 1, "time": "2023-11-14T22:14:20.000Z", "accuracy": 12, "altitude": 525, "speed": 2, "bearing": 275, "battery": 90, "battery_status": "Full"+ }+ },+ {+ "type": "Feature",+ "geometry": {+ "type": "Point",+ "coordinates": [11.58, 48.14]+ },+ "properties": {+ "trip": 2, "time": "2023-11-14T22:30:00.000Z", "accuracy": 5, "altitude": 530, "speed": 3, "bearing": 10, "battery": 88, "battery_status": "Unplugged/Discharging"+ }+ },+ {+ "type": "Feature",+ "geometry": {+ "type": "Point",+ "coordinates": [11.5811, 48.1405]+ },+ "properties": {+ "trip": 2, "time": "2023-11-14T22:31:00.000Z", "accuracy": 6.2, "altitude": 0, "speed": 0, "bearing": 0, "battery": 87, "battery_status": "Unknown"}}]diff --git a/apps/mobile/src/constants/index.ts b/apps/mobile/src/constants/index.tsindex 5f462e36..1408b43b 100644--- a/apps/mobile/src/constants/index.ts+++ b/apps/mobile/src/constants/index.ts@@ -8,35 +8,80 @@ import { Zap, Car, ArrowUp, ArrowDown, Pause } from "lucide-react-native"// Timingexport const AUTOSAVE_DEBOUNCE_MS = 1500-export const STATS_REFRESH_IDLE = 30_000-export const STATS_REFRESH_FAST = 3_000-export const CONNECTION_TEST_TIMEOUT = 10_000export const SAVE_SUCCESS_DISPLAY_MS = 2000-export const TEST_RESULT_DISPLAY_MS = 5_000+/** manualFlush is fire and forget, so the screen gives up on progress events after this. */+export const MANUAL_FLUSH_TIMEOUT_MS = 30_000+/** A retention preview runs a COUNT per keystroke, so it waits for the typing to settle. */+export const RETENTION_PREVIEW_DEBOUNCE_MS = 300++/** The log file grows off-thread, so the size is read once after the toggle settles. */+export const LOG_SIZE_SETTLE_MS = 2000++export const LOG_FILTER_DEBOUNCE_MS = 200+export const RETENTION_PRESET_DAYS = [30, 90, 365]+/** A certificate this close to its notAfter reads as expiring: a CA round trip takes weeks. */+export const CERT_EXPIRY_WARNING_DAYS = 30export const SERVICE_RESTART_DELAY_MS = 500export const RESTART_DEBOUNCE_MS = 100export const SETTINGS_READ_ATTEMPTS = 3export const SETTINGS_READ_RETRY_DELAY_MS = 150-// Touch targets+// Spacing scale. Every padding, margin and gap reads from here; designSystemGuard fails a literal.+// The grid is 4dp from xs up. xxs is the one sub-grid step and has one job: the gap between a+// label and its own caption, which is type pairing rather than layout.+export const space = { xxs: 2, xs: 4, sm: 8, md: 12, lg: 16, xl: 24, xxl: 32 } as const++// Sizes are not spacing: these are the painted or touchable extents of a control.+export const size = {+ touch: 48,+ row: 56,+ chip: 32,+ iconButton: 32,+ iconColumn: 40,+ numericField: 88,+ /** The disc behind an empty screen's glyph. */+ emptyIcon: 64,+ icon: { sm: 16, md: 20, lg: 24 }+} as const++/**+ * Material's pressed state layer: 10 percent of the element's own content colour, concatenated+ * onto a hex token. Android draws it as a ripple from the touch point, which an opacity fade+ * of the whole element is not.+ */+export const STATE_LAYER_ALPHA = "1A"+export const HIT_SLOP_SM = { top: 6, right: 6, bottom: 6, left: 6 } as constexport const HIT_SLOP_MD = { top: 8, right: 8, bottom: 8, left: 8 } as constexport const HIT_SLOP_LG = { top: 12, right: 12, bottom: 12, left: 12 } as const// Map+/**+ * Material's elevation levels, named for the job rather than the number: 0, 1, 3 and 6 are levels+ * 0 to 3. The app had 0, 1, 4, 5, 6 and 8, and 4 and 5 are not levels at all.+ */+export const elevation = {+ /** Sits on the ground: the tab bar. */+ flat: 0,+ /** An elevated card, lifted off the ground but not over anything. */+ raised: 1,+ /** A control or badge floating over content, usually the map. */+ floating: 3,+ /** A dialog, a popup or a toast, over everything. */+ overlay: 6+} as const+export const DEFAULT_MAP_ZOOM = 17export const WORLD_MAP_ZOOM = 2export const MAX_MAP_ZOOM = 18export const GEOFENCE_ZOOM_PADDING = [80, 80, 80, 80] as constexport const MAP_ANIMATION_DURATION_MS = 400-export const MIN_STATS_INTERVAL_MS = 2000--// Profiles-export const MS_TO_KMH = 3.6+export const LOADING_INDICATOR_DELAY_MS = 200// Doze batches motion sensors past this; longer Stationary intervals risk missed trip starts.export const STATIONARY_MAX_INTERVAL_SECONDS = 60+/** `label` names the condition, `listLabel` opens a row's sentence, `description` says what watching it costs. */export const PROFILE_CONDITIONS: {type: ProfileConditionTypelabel: string@@ -75,9 +120,6 @@ 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: numberdeactivationDelay: number@@ -97,14 +139,17 @@ export const SYNC_INTERVAL_LABELS: Record<number, string> = {900: "15 min"}+export const SYNC_INTERVAL_SUBS: Record<number, string> = {+ 0: "Each fix is its own request · radio never idles",+ 60: "One request a minute · fixes wait in between",+ 300: "One request every 5 min · fewer wake-ups",+ 900: "One request every 15 min · the server hears you up to 15 min late"+}+// Overland batch envelope (Dawarich + batch mode, Overland template)export const OVERLAND_BATCH_MIN = 1export const OVERLAND_BATCH_MAX = 500-// Thresholds-export const HIGH_QUEUE_THRESHOLD = 50-export const CRITICAL_QUEUE_THRESHOLD = 100-// Map styleexport const MAP_STYLE_URL_LIGHT = "https://maps.mxd.codes/styles/bright/style.json"export const MAP_STYLE_URL_DARK = "https://maps.mxd.codes/styles/dark/style.json"@@ -113,4 +158,17 @@ export const MAP_STYLE_URL_DARK = "https://maps.mxd.codes/styles/dark/style.jsonexport const REPO_URL = "https://github.com/dietrichmax/colota"export const ISSUES_URL = `${REPO_URL}/issues`export const PRIVACY_POLICY_URL = "https://colota.app/privacy-policy"+export const RELEASES_URL = "https://colota.app/releases"+export const SUPPORT_URL = "https://mxd.codes/support"+/** market:// opens the Play app straight on the listing; the https form is the fallback. */+export const PLAY_STORE_MARKET_URL = "market://details?id=com.Colota"+export const PLAY_STORE_WEB_URL = "https://play.google.com/store/apps/details?id=com.Colota"++export const STATS_REFRESH_IDLE = 30_000+export const STATS_REFRESH_FAST = 3_000+export const MIN_STATS_INTERVAL_MS = 2000+export const MS_TO_KMH = 3.6+export const HIGH_QUEUE_THRESHOLD = 50+export const CRITICAL_QUEUE_THRESHOLD = 100export const TILE_SERVER_DOCS_URL = "https://colota.app/docs/guides/tile-server"+export const TEST_RESULT_DISPLAY_MS = 5_000diff --git a/apps/mobile/src/contexts/TrackingProvider.tsx b/apps/mobile/src/contexts/TrackingProvider.tsxindex e507c81a..65b6cbbe 100644--- a/apps/mobile/src/contexts/TrackingProvider.tsx+++ b/apps/mobile/src/contexts/TrackingProvider.tsx@@ -25,9 +25,10 @@ type TrackingContextType = {settingsHydrated: booleanerror: Error | nullactiveProfileName: string | null+ activeProfileId: number | nullstartTracking: () => Promise<void>stopTracking: () => void- restartTracking: (newSettings?: Settings) => Promise<void>+ restartTracking: (newSettings?: Settings) => Promise<boolean>}const TrackingContext = createContext<TrackingContextType | null>(null)@@ -103,6 +104,7 @@ export function TrackingProvider({ children }: { children: React.ReactNode }) {const [isLoading, setIsLoading] = useState(true)const [error, setError] = useState<Error | null>(null)const [activeProfileName, setActiveProfileName] = useState<string | null>(null)+ const [activeProfileId, setActiveProfileId] = useState<number | null>(null)// Ref to track if component is mounted (prevents state updates after unmount)const isMountedRef = useRef(true)@@ -203,11 +205,12 @@ export function TrackingProvider({ children }: { children: React.ReactNode }) {// the next render, and a restart from here would start the service configured wrong.internalReconnect(mergedSettings)- // Restore active profile name from the running service- const profileName = await NativeLocationService.getActiveProfileName()- logger.debug(`[TrackingContext] Active profile on reconnect: ${profileName ?? "(default)"}`)+ // Restore the active profile from the running service+ const profile = await NativeLocationService.getActiveProfile()+ logger.debug(`[TrackingContext] Active profile on reconnect: ${profile?.name ?? "(default)"}`)if (isMountedRef.current) {- setActiveProfileName(profileName)+ setActiveProfileName(profile?.name ?? null)+ setActiveProfileId(profile?.id ?? null)}}} catch (err) {@@ -246,6 +249,7 @@ export function TrackingProvider({ children }: { children: React.ReactNode }) {const listener = DeviceEventEmitter.addListener("onProfileSwitch", (event) => {if (isMountedRef.current) {setActiveProfileName(event?.profileName ?? null)+ setActiveProfileId(event?.profileId ?? null)}})return () => listener.remove()@@ -282,6 +286,7 @@ export function TrackingProvider({ children }: { children: React.ReactNode }) {internalStop()if (isMountedRef.current) {setActiveProfileName(null)+ setActiveProfileId(null)setError(null)}} catch (err) {@@ -295,10 +300,11 @@ export function TrackingProvider({ children }: { children: React.ReactNode }) {const restartTracking = useCallback(async (newSettings?: Settings) => {try {- await internalRestart(newSettings || settings)+ const restarted = await internalRestart(newSettings || settings)if (isMountedRef.current) {setError(null)}+ return restarted} catch (err) {logger.error("[TrackingContext] Failed to restart tracking:", err)if (isMountedRef.current) {@@ -324,6 +330,7 @@ export function TrackingProvider({ children }: { children: React.ReactNode }) {settingsHydrated: hydrated,error,activeProfileName,+ activeProfileId,startTracking,stopTracking,restartTracking@@ -335,6 +342,7 @@ export function TrackingProvider({ children }: { children: React.ReactNode }) {hydrated,error,activeProfileName,+ activeProfileId,setSettings,startTracking,stopTracking,diff --git a/apps/mobile/src/contexts/__tests__/TrackingProvider.test.tsx b/apps/mobile/src/contexts/__tests__/TrackingProvider.test.tsxindex f70b8d2e..568af7db 100644--- a/apps/mobile/src/contexts/__tests__/TrackingProvider.test.tsx+++ b/apps/mobile/src/contexts/__tests__/TrackingProvider.test.tsx@@ -9,7 +9,7 @@ jest.mock("../../services/NativeLocationService", () => ({saveSetting: jest.fn().mockResolvedValue(undefined),isServiceRunning: jest.fn().mockResolvedValue(false),isTrackingActive: jest.fn().mockResolvedValue(false),- getActiveProfileName: jest.fn().mockResolvedValue(null)+ getActiveProfile: jest.fn().mockResolvedValue(null)}))jest.mock("../../services/SettingsService", () => ({@@ -62,7 +62,7 @@ import { logger } from "../../utils/logger"const mockGetAllSettings = NativeLocationService.getAllSettings as jest.Mockconst mockUpdateMultiple = SettingsService.updateMultiple as jest.Mock-const mockGetActiveProfileName = NativeLocationService.getActiveProfileName as jest.Mock+const mockGetActiveProfile = NativeLocationService.getActiveProfile as jest.MockbeforeEach(() => {jest.clearAllMocks()@@ -219,7 +219,7 @@ describe("useTracking", () => {it("keeps saving when hydration fails after the read landed", async () => {// The stored settings are on screen at that point, so blocking saves would be wrong.mockGetAllSettings.mockResolvedValueOnce({ endpoint: "https://kept.example/api", tracking_enabled: "true" })- mockGetActiveProfileName.mockRejectedValueOnce(new Error("bridge died"))+ mockGetActiveProfile.mockRejectedValueOnce(new Error("bridge died"))const { result } = renderHook(() => useTracking(), { wrapper })@@ -388,6 +388,31 @@ describe("useTracking", () => {expect(result.current.activeProfileName).toBeNull()})+ it("keeps the profile id beside the name so the dashboard can resolve the profile's interval, and drops both on reset", async () => {+ mockGetAllSettings.mockResolvedValueOnce({ interval: "5000" })++ const { DeviceEventEmitter } = require("react-native")+ const { result } = renderHook(() => useTracking(), { wrapper })++ await act(async () => {+ await new Promise<void>((resolve) => setTimeout(resolve, 100))+ })++ expect(result.current.activeProfileId).toBeNull()++ await act(async () => {+ DeviceEventEmitter.emit("onProfileSwitch", { profileName: "Night", profileId: 7 })+ })++ expect(result.current.activeProfileId).toBe(7)++ await act(async () => {+ DeviceEventEmitter.emit("onProfileSwitch", { profileName: null, profileId: null })+ })++ expect(result.current.activeProfileId).toBeNull()+ })+it("clears activeProfileName when stopTracking is called", async () => {mockGetAllSettings.mockResolvedValueOnce({ interval: "5000" })@@ -399,7 +424,7 @@ describe("useTracking", () => {})await act(async () => {- DeviceEventEmitter.emit("onProfileSwitch", { profileName: "Fast Driving" })+ DeviceEventEmitter.emit("onProfileSwitch", { profileName: "Fast Driving", profileId: 3 })})expect(result.current.activeProfileName).toBe("Fast Driving")@@ -409,10 +434,11 @@ describe("useTracking", () => {})expect(result.current.activeProfileName).toBeNull()+ expect(result.current.activeProfileId).toBeNull()})- it("restores activeProfileName on reconnect when tracking was active", async () => {- mockGetActiveProfileName.mockResolvedValueOnce("Charging")+ it("restores the active profile's name and id on reconnect, so the dock shows the profile's interval after a restart", async () => {+ mockGetActiveProfile.mockResolvedValueOnce({ name: "Charging", id: 3 })mockGetAllSettings.mockResolvedValueOnce({interval: "5000",tracking_enabled: "true"@@ -424,8 +450,23 @@ describe("useTracking", () => {await new Promise<void>((resolve) => setTimeout(resolve, 100))})- expect(mockGetActiveProfileName).toHaveBeenCalled()+ expect(mockGetActiveProfile).toHaveBeenCalled()expect(result.current.activeProfileName).toBe("Charging")+ expect(result.current.activeProfileId).toBe(3)+ })++ it("leaves both profile fields null on reconnect when the service runs the default settings", async () => {+ mockGetActiveProfile.mockResolvedValueOnce(null)+ mockGetAllSettings.mockResolvedValueOnce({ interval: "5000", tracking_enabled: "true" })++ const { result } = renderHook(() => useTracking(), { wrapper })++ await act(async () => {+ await new Promise<void>((resolve) => setTimeout(resolve, 100))+ })++ expect(result.current.activeProfileName).toBeNull()+ expect(result.current.activeProfileId).toBeNull()})})diff --git a/apps/mobile/src/hooks/__tests__/useActiveProfile.test.ts b/apps/mobile/src/hooks/__tests__/useActiveProfile.test.tsnew file mode 100644index 00000000..6886e9c3--- /dev/null+++ b/apps/mobile/src/hooks/__tests__/useActiveProfile.test.ts@@ -0,0 +1,71 @@+import { renderHook, waitFor } from "@testing-library/react-native"++jest.mock("../../utils/logger", () => ({+ logger: { error: jest.fn() }+}))++const mockGetProfiles = jest.fn()+jest.mock("../../services/NativeLocationService", () => ({+ __esModule: true,+ default: {+ getProfiles: (...args: unknown[]) => mockGetProfiles(...args)+ }+}))++import { useActiveProfile } from "../useActiveProfile"+import { logger } from "../../utils/logger"++const profiles = [+ { id: 3, name: "Charging", interval: 5, distance: 20, syncInterval: 900 },+ { id: 7, name: "Night", interval: 300, distance: 50, syncInterval: 3600 }+]++beforeEach(() => {+ jest.clearAllMocks()+ mockGetProfiles.mockResolvedValue(profiles)+})++describe("useActiveProfile", () => {+ it("resolves the profile behind the id, so a screen can print the values in force", async () => {+ const { result } = renderHook(() => useActiveProfile(7))++ await waitFor(() => expect(result.current?.name).toBe("Night"))+ })++ it("is null with no id and reads nothing, since nothing is in force", () => {+ const { result } = renderHook(() => useActiveProfile(null))++ expect(result.current).toBeNull()+ expect(mockGetProfiles).not.toHaveBeenCalled()+ })++ it("is null when the id matches no saved profile, rather than showing a stale one", async () => {+ const { result, rerender } = renderHook(({ id }: { id: number | null }) => useActiveProfile(id), {+ initialProps: { id: 3 as number | null }+ })+ await waitFor(() => expect(result.current?.name).toBe("Charging"))++ rerender({ id: 99 })++ await waitFor(() => expect(result.current).toBeNull())+ })++ it("clears when the profile deactivates", async () => {+ const { result, rerender } = renderHook(({ id }: { id: number | null }) => useActiveProfile(id), {+ initialProps: { id: 3 as number | null }+ })+ await waitFor(() => expect(result.current?.name).toBe("Charging"))++ rerender({ id: null })++ expect(result.current).toBeNull()+ })++ it("only logs a failed read, because the line is background state", async () => {+ mockGetProfiles.mockRejectedValue(new Error("db closed"))+ const { result } = renderHook(() => useActiveProfile(3))++ await waitFor(() => expect(logger.error).toHaveBeenCalled())+ expect(result.current).toBeNull()+ })+})diff --git a/apps/mobile/src/hooks/__tests__/useAutoSave.test.ts b/apps/mobile/src/hooks/__tests__/useAutoSave.test.tsindex 9eb5f79a..940e3673 100644--- a/apps/mobile/src/hooks/__tests__/useAutoSave.test.ts+++ b/apps/mobile/src/hooks/__tests__/useAutoSave.test.ts@@ -14,18 +14,18 @@ afterEach(() => {describe("useAutoSave", () => {describe("initial state", () => {- it("starts with saving=false and saveSuccess=false", () => {+ it("starts with saving=false and nothing to say", () => {const { result } = renderHook(() => useAutoSave())expect(result.current.saving).toBe(false)- expect(result.current.saveSuccess).toBe(false)+ expect(result.current.message).toBeNull()})})describe("debouncedSaveAndRestart", () => {it("does not call saveFn immediately", () => {const saveFn = jest.fn().mockResolvedValue(undefined)- const restartFn = jest.fn().mockResolvedValue(undefined)+ const restartFn = jest.fn().mockResolvedValue(true)const { result } = renderHook(() => useAutoSave())act(() => {@@ -37,7 +37,7 @@ describe("useAutoSave", () => {it("calls saveFn after debounce delay", async () => {const saveFn = jest.fn().mockResolvedValue(undefined)- const restartFn = jest.fn().mockResolvedValue(undefined)+ const restartFn = jest.fn().mockResolvedValue(true)const { result } = renderHook(() => useAutoSave())act(() => {@@ -54,7 +54,7 @@ describe("useAutoSave", () => {it("cancels previous debounce when called again", async () => {const saveFn1 = jest.fn().mockResolvedValue(undefined)const saveFn2 = jest.fn().mockResolvedValue(undefined)- const restartFn = jest.fn().mockResolvedValue(undefined)+ const restartFn = jest.fn().mockResolvedValue(true)const { result } = renderHook(() => useAutoSave())act(() => {@@ -75,7 +75,7 @@ describe("useAutoSave", () => {it("sets saving=true during save, then restarts immediately", async () => {const saveFn = jest.fn().mockResolvedValue(undefined)- const restartFn = jest.fn().mockResolvedValue(undefined)+ const restartFn = jest.fn().mockResolvedValue(true)const { result } = renderHook(() => useAutoSave())act(() => {@@ -91,9 +91,9 @@ describe("useAutoSave", () => {expect(restartFn).toHaveBeenCalledTimes(1)})- it("sets saveSuccess=true after restart completes, then clears it", async () => {+ it("says the service was restarted, because nothing on screen shows that it was", async () => {const saveFn = jest.fn().mockResolvedValue(undefined)- const restartFn = jest.fn().mockResolvedValue(undefined)+ const restartFn = jest.fn().mockResolvedValue(true)const { result } = renderHook(() => useAutoSave())act(() => {@@ -105,19 +105,35 @@ describe("useAutoSave", () => {jest.advanceTimersByTime(AUTOSAVE_DEBOUNCE_MS)})- expect(result.current.saveSuccess).toBe(true)+ expect(result.current.message).toBe("Tracking restarted")+ expect(result.current.isError).toBe(false)- // Success display clearsawait act(async () => {jest.advanceTimersByTime(SAVE_SUCCESS_DISPLAY_MS)})- expect(result.current.saveSuccess).toBe(false)+ expect(result.current.message).toBeNull()})- it("handles save failure gracefully", async () => {+ it("stays quiet when the service was not running, since a plain write needs no confirming", async () => {+ const saveFn = jest.fn().mockResolvedValue(undefined)+ const restartFn = jest.fn().mockResolvedValue(false)+ const { result } = renderHook(() => useAutoSave())++ act(() => {+ result.current.debouncedSaveAndRestart(saveFn, restartFn)+ })++ await act(async () => {+ jest.advanceTimersByTime(AUTOSAVE_DEBOUNCE_MS)+ })++ expect(result.current.message).toBeNull()+ })++ it("says a failed save failed, rather than looking exactly like a success", async () => {const saveFn = jest.fn().mockRejectedValue(new Error("save failed"))- const restartFn = jest.fn().mockResolvedValue(undefined)+ const restartFn = jest.fn().mockResolvedValue(true)const { result } = renderHook(() => useAutoSave())act(() => {@@ -129,10 +145,12 @@ describe("useAutoSave", () => {})expect(result.current.saving).toBe(false)+ expect(result.current.message).toBe("Could not save")+ expect(result.current.isError).toBe(true)expect(restartFn).not.toHaveBeenCalled()})- it("handles restart failure gracefully", async () => {+ it("says a failed restart failed, which was silent before", async () => {const saveFn = jest.fn().mockResolvedValue(undefined)const restartFn = jest.fn().mockRejectedValue(new Error("restart failed"))const { result } = renderHook(() => useAutoSave())@@ -147,14 +165,15 @@ describe("useAutoSave", () => {})expect(result.current.saving).toBe(false)- expect(result.current.saveSuccess).toBe(false)+ expect(result.current.message).toBe("Could not restart tracking")+ expect(result.current.isError).toBe(true)})})describe("immediateSaveAndRestart", () => {it("calls saveFn immediately", async () => {const saveFn = jest.fn().mockResolvedValue(undefined)- const restartFn = jest.fn().mockResolvedValue(undefined)+ const restartFn = jest.fn().mockResolvedValue(true)const { result } = renderHook(() => useAutoSave())await act(async () => {@@ -166,7 +185,7 @@ describe("useAutoSave", () => {it("sets saving=true immediately", () => {const saveFn = jest.fn().mockReturnValue(new Promise(() => {})) // never resolves- const restartFn = jest.fn().mockResolvedValue(undefined)+ const restartFn = jest.fn().mockResolvedValue(true)const { result } = renderHook(() => useAutoSave())act(() => {@@ -179,7 +198,7 @@ describe("useAutoSave", () => {it("cancels any pending debounced save", async () => {const debouncedSave = jest.fn().mockResolvedValue(undefined)const immediateSave = jest.fn().mockResolvedValue(undefined)- const restartFn = jest.fn().mockResolvedValue(undefined)+ const restartFn = jest.fn().mockResolvedValue(true)const { result } = renderHook(() => useAutoSave())// Start a debounced save@@ -202,7 +221,7 @@ describe("useAutoSave", () => {it("schedules debounced restart after save", async () => {const saveFn = jest.fn().mockResolvedValue(undefined)- const restartFn = jest.fn().mockResolvedValue(undefined)+ const restartFn = jest.fn().mockResolvedValue(true)const { result } = renderHook(() => useAutoSave())await act(async () => {@@ -221,7 +240,7 @@ describe("useAutoSave", () => {it("handles save failure gracefully", async () => {const saveFn = jest.fn().mockRejectedValue(new Error("save failed"))- const restartFn = jest.fn().mockResolvedValue(undefined)+ const restartFn = jest.fn().mockResolvedValue(true)const { result } = renderHook(() => useAutoSave())await act(async () => {diff --git a/apps/mobile/src/hooks/__tests__/useLocationTracking.test.ts b/apps/mobile/src/hooks/__tests__/useLocationTracking.test.tsindex 2c7c1c5b..144e95c5 100644--- a/apps/mobile/src/hooks/__tests__/useLocationTracking.test.ts+++ b/apps/mobile/src/hooks/__tests__/useLocationTracking.test.ts@@ -13,13 +13,15 @@ const mockStop = jest.fn()const mockGetMostRecentLocation = jest.fn().mockResolvedValue(null)const mockIsTrackingActive = jest.fn().mockResolvedValue(false)const mockIsServiceRunning = jest.fn().mockResolvedValue(true)+const mockSaveSetting = jest.fn().mockResolvedValue(undefined)jest.mock("../../services/NativeLocationService", () => ({start: (...args: any[]) => mockStart(...args),stop: (...args: any[]) => mockStop(...args),getMostRecentLocation: (...args: any[]) => mockGetMostRecentLocation(...args),isTrackingActive: (...args: any[]) => mockIsTrackingActive(...args),- isServiceRunning: (...args: any[]) => mockIsServiceRunning(...args)+ isServiceRunning: (...args: any[]) => mockIsServiceRunning(...args),+ saveSetting: (...args: any[]) => mockSaveSetting(...args)}))// Mock permissions@@ -50,6 +52,7 @@ beforeEach(() => {// clearAllMocks keeps implementations, so restore the defaults each test explicitly overridesmockIsTrackingActive.mockResolvedValue(false)mockIsServiceRunning.mockResolvedValue(true)+ mockSaveSetting.mockResolvedValue(undefined)mockCheckPermissions.mockResolvedValue({ location: true, background: true, notifications: true })jest.spyOn(console, "log").mockImplementation()jest.spyOn(console, "error").mockImplementation()@@ -470,19 +473,31 @@ describe("useLocationTracking", () => {expect(mockStart).toHaveBeenCalledTimes(1)})- it("does not restart a dead service when location permission is gone", async () => {+ it("turns tracking off when the permission was revoked under a running service", async () => {+ // Revoking location stops the service without killing the process, so no onTrackingStopped+ // arrives and the DB intent stays true. Offering Stop for a service that can never come back+ // is the state the user sees until the next cold start, so the hook has to clear it here.mockIsTrackingActive.mockResolvedValue(true)- mockIsServiceRunning.mockResolvedValue(false)- mockCheckPermissions.mockResolvedValue({ location: false, background: false, notifications: true })mockGetMostRecentLocation.mockResolvedValue(null)- renderHook(() => useLocationTracking(DEFAULT_SETTINGS, true))+ const { result } = renderHook(() => useLocationTracking(DEFAULT_SETTINGS, true))++ await act(async () => {+ await result.current.startTracking(DEFAULT_SETTINGS)+ })+ expect(result.current.tracking).toBe(true)++ mockIsServiceRunning.mockResolvedValue(false)+ mockCheckPermissions.mockResolvedValue({ location: false, background: false, notifications: true })+ mockStart.mockClear()await act(async () => {await appStateCallback("active")})expect(mockStart).not.toHaveBeenCalled()+ expect(mockSaveSetting).toHaveBeenCalledWith("tracking_enabled", "false")+ expect(result.current.tracking).toBe(false)})it("does nothing when transitioning to background", async () => {@@ -508,7 +523,7 @@ describe("useLocationTracking", () => {expect(mockAddListener).toHaveBeenCalledWith("onLocationUpdate", expect.any(Function))})- it("updates coords when location event fires", async () => {+ it("stores a live fix's millisecond timestamp in seconds, the unit the database rows and formatTime use", async () => {let eventCallback: (event: any) => voidmockAddListener.mockImplementation((_event: string, cb: (event: any) => void) => {eventCallback = cb@@ -529,7 +544,7 @@ describe("useLocationTracking", () => {altitude: 500,speed: 1.2,bearing: 90,- timestamp: 1700000000,+ timestamp: 1700000000456,battery: 85,batteryStatus: 2})diff --git a/apps/mobile/src/hooks/__tests__/useTimeout.test.ts b/apps/mobile/src/hooks/__tests__/useTimeout.test.tsindex 8b32dbaf..03ced93f 100644--- a/apps/mobile/src/hooks/__tests__/useTimeout.test.ts+++ b/apps/mobile/src/hooks/__tests__/useTimeout.test.ts@@ -84,6 +84,18 @@ describe("useTimeout", () => {expect(callback).not.toHaveBeenCalled()})+ // Callers list the returned object in dependency arrays. A fresh one per render re-runs their+ // effects every render, which is how DataManagementScreen came to poll the database in a loop.+ it("returns the same object across renders, so a dependency on it is stable", () => {+ const { result, rerender } = renderHook(() => useTimeout())+ const first = result.current++ rerender({})+ rerender({})++ expect(result.current).toBe(first)+ })+it("clear is safe to call with no pending timeout", () => {const { result } = renderHook(() => useTimeout())diff --git a/apps/mobile/src/hooks/__tests__/useTodayTrack.test.ts b/apps/mobile/src/hooks/__tests__/useTodayTrack.test.tsindex f8db9651..a49de61d 100644--- a/apps/mobile/src/hooks/__tests__/useTodayTrack.test.ts+++ b/apps/mobile/src/hooks/__tests__/useTodayTrack.test.ts@@ -41,9 +41,17 @@ function makeCoords(ts: number, lat = 48.1, lon = 11.5) {describe("useTodayTrack", () => {describe("initial state", () => {- it("returns empty locations when not tracking", () => {+ it("loads today's track from the DB while idle, so the map can draw it before Start", async () => {+ const dbRows = [{ latitude: 48.1, longitude: 11.5, timestamp: 1000, accuracy: 10, speed: 2, altitude: 500 }]+ mockGetLocationsByDateRange.mockResolvedValueOnce(dbRows)+const { result } = renderHook(() => useTodayTrack(false, null))expect(result.current.locations).toEqual([])++ await act(async () => {})++ expect(mockGetLocationsByDateRange).toHaveBeenCalledTimes(1)+ expect(result.current.locations).toHaveLength(1)})it("loads locations from DB when tracking starts", async () => {@@ -64,10 +72,10 @@ describe("useTodayTrack", () => {})})- describe("clearing on tracking stop", () => {- it("clears locations when tracking becomes false", async () => {+ describe("tracking stop", () => {+ it("keeps today's points when tracking stops, because the day's track is still today's track", async () => {const dbRows = [{ latitude: 48.1, longitude: 11.5, timestamp: 1000, accuracy: 10, speed: 2, altitude: 500 }]- mockGetLocationsByDateRange.mockResolvedValueOnce(dbRows)+ mockGetLocationsByDateRange.mockResolvedValue(dbRows)const { result, rerender } = renderHook(({ tracking }: { tracking: boolean }) => useTodayTrack(tracking, null), {initialProps: { tracking: true }@@ -77,7 +85,8 @@ describe("useTodayTrack", () => {expect(result.current.locations).toHaveLength(1)rerender({ tracking: false })- expect(result.current.locations).toEqual([])+ await act(async () => {})+ expect(result.current.locations).toHaveLength(1)})})@@ -197,11 +206,36 @@ describe("useTodayTrack", () => {expect(calls[1][0]).toBeGreaterThan(1000000)})- it("does not subscribe to AppState when not tracking", async () => {+ it("reads nothing on an idle foreground within the same day, since nothing records idle", async () => {renderHook(() => useTodayTrack(false, null))await act(async () => {})+ expect(mockGetLocationsByDateRange).toHaveBeenCalledTimes(1)++ await act(async () => {+ appStateCallback?.("active")+ })++ expect(mockGetLocationsByDateRange).toHaveBeenCalledTimes(1)+ })++ it("drops yesterday's track on the first idle foreground after midnight, so the map does not keep drawing it as today's", async () => {+ jest.setSystemTime(new Date(2026, 8, 7, 23, 30))+ const dbRows = [{ latitude: 48.1, longitude: 11.5, timestamp: 1000, accuracy: 10, speed: 2, altitude: 500 }]+ mockGetLocationsByDateRange.mockResolvedValueOnce(dbRows)++ const { result } = renderHook(() => useTodayTrack(false, null))+ await act(async () => {})+ expect(result.current.locations).toHaveLength(1)++ jest.setSystemTime(new Date(2026, 8, 8, 0, 30))+ mockGetLocationsByDateRange.mockResolvedValueOnce([])+ await act(async () => {+ appStateCallback?.("active")+ })- expect(appStateCallback).toBeNull()+ expect(mockGetLocationsByDateRange).toHaveBeenCalledTimes(2)+ expect(mockGetLocationsByDateRange.mock.calls[1][0]).toBeGreaterThan(1000)+ expect(result.current.locations).toHaveLength(0)})})diff --git a/apps/mobile/src/hooks/useActiveProfile.ts b/apps/mobile/src/hooks/useActiveProfile.tsnew file mode 100644index 00000000..57549768--- /dev/null+++ b/apps/mobile/src/hooks/useActiveProfile.ts@@ -0,0 +1,32 @@+/**+ * Copyright (C) 2026 Max Dietrich+ * Licensed under the GNU AGPLv3. See LICENSE in the project root for details.+ */++import { useEffect, useState } from "react"+import NativeLocationService from "../services/NativeLocationService"+import type { SavedTrackingProfile } from "../types/global"+import { logger } from "../utils/logger"++/** The profile behind `activeProfileId`, or null while none is active or the id matches no saved profile. */+export function useActiveProfile(activeProfileId: number | null): SavedTrackingProfile | null {+ const [profile, setProfile] = useState<SavedTrackingProfile | null>(null)++ useEffect(() => {+ if (activeProfileId === null) {+ setProfile(null)+ return+ }+ let cancelled = false+ NativeLocationService.getProfiles()+ .then((profiles) => {+ if (!cancelled) setProfile(profiles.find((p) => p.id === activeProfileId) ?? null)+ })+ .catch((err) => logger.error("[useActiveProfile] Failed to resolve the active profile:", err))+ return () => {+ cancelled = true+ }+ }, [activeProfileId])++ return profile+}diff --git a/apps/mobile/src/hooks/useAutoSave.ts b/apps/mobile/src/hooks/useAutoSave.tsindex 76b715dd..9d4cb503 100644--- a/apps/mobile/src/hooks/useAutoSave.ts+++ b/apps/mobile/src/hooks/useAutoSave.ts@@ -9,48 +9,69 @@ import { AUTOSAVE_DEBOUNCE_MS, SAVE_SUCCESS_DISPLAY_MS } from "../constants"import { logger } from "../utils/logger"/**- * Hook that encapsulates the debounced auto-save pattern used across settings screens.+ * The debounced auto-save behind the settings screens.*- * Manages:- * - Debounced and immediate save triggers- * - Saving/success state for FloatingSaveIndicator- * - Timeout cleanup on unmount (via useTimeout)+ * A plain write is not announced: the control the user moved is the confirmation, which is how+ * Android settings behave. Only two outcomes get a message - a restart, because the service+ * cycling has nothing on screen to show for it, and a failure.*/export function useAutoSave() {const [saving, setSaving] = useState(false)const [saveSuccess, setSaveSuccess] = useState(false)+ const [message, setMessage] = useState<string | null>(null)+ const [isError, setIsError] = useState(false)const saveTimeout = useTimeout()const restartTimeout = useTimeout()+ const messageTimeout = useTimeout()const successTimeout = useTimeout()+ const announce = useCallback(+ (text: string, failed: boolean) => {+ setMessage(text)+ setIsError(failed)+ messageTimeout.set(() => setMessage(null), SAVE_SUCCESS_DISPLAY_MS)+ },+ [messageTimeout]+ )++ const runRestart = useCallback(+ async (restartFn: () => Promise<boolean>) => {+ try {+ setSaveSuccess(true)+ successTimeout.set(() => setSaveSuccess(false), SAVE_SUCCESS_DISPLAY_MS)+ if (await restartFn()) announce("Tracking restarted", false)+ } catch (err) {+ logger.error("[useAutoSave] Restart failed:", err)+ announce("Could not restart tracking", true)+ } finally {+ setSaving(false)+ }+ },+ [announce, successTimeout]+ )+/*** Schedules a debounced restart after settings are persisted.* Use when you need to save settings first, then restart tracking after the debounce.*/const debouncedSaveAndRestart = useCallback(- (saveFn: () => Promise<void>, restartFn: () => Promise<void>) => {+ (saveFn: () => Promise<void>, restartFn: () => Promise<boolean>) => {saveTimeout.set(async () => {setSaving(true)try {await saveFn()- // Restart immediately — input was already debounced by saveTimeout- restartTimeout.clear()- try {- await restartFn()- setSaveSuccess(true)- successTimeout.set(() => setSaveSuccess(false), SAVE_SUCCESS_DISPLAY_MS)- } catch (err) {- logger.error("[useAutoSave] Restart failed:", err)- } finally {- setSaving(false)- }} catch (err) {setSaving(false)logger.error("[useAutoSave] Save failed:", err)+ announce("Could not save", true)+ return}+ // Restart immediately: the input was already debounced by saveTimeout.+ restartTimeout.clear()+ await runRestart(restartFn)}, AUTOSAVE_DEBOUNCE_MS)},- [saveTimeout, restartTimeout, successTimeout]+ [saveTimeout, restartTimeout, runRestart, announce])/**@@ -59,34 +80,27 @@ export function useAutoSave() {* but batch the restart.*/const immediateSaveAndRestart = useCallback(- (saveFn: () => Promise<void>, restartFn: () => Promise<void>) => {+ (saveFn: () => Promise<void>, restartFn: () => Promise<boolean>) => {saveTimeout.clear()setSaving(true)saveFn().then(() => {- restartTimeout.set(async () => {- try {- await restartFn()- setSaveSuccess(true)- successTimeout.set(() => setSaveSuccess(false), SAVE_SUCCESS_DISPLAY_MS)- } catch (err) {- logger.error("[useAutoSave] Restart failed:", err)- } finally {- setSaving(false)- }- }, AUTOSAVE_DEBOUNCE_MS)+ restartTimeout.set(() => runRestart(restartFn), AUTOSAVE_DEBOUNCE_MS)}).catch((err) => {setSaving(false)logger.error("[useAutoSave] Save failed:", err)+ announce("Could not save", true)})},- [saveTimeout, restartTimeout, successTimeout]+ [saveTimeout, restartTimeout, runRestart, announce])return {saving,saveSuccess,+ message,+ isError,debouncedSaveAndRestart,immediateSaveAndRestart}diff --git a/apps/mobile/src/hooks/useLocationTracking.ts b/apps/mobile/src/hooks/useLocationTracking.tsindex fcaf86ef..471266e9 100644--- a/apps/mobile/src/hooks/useLocationTracking.ts+++ b/apps/mobile/src/hooks/useLocationTracking.ts@@ -70,7 +70,7 @@ export function useLocationTracking(settings: Settings, settingsHydrated: booleaaltitude: latest.altitude ?? 0,speed: latest.speed ?? 0,bearing: latest.bearing ?? 0,- timestamp: latest.timestamp ?? Date.now(),+ timestamp: latest.timestamp ?? Math.floor(Date.now() / 1000),battery: latest.battery,battery_status: latest.batteryStatus})@@ -98,7 +98,7 @@ export function useLocationTracking(settings: Settings, settingsHydrated: booleaaltitude: event.altitude,speed: event.speed,bearing: event.bearing,- timestamp: event.timestamp,+ timestamp: Math.floor(event.timestamp / 1000),battery: event.battery,battery_status: event.batteryStatus})@@ -211,19 +211,20 @@ export function useLocationTracking(settings: Settings, settingsHydrated: boolea* Includes delay for Android to release foreground service resources* @param newSettings Settings for the new service instance*/+ /** False when nothing was cycled: tracking was off, or a restart was already in flight. */const restartTracking = useCallback(- async (newSettings?: Settings) => {- // Only restart if tracking is active — settings are persisted separately,+ async (newSettings?: Settings): Promise<boolean> => {+ // Only restart if tracking is active - settings are persisted separately,// so they'll be picked up when the user starts tracking later.if (!isTrackingRef.current) {logger.debug("[useLocationTracking] Not tracking, skip restart (settings saved separately)")- return+ return false}if (restartingRef.current) {logger.debug("[useLocationTracking] Restart already in progress, queuing")restartQueuedRef.current = true- return+ return false}logger.debug("[useLocationTracking] Restarting service")@@ -237,6 +238,7 @@ export function useLocationTracking(settings: Settings, settingsHydrated: booleaawait new Promise<void>((resolve) => setTimeout(resolve, SERVICE_RESTART_DELAY_MS))await startTracking(newSettings ?? settingsRef.current)+ return true} finally {restartingRef.current = falsesetIsRestarting(false)@@ -271,7 +273,13 @@ export function useLocationTracking(settings: Settings, settingsHydrated: booleaconst perms = await checkPermissions()if (!perms.location) {- logger.warn("[useLocationTracking] Service is dead but location permission is gone, not restarting")+ logger.warn("[useLocationTracking] Service is dead and location permission is gone - clearing tracking state")+ await NativeLocationService.saveSetting("tracking_enabled", "false")+ if (listenerRef.current) {+ listenerRef.current.remove()+ listenerRef.current = null+ }+ setTracking(false)return}@@ -289,36 +297,39 @@ export function useLocationTracking(settings: Settings, settingsHydrated: boolea* Used after app restart when tracking_enabled is true in the DB.* Does NOT request permissions, but does restart the service if it died.*/- const reconnect = useCallback(async (startSettings?: Settings) => {- if (isTrackingRef.current) {- logger.debug("[useLocationTracking] Already tracking, skip reconnect")- return- }+ const reconnect = useCallback(+ async (startSettings?: Settings) => {+ if (isTrackingRef.current) {+ logger.debug("[useLocationTracking] Already tracking, skip reconnect")+ return+ }- logger.debug("[useLocationTracking] Reconnecting to active service")- setTracking(true)+ logger.debug("[useLocationTracking] Reconnecting to active service")+ setTracking(true)- await reviveIfDead(startSettings ?? settingsRef.current)+ await reviveIfDead(startSettings ?? settingsRef.current)- try {- const latest = await NativeLocationService.getMostRecentLocation()- if (latest) {- setCoords({- latitude: latest.latitude,- longitude: latest.longitude,- accuracy: latest.accuracy,- altitude: latest.altitude ?? 0,- speed: latest.speed ?? 0,- bearing: latest.bearing ?? 0,- timestamp: latest.timestamp ?? Date.now(),- battery: latest.battery,- battery_status: latest.batteryStatus- })+ try {+ const latest = await NativeLocationService.getMostRecentLocation()+ if (latest) {+ setCoords({+ latitude: latest.latitude,+ longitude: latest.longitude,+ accuracy: latest.accuracy,+ altitude: latest.altitude ?? 0,+ speed: latest.speed ?? 0,+ bearing: latest.bearing ?? 0,+ timestamp: latest.timestamp ?? Math.floor(Date.now() / 1000),+ battery: latest.battery,+ battery_status: latest.batteryStatus+ })+ }+ } catch (err) {+ logger.error("[useLocationTracking] Failed to fetch location on reconnect:", err)}- } catch (err) {- logger.error("[useLocationTracking] Failed to fetch location on reconnect:", err)- }- }, [reviveIfDead])+ },+ [reviveIfDead]+ )/*** Syncs tracking state and coords when app returns to foreground.@@ -362,7 +373,7 @@ export function useLocationTracking(settings: Settings, settingsHydrated: booleaaltitude: latest.altitude ?? 0,speed: latest.speed ?? 0,bearing: latest.bearing ?? 0,- timestamp: latest.timestamp ?? Date.now(),+ timestamp: latest.timestamp ?? Math.floor(Date.now() / 1000),battery: latest.battery,battery_status: latest.batteryStatus})diff --git a/apps/mobile/src/hooks/useTimeout.ts b/apps/mobile/src/hooks/useTimeout.tsindex 0a3ae1e2..3d11ee69 100644--- a/apps/mobile/src/hooks/useTimeout.ts+++ b/apps/mobile/src/hooks/useTimeout.ts@@ -3,7 +3,7 @@* Licensed under the GNU AGPLv3. See LICENSE in the project root for details.*/-import { useRef, useEffect, useCallback } from "react"+import { useRef, useEffect, useCallback, useMemo } from "react"/*** Hook that manages a single timeout with automatic cleanup on unmount.@@ -30,5 +30,7 @@ export function useTimeout() {}}, [])- return { set, clear }+ // Stable identity: callers list this object in dependency arrays, and a fresh one per render+ // re-runs their effects forever.+ return useMemo(() => ({ set, clear }), [set, clear])}diff --git a/apps/mobile/src/hooks/useTodayTrack.ts b/apps/mobile/src/hooks/useTodayTrack.tsindex 3a09f2d9..5ebe2450 100644--- a/apps/mobile/src/hooks/useTodayTrack.ts+++ b/apps/mobile/src/hooks/useTodayTrack.ts@@ -91,15 +91,8 @@ export function useTodayTrack(tracking: boolean, coords: LocationCoords | null)}}, [])- // Initial load + day rollover check+ // Today's track is drawn idle too, so the load does not wait for tracking; a start or stop reloads.useEffect(() => {- if (!tracking) {- locationsRef.current = []- lastTimestampRef.current = 0- loadedDayRef.current = ""- setVersion((v) => v + 1)- return- }loadFromDb()}, [tracking, loadFromDb])@@ -130,14 +123,19 @@ export function useTodayTrack(tracking: boolean, coords: LocationCoords | null)scheduleFlush()}, [tracking, coords, scheduleFlush])- // Catch up on locations missed while backgrounded (incremental)+ // Catch up on locations missed while backgrounded, and drop yesterday's track once the day has turned.useEffect(() => {- if (!tracking) return-const sub = AppState.addEventListener("change", (state) => {- if (state === "active" && lastTimestampRef.current > 0) {+ if (state !== "active") return+ if (loadedDayRef.current && loadedDayRef.current !== todayDateStr()) {+ locationsRef.current = []+ lastTimestampRef.current = 0+ loadFromDb()+ } else if (!tracking) {+ return+ } else if (lastTimestampRef.current > 0) {loadFromDb(lastTimestampRef.current)- } else if (state === "active") {+ } else {loadFromDb()}})diff --git a/apps/mobile/src/services/BackupService.ts b/apps/mobile/src/services/BackupService.tsindex ff44402c..b9f1c951 100644--- a/apps/mobile/src/services/BackupService.ts+++ b/apps/mobile/src/services/BackupService.ts@@ -7,9 +7,6 @@ import { NativeModules } from "react-native"const { BackupServiceModule } = NativeModules-export const MIN_BACKUP_PASSWORD_LENGTH = 12-export const MIN_BACKUP_PASSWORD_BITS = 50-type PasswordStrengthScore = 0 | 1 | 2 | 3 | 4export type PasswordStrengthResult = {@@ -23,6 +20,16 @@ export type BackupSource = {displayName: string | null}+export const MIN_BACKUP_PASSWORD_LENGTH = 12+export const MIN_BACKUP_PASSWORD_BITS = 50++export type BackupManifest = {+ createdAt: string+ appVersion: string+ appBuild: number+ schemaDb: number+}+function passwordToCodes(password: string): number[] {const codes = new Array<number>(password.length)for (let i = 0; i < password.length; i++) codes[i] = password.charCodeAt(i)@@ -68,6 +75,12 @@ class BackupService {}}+ /** Reads the archive's manifest and nothing else, so a wrong password costs only a retry. */+ static async describeBackup(uri: string, password: string): Promise<BackupManifest> {+ BackupService.ensureModule()+ return BackupServiceModule.describeBackup(uri, passwordToCodes(password))+ }+static async restoreBackup(uri: string, password: string): Promise<void> {BackupService.ensureModule()const codes = passwordToCodes(password)diff --git a/apps/mobile/src/services/NativeLocationService.ts b/apps/mobile/src/services/NativeLocationService.tsindex 5287351a..60dcd873 100644--- a/apps/mobile/src/services/NativeLocationService.ts+++ b/apps/mobile/src/services/NativeLocationService.ts@@ -20,6 +20,7 @@ import {TripBoundaryOverride} from "../types/global"import { logger } from "../utils/logger"+import { parseSystemPalette, type SystemPalette } from "../styles/dynamicColors"import { SETTINGS_READ_ATTEMPTS, SETTINGS_READ_RETRY_DELAY_MS } from "../constants"const { LocationServiceModule, MtlsBridgeModule, BuildConfigModule } = NativeModules@@ -255,23 +256,20 @@ class NativeLocationService {)}- /** DEV ONLY: Insert dummy location data for testing */+ // ============================================================================+ // CLEANUP OPERATIONS+ // ============================================================================+static async insertDummyData(): Promise<number> {this.ensureModule()return this.safeExecute(() => LocationServiceModule.insertDummyData(), 0, "insertDummyData failed")}- // ============================================================================- // CLEANUP OPERATIONS- // ============================================================================-- /**- * Deletes all successfully sent locations- */- static async clearSentHistory(): Promise<void> {+ /** Deletes the locations themselves where `sent = 1`, imported rows included. Resolves how many went. */+ static async clearSentHistory(): Promise<number> {this.ensureModule()- logger.debug("[NativeLocationService] Clearing sent history")- await LocationServiceModule.clearSentHistory()+ logger.debug("[NativeLocationService] Deleting synced locations")+ return LocationServiceModule.clearSentHistory()}/**@@ -305,6 +303,21 @@ class NativeLocationService {return LocationServiceModule.deleteOlderThan(days)}+ /**+ * What `deleteOlderThan(days)` would take, plus the boundary it used, so a preview cannot name a+ * different one. The timestamp index answers this, so it is safe to call as the user types.+ */+ static async countOlderThan(days: number): Promise<{ total: number; cutoffSeconds: number }> {+ this.ensureModule()+ return LocationServiceModule.countOlderThan(days)+ }++ /** How many of those have never been uploaded. Reads every match, so call it only on a press. */+ static async countUnsentOlderThan(days: number): Promise<number> {+ this.ensureModule()+ return LocationServiceModule.countUnsentOlderThan(days)+ }+/*** Deletes locations within an inclusive timestamp range (seconds since epoch)* @returns Count of deleted records@@ -549,9 +562,9 @@ class NativeLocationService {}/**- * Returns the name of the currently active tracking profile, or null if using defaults+ * Returns the name and id of the currently active tracking profile, or null if using defaults*/- static async getActiveProfileName(): Promise<string | null> {+ static async getActiveProfile(): Promise<{ name: string; id: number | null } | null> {this.ensureModule()return this.safeExecute(() => LocationServiceModule.getActiveProfile(), null, "getActiveProfile failed")}@@ -713,16 +726,16 @@ class NativeLocationService {* @returns Build config object with SDK versions, tools versions, etc.*/static getBuildConfig(): {+ VERSION_NAME: string+ VERSION_CODE: number+ FLAVOR: string+ APP_LANGUAGE: stringMIN_SDK_VERSION: numberTARGET_SDK_VERSION: numberCOMPILE_SDK_VERSION: numberBUILD_TOOLS_VERSION: stringKOTLIN_VERSION: stringNDK_VERSION: string- VERSION_NAME: string- VERSION_CODE: number- FLAVOR: string- APP_LANGUAGE: string} | null {if (!BuildConfigModule) {logger.warn("[NativeLocationService] BuildConfigModule not available")@@ -731,6 +744,19 @@ class NativeLocationService {return BuildConfigModule}+ /**+ * The wallpaper-derived tonal steps, or null below API 31 and whenever the map is not the+ * complete set the theme reads.+ */+ static async getSystemPalette(): Promise<SystemPalette | null> {+ if (!BuildConfigModule) return null+ return this.safeExecute(+ async () => parseSystemPalette(await BuildConfigModule.getSystemPalette()),+ null,+ "Failed to read the system palette"+ )+ }+// ============================================================================// DEVICE INFORMATION// ============================================================================@@ -741,11 +767,10 @@ class NativeLocationService {static async getDeviceInfo(): Promise<{model: stringbrand: string- manufacturer: string- device: string- deviceId: stringsystemVersion: stringapiLevel: number+ manufacturer: string+ deviceId: string}> {this.ensureModule()return LocationServiceModule.getDeviceInfo()@@ -821,9 +846,9 @@ class NativeLocationService {}/** Returns null if there are no entries to export. */- static async exportFileLogToUri(treeUri: string): Promise<string | null> {+ static async exportFileLogToUri(treeUri: string, header = "", appLog = ""): Promise<string | null> {this.ensureModule()- return LocationServiceModule.exportFileLogToUri(treeUri)+ return LocationServiceModule.exportFileLogToUri(treeUri, header, appLog)}// ============================================================================@@ -876,6 +901,7 @@ class NativeLocationService {*/static async getAutoExportStatus(): Promise<{enabled: boolean+ running: booleanformat: stringinterval: stringuri: string | nulldiff --git a/apps/mobile/src/services/__tests__/NativeLocationService.test.ts b/apps/mobile/src/services/__tests__/NativeLocationService.test.tsindex 2ece1609..227766aa 100644--- a/apps/mobile/src/services/__tests__/NativeLocationService.test.ts+++ b/apps/mobile/src/services/__tests__/NativeLocationService.test.ts@@ -9,16 +9,20 @@ jest.mock("react-native", () => ({sent: 100,total: 105,today: 20,- databaseSizeMB: 1.5+ databaseSizeMB: 1.5,+ lastSyncTime: 0,+ lastSyncError: ""}),getTableData: jest.fn().mockResolvedValue([]),getLocationsByDateRange: jest.fn().mockResolvedValue([]),getMostRecentLocation: jest.fn().mockResolvedValue(null),manualFlush: jest.fn().mockResolvedValue(true),- clearSentHistory: jest.fn().mockResolvedValue(undefined),+ clearSentHistory: jest.fn().mockResolvedValue(42),clearQueue: jest.fn().mockResolvedValue(10),clearAllLocations: jest.fn().mockResolvedValue(50),deleteOlderThan: jest.fn().mockResolvedValue(25),+ countOlderThan: jest.fn().mockResolvedValue({ total: 3120, cutoffSeconds: 1735689600 }),+ countUnsentOlderThan: jest.fn().mockResolvedValue(96),deleteLocationsInRange: jest.fn().mockResolvedValue(7),deleteLocationsByIds: jest.fn().mockResolvedValue(1),vacuumDatabase: jest.fn().mockResolvedValue(undefined),@@ -36,13 +40,15 @@ jest.mock("react-native", () => ({getDeviceInfo: jest.fn().mockResolvedValue({model: "Pixel 7",brand: "Google",- manufacturer: "Google",- device: "panther",- deviceId: "panther",systemVersion: "14",apiLevel: 34}),writeFile: jest.fn().mockResolvedValue("/cache/test.csv"),+ setFileLoggingEnabled: jest.fn().mockResolvedValue(undefined),+ clearFileLog: jest.fn().mockResolvedValue(undefined),+ getFileLogSize: jest.fn().mockResolvedValue(2516582),+ getNativeLogs: jest.fn().mockResolvedValue(["2026-09-09 09:00:00.000 INFO/Service: started"]),+ exportFileLogToUri: jest.fn().mockResolvedValue("content://tree/logs/colota-log.txt"),shareFile: jest.fn().mockResolvedValue(true),pickExportDirectory: jest.fn().mockResolvedValue("content://com.android.externalstorage/tree/primary%3AExports"),scheduleAutoExport: jest.fn().mockResolvedValue(true),@@ -81,15 +87,10 @@ jest.mock("react-native", () => ({getActiveProfile: jest.fn().mockResolvedValue(null)},BuildConfigModule: {- MIN_SDK_VERSION: 26,- TARGET_SDK_VERSION: 34,- COMPILE_SDK_VERSION: 34,- BUILD_TOOLS_VERSION: "34.0.0",- KOTLIN_VERSION: "1.9.0",- NDK_VERSION: "25.1.8937393",VERSION_NAME: "1.0.0",VERSION_CODE: 1,- FLAVOR: "gms"+ FLAVOR: "gms",+ getSystemPalette: jest.fn().mockResolvedValue(null)}}}))@@ -234,7 +235,9 @@ describe("NativeLocationService", () => {sent: 100,total: 105,today: 20,- databaseSizeMB: 1.5+ databaseSizeMB: 1.5,+ lastSyncTime: 0,+ lastSyncError: ""})})})@@ -328,13 +331,64 @@ describe("NativeLocationService", () => {const config = NativeLocationService.getBuildConfig()expect(config).toEqual(expect.objectContaining({- MIN_SDK_VERSION: 26,VERSION_NAME: "1.0.0"}))})})+ describe("getSystemPalette", () => {+ const palette = {+ accent1_100: "#D6E3FF",+ accent1_200: "#ABC7FF",+ accent1_300: "#8AB4F8",+ accent1_600: "#2B5CB8",+ accent1_700: "#12459E",+ accent1_800: "#002E6B",+ accent1_900: "#001B3F",+ neutral1_0: "#FFFFFF",+ neutral1_50: "#F3F3F6",+ neutral1_600: "#5B5C63",+ neutral1_700: "#43444B",+ neutral1_800: "#2C2D33",+ neutral1_900: "#1A1B1F",+ neutral2_100: "#E3E2E9",+ neutral2_200: "#C7C6CE",+ neutral2_300: "#ABAAB2",+ neutral2_400: "#909097",+ neutral2_500: "#76767D",+ neutral2_600: "#5E5E65",+ neutral2_700: "#46464D",+ neutral2_800: "#2F2F35"+ }++ it("passes a complete palette through", async () => {+ ;(NativeModules.BuildConfigModule.getSystemPalette as jest.Mock).mockResolvedValueOnce(palette)++ await expect(NativeLocationService.getSystemPalette()).resolves.toEqual(palette)+ })++ it("returns null below API 31, where the native side has nothing to send", async () => {+ ;(NativeModules.BuildConfigModule.getSystemPalette as jest.Mock).mockResolvedValueOnce(null)++ await expect(NativeLocationService.getSystemPalette()).resolves.toBeNull()+ })++ it("drops a partial palette rather than letting undefined reach a style prop", async () => {+ const incomplete: Record<string, string> = { ...palette }+ delete incomplete.neutral2_500+ ;(NativeModules.BuildConfigModule.getSystemPalette as jest.Mock).mockResolvedValueOnce(incomplete)++ await expect(NativeLocationService.getSystemPalette()).resolves.toBeNull()+ })++ it("returns null when the bridge rejects, so a failed read is not a crash", async () => {+ ;(NativeModules.BuildConfigModule.getSystemPalette as jest.Mock).mockRejectedValueOnce(new Error("no resource"))++ await expect(NativeLocationService.getSystemPalette()).resolves.toBeNull()+ })+ })+describe("geofence operations", () => {it("createGeofence passes correct parameters", async () => {await NativeLocationService.createGeofence({@@ -360,24 +414,24 @@ describe("NativeLocationService", () => {})})- describe("getActiveProfileName", () => {- it("returns profile name when a profile is active", async () => {- nativeMock.getActiveProfile.mockResolvedValueOnce("Charging")- const name = await NativeLocationService.getActiveProfileName()- expect(name).toBe("Charging")+ describe("getActiveProfile", () => {+ it("returns the name and id when a profile is active, so a reconnecting UI can resolve its interval", async () => {+ nativeMock.getActiveProfile.mockResolvedValueOnce({ name: "Charging", id: 3 })+ const profile = await NativeLocationService.getActiveProfile()+ expect(profile).toEqual({ name: "Charging", id: 3 })expect(nativeMock.getActiveProfile).toHaveBeenCalled()})it("returns null when no profile is active", async () => {nativeMock.getActiveProfile.mockResolvedValueOnce(null)- const name = await NativeLocationService.getActiveProfileName()- expect(name).toBeNull()+ const profile = await NativeLocationService.getActiveProfile()+ expect(profile).toBeNull()})it("returns null on error", async () => {nativeMock.getActiveProfile.mockRejectedValueOnce(new Error("Native error"))- const name = await NativeLocationService.getActiveProfileName()- expect(name).toBeNull()+ const profile = await NativeLocationService.getActiveProfile()+ expect(profile).toBeNull()})})@@ -395,6 +449,44 @@ describe("NativeLocationService", () => {})})+ describe("the age counts", () => {+ it("hands the age to the cheap count and returns the boundary native used", async () => {+ const counted = await NativeLocationService.countOlderThan(90)++ expect(nativeMock.countOlderThan).toHaveBeenCalledWith(90)+ expect(counted).toEqual({ total: 3120, cutoffSeconds: 1735689600 })+ })++ // Separate on purpose: this one reads every matching row, so it runs on a press and never while+ // the user types. A single method would put that cost on the typing path.+ it("keeps the expensive unsent count a separate call", async () => {+ const unsent = await NativeLocationService.countUnsentOlderThan(90)++ expect(nativeMock.countUnsentOlderThan).toHaveBeenCalledWith(90)+ expect(unsent).toBe(96)+ expect(nativeMock.countOlderThan).not.toHaveBeenCalled()+ })+ })++ describe("the bulk deletes", () => {+ it("resolves how many rows each one took", async () => {+ expect(await NativeLocationService.clearSentHistory()).toBe(42)+ expect(await NativeLocationService.clearQueue()).toBe(10)+ expect(await NativeLocationService.clearAllLocations()).toBe(50)+ expect(await NativeLocationService.deleteOlderThan(90)).toBe(25)+ expect(nativeMock.deleteOlderThan).toHaveBeenCalledWith(90)+ })++ // Each is a static opening with this.ensureModule(), so a bare reference loses its receiver and+ // throws before it reaches native. Three of these shipped dead exactly that way.+ it("survives being passed as a bare callback", async () => {+ const run = async (fn: () => Promise<number>) => fn()++ await expect(run(() => NativeLocationService.clearSentHistory())).resolves.toBe(42)+ await expect(run(() => NativeLocationService.clearAllLocations())).resolves.toBe(50)+ })+ })+describe("file operations", () => {it("writeFile returns file path", async () => {const path = await NativeLocationService.writeFile("test.csv", "data")@@ -402,6 +494,48 @@ describe("NativeLocationService", () => {})})+ describe("file logging", () => {+ it("setFileLoggingEnabled passes the value through", async () => {+ await NativeLocationService.setFileLoggingEnabled(true)+ expect(nativeMock.setFileLoggingEnabled).toHaveBeenCalledWith(true)++ await NativeLocationService.setFileLoggingEnabled(false)+ expect(nativeMock.setFileLoggingEnabled).toHaveBeenCalledWith(false)+ })++ it("clearFileLog calls native module", async () => {+ await NativeLocationService.clearFileLog()+ expect(nativeMock.clearFileLog).toHaveBeenCalled()+ })++ it("getFileLogSize returns the byte count", async () => {+ await expect(NativeLocationService.getFileLogSize()).resolves.toBe(2516582)+ })++ it("getNativeLogs returns the lines the bridge answered with", async () => {+ await expect(NativeLocationService.getNativeLogs()).resolves.toEqual([+ "2026-09-09 09:00:00.000 INFO/Service: started"+ ])+ })++ /**+ * The header and the app log are what turn the exported file from a Kotlin-only stream into+ * the whole picture, and nothing else can supply them: native has no access to the JS ring+ * buffer or the build config. Dropping either argument silently exports the old file.+ */+ it("exportFileLogToUri carries the header and the app log across", async () => {+ const uri = await NativeLocationService.exportFileLogToUri("content://tree/logs", "HEADER\n", "APPLOG\n")++ expect(uri).toBe("content://tree/logs/colota-log.txt")+ expect(nativeMock.exportFileLogToUri).toHaveBeenCalledWith("content://tree/logs", "HEADER\n", "APPLOG\n")+ })++ it("exportFileLogToUri returns null when there was nothing recorded", async () => {+ nativeMock.exportFileLogToUri.mockResolvedValueOnce(null)+ await expect(NativeLocationService.exportFileLogToUri("content://tree/logs", "", "")).resolves.toBeNull()+ })+ })+describe("auto-export", () => {it("pickExportDirectory returns SAF URI", async () => {const uri = await NativeLocationService.pickExportDirectory()diff --git a/apps/mobile/src/services/__tests__/modalService.test.ts b/apps/mobile/src/services/__tests__/modalService.test.tsnew file mode 100644index 00000000..d168374f--- /dev/null+++ b/apps/mobile/src/services/__tests__/modalService.test.ts@@ -0,0 +1,31 @@+import { registerModalHandler, showPrompt, type ModalRequest } from "../modalService"++describe("showPrompt", () => {+ let last: ModalRequest | null = null++ beforeEach(() => {+ last = null+ registerModalHandler((request) => {+ last = request+ })+ })++ it("puts Cancel first and the confirm last, seeds the field and resolves the trimmed text on confirm", async () => {+ const answer = showPrompt({ title: "Note", initialValue: "Coffee", placeholder: "Add a note", multiline: true })++ expect(last!.buttons.map((b) => b.text)).toEqual(["Cancel", "Save"])+ expect(last!.input).toEqual({ placeholder: "Add a note", initialValue: "Coffee", multiline: true })+ last!.resolve(1, " Lunch ")+ await expect(answer).resolves.toBe("Lunch")+ })++ it("resolves null on Cancel and an empty string on a cleared field, which are different answers", async () => {+ const cancelled = showPrompt({ title: "Note" })+ last!.resolve(0, "typed anyway")+ await expect(cancelled).resolves.toBeNull()++ const cleared = showPrompt({ title: "Note" })+ last!.resolve(1, " ")+ await expect(cleared).resolves.toBe("")+ })+})diff --git a/apps/mobile/src/services/modalService.ts b/apps/mobile/src/services/modalService.tsindex d32ba3d5..24098b87 100644--- a/apps/mobile/src/services/modalService.ts+++ b/apps/mobile/src/services/modalService.ts@@ -7,15 +7,22 @@ import { Alert } from "react-native"export type AlertVariant = "info" | "error" | "warning" | "success"+export interface PromptInput {+ placeholder?: string+ initialValue?: string+ multiline?: boolean+}+export interface ModalRequest {title: stringmessage: stringvariant: AlertVariant+ input?: PromptInputbuttons: Array<{text: stringstyle: "primary" | "secondary" | "destructive"}>- resolve: (buttonIndex: number) => void+ resolve: (buttonIndex: number, value?: string) => void}type ModalHandler = (request: ModalRequest) => void@@ -115,3 +122,42 @@ export function showConfirm(options: {})})}++export function showPrompt(options: {+ title: string+ message?: string+ placeholder?: string+ initialValue?: string+ multiline?: boolean+ confirmText?: string+ cancelText?: string+}): Promise<string | null> {+ const {+ title,+ message = "",+ placeholder,+ initialValue,+ multiline,+ confirmText = "Save",+ cancelText = "Cancel"+ } = options++ return new Promise((resolve) => {+ if (!_handler) {+ resolve(null)+ return+ }++ _handler({+ title,+ message,+ variant: "info",+ input: { placeholder, initialValue, multiline },+ buttons: [+ { text: cancelText, style: "secondary" },+ { text: confirmText, style: "primary" }+ ],+ resolve: (index, value) => resolve(index === 1 ? (value ?? "").trim() : null)+ })+ })+}diff --git a/apps/mobile/src/styles/__tests__/dynamicColors.test.ts b/apps/mobile/src/styles/__tests__/dynamicColors.test.tsnew file mode 100644index 00000000..be5d30a4--- /dev/null+++ b/apps/mobile/src/styles/__tests__/dynamicColors.test.ts@@ -0,0 +1,98 @@+import { lightColors, darkColors } from "@colota/shared"+import { buildDynamicColors, parseSystemPalette, type SystemPalette } from "../dynamicColors"++// A wallpaper palette in the Android numbering: 0 is the lightest step, 900 the darkest.+const palette: SystemPalette = {+ accent1_100: "#D6E3FF",+ accent1_200: "#ABC7FF",+ accent1_300: "#8AB4F8",+ accent1_600: "#2B5CB8",+ accent1_700: "#12459E",+ accent1_800: "#002E6B",+ accent1_900: "#001B3F",+ neutral1_0: "#FFFFFF",+ neutral1_50: "#F3F3F6",+ neutral1_600: "#5B5C63",+ neutral1_700: "#43444B",+ neutral1_800: "#2C2D33",+ neutral1_900: "#1A1B1F",+ neutral2_100: "#E3E2E9",+ neutral2_200: "#C7C6CE",+ neutral2_300: "#ABAAB2",+ neutral2_400: "#909097",+ neutral2_500: "#76767D",+ neutral2_600: "#5E5E65",+ neutral2_700: "#46464D",+ neutral2_800: "#2F2F35"+}++describe("parseSystemPalette", () => {+ it("accepts the complete map the bridge returns", () => {+ expect(parseSystemPalette({ ...palette })).toEqual(palette)+ })++ it("rejects a map missing a step, which would put undefined into a style prop", () => {+ const incomplete: Record<string, string> = { ...palette }+ delete incomplete.neutral2_500++ expect(parseSystemPalette(incomplete)).toBeNull()+ })++ it("rejects a value that is not opaque hex, because the theme concatenates alpha onto it", () => {+ expect(parseSystemPalette({ ...palette, accent1_600: "rgb(43, 92, 184)" })).toBeNull()+ })++ it("rejects null, which is what the bridge returns below API 31", () => {+ expect(parseSystemPalette(null)).toBeNull()+ })+})++describe("buildDynamicColors", () => {+ it("keeps the status colours out of the wallpaper, so an error stays red", () => {+ const light = buildDynamicColors(palette, false)+ const dark = buildDynamicColors(palette, true)++ expect(light.error).toBe(lightColors.error)+ expect(light.warning).toBe(lightColors.warning)+ expect(light.success).toBe(lightColors.success)+ expect(light.info).toBe(lightColors.info)+ expect(dark.error).toBe(darkColors.error)+ })++ it("fills every key the theme has, so no consumer reads undefined", () => {+ expect(Object.keys(buildDynamicColors(palette, false)).sort()).toEqual(Object.keys(lightColors).sort())+ expect(Object.keys(buildDynamicColors(palette, true)).sort()).toEqual(Object.keys(darkColors).sort())+ })++ it("pairs light text with a dark accent and the reverse, so contrast survives any wallpaper hue", () => {+ const light = buildDynamicColors(palette, false)+ const dark = buildDynamicColors(palette, true)++ // Light mode paints on a dark accent, so its ink is the lightest neutral.+ expect(light.primary).toBe(palette.accent1_600)+ expect(light.textOnPrimary).toBe(palette.neutral1_0)+ // Dark mode paints on a light accent, so its ink is the darkest.+ expect(dark.primary).toBe(palette.accent1_200)+ expect(dark.textOnPrimary).toBe(palette.neutral1_900)+ })++ it("puts dark ink on the light container and the reverse, which a single mapping could not", () => {+ const light = buildDynamicColors(palette, false)+ const dark = buildDynamicColors(palette, true)++ expect(light.primaryContainer).toBe(palette.accent1_100)+ expect(light.onPrimaryContainer).toBe(palette.accent1_900)+ expect(dark.primaryContainer).toBe(palette.accent1_800)+ expect(dark.onPrimaryContainer).toBe(palette.accent1_100)+ })++ it("puts text above its surface in tone, in both modes", () => {+ const light = buildDynamicColors(palette, false)+ const dark = buildDynamicColors(palette, true)++ expect(light.background).toBe(palette.neutral1_50)+ expect(light.text).toBe(palette.neutral1_900)+ expect(dark.background).toBe(palette.neutral1_900)+ expect(dark.text).toBe(palette.neutral1_50)+ })+})diff --git a/apps/mobile/src/styles/dynamicColors.ts b/apps/mobile/src/styles/dynamicColors.tsnew file mode 100644index 00000000..c77bf1af--- /dev/null+++ b/apps/mobile/src/styles/dynamicColors.ts@@ -0,0 +1,120 @@+/**+ * Copyright (C) 2026 Max Dietrich+ * Licensed under the GNU AGPLv3. See LICENSE in the project root for details.+ */++import { ThemeColors } from "../types/global"+import { darkColors, lightColors } from "./colors"++// The steps BuildConfigModule.getSystemPalette returns. Android numbers them the other way round+// from Material tone: 0 is the lightest step and 900 the darkest.+const PALETTE_STEPS = [+ "accent1_100",+ "accent1_200",+ "accent1_300",+ "accent1_600",+ "accent1_700",+ "accent1_800",+ "accent1_900",+ "neutral1_0",+ "neutral1_50",+ "neutral1_600",+ "neutral1_700",+ "neutral1_800",+ "neutral1_900",+ "neutral2_100",+ "neutral2_200",+ "neutral2_300",+ "neutral2_400",+ "neutral2_500",+ "neutral2_600",+ "neutral2_700",+ "neutral2_800"+] as const++export type SystemPalette = Record<(typeof PALETTE_STEPS)[number], string>++const HEX = /^#[0-9A-Fa-f]{6}$/++/**+ * A palette missing a step would put `undefined` into a style prop, so a partial map is no palette+ * at all and the caller keeps the brand colours.+ */+export function parseSystemPalette(raw: unknown): SystemPalette | null {+ if (!raw || typeof raw !== "object") return null+ const map = raw as Record<string, unknown>+ for (const step of PALETTE_STEPS) {+ if (typeof map[step] !== "string" || !HEX.test(map[step] as string)) return null+ }+ return map as SystemPalette+}++/**+ * Maps the wallpaper palette onto the theme. Status colours are never mapped: an error stays red+ * whatever the wallpaper is. Text is paired with its surface by tone, so contrast does not depend+ * on which hue the wallpaper produced.+ */+export function buildDynamicColors(palette: SystemPalette, isDark: boolean): ThemeColors {+ const base = isDark ? darkColors : lightColors+ const fixed = {+ success: base.success,+ warning: base.warning,+ error: base.error,+ info: base.info,+ overlay: base.overlay,+ primaryLight: base.primaryLight,+ cardElevated: base.cardElevated,+ pressedOpacity: base.pressedOpacity,+ borderRadius: base.borderRadius+ }++ if (isDark) {+ return {+ ...fixed,+ primary: palette.accent1_200,+ primaryDark: palette.accent1_300,+ primaryContainer: palette.accent1_800,+ onPrimaryContainer: palette.accent1_100,+ well: palette.neutral1_800,+ background: palette.neutral1_900,+ backgroundElevated: palette.neutral1_800,+ card: palette.neutral1_700,+ surfaceRaised: palette.neutral1_600,+ surface: palette.neutral1_800,+ text: palette.neutral1_50,+ textSecondary: palette.neutral2_200,+ textLight: palette.neutral2_300,+ textDisabled: palette.neutral2_400,+ border: palette.neutral2_700,+ borderLight: palette.neutral2_800,+ divider: palette.neutral2_700,+ placeholder: palette.neutral2_400,+ link: palette.accent1_200,+ textOnPrimary: palette.neutral1_900+ }+ }++ return {+ ...fixed,+ primary: palette.accent1_600,+ primaryDark: palette.accent1_700,+ primaryContainer: palette.accent1_100,+ onPrimaryContainer: palette.accent1_900,+ well: palette.neutral2_100,+ background: palette.neutral1_50,+ backgroundElevated: palette.neutral1_0,+ card: palette.neutral1_0,+ surfaceRaised: palette.neutral1_0,+ surface: palette.neutral1_0,+ text: palette.neutral1_900,+ textSecondary: palette.neutral2_700,+ textLight: palette.neutral2_600,+ textDisabled: palette.neutral2_500,+ border: palette.neutral2_200,+ borderLight: palette.neutral2_100,+ divider: palette.neutral2_200,+ placeholder: palette.neutral2_500,+ link: palette.accent1_700,+ textOnPrimary: palette.neutral1_0+ }+}diff --git a/apps/mobile/src/types/__tests__/defaults.test.ts b/apps/mobile/src/types/__tests__/defaults.test.tsindex c1c056d8..29d3ad2e 100644--- a/apps/mobile/src/types/__tests__/defaults.test.ts+++ b/apps/mobile/src/types/__tests__/defaults.test.ts@@ -117,15 +117,12 @@ describe("TRACKING_PRESETS", () => {expect(TRACKING_PRESETS[name].label).toBeTruthy()})- it.each(presetNames)("%s description uses bullet separator for sync info", (name) => {- const parts = TRACKING_PRESETS[name].description.split(" • ")- expect(parts[0]).toBeTruthy()- expect(parts[0]).not.toContain("Send")- expect(parts[0]).not.toContain("Batch")+ it.each(presetNames)("%s names its cost, which the row prints beside the numbers it prices", (name) => {+ expect(TRACKING_PRESETS[name].cost).toMatch(/battery/)})- it.each(presetNames)("%s has valid batteryImpact", (name) => {- expect(["Low", "Medium", "High"]).toContain(TRACKING_PRESETS[name].batteryImpact)+ it("labels read in sentence case, like every other row", () => {+ expect(TRACKING_PRESETS.powersaver.label).toBe("Power saver")})it("instant has shortest interval", () => {@@ -155,6 +152,13 @@ describe("API_TEMPLATES", () => {expect(API_TEMPLATES[name].description).toBeTruthy()})+ it.each(templateNames)(+ "%s shows the endpoint shape it expects, since the field is where a self-hoster needs it",+ (name) => {+ expect(API_TEMPLATES[name].endpointExample).toMatch(/^https?:\/\//)+ }+ )+it.each(templateNames)("%s customFields have key and value", (name) => {for (const field of API_TEMPLATES[name].customFields) {expect(field.key).toBeTruthy()diff --git a/apps/mobile/src/types/global.ts b/apps/mobile/src/types/global.tsindex aa38e6bf..32caa06e 100644--- a/apps/mobile/src/types/global.ts+++ b/apps/mobile/src/types/global.ts@@ -34,6 +34,8 @@ export interface LocationCoords {timestamp?: number/** User-entered free-text note (POI annotation). Local-only, not synced. */note?: string+ /** 1 once the point reached the server, 0 while it waits in the queue. */+ sent?: number}export interface Geofence {@@ -60,7 +62,7 @@ export interface LocationTrackingResult {tracking: booleanstartTracking: (overrideSettings?: Settings) => Promise<void>stopTracking: () => void- restartTracking: (newSettings?: Settings) => Promise<void>+ restartTracking: (newSettings?: Settings) => Promise<boolean>reconnect: (settings?: Settings) => Promise<void>settings: Settings}@@ -69,8 +71,6 @@ export interface LocationTrackingResult {// API CONFIGURATION// ============================================================================-export type ServerStatus = "connected" | "error" | "notConfigured"-export interface ConnectionStatusProps {endpoint: string | nullnavigation: any@@ -109,6 +109,8 @@ export type HttpMethod = "POST" | "GET"export type SyncCondition = "any" | "wifi_any" | "wifi_ssid" | "vpn"+export type ServerStatus = "connected" | "error" | "notConfigured"+export type ApiTemplateName ="custom" | "dawarich" | "geopulse" | "overland" | "owntracks" | "phonetrack" | "reitti" | "traccar"@@ -121,11 +123,17 @@ export interface ApiTemplate {fieldMap: FieldMapcustomFields: CustomField[]httpMethod?: HttpMethod+ /** The shape of a working endpoint, shown as the field's placeholder and helper. */+ endpointExample: string+ /** Dawarich's batch mode posts elsewhere than its OwnTracks mode. */+ batchEndpointExample?: string}export const API_TEMPLATES: Record<Exclude<ApiTemplateName, "custom">, ApiTemplate> = {dawarich: {name: "dawarich",+ endpointExample: "https://dawarich.example/api/v1/owntracks/points?api_key=YOUR_KEY",+ batchEndpointExample: "https://dawarich.example/api/v1/overland/batches?api_key=YOUR_KEY",label: "Dawarich",description: "OwnTracks-compatible format for Dawarich",fieldMap: {@@ -143,6 +151,7 @@ export const API_TEMPLATES: Record<Exclude<ApiTemplateName, "custom">, ApiTempla},geopulse: {name: "geopulse",+ endpointExample: "https://geopulse.example/api/colota",label: "GeoPulse",description: "Native Colota format for GeoPulse",fieldMap: {@@ -160,6 +169,7 @@ export const API_TEMPLATES: Record<Exclude<ApiTemplateName, "custom">, ApiTempla},overland: {name: "overland",+ endpointExample: "https://overland.example/",label: "Overland",description: "Overland-compatible batch endpoint (GeoJSON Features)",fieldMap: {@@ -177,6 +187,7 @@ export const API_TEMPLATES: Record<Exclude<ApiTemplateName, "custom">, ApiTempla},owntracks: {name: "owntracks",+ endpointExample: "https://owntracks.example/pub",label: "OwnTracks",description: "Standard OwnTracks HTTP format",fieldMap: {@@ -197,6 +208,7 @@ export const API_TEMPLATES: Record<Exclude<ApiTemplateName, "custom">, ApiTempla},phonetrack: {name: "phonetrack",+ endpointExample: "https://nextcloud.example/apps/phonetrack/log/owntracks/SESSION_TOKEN/DEVICE_NAME",label: "PhoneTrack",description: "Nextcloud PhoneTrack logging format",fieldMap: {@@ -214,6 +226,7 @@ export const API_TEMPLATES: Record<Exclude<ApiTemplateName, "custom">, ApiTempla},reitti: {name: "reitti",+ endpointExample: "https://reitti.example/api/location",label: "Reitti",description: "OwnTracks-compatible format for Reitti",fieldMap: {@@ -231,6 +244,7 @@ export const API_TEMPLATES: Record<Exclude<ApiTemplateName, "custom">, ApiTempla},traccar: {name: "traccar",+ endpointExample: "http://192.168.1.10:5055",label: "Traccar",description: "Traccar OsmAnd protocol (HTTP GET)",httpMethod: "GET",@@ -261,6 +275,8 @@ export interface TrackingPresetConfig {syncInterval: numberretryInterval: numberlabel: string+ /** What the preset costs, read beside the numbers it prices. */+ cost: stringdescription: stringbatteryImpact: BatteryImpact}@@ -272,6 +288,7 @@ export const TRACKING_PRESETS = {syncInterval: 0,retryInterval: 30,label: "Instant",+ cost: "most battery, finest track",description: "Track every 5s • Send instantly",batteryImpact: "High"},@@ -281,6 +298,7 @@ export const TRACKING_PRESETS = {syncInterval: 300,retryInterval: 300,label: "Balanced",+ cost: "moderate battery, fewer wake-ups",description: "Track every 30s • Batch 5 min",batteryImpact: "Medium"},@@ -289,7 +307,8 @@ export const TRACKING_PRESETS = {distance: 2,syncInterval: 900,retryInterval: 900,- label: "Power Saver",+ label: "Power saver",+ cost: "least battery, coarser track",description: "Track every 60s • Batch 15 min",batteryImpact: "Low"}@@ -419,6 +438,10 @@ export interface DatabaseStats {total: numbertoday: numberdatabaseSizeMB: number+ /** Epoch milliseconds of the last successful sync, 0 when none has happened yet. */+ lastSyncTime?: number+ /** The masked message of the last sync failure that crossed the consecutive-failure gate, empty after a success. */+ lastSyncError?: string}// ============================================================================diff --git a/apps/mobile/src/utils/__tests__/certificateState.test.ts b/apps/mobile/src/utils/__tests__/certificateState.test.tsnew file mode 100644index 00000000..5a8aadd2--- /dev/null+++ b/apps/mobile/src/utils/__tests__/certificateState.test.ts@@ -0,0 +1,69 @@+import { describeCertificate } from "../certificateState"+import { CERT_EXPIRY_WARNING_DAYS } from "../../constants"+import { formatDateWithYear, loadDisplayPreferences } from "../geo"++const mockGetSetting = jest.fn()+jest.mock("../../services/NativeLocationService", () => ({+ __esModule: true,+ default: { getSetting: (...args: string[]) => mockGetSetting(...args) }+}))++beforeAll(async () => {+ mockGetSetting.mockResolvedValue("")+ await loadDisplayPreferences()+})++const DAY = 24 * 60 * 60 * 1000+const NOW = new Date(2026, 8, 9, 12, 0, 0)+const cert = (daysLeft: number, extra: Record<string, unknown> = {}) => ({+ configured: true as const,+ subject: "CN=max",+ issuer: "CN=Home CA",+ notBefore: NOW.getTime() - 365 * DAY,+ notAfter: NOW.getTime() + daysLeft * DAY + 1000,+ ...extra+})++describe("describeCertificate", () => {+ it("is Not set without a certificate, so the hub row and the card agree", () => {+ expect(describeCertificate(null).rowSub).toBe("Not set")+ expect(describeCertificate({ configured: false }).state).toBe("none")+ })++ it("reads Valid with the date and where the key lives, since the two origins differ on backup and reinstall", () => {+ const until = formatDateWithYear(Math.floor(cert(300).notAfter / 1000))+ expect(describeCertificate(cert(300, { source: "keychain" }), NOW)).toMatchObject({+ state: "valid",+ word: "Valid",+ caption: `Until ${until} · device credential store`,+ rowSub: `Valid until ${until}`+ })+ expect(describeCertificate(cert(300, { source: "p12" }), NOW).caption).toBe(`Until ${until} · imported .p12`)+ })++ it("warns inside the window, because a CA round trip takes weeks", () => {+ expect(describeCertificate(cert(CERT_EXPIRY_WARNING_DAYS - 1), NOW).word).toBe(+ `Expires in ${CERT_EXPIRY_WARNING_DAYS - 1} days`+ )+ expect(describeCertificate(cert(CERT_EXPIRY_WARNING_DAYS), NOW).state).toBe("valid")+ expect(describeCertificate(cert(1), NOW).word).toBe("Expires in 1 day")+ })++ it("keeps the year on the date, since a certificate can be years away", () => {+ expect(describeCertificate(cert(300), NOW).caption).toMatch(/\b20\d\d\b/)+ })++ it("says what an expired certificate will do", () => {+ const s = describeCertificate(cert(-3), NOW)+ expect(s.word).toBe("Expired")+ expect(s.caption).toMatch(/^Expired .* · the server will refuse it$/)+ expect(describeCertificate(cert(-3), NOW, "server certificate checks will fail").caption).toMatch(+ /server certificate checks will fail$/+ )+ })++ it("names an unreadable store with the bridge's sentence rather than a date it does not have", () => {+ const s = describeCertificate({ configured: true, error: "Keystore entry missing" }, NOW)+ expect(s).toMatchObject({ state: "unreadable", word: "Cannot be read", caption: "Keystore entry missing" })+ })+})diff --git a/apps/mobile/src/utils/__tests__/geo.test.ts b/apps/mobile/src/utils/__tests__/geo.test.tsindex cc179b09..26cf6225 100644--- a/apps/mobile/src/utils/__tests__/geo.test.ts+++ b/apps/mobile/src/utils/__tests__/geo.test.ts@@ -1,4 +1,5 @@import {+ formatDuration,computeTotalDistance,formatDistance,formatShortDistance,@@ -8,6 +9,8 @@ import {inputToMeters,metersToInput,getSpeedUnit,+ speedToInput,+ inputToSpeed,loadDisplayPreferences,getUnitSystem,getTimeFormat@@ -130,6 +133,16 @@ describe("formatDistance", () => {})})+describe("formatDuration", () => {+ it("abbreviates minutes as min, because m is metres and both appear on a trip", () => {+ expect(formatDuration(34 * 60)).toBe("34m")+ })++ it("carries the hour when there is one", () => {+ expect(formatDuration(3600 + 34 * 60)).toBe("1h 34m")+ })+})+describe("formatShortDistance", () => {afterEach(async () => {await setPreferences("", "")@@ -292,3 +305,17 @@ describe("formatTime", () => {expect(result).toMatch(/am|pm/i)})})++describe("speedToInput / inputToSpeed", () => {+ it("round-trips a stored speed through the display unit, so 13.9 m/s reads 50 km/h and 31 mph", async () => {+ mockGetSetting.mockImplementation((key: string) => Promise.resolve(key === "unitSystem" ? "metric" : ""))+ await loadDisplayPreferences()+ expect(speedToInput(13.89)).toBe(50)+ expect(inputToSpeed(50)).toBeCloseTo(13.89, 2)++ mockGetSetting.mockImplementation((key: string) => Promise.resolve(key === "unitSystem" ? "imperial" : ""))+ await loadDisplayPreferences()+ expect(speedToInput(13.89)).toBe(31)+ expect(inputToSpeed(31)).toBeCloseTo(13.86, 2)+ })+})diff --git a/apps/mobile/src/utils/__tests__/serverState.test.ts b/apps/mobile/src/utils/__tests__/serverState.test.tsnew file mode 100644index 00000000..93b098f6--- /dev/null+++ b/apps/mobile/src/utils/__tests__/serverState.test.ts@@ -0,0 +1,108 @@+import { describeServer, endpointHost } from "../serverState"+import { formatDate, formatTime, loadDisplayPreferences } from "../geo"++const mockGetSetting = jest.fn()+jest.mock("../../services/NativeLocationService", () => ({+ __esModule: true,+ default: { getSetting: (...args: string[]) => mockGetSetting(...args) }+}))++beforeAll(async () => {+ mockGetSetting.mockImplementation((key: string) => Promise.resolve(key === "timeFormat" ? "24h" : ""))+ await loadDisplayPreferences()+})++const NOW = new Date(2026, 8, 9, 15, 0, 0)+const TODAY_14_02 = new Date(2026, 8, 9, 14, 2, 0).getTime()+const YESTERDAY = new Date(2026, 8, 8, 9, 14, 0).getTime()++const base = {+ offline: false,+ endpoint: "https://tracks.example.org/api",+ deviceOnline: true,+ queued: 0,+ today: 12,+ lastSyncTime: TODAY_14_02,+ lastSyncError: "",+ now: NOW+}++describe("describeServer", () => {+ it("reads offline mode first, since nothing else matters while nothing is sent", () => {+ const s = describeServer({ ...base, offline: true, endpoint: "", lastSyncError: "boom" })+ expect(s.word).toBe("Offline mode")+ expect(s.caption).toBe("12 saved today · nothing is sent")+ expect(s.rowSub).toBe("Offline - saved locally · 12 today")+ })++ it("names a missing server before a missing network", () => {+ const s = describeServer({ ...base, endpoint: "", deviceOnline: false, queued: 38 })+ expect(s.word).toBe("No server")+ expect(s.caption).toBe("38 queued on this device")+ expect(s.rowSub).toBe("No server configured")+ })++ it("says the device has no network and when it last synced", () => {+ const s = describeServer({ ...base, deviceOnline: false, queued: 3 })+ expect(s.word).toBe("No network")+ expect(s.caption).toBe(`3 queued · last sync ${formatTime(Math.floor(TODAY_14_02 / 1000))}`)+ expect(s.rowSub).toBe("tracks.example.org · 3 queued · no network")+ })++ it("puts the server's own sentence first when sync is failing, then the queue and the last success", () => {+ const s = describeServer({ ...base, lastSyncError: "HTTP 401 Unauthorized", queued: 38 })+ expect(s.word).toBe("Sync failing")+ expect(s.tone).toBe("error")+ expect(s.caption).toBe(+ `HTTP 401 Unauthorized · 38 queued · last success ${formatTime(Math.floor(TODAY_14_02 / 1000))}`+ )+ expect(s.rowSub).toBe("tracks.example.org · 38 queued · sync failing")+ })++ it("does not fabricate a verdict before the first sync", () => {+ const s = describeServer({ ...base, lastSyncTime: 0, queued: 5 })+ expect(s.word).toBe("Not synced yet")+ expect(s.caption).toBe("5 queued")+ expect(s.rowSub).toBe("tracks.example.org · 5 queued")+ })++ it("reads synced with the time today and the date otherwise, and says when the queue is empty", () => {+ const today = describeServer(base)+ expect(today.word).toBe("Synced")+ expect(today.tone).toBe("success")+ expect(today.caption).toBe(`Last sync ${formatTime(Math.floor(TODAY_14_02 / 1000))} · queue empty`)++ const older = describeServer({ ...base, lastSyncTime: YESTERDAY, queued: 2 })+ const seconds = Math.floor(YESTERDAY / 1000)+ expect(older.caption).toBe(`Last sync ${formatDate(seconds)} · ${formatTime(seconds)} · 2 queued`)+ expect(older.rowSub).toBe(+ `tracks.example.org · 2 queued · last sync ${formatDate(seconds)} · ${formatTime(seconds)}`+ )+ })++ it("appends the certificate clause so a failing sync shows its cause on the first row", () => {+ const expiring = describeServer({+ ...base,+ certificate: { state: "expiring", days: 12, word: "Expires in 12 days", caption: "", rowSub: "" }+ })+ expect(expiring.caption).toMatch(/ · client certificate expires in 12 days$/)++ const expired = describeServer({+ ...base,+ lastSyncError: "TLS handshake failed",+ certificate: { state: "expired", days: -3, word: "Expired", caption: "", rowSub: "" }+ })+ expect(expired.caption).toMatch(/ · client certificate expired$/)+ })++ it("abbreviates a large queue the way the Settings row already did", () => {+ expect(describeServer({ ...base, lastSyncTime: 0, queued: 120_000 }).caption).toBe("120K queued")+ })+})++describe("endpointHost", () => {+ it("keeps the host for a row label and the raw text while it is not a URL yet", () => {+ expect(endpointHost("https://tracks.example.org:8443/api/v1")).toBe("tracks.example.org:8443")+ expect(endpointHost("tracks")).toBe("tracks")+ })+})diff --git a/apps/mobile/src/utils/__tests__/settingsValidation.test.ts b/apps/mobile/src/utils/__tests__/settingsValidation.test.tsindex 1f32d8aa..032985fd 100644--- a/apps/mobile/src/utils/__tests__/settingsValidation.test.ts+++ b/apps/mobile/src/utils/__tests__/settingsValidation.test.ts@@ -1,4 +1,13 @@-import { isEndpointAllowed, isPositiveInt, parsePositiveInt } from "../settingsValidation"+import {+ endpointCarriesKey,+ endpointExample,+ isEndpointAllowed,+ isPositiveInt,+ parsePositiveInt,+ parseWholeNumber,+ wholeNumberError+} from "../settingsValidation"+import { API_TEMPLATES } from "../../types/global"describe("isEndpointAllowed", () => {it("allows valid http and https URLs", () => {@@ -54,3 +63,44 @@ describe("parsePositiveInt", () => {expect(parsePositiveInt("5.9", 99)).toBe(5)})})++describe("parseWholeNumber", () => {+ it("accepts only digits, so a decimal, a sign, an exponent or nothing never reaches a setting", () => {+ expect(parseWholeNumber("20")).toBe(20)+ expect(parseWholeNumber("0")).toBe(0)+ expect(parseWholeNumber("1.5")).toBeNull()+ expect(parseWholeNumber("-3")).toBeNull()+ expect(parseWholeNumber("1e3")).toBeNull()+ expect(parseWholeNumber("")).toBeNull()+ })+})++describe("wholeNumberError", () => {+ it("stays silent on an empty field and on a valid value", () => {+ expect(wholeNumberError("", 1, "s")).toBeUndefined()+ expect(wholeNumberError("5", 1, "s")).toBeUndefined()+ })++ it("names the rule the text breaks, with the unit the field shows", () => {+ expect(wholeNumberError("1.5", 1, "s")).toBe("A whole number")+ expect(wholeNumberError("0", 1, "m")).toBe("At least 1 m")+ })+})++describe("endpointExample", () => {+ it("hands the field the shape the chosen template expects, and Dawarich's batch path in batch mode", () => {+ expect(endpointExample("custom")).toBe("https://your-server.example/api")+ expect(endpointExample("traccar")).toBe(API_TEMPLATES.traccar.endpointExample)+ expect(endpointExample("dawarich", "single")).toBe(API_TEMPLATES.dawarich.endpointExample)+ expect(endpointExample("dawarich", "batch")).toBe(API_TEMPLATES.dawarich.batchEndpointExample)+ })+})++describe("endpointCarriesKey", () => {+ it("spots a credential in the query string, which settings store in the clear", () => {+ expect(endpointCarriesKey("https://d.example/api?api_key=abc")).toBe(true)+ expect(endpointCarriesKey("https://d.example/api?Token=abc&x=1")).toBe(true)+ expect(endpointCarriesKey("https://d.example/api?device=phone")).toBe(false)+ expect(endpointCarriesKey("https://d.example/api")).toBe(false)+ })+})diff --git a/apps/mobile/src/utils/certificateState.ts b/apps/mobile/src/utils/certificateState.tsnew file mode 100644index 00000000..b2215355--- /dev/null+++ b/apps/mobile/src/utils/certificateState.ts@@ -0,0 +1,58 @@+/**+ * Copyright (C) 2026 Max Dietrich+ * Licensed under the GNU AGPLv3. See LICENSE in the project root for details.+ */++import { CERT_EXPIRY_WARNING_DAYS } from "../constants"+import type { ClientCertInfoResult } from "../types/global"+import { formatDateWithYear } from "./geo"++export type CertificateStateKind = "none" | "valid" | "expiring" | "expired" | "unreadable"++export interface CertificateState {+ state: CertificateStateKind+ /** Whole days until notAfter, negative once past it, 0 when unknown. */+ days: number+ word: string+ caption: string+ /** The Connection hub row's sub. */+ rowSub: string+}++const DAY_MS = 24 * 60 * 60 * 1000++function source(info: { source?: "keychain" | "p12" }): string {+ if (info.source === "keychain") return " · device credential store"+ if (info.source === "p12") return " · imported .p12"+ return ""+}++/** The words for a stored certificate, shared by the certificate cards and the Connection hub row. */+export function describeCertificate(+ info: ClientCertInfoResult | null,+ now: Date = new Date(),+ failureCaption = "the server will refuse it"+): CertificateState {+ if (!info || !info.configured) return { state: "none", days: 0, word: "Not set", caption: "", rowSub: "Not set" }+ if (info.error || !info.notAfter || !info.subject) {+ const caption = info.error ?? "Missing certificate fields"+ return { state: "unreadable", days: 0, word: "Cannot be read", caption, rowSub: "Cannot be read" }+ }+ const days = Math.floor((info.notAfter - now.getTime()) / DAY_MS)+ const until = formatDateWithYear(Math.floor(info.notAfter / 1000))+ if (days < 0) {+ return {+ state: "expired",+ days,+ word: "Expired",+ caption: `Expired ${until} · ${failureCaption}`,+ rowSub: "Expired"+ }+ }+ const caption = `Until ${until}${source(info)}`+ if (days < CERT_EXPIRY_WARNING_DAYS) {+ const word = `Expires in ${days} ${days === 1 ? "day" : "days"}`+ return { state: "expiring", days, word, caption, rowSub: word }+ }+ return { state: "valid", days, word: "Valid", caption, rowSub: `Valid until ${until}` }+}diff --git a/apps/mobile/src/utils/format.ts b/apps/mobile/src/utils/format.tsindex 27a7de21..3d3f7472 100644--- a/apps/mobile/src/utils/format.ts+++ b/apps/mobile/src/utils/format.ts@@ -20,6 +20,9 @@ export const formatCount = (count: number): string => {return `${(count / 1_000_000).toFixed(1)}M`}+/** "1 file", "12 files". The count carries thousands separators; the noun takes the s. */+export const plural = (n: number, noun: string): string => `${n.toLocaleString()} ${noun}${n === 1 ? "" : "s"}`+/** Clamps `value` to the inclusive range [min, max]. */export const clamp = (value: number, min: number, max: number): number => Math.max(min, Math.min(max, value))diff --git a/apps/mobile/src/utils/geo.ts b/apps/mobile/src/utils/geo.tsindex 56dd957e..23db6f01 100644--- a/apps/mobile/src/utils/geo.ts+++ b/apps/mobile/src/utils/geo.ts@@ -103,8 +103,12 @@ export function formatSpeed(metersPerSecond: number): string {}/** Return the speed unit info (used by TrackMap). */+// Module-level so the identity tracks the unit, and a caller can read it during render.+const MPH = Object.freeze({ factor: MPH_PER_MPS, unit: "mph" })+const KMH = Object.freeze({ factor: 3.6, unit: "km/h" })+export function getSpeedUnit(): { factor: number; unit: string } {- return usesMiles() ? { factor: MPH_PER_MPS, unit: "mph" } : { factor: 3.6, unit: "km/h" }+ return usesMiles() ? MPH : KMH}/** Format seconds duration as "Xh Ym" or "Ym" */@@ -117,16 +121,26 @@ export function formatDuration(seconds: number): string {}/** Format a Unix-seconds timestamp as a localized time string. */-export function formatTime(unixSeconds: number, showSeconds = false): string {+/** The unit spelled out, for a screen reader. */+export function spokenDistance(meters: number): string {+ return formatDistance(meters).replace(/ km$/, " kilometres").replace(/ mi$/, " miles")+}++/** The app's clock, with the format passed in, so a sample of a format cannot drift from it. */+export function formatTimeIn(unixSeconds: number, format: TimeFormat | null, showSeconds = false): string {const d = new Date(unixSeconds * 1000)return d.toLocaleTimeString(undefined, {hour: "2-digit",minute: "2-digit",...(showSeconds && { second: "2-digit" }),- ...(cachedTimeFormat && { hour12: cachedTimeFormat === "12h" })+ ...(format && { hour12: format === "12h" })})}+export function formatTime(unixSeconds: number, showSeconds = false): string {+ return formatTimeIn(unixSeconds, cachedTimeFormat, showSeconds)+}+/** Format a Unix-seconds timestamp as a localized date string (e.g. "Wed, Feb 27"). */export function formatDate(unixSeconds: number): string {return new Date(unixSeconds * 1000).toLocaleDateString(undefined, {@@ -153,6 +167,16 @@ export function shortDistanceUnit(): string {return usesMiles() ? "ft" : "m"}+/** A stored speed in m/s as the whole number the speed field shows, in the user's unit. */+export function speedToInput(metersPerSecond: number): number {+ return Math.round(metersPerSecond * getSpeedUnit().factor)+}++/** A typed speed in the user's unit back to the m/s the profile stores. */+export function inputToSpeed(value: number): number {+ return value / getSpeedUnit().factor+}+/** Convert a user-entered short distance to meters. */export function inputToMeters(value: number): number {return usesMiles() ? value / FEET_PER_METER : value@@ -163,6 +187,17 @@ export function metersToInput(meters: number): number {return usesMiles() ? Math.round(meters * FEET_PER_METER) : meters}+/** A calendar date with its year, for a date that can be years away, such as a certificate's expiry. */+export function formatDateWithYear(unixSeconds: number): string {+ return new Date(unixSeconds * 1000).toLocaleDateString(undefined, { year: "numeric", month: "short", day: "numeric" })+}++/** A time alone for today, the date otherwise, so a caption stays short where the day is implied. */+export function formatWhen(unixSeconds: number, now: Date = new Date()): string {+ const sameDay = startOfDaySec(new Date(unixSeconds * 1000)) === startOfDaySec(now)+ return sameDay ? formatTime(unixSeconds) : `${formatDate(unixSeconds)} · ${formatTime(unixSeconds)}`+}+/** Start of `date`'s local day, in Unix seconds. */export function startOfDaySec(date: Date): number {const d = new Date(date)diff --git a/apps/mobile/src/utils/serverState.ts b/apps/mobile/src/utils/serverState.tsnew file mode 100644index 00000000..10078f74--- /dev/null+++ b/apps/mobile/src/utils/serverState.ts@@ -0,0 +1,116 @@+/**+ * Copyright (C) 2026 Max Dietrich+ * Licensed under the GNU AGPLv3. See LICENSE in the project root for details.+ */++import { formatWhen } from "./geo"+import { formatCount } from "./format"+import type { CertificateState } from "./certificateState"++export type ServerIcon = "cloudOff" | "cloud" | "wifiOff" | "alert" | "dashed" | "check"+export type ServerTone = "secondary" | "warning" | "error" | "light" | "success"++export interface ServerStateInput {+ offline: boolean+ endpoint: string+ deviceOnline: boolean+ queued: number+ today: number+ /** Epoch milliseconds, 0 when nothing has synced yet. */+ lastSyncTime: number+ lastSyncError: string+ certificate?: CertificateState | null+ now?: Date+}++export interface ServerState {+ icon: ServerIcon+ tone: ServerTone+ word: string+ caption: string+ /** The Settings row and the dock: today's words plus the time. */+ rowSub: string+}++function count(n: number, noun: string): string {+ return `${formatCount(n)} ${noun}`+}++/** The host of an endpoint for a row label, or the text itself when it is not a URL yet. */+export function endpointHost(endpoint: string): string {+ try {+ return new URL(endpoint).host+ } catch {+ return endpoint+ }+}++function certificateClause(certificate: CertificateState | null | undefined): string {+ if (certificate?.state === "expiring")+ return ` · client certificate expires in ${certificate.days} ${certificate.days === 1 ? "day" : "days"}`+ if (certificate?.state === "expired") return " · client certificate expired"+ return ""+}++/** One derivation of the server relationship for the Connection card, the dock and the Settings row. First match wins. */+export function describeServer(input: ServerStateInput): ServerState {+ const now = input.now ?? new Date()+ const queued = count(input.queued, "queued")+ const lastSync = input.lastSyncTime > 0 ? formatWhen(Math.floor(input.lastSyncTime / 1000), now) : "never"+ const cert = certificateClause(input.certificate)++ if (input.offline) {+ return {+ icon: "cloudOff",+ tone: "secondary",+ word: "Offline mode",+ caption: `${count(input.today, "saved today")} · nothing is sent`,+ rowSub: `Offline - saved locally · ${count(input.today, "today")}`+ }+ }+ if (!input.endpoint) {+ return {+ icon: "cloud",+ tone: "warning",+ word: "No server",+ caption: `${queued} on this device`,+ rowSub: "No server configured"+ }+ }+ const server = endpointHost(input.endpoint)+ const rowQueue = input.queued > 0 ? ` · ${queued}` : ""+ if (!input.deviceOnline) {+ return {+ icon: "wifiOff",+ tone: "secondary",+ word: "No network",+ caption: `${queued} · last sync ${lastSync}${cert}`,+ rowSub: `${server}${rowQueue} · no network`+ }+ }+ if (input.lastSyncError !== "") {+ return {+ icon: "alert",+ tone: "error",+ word: "Sync failing",+ caption: `${input.lastSyncError} · ${queued} · last success ${lastSync}${cert}`,+ rowSub: `${server}${rowQueue} · sync failing`+ }+ }+ if (input.lastSyncTime === 0) {+ return {+ icon: "dashed",+ tone: "light",+ word: "Not synced yet",+ caption: `${queued}${cert}`,+ rowSub: `${server}${rowQueue}`+ }+ }+ return {+ icon: "check",+ tone: "success",+ word: "Synced",+ caption: `Last sync ${lastSync} · ${input.queued > 0 ? queued : "queue empty"}${cert}`,+ rowSub: `${server}${rowQueue} · last sync ${lastSync}`+ }+}diff --git a/apps/mobile/src/utils/settingsValidation.ts b/apps/mobile/src/utils/settingsValidation.tsindex af957f91..8d9864aa 100644--- a/apps/mobile/src/utils/settingsValidation.ts+++ b/apps/mobile/src/utils/settingsValidation.ts@@ -3,6 +3,28 @@* Licensed under the GNU AGPLv3. See LICENSE in the project root for details.*/+import { API_TEMPLATES, type ApiTemplateName, type DawarichMode } from "../types/global"++export const CUSTOM_ENDPOINT_EXAMPLE = "https://your-server.example/api"++/** The endpoint shape the chosen template expects, for the field's placeholder and helper. */+export function endpointExample(template: ApiTemplateName, dawarichMode: DawarichMode = "single"): string {+ if (template === "custom") return CUSTOM_ENDPOINT_EXAMPLE+ const entry = API_TEMPLATES[template]+ if (template === "dawarich" && dawarichMode === "batch" && entry.batchEndpointExample)+ return entry.batchEndpointExample+ return entry.endpointExample+}++const KEY_QUERY_PARAMS = ["api_key", "apikey", "token", "access_token", "secret", "password", "auth"]++/** True when the address carries a credential in its query string, which settings store in the clear. */+export function endpointCarriesKey(url: string): boolean {+ const query = url.split("#")[0].split("?")[1]+ if (!query) return false+ return query.split("&").some((pair) => KEY_QUERY_PARAMS.includes(pair.split("=")[0].toLowerCase()))+}+/*** Returns the set of strings that appear more than once in the input.*/@@ -31,3 +53,17 @@ export function parsePositiveInt(str: string, fallback: number): number {export function isPositiveInt(str: string): boolean {return parseInt(str, 10) >= 1}++/** The digits of a whole number, or null: decimals, signs, exponents and the empty string never reach a setting. */+export function parseWholeNumber(text: string): number | null {+ return /^\d+$/.test(text) ? Number(text) : null+}++/** The error a numeric field shows while its text is non-empty and would not be stored. */+export function wholeNumberError(text: string, min: number, unit: string): string | undefined {+ if (text === "") return undefined+ const value = parseWholeNumber(text)+ if (value === null) return "A whole number"+ if (value < min) return `At least ${min} ${unit}`+ return undefined+}diff --git a/packages/shared/src/colors.ts b/packages/shared/src/colors.tsindex f987ecd5..ffd78fb2 100644--- a/packages/shared/src/colors.ts+++ b/packages/shared/src/colors.ts@@ -13,31 +13,28 @@ export interface ThemeColors {primary: stringprimaryDark: stringprimaryLight: string+ primaryContainer: string+ onPrimaryContainer: string+ border: string+ well: string// Secondary colors- secondary: string- secondaryDark: string- secondaryLight: string// Semantic colorssuccess: string- successDark: string- successLight: stringwarning: string- warningDark: string- warningLight: stringerror: string- errorDark: string- errorLight: stringinfo: string- infoDark: string- infoLight: string// Surfaces & backgroundsbackground: stringbackgroundElevated: stringcard: stringcardElevated: string+ pressedOpacity: number+ borderRadius: number+ /** One tonal step above `card` for what floats over content: docks, dialogs, banners, map discs. Never a list card. */+ surfaceRaised: stringsurface: string// Text colors@@ -47,58 +44,47 @@ export interface ThemeColors {textDisabled: string// Borders & dividers- border: stringborderLight: stringdivider: string// Interactive elementsplaceholder: stringlink: string- linkVisited: string// Utilityoverlay: string- shadow: string- transparent: string- pressedOpacity: number- borderRadius: numbertextOnPrimary: string}export const lightColors: ThemeColors = {// Brand (Teal)- primary: "#0d9488",+ primary: "#0B7D73",primaryDark: "#115E59",primaryLight: "#99F6E4",- secondary: "#F59E0B",- secondaryDark: "#92400E",- secondaryLight: "#FDE68A",+ primaryContainer: "#B9E4DC",+ onPrimaryContainer: "#115E59",+ well: "#E9EDF0",// Statussuccess: "#2E7D32",- successDark: "#1B5E20",- successLight: "#A5D6A7",warning: "#C2410C",- warningDark: "#9A3412",- warningLight: "#FED7AA",error: "#D32F2F",- errorDark: "#B71C1C",- errorLight: "#FFCDD2",- info: "#1976D2",- infoDark: "#0D47A1",- infoLight: "#BBDEFB",+ info: "#1870C8",// UI- background: "#f8fafb",+ background: "#F1F4F6",backgroundElevated: "#FFFFFF",card: "#FFFFFF",cardElevated: "#FFFFFF",+ pressedOpacity: 0.7,+ borderRadius: 8,+ surfaceRaised: "#FFFFFF",surface: "#FFFFFF",// Texttext: "#202124",textSecondary: "#5F6368",- textLight: "#9AA0A6",+ textLight: "#697077",textDisabled: "#9AA0A6",// Border & divider@@ -109,68 +95,53 @@ export const lightColors: ThemeColors = {// Interactiveplaceholder: "#9AA0A6",link: "#115E59",- linkVisited: "#134E4A",overlay: "rgba(0, 0, 0, 0.5)",- shadow: "rgba(0, 0, 0, 0.1)",// Special- transparent: "transparent",- pressedOpacity: 0.7,- borderRadius: 8,textOnPrimary: "#FFFFFF"}export const darkColors: ThemeColors = {// Brand (Teal)primary: "#2DD4BF",- primaryDark: "#0d9488",+ primaryDark: "#0FA698",primaryLight: "#99F6E4",- secondary: "#FBBF24",- secondaryDark: "#F59E0B",- secondaryLight: "#FDE68A",+ primaryContainer: "#0F3B36",+ onPrimaryContainer: "#99F6E4",+ well: "#232323",// Statussuccess: "#4CAF50",- successDark: "#388E3C",- successLight: "#C8E6C9",warning: "#FB923C",- warningDark: "#F97316",- warningLight: "#FED7AA",- error: "#EF5350",- errorDark: "#D32F2F",- errorLight: "#FFCDD2",- info: "#4285F4",- infoDark: "#1976D2",- infoLight: "#BBDEFB",+ error: "#F16765",+ info: "#5793F5",// UIbackground: "#121212",backgroundElevated: "#1E1E1E",card: "#2D2D2D",cardElevated: "#3D3D3D",+ pressedOpacity: 0.7,+ borderRadius: 8,+ surfaceRaised: "#353535",surface: "#1E1E1E",// Texttext: "#E8EAED",textSecondary: "#AAAAAA",- textLight: "#888888",+ textLight: "#949494",textDisabled: "#666666",// Border & dividerborder: "#424242",borderLight: "#333333",- divider: "#333333",+ divider: "#505050",// Interactiveplaceholder: "#AAAAAA",link: "#2DD4BF",- linkVisited: "#14B8A6",overlay: "rgba(0, 0, 0, 0.7)",- shadow: "rgba(0, 0, 0, 0.3)",// Special- transparent: "transparent",- pressedOpacity: 0.7,- borderRadius: 8,textOnPrimary: "#121212"}diff --git a/packages/shared/src/index.ts b/packages/shared/src/index.tsindex 60e90755..25315da1 100644--- a/packages/shared/src/index.ts+++ b/packages/shared/src/index.ts@@ -6,3 +6,5 @@export { lightColors, darkColors } from "./colors"export type { ThemeColors, ThemeMode } from "./colors"export { fontFamily, fontSizes } from "./typography"+export { radius } from "./radius"+export type { RadiusName } from "./radius"diff --git a/packages/shared/src/radius.ts b/packages/shared/src/radius.tsnew file mode 100644index 00000000..9da500d2--- /dev/null+++ b/packages/shared/src/radius.ts@@ -0,0 +1,17 @@+/**+ * Copyright (C) 2026 Max Dietrich+ * Licensed under the GNU AGPLv3. See LICENSE in the project root for details.+ *+ * Single source of truth for Colota corner radii.+ * Used by: apps/mobile, apps/docs+ */++export const radius = {+ xs: 4,+ sm: 8,+ md: 12,+ lg: 16,+ pill: 999+} as const++export type RadiusName = keyof typeof radius