Colota - Android GPS Location tracker
fix(dashboard): reflect real sync status instead of a separate health probe (#549)
Max Dietrich2a3445c6cce9
diff --git a/apps/docs/docs/configuration/server-settings.md b/apps/docs/docs/configuration/server-settings.mdindex 2df76181..ca75ec2c 100644--- a/apps/docs/docs/configuration/server-settings.md+++ b/apps/docs/docs/configuration/server-settings.md@@ -89,6 +89,8 @@ Toggle offline mode off in Settings to return to online mode. If you had an endp## Retry Behavior+A location counts as delivered only when your server responds with a `2xx` status - any other status or a network error is treated as a failure and retried. For custom endpoints, make sure your script or webhook returns `2xx` on success.+When sync attempts fail, Colota uses exponential backoff:```diff --git a/apps/docs/src/pages/privacy-policy.md b/apps/docs/src/pages/privacy-policy.mdindex b276d353..85283311 100644--- a/apps/docs/src/pages/privacy-policy.md+++ b/apps/docs/src/pages/privacy-policy.md@@ -4,7 +4,7 @@ title: Privacy Policy# Privacy Policy-**Last updated: June 14, 2026**+**Last updated: August 2, 2026**Colota ("the App") is a self-hosted GPS tracking application for Android, developed by Max Dietrich. This privacy policy explains what data the App collects, how it is used, and your rights regarding that data.@@ -83,7 +83,7 @@ You can also generate a setup link to share your own configuration (Settings ->The App **only transmits data to a server endpoint that you configure**. No data is sent anywhere by default.- Data is sent via HTTPS (HTTP is only allowed for local/private network addresses). Self-signed or private-CA TLS certificates are supported by importing the CA in the in-app mTLS Settings (Trusted Server CA). Trust is scoped to Colota only-- When a server is configured, the App may send health check requests to backend-specific endpoints to verify connectivity. These requests go only to your own server+- The **Test Connection** button sends a request to your configured endpoint to verify it works. These requests go only to your own server- No analytics, tracking pixels, or advertising networks are used- No data is shared with the developer, advertisers or analytics providersdiff --git a/apps/mobile/src/components/features/dashboard/ConnectionStatus.tsx b/apps/mobile/src/components/features/dashboard/ConnectionStatus.tsxindex 43bb7f41..9ad00855 100644--- a/apps/mobile/src/components/features/dashboard/ConnectionStatus.tsx+++ b/apps/mobile/src/components/features/dashboard/ConnectionStatus.tsx@@ -3,8 +3,8 @@* Licensed under the GNU AGPLv3. See LICENSE in the project root for details.*/-import React, { useState, useCallback, useMemo, useRef } from "react"-import { StyleSheet, View, Text, Pressable } from "react-native"+import React, { useState, useCallback, useMemo } from "react"+import { StyleSheet, View, Text, Pressable, DeviceEventEmitter } from "react-native"import { ChevronRight } from "lucide-react-native"import { useFocusEffect } from "@react-navigation/native"import { useTheme } from "../../../hooks/useTheme"@@ -12,8 +12,6 @@ import { useTracking } from "../../../contexts/TrackingProvider"import { ServerStatus, ConnectionStatusProps } from "../../../types/global"import { fonts } from "../../../styles/typography"import NativeLocationService from "../../../services/NativeLocationService"-import { SERVER_TIMEOUT, SERVER_CHECK_INTERVAL } from "../../../constants"-import { resolveHealthUrls } from "../../../utils/healthCheck"export function ConnectionStatus({ endpoint, navigation }: ConnectionStatusProps) {const { colors } = useTheme()@@ -22,67 +20,48 @@ export function ConnectionStatus({ endpoint, navigation }: ConnectionStatusPropsconst [serverStatus, setServerStatus] = useState<ServerStatus | "offline" | "deviceOffline" | null>(null)- const hasChecked = useRef(false)-- const checkServer = useCallback(async () => {- if (isOffline) {- setServerStatus("offline")- hasChecked.current = true- return- }-- const networkAvailable = await NativeLocationService.isNetworkAvailable()- if (!networkAvailable) {- setServerStatus("deviceOffline")- hasChecked.current = true- return- }-- if (!endpoint) {- setServerStatus("notConfigured")- hasChecked.current = true- return- }-- const controller = new AbortController()- const timeoutId = setTimeout(() => controller.abort(), SERVER_TIMEOUT)-- try {- let authHeaders: Record<string, string> = {}- try {- authHeaders = await NativeLocationService.getAuthHeaders()- } catch {- // proceed without auth headers+ useFocusEffect(+ useCallback(() => {+ // A stale run (e.g. one started before the endpoint loaded) must not overwrite a newer status.+ let cancelled = false++ const refresh = async () => {+ if (isOffline) {+ setServerStatus("offline")+ return+ }++ const networkAvailable = await NativeLocationService.isNetworkAvailable()+ if (cancelled) return+ if (!networkAvailable) {+ setServerStatus("deviceOffline")+ return+ }++ if (!endpoint) {+ setServerStatus("notConfigured")+ return+ }++ try {+ const stats = await NativeLocationService.getStats()+ if (cancelled) return+ // Empty queue plus a prior successful send (sent = retained synced rows) means caught up.+ if (stats.queued === 0 && stats.sent > 0) {+ setServerStatus("connected")+ }+ } catch {+ // getStats is a local DB read; a failure here says nothing about the server.+ }}- const healthUrls = resolveHealthUrls(endpoint, settings.apiTemplate)- let response!: Response- for (const url of healthUrls) {- response = await fetch(url, {- method: "HEAD",- signal: controller.signal,- headers: authHeaders- })- if (response.ok || (response.status !== 404 && response.status !== 405)) break+ refresh()+ const sub = DeviceEventEmitter.addListener("onSyncError", () => setServerStatus("error"))+ return () => {+ cancelled = true+ sub.remove()}-- const reachable = response.ok || response.status === 405- setServerStatus(reachable ? "connected" : "error")- hasChecked.current = true- } catch {- setServerStatus("error")- hasChecked.current = true- } finally {- clearTimeout(timeoutId)- }- }, [endpoint, isOffline, settings.apiTemplate])-- useFocusEffect(- useCallback(() => {- checkServer()- const timer = setInterval(checkServer, SERVER_CHECK_INTERVAL)- return () => clearInterval(timer)- }, [checkServer])+ }, [endpoint, isOffline]))const displayUrl = endpoint ? endpoint.replace(/^https?:\/\//, "").split("/")[0] : ""diff --git a/apps/mobile/src/components/features/dashboard/__tests__/ConnectionStatus.test.tsx b/apps/mobile/src/components/features/dashboard/__tests__/ConnectionStatus.test.tsxindex 8003b667..fc199f2e 100644--- a/apps/mobile/src/components/features/dashboard/__tests__/ConnectionStatus.test.tsx+++ b/apps/mobile/src/components/features/dashboard/__tests__/ConnectionStatus.test.tsx@@ -1,5 +1,6 @@import React from "react"-import { render, waitFor } from "@testing-library/react-native"+import { render, waitFor, act } from "@testing-library/react-native"+import { DeviceEventEmitter } from "react-native"jest.mock("../../../../hooks/useTheme", () => ({useTheme: () => ({@@ -11,26 +12,22 @@ jest.mock("../../../../hooks/useTheme", () => ({textLight: "#9ca3af",text: "#000",card: "#fff",- border: "#e5e7eb"+ border: "#e5e7eb",+ pressedOpacity: 0.6}})}))-const mockSettings = {- isOfflineMode: false,- apiTemplate: "custom" as const-}+const mockSettings = { isOfflineMode: false }jest.mock("../../../../contexts/TrackingProvider", () => ({- useTracking: () => ({- settings: mockSettings- })+ useTracking: () => ({ settings: mockSettings })}))const mockIsNetworkAvailable = jest.fn().mockResolvedValue(true)-const mockGetAuthHeaders = jest.fn().mockResolvedValue({})+const mockGetStats = jest.fn()jest.mock("../../../../services/NativeLocationService", () => ({isNetworkAvailable: (...args: any[]) => mockIsNetworkAvailable(...args),- getAuthHeaders: (...args: any[]) => mockGetAuthHeaders(...args)+ getStats: (...args: any[]) => mockGetStats(...args)}))jest.mock("@react-navigation/native", () => ({@@ -43,174 +40,132 @@ jest.mock("@react-navigation/native", () => ({}}))+// #546: the chip must never issue its own request - a JS fetch bypasses the native TLS+// trust and breaks custom-CA / mTLS users.const mockFetch = jest.fn();(globalThis as any).fetch = mockFetchimport { ConnectionStatus } from "../ConnectionStatus"const mockNavigation = { navigate: jest.fn() }+const stats = (queued: number, sent: number) => ({ queued, sent, total: sent, today: 0, databaseSizeMB: 0 })+const emit = (event: string, payload: object) =>+ act(() => {+ DeviceEventEmitter.emit(event, payload)+ })beforeEach(() => {jest.clearAllMocks()- jest.useFakeTimers()mockSettings.isOfflineMode = falsemockIsNetworkAvailable.mockResolvedValue(true)- mockGetAuthHeaders.mockResolvedValue({})-})--afterEach(() => {- jest.useRealTimers()+ mockGetStats.mockResolvedValue(stats(0, 0))})describe("ConnectionStatus", () => {- it("shows 'Checking' initially before server check completes", () => {- mockFetch.mockReturnValue(new Promise(() => {}))+ const url = "https://example.com/api/locations"- const { getByText } = render(- <ConnectionStatus endpoint="https://example.com/api/locations" navigation={mockNavigation} />- )+ it("shows 'Checking' until a sync result is known", async () => {+ const { getByText } = render(<ConnectionStatus endpoint={url} navigation={mockNavigation} />)expect(getByText("Checking")).toBeTruthy()+ await waitFor(() => expect(mockGetStats).toHaveBeenCalled())+ expect(getByText("Checking")).toBeTruthy()})- it("shows 'Connected' when server responds OK", async () => {- mockFetch.mockResolvedValue({ ok: true, status: 200 })+ it("shows 'Connected' when the queue is empty and locations have synced", async () => {+ mockGetStats.mockResolvedValue(stats(0, 5))- const { getByText } = render(- <ConnectionStatus endpoint="https://example.com/api/locations" navigation={mockNavigation} />- )+ const { getByText } = render(<ConnectionStatus endpoint={url} navigation={mockNavigation} />)- await waitFor(() => {- expect(getByText("Connected")).toBeTruthy()- })+ await waitFor(() => expect(getByText("Connected")).toBeTruthy())})- it("shows 'Unreachable' when fetch throws", async () => {- mockFetch.mockRejectedValue(new Error("Network error"))+ it("stays 'Checking' on a backlog with no sync event yet (does not fabricate a status)", async () => {+ mockGetStats.mockResolvedValue(stats(3, 0))- const { getByText } = render(- <ConnectionStatus endpoint="https://example.com/api/locations" navigation={mockNavigation} />- )+ const { getByText, queryByText } = render(<ConnectionStatus endpoint={url} navigation={mockNavigation} />)- await waitFor(() => {- expect(getByText("Unreachable")).toBeTruthy()- })+ await waitFor(() => expect(mockGetStats).toHaveBeenCalled())+ expect(getByText("Checking")).toBeTruthy()+ expect(queryByText("Connected")).toBeNull()+ expect(queryByText("Unreachable")).toBeNull()})- it("shows 'No endpoint' when endpoint is empty", async () => {- const { getByText } = render(<ConnectionStatus endpoint="" navigation={mockNavigation} />)-- await waitFor(() => {- expect(getByText("No endpoint")).toBeTruthy()- })- })+ it("shows 'Unreachable' on a sync error event", async () => {+ const { getByText } = render(<ConnectionStatus endpoint={url} navigation={mockNavigation} />)+ await waitFor(() => expect(mockGetStats).toHaveBeenCalled())- it("shows 'No endpoint' when endpoint is null", async () => {- const { getByText } = render(<ConnectionStatus endpoint={null} navigation={mockNavigation} />)+ emit("onSyncError", { message: "send failed", queuedCount: 3 })- await waitFor(() => {- expect(getByText("No endpoint")).toBeTruthy()- })+ await waitFor(() => expect(getByText("Unreachable")).toBeTruthy())})- it("shows 'Offline Mode' when offline mode is enabled", async () => {- mockSettings.isOfflineMode = true+ it("never performs a network request itself", async () => {+ mockGetStats.mockResolvedValue(stats(0, 5))- const { getByText } = render(- <ConnectionStatus endpoint="https://example.com/api/locations" navigation={mockNavigation} />- )+ render(<ConnectionStatus endpoint={url} navigation={mockNavigation} />)- await waitFor(() => {- expect(getByText("Offline Mode")).toBeTruthy()- })+ await waitFor(() => expect(mockGetStats).toHaveBeenCalled())+ expect(mockFetch).not.toHaveBeenCalled()})- it("shows 'Device offline' when network is unavailable", async () => {- mockIsNetworkAvailable.mockResolvedValue(false)+ it("a stale run from before the endpoint loaded does not clobber Connected", async () => {+ // The empty-endpoint run resolves after the endpoint loads; it must not flip back to "No endpoint".+ let resolveStale: (v: boolean) => void = () => {}+ mockIsNetworkAvailable+ .mockImplementationOnce(() => new Promise<boolean>((r) => (resolveStale = r)))+ .mockResolvedValue(true)+ mockGetStats.mockResolvedValue(stats(0, 5))- const { getByText } = render(- <ConnectionStatus endpoint="https://example.com/api/locations" navigation={mockNavigation} />- )+ const { getByText, rerender } = render(<ConnectionStatus endpoint="" navigation={mockNavigation} />)+ rerender(<ConnectionStatus endpoint={url} navigation={mockNavigation} />)- await waitFor(() => {- expect(getByText("Device offline")).toBeTruthy()- })+ await waitFor(() => expect(getByText("Connected")).toBeTruthy())+ await act(async () => resolveStale(true))+ expect(getByText("Connected")).toBeTruthy()})- it("falls back to endpoint URL when /health returns 404", async () => {- mockFetch- .mockResolvedValueOnce({ ok: false, status: 404 }) // /health- .mockResolvedValueOnce({ ok: true, status: 200 }) // original endpoint+ it("shows 'No endpoint' when endpoint is empty", async () => {+ const { getByText } = render(<ConnectionStatus endpoint="" navigation={mockNavigation} />)- const { getByText } = render(- <ConnectionStatus endpoint="https://example.com/api/locations" navigation={mockNavigation} />- )+ await waitFor(() => expect(getByText("No endpoint")).toBeTruthy())+ })- await waitFor(() => {- expect(getByText("Connected")).toBeTruthy()- })+ it("shows 'No endpoint' when endpoint is null", async () => {+ const { getByText } = render(<ConnectionStatus endpoint={null} navigation={mockNavigation} />)- expect(mockFetch).toHaveBeenCalledTimes(2)+ await waitFor(() => expect(getByText("No endpoint")).toBeTruthy())})- it("falls back to origin when /health returns 404", async () => {- mockFetch- .mockResolvedValueOnce({ ok: false, status: 404 }) // origin/health- .mockResolvedValueOnce({ ok: true, status: 200 }) // origin+ it("shows 'Offline Mode' when offline mode is enabled", async () => {+ mockSettings.isOfflineMode = true- const { getByText } = render(- <ConnectionStatus endpoint="https://example.com/api/locations" navigation={mockNavigation} />- )+ const { getByText } = render(<ConnectionStatus endpoint={url} navigation={mockNavigation} />)- await waitFor(() => {- expect(getByText("Connected")).toBeTruthy()- })+ await waitFor(() => expect(getByText("Offline Mode")).toBeTruthy())+ })++ it("shows 'Device offline' when the device has no network", async () => {+ mockIsNetworkAvailable.mockResolvedValue(false)- expect(mockFetch).toHaveBeenCalledTimes(2)+ const { getByText } = render(<ConnectionStatus endpoint={url} navigation={mockNavigation} />)++ await waitFor(() => expect(getByText("Device offline")).toBeTruthy())})it("displays the host portion of the endpoint URL", async () => {- mockFetch.mockResolvedValue({ ok: true, status: 200 })-const { getByText } = render(<ConnectionStatus endpoint="https://my-server.com/api/locations" navigation={mockNavigation} />)expect(getByText("my-server.com")).toBeTruthy()+ await waitFor(() => expect(mockGetStats).toHaveBeenCalled())})- it("displays 'Server' when endpoint is empty", () => {+ it("displays 'Server' when endpoint is empty", async () => {const { getByText } = render(<ConnectionStatus endpoint="" navigation={mockNavigation} />)expect(getByText("Server")).toBeTruthy()- })-- it("includes auth headers in health check", async () => {- mockGetAuthHeaders.mockResolvedValue({ Authorization: "Bearer token123" })- mockFetch.mockResolvedValue({ ok: true, status: 200 })-- render(<ConnectionStatus endpoint="https://example.com/api/locations" navigation={mockNavigation} />)-- await waitFor(() => {- expect(mockFetch).toHaveBeenCalledWith(- expect.any(String),- expect.objectContaining({- headers: { Authorization: "Bearer token123" }- })- )- })- })-- it("proceeds without auth headers if getAuthHeaders fails", async () => {- mockGetAuthHeaders.mockRejectedValue(new Error("no credentials"))- mockFetch.mockResolvedValue({ ok: true, status: 200 })-- const { getByText } = render(- <ConnectionStatus endpoint="https://example.com/api/locations" navigation={mockNavigation} />- )-- await waitFor(() => {- expect(getByText("Connected")).toBeTruthy()- })+ await waitFor(() => expect(getByText("No endpoint")).toBeTruthy())})})diff --git a/apps/mobile/src/constants/index.ts b/apps/mobile/src/constants/index.tsindex 0f45967b..a022f669 100644--- a/apps/mobile/src/constants/index.ts+++ b/apps/mobile/src/constants/index.ts@@ -10,9 +10,7 @@ import { Zap, Car, ArrowUp, ArrowDown, Pause } from "lucide-react-native"export const AUTOSAVE_DEBOUNCE_MS = 1500export const STATS_REFRESH_IDLE = 30_000export const STATS_REFRESH_FAST = 3_000-export const SERVER_TIMEOUT = 5_000export const CONNECTION_TEST_TIMEOUT = 10_000-export const SERVER_CHECK_INTERVAL = 5 * 60 * 1000export const SAVE_SUCCESS_DISPLAY_MS = 2000export const TEST_RESULT_DISPLAY_MS = 5_000export const SERVICE_RESTART_DELAY_MS = 500diff --git a/apps/mobile/src/utils/__tests__/healthCheck.test.ts b/apps/mobile/src/utils/__tests__/healthCheck.test.tsdeleted file mode 100644index fefdeee1..00000000--- a/apps/mobile/src/utils/__tests__/healthCheck.test.ts+++ /dev/null@@ -1,56 +0,0 @@-import { resolveHealthUrls } from "../healthCheck"--describe("resolveHealthUrls", () => {- it("traccar: primary is port 8082/api/server, fallback is origin", () => {- expect(resolveHealthUrls("http://192.168.1.1:5055", "traccar")).toEqual([- "http://192.168.1.1:8082/api/server",- "http://192.168.1.1:8082"- ])- })-- it("dawarich: primary is /api/v1/health, fallback is origin", () => {- expect(resolveHealthUrls("https://dawarich.example.com:3000/api/v1/points", "dawarich")).toEqual([- "https://dawarich.example.com:3000/api/v1/health",- "https://dawarich.example.com:3000"- ])- })-- it("owntracks: tries /api/0/version then origin", () => {- expect(resolveHealthUrls("http://owntracks.local/pub", "owntracks")).toEqual([- "http://owntracks.local/api/0/version",- "http://owntracks.local"- ])- })-- it("phonetrack: primary is /status.php, fallback is origin", () => {- expect(resolveHealthUrls("https://nextcloud.example.com/apps/phonetrack", "phonetrack")).toEqual([- "https://nextcloud.example.com/status.php",- "https://nextcloud.example.com"- ])- })-- it("geopulse: tries /api/health then origin", () => {- expect(resolveHealthUrls("http://geopulse.local/ingest", "geopulse")).toEqual([- "http://geopulse.local/api/health",- "http://geopulse.local"- ])- })-- it("reitti: tries /health then origin", () => {- expect(resolveHealthUrls("http://reitti.local/api/locations", "reitti")).toEqual([- "http://reitti.local/health",- "http://reitti.local"- ])- })-- it("custom: tries /health then origin regardless of endpoint path", () => {- expect(resolveHealthUrls("https://custom.example.com/track", "custom")).toEqual([- "https://custom.example.com/health",- "https://custom.example.com"- ])- })-- it("returns only endpoint on invalid URL", () => {- expect(resolveHealthUrls("not-a-url", "custom")).toEqual(["not-a-url"])- })-})diff --git a/apps/mobile/src/utils/healthCheck.ts b/apps/mobile/src/utils/healthCheck.tsdeleted file mode 100644index 0db5f1a0..00000000--- a/apps/mobile/src/utils/healthCheck.ts+++ /dev/null@@ -1,37 +0,0 @@-import { ApiTemplateName } from "../types/global"--// Returns URLs to try in order: known health path first, origin root as fallback.-export function resolveHealthUrls(endpoint: string, apiTemplate: ApiTemplateName): string[] {- try {- const origin = new URL(endpoint).origin-- switch (apiTemplate) {- case "traccar": {- // Traccar web API runs on port 8082 regardless of the OsmAnd ingest port (5055)- const { protocol, hostname } = new URL(endpoint)- const base = `${protocol}//${hostname}:8082`- return [`${base}/api/server`, base]- }- case "dawarich":- return [`${origin}/api/v1/health`, origin]- case "overland":- // Portable format, no canonical server- return [origin]- case "owntracks":- // /api/0/version for OwnTracks Recorder; Home Assistant responds at root if that 404s- return [`${origin}/api/0/version`, origin]- case "phonetrack":- // PhoneTrack is a Nextcloud app - use Nextcloud's status endpoint- return [`${origin}/status.php`, origin]- case "geopulse":- return [`${origin}/api/health`, origin]- case "reitti":- case "custom":- // no UI yet for adding custom healthcheck endpoints; could be added once the server conenction settings get a own screen- default:- return [`${origin}/health`, origin]- }- } catch {- return [endpoint]- }-}diff --git a/fastlane/metadata/android/en-US/changelogs/43.txt b/fastlane/metadata/android/en-US/changelogs/43.txtindex faec1833..4701d25a 100644--- a/fastlane/metadata/android/en-US/changelogs/43.txt+++ b/fastlane/metadata/android/en-US/changelogs/43.txt@@ -3,4 +3,5 @@- FOSS: more reliable GPS on Android 12+ and a crash fix on GPS-less devices- Fixed a paused geofence wrongly resuming after a restart- Fixed the Stationary profile getting stuck active while still driving+- Fixed the dashboard showing the server unreachable while syncing worked- Fixed tracking silently stopping after restoring a backup