diff --git a/AGENTS.md b/AGENTS.md
index e4a90922..e6842e15 100644
--- a/AGENTS.md
+++ b/AGENTS.md
@@ -1158,11 +1158,17 @@ their data. Each rule fails silently if broken:
- **Tokens are shown once and stored as SHA-256 only**, in `mcp_server` preferences. That file,
and the on/off switch in it, are device state and security material: **never add them to
`ArchivedSettings`** — a restore on a new phone must start off with nothing paired.
-- **Off by default, foreground while on, never back by itself**: `START_NOT_STICKY`, no boot
- receiver, auto-off after the chosen hours (default 8), and stopping for any reason clears the
- switch. On Android 15+ the choices stop at 6 h and a stored 8 reads as 6
- (`McpConfig.autoOffHours`): a `dataSync` service gets about 6 h a day there. The notification's tap stops it. Type `dataSync` (Android 15 ends it at its daily
- limit through `onTimeout`; keep that override).
+- **Off by default, foreground while on, and back by itself only when the user chose it**. A
+ timed session: `START_NOT_STICKY`, auto-off after the chosen hours (1/4/8; on Android 15+ the
+ choices stop at 6 h and a stored 8 reads as 6, `McpConfig.autoOffHours`, because a `dataSync`
+ service gets about 6 h a day there and ends through `onTimeout` — keep that override), and
+ stopping for any reason clears the switch. **Always on** (`McpPrefs.alwaysOn`) is the user's
+ explicit choice behind a confirm dialog: no auto-off, `START_STICKY`, `specialUse` foreground
+ type on Android 14+ (no daily limit, may start at boot; needs the
+ `PROPERTY_SPECIAL_USE_FGS_SUBTYPE` property), and `McpBootReceiver` restarts it after a reboot
+ or an update only when it was left on. Only the user's Stop clears `enabled` then. Never make
+ always on a default, never skip the dialog, and never hide the ongoing notification: it is how
+ someone sees that their health data is reachable. The notification's tap stops it.
- **The `instructions` say it is not a diagnostic tool** and the numbers are estimates — the same
rule the coach follows. Keep them in step with the coach's prompt.
- The protocol, HTTP, address and token code has no Android imports and is JVM-tested; keep new
diff --git a/app/src/main/AndroidManifest.xml b/app/src/main/AndroidManifest.xml
index 1e61a210..a1004397 100644
--- a/app/src/main/AndroidManifest.xml
+++ b/app/src/main/AndroidManifest.xml
@@ -36,6 +36,12 @@
+
+
+
+
@@ -169,8 +175,22 @@
only PulseLoop's settings screen starts it. docs/mcp-threat-model.md -->
+ android:foregroundServiceType="dataSync|specialUse"
+ android:exported="false">
+
+
+
+
+
+
+
+
+
+
diff --git a/app/src/main/assets/i18n/pt-BR.json b/app/src/main/assets/i18n/pt-BR.json
index c9fcee6a..aa4483f3 100644
--- a/app/src/main/assets/i18n/pt-BR.json
+++ b/app/src/main/assets/i18n/pt-BR.json
@@ -81,7 +81,6 @@
"A little below your usual range.": "Um pouco abaixo da sua faixa habitual.",
"A low resting heart rate is common with high fitness.": "Frequência cardíaca em repouso baixa é comum em quem tem bom condicionamento.",
"A low score. Keep checking in; how you feel can change in the months after birth.": "Uma pontuação baixa. Continue respondendo de tempos em tempos; o que você sente pode mudar nos meses depois do parto.",
- "A new time applies the next time it's turned on.": "Um novo tempo vale a partir da próxima vez que for ativado.",
"A new version is available.": "Uma nova versão está disponível.",
"A normal blood-oxygen level is 95–100%.{0}": "Um nível normal de oxigênio no sangue é 95–100%.{0}",
"A nudge about 30 minutes before your suggested bedtime.": "Um lembrete cerca de 30 minutos antes do horário sugerido para dormir.",
@@ -187,16 +186,20 @@
"Allow Bluetooth access": "Permitir acesso ao Bluetooth",
"Allow access": "Permitir acesso",
"Allow background access so imports also run while PulseLoop is closed.": "Permita o acesso em segundo plano para que as importações também rodem com o PulseLoop fechado.",
+ "Allow background running": "Permitir em segundo plano",
"Allow background sync": "Permitir sincronização em segundo plano",
"Allow camera access in Settings to scan barcodes, or enter the food manually instead.": "Permita o acesso à câmera em Configurações para ler códigos de barras, ou insira o alimento manualmente.",
"Allow installs from this app, then tap Update again.": "Permita instalações deste app e toque em Atualizar de novo.",
"Allow more": "Permitir mais",
+ "Always": "Sempre",
+ "Always on: paired AI tools on this network can read your health data. Tap to stop.": "Sempre ligado: ferramentas de IA pareadas nesta rede podem ler seus dados de saúde. Toque para parar.",
"An LLM-native health app that turns a cheap Bluetooth smart ring into a real, conversational health tracker. It talks to the ring directly over Bluetooth — no vendor cloud, no account — and layers an AI coach on top of your own data.": "Um app de saúde nativo de LLM que transforma um anel inteligente Bluetooth barato em um monitor de saúde de verdade, com conversa. Ele se comunica com o anel diretamente via Bluetooth — sem nuvem do fabricante, sem conta — e adiciona um coach de IA sobre os seus próprios dados.",
"An estimated glucose value. No smart ring is cleared to measure glucose, so treat this as a wellness estimate only.": "Um valor estimado de glicose. Nenhum anel inteligente é aprovado para medir glicose, então trate isto apenas como uma estimativa de bem-estar.",
"An urgently low oxygen reading. Seek care if you also feel unwell.{0}": "Uma leitura de oxigênio urgentemente baixa. Procure atendimento se também estiver se sentindo mal.{0}",
"Analysis failed: {0}": "Falha na análise: {0}",
"Analyze": "Analisar",
"Android may delay background syncs by hours while your phone is idle. Your ring keeps recording either way; allowing this keeps the app up to date.": "O Android pode atrasar as sincronizações em segundo plano por horas enquanto o celular está ocioso. Seu anel continua gravando de qualquer forma; permitir isso mantém o app atualizado.",
+ "Android may pause it while the phone sleeps. Allow it to run in the background so your tools can always reach it.": "O Android pode pausá-lo enquanto o celular dorme. Permita que ele rode em segundo plano para que suas ferramentas sempre o alcancem.",
"Anonymize export": "Anonimizar exportação",
"Answers on this phone, with no key and no connection. Nothing you ask leaves the phone. It is slower and simpler than a cloud coach: no charts, no goal changes, no live measurements.": "Responde neste celular, sem chave e sem conexão. Nada do que você pergunta sai do celular. É mais lento e mais simples que um coach na nuvem: sem gráficos, sem mudar metas, sem medições ao vivo.",
"Anything else": "Outra coisa",
@@ -883,6 +886,8 @@
"Keep": "Manter",
"Keep editing": "Continuar editando",
"Keep going": "Continue",
+ "Keep it always on?": "Deixar sempre ligado?",
+ "Keep it on": "Deixar ligado",
"Keep recording": "Continuar gravando",
"Keep still — measuring blood oxygen…": "Fique parado — medindo o oxigênio no sangue…",
"Keep still — measuring blood pressure, SpO₂, stress, fatigue & blood sugar…": "Fique parado — medindo pressão arterial, SpO₂, estresse, fadiga e glicose…",
@@ -1214,6 +1219,7 @@
"On this phone (no key, works offline)": "Neste celular (sem chave, funciona offline)",
"On this phone · {0}": "Neste celular · {0}",
"On track": "No caminho certo",
+ "On until you turn it off, including after a restart.": "Ligado até você desligar, inclusive depois de reiniciar o celular.",
"On until {0}": "Ativado até {0}",
"On until {0}/{1}: activity nudges paused, the coach eases off.": "Ativo até {0}/{1}: lembretes de atividade pausados, o Coach pega mais leve.",
"On until {0}: activity nudges paused, the coach eases off.": "Ativo até {0}: lembretes de atividade pausados, o coach pega mais leve.",
@@ -1274,6 +1280,7 @@
"Pair your ring first: a check compares it against the other device.": "Pareie seu anel primeiro: a verificação o compara com o outro dispositivo.",
"Paired tools": "Ferramentas pareadas",
"Paired tools on this network can read your health data while this is on. Nothing is sent anywhere by itself.": "Ferramentas pareadas nesta rede podem ler seus dados de saúde enquanto isto estiver ativado. Nada é enviado a lugar nenhum por conta própria.",
+ "Paired tools on this network will be able to read your health data at any time, also after the phone restarts, until you turn it off here or tap Stop in its notification. The notification stays while it's on.": "As ferramentas pareadas nesta rede poderão ler seus dados de saúde a qualquer momento, também depois que o celular reiniciar, até você desligar aqui ou tocar em Parar na notificação. A notificação fica visível enquanto estiver ligado.",
"Paired {0} · last used {1}": "Pareada em {0} · último uso em {1}",
"Paired {0} · not used yet": "Pareada em {0} · ainda não usada",
"Past checks": "Verificações anteriores",
@@ -1635,6 +1642,7 @@
"Starting the download…": "Iniciando o download…",
"Starting…": "Iniciando…",
"Starts": "Início",
+ "Stays on for": "Fica ligado por",
"Steady build": "Evolução constante",
"Step progress": "Progresso de passos",
"Step {0} of {1}": "Etapa {0} de {1}",
@@ -1816,7 +1824,6 @@
"Turn off Drinks?": "Desativar Bebidas?",
"Turn on": "Ativar",
"Turn on Bluetooth to find and connect your ring.": "Ative o Bluetooth para encontrar e conectar seu anel.",
- "Turns itself off after": "Desliga sozinho depois de",
"Two hours after against two hours before, over {0} sessions. Readings during a session aren't counted: slow breathing raises HRV while it lasts.": "Duas horas depois comparadas com duas horas antes, em {0} sessões. Leituras durante a sessão não contam: a respiração lenta eleva a HRV enquanto dura.",
"Two-hour 140–199 is above the typical range.": "Duas horas após: 140–199 está acima da faixa típica.",
"Two-hour post-meal normal is up to 140 mg/dL.": "O normal duas horas após a refeição é até 140 mg/dL.",
diff --git a/app/src/main/java/com/pulseloop/mcp/McpBootReceiver.kt b/app/src/main/java/com/pulseloop/mcp/McpBootReceiver.kt
new file mode 100644
index 00000000..9eb5d283
--- /dev/null
+++ b/app/src/main/java/com/pulseloop/mcp/McpBootReceiver.kt
@@ -0,0 +1,26 @@
+package com.pulseloop.mcp
+
+import android.content.BroadcastReceiver
+import android.content.Context
+import android.content.Intent
+
+/**
+ * Brings the MCP server back after a reboot or an app update, and only when the user left it on
+ * with "Always on" chosen ([McpConfig.restartAfterBoot]). A timed session never comes back by
+ * itself. Both broadcasts are protected (only the system sends them), so the receiver can't be
+ * triggered by another app.
+ */
+class McpBootReceiver : BroadcastReceiver() {
+ override fun onReceive(context: Context, intent: Intent) {
+ if (intent.action != Intent.ACTION_BOOT_COMPLETED && intent.action != Intent.ACTION_MY_PACKAGE_REPLACED) return
+ val prefs = McpPrefs(context)
+ if (!McpConfig.restartAfterBoot(prefs.enabled, prefs.alwaysOn)) return
+ try {
+ McpService.start(context)
+ } catch (e: Exception) {
+ // A start the system refuses leaves it off; the switch then reads Off.
+ android.util.Log.w("McpBootReceiver", "MCP restart refused: ${e.javaClass.simpleName}")
+ prefs.enabled = false
+ }
+ }
+}
diff --git a/app/src/main/java/com/pulseloop/mcp/McpConfig.kt b/app/src/main/java/com/pulseloop/mcp/McpConfig.kt
index 3ab86842..1ae6cfdd 100644
--- a/app/src/main/java/com/pulseloop/mcp/McpConfig.kt
+++ b/app/src/main/java/com/pulseloop/mcp/McpConfig.kt
@@ -52,4 +52,24 @@ object McpConfig {
val capped = if (sdkInt >= DATA_SYNC_LIMIT_SDK) stored.coerceAtMost(DATA_SYNC_LIMIT_HOURS) else stored
return capped.takeIf { it in autoOffChoices(sdkInt) } ?: defaultAutoOffHours(sdkInt)
}
+
+ /**
+ * "Always on" uses the `specialUse` foreground-service type on Android 14+ (API 34), where it
+ * exists: unlike `dataSync` it has no daily limit (Android 15) and may start from
+ * `BOOT_COMPLETED`, which Android 15 forbids for `dataSync`. Below 14, `dataSync` has neither
+ * restriction. A timed session keeps `dataSync`.
+ */
+ const val SPECIAL_USE_SDK = 34
+
+ fun usesSpecialUse(alwaysOn: Boolean, sdkInt: Int): Boolean = alwaysOn && sdkInt >= SPECIAL_USE_SDK
+
+ /** [McpPrefs.offAt] while always on: never reached, so [McpPrefs.isOn] needs no second rule. */
+ const val NEVER = Long.MAX_VALUE
+
+ /** When a session that starts at [now] turns itself off. */
+ fun offAt(now: Long, alwaysOn: Boolean, hours: Int): Long =
+ if (alwaysOn) NEVER else now + hours * 3_600_000L
+
+ /** Whether to start the server again after a reboot or an app update. */
+ fun restartAfterBoot(enabled: Boolean, alwaysOn: Boolean): Boolean = enabled && alwaysOn
}
diff --git a/app/src/main/java/com/pulseloop/mcp/McpPrefs.kt b/app/src/main/java/com/pulseloop/mcp/McpPrefs.kt
index 91ea456d..b8435bb1 100644
--- a/app/src/main/java/com/pulseloop/mcp/McpPrefs.kt
+++ b/app/src/main/java/com/pulseloop/mcp/McpPrefs.kt
@@ -18,7 +18,8 @@ class McpPrefs(context: Context) : McpTokenStorage {
private val prefs: SharedPreferences =
context.applicationContext.getSharedPreferences(FILE, Context.MODE_PRIVATE)
- /** Set while the service runs; cleared whenever it stops, so it never outlives the process. */
+ /** Set while the service runs. Cleared when it stops, except while [alwaysOn], where only the
+ * user's own Stop clears it (so a reboot brings it back). */
var enabled: Boolean
get() = prefs.getBoolean(KEY_ENABLED, false)
set(v) { prefs.edit().putBoolean(KEY_ENABLED, v).apply() }
@@ -33,6 +34,15 @@ class McpPrefs(context: Context) : McpTokenStorage {
get() = McpConfig.autoOffHours(prefs.getInt(KEY_HOURS, McpConfig.defaultAutoOffHours(SDK)), SDK)
set(v) { prefs.edit().putInt(KEY_HOURS, v).apply() }
+ /**
+ * The user chose "Always on": no auto-off, back after a reboot or an app update, and Android
+ * restarts it if it is killed. Stays chosen when the switch is turned off, so turning it back
+ * on keeps the choice.
+ */
+ var alwaysOn: Boolean
+ get() = prefs.getBoolean(KEY_ALWAYS_ON, false)
+ set(v) { prefs.edit().putBoolean(KEY_ALWAYS_ON, v).apply() }
+
/** Whether a request may be answered now: switched on and not past its auto-off time. */
fun isOn(now: Long = System.currentTimeMillis()): Boolean = enabled && now < offAt
@@ -50,6 +60,7 @@ class McpPrefs(context: Context) : McpTokenStorage {
private const val KEY_ENABLED = "enabled"
private const val KEY_OFF_AT = "offAt"
private const val KEY_HOURS = "autoOffHours"
+ private const val KEY_ALWAYS_ON = "alwaysOn"
private const val KEY_TOOLS = "pairedTools"
private val SDK get() = android.os.Build.VERSION.SDK_INT
/** The auto-off lengths this device offers (1, 4 and 8 h; 6 h instead of 8 on Android 15+). */
diff --git a/app/src/main/java/com/pulseloop/mcp/McpService.kt b/app/src/main/java/com/pulseloop/mcp/McpService.kt
index 7886b9b2..25218564 100644
--- a/app/src/main/java/com/pulseloop/mcp/McpService.kt
+++ b/app/src/main/java/com/pulseloop/mcp/McpService.kt
@@ -30,13 +30,14 @@ import kotlinx.coroutines.runBlocking
/**
* Runs [McpServer] while the user has it on, always behind an ongoing notification that says so
* and stops it on a tap. Listens only on Wi-Fi, Ethernet, hotspot and Tailscale addresses, never
- * on mobile data; turns itself off after the chosen time; never comes back by itself
- * (`START_NOT_STICKY`, not started on boot). Not exported: only PulseLoop's own settings screen
- * starts it. Threat model: docs/mcp-threat-model.md.
+ * on mobile data. A timed session turns itself off after the chosen time and never comes back by
+ * itself (`START_NOT_STICKY`). "Always on", the user's explicit choice, has no auto-off, is
+ * `START_STICKY`, and is started again after a reboot or an app update ([McpBootReceiver]); only
+ * the user's Stop ends it. Not exported: only PulseLoop's settings screen and the boot receiver
+ * start it. Threat model: docs/mcp-threat-model.md.
*
- * Foreground-service type `dataSync`: the closest type that exists for minSdk 26 / targetSdk 35.
- * Android 15 caps `dataSync` at about 6 hours a day and then calls [onTimeout], which stops it,
- * so on those phones the 8-hour choice ends at the system's limit.
+ * Foreground-service type: `dataSync` for a timed session (Android 15 caps it at about 6 hours a
+ * day and calls [onTimeout]), `specialUse` for always on from Android 14 ([McpConfig.usesSpecialUse]).
*
* While it runs it follows the phone's networks ([watchNetworks]): when an address comes or goes
* (Wi-Fi joined or left, a DHCP renewal, Tailscale up or down) it listens on the new set and the
@@ -70,20 +71,32 @@ class McpService : Service() {
val prefs = McpPrefs(this)
if (intent?.action == ACTION_STOP) {
prefs.enabled = false
+ prefs.offAt = 0L
stopSelf()
return START_NOT_STICKY
}
// A foreground service must be in the foreground within seconds of starting, whatever follows.
- goForeground()
+ val alwaysOn = prefs.alwaysOn
+ try {
+ goForeground(alwaysOn)
+ } catch (e: Exception) {
+ // Android can refuse a foreground start from the background (a sticky restart on some
+ // versions). Stop quietly; always on stays chosen and returns at the next boot or when
+ // the settings screen is opened.
+ android.util.Log.w(TAG, "MCP foreground start refused: ${e.javaClass.simpleName}")
+ stopSelf()
+ return START_NOT_STICKY
+ }
val now = System.currentTimeMillis()
if (!prefs.isOn(now)) {
stopSelf()
return START_NOT_STICKY
}
main.removeCallbacks(autoOff)
- main.postDelayed(autoOff, (prefs.offAt - now).coerceAtLeast(0L))
+ if (!alwaysOn) main.postDelayed(autoOff, (prefs.offAt - now).coerceAtLeast(0L))
Thread({ startServer(prefs) }, "pulseloop-mcp-start").start()
- return START_NOT_STICKY // not brought back by Android: the user turns it on
+ // A timed session is never brought back by Android; always on is, if the process is killed.
+ return if (alwaysOn) START_STICKY else START_NOT_STICKY
}
@Synchronized
@@ -96,7 +109,8 @@ class McpService : Service() {
val handler = McpHandler(table, McpTokens(prefs), BuildConfig.VERSION_NAME, isOn = { prefs.isOn() })
val s = McpServer(handler)
val bound = s.start(McpNet.localAddresses(), McpNet.PORT)
- if (bound.isEmpty()) {
+ // Always on waits for a network instead of giving up: watchNetworks binds when one comes.
+ if (bound.isEmpty() && !prefs.alwaysOn) {
s.stop()
statusFlow.value = Status(unreachable = true)
main.post { stopSelf() }
@@ -170,12 +184,14 @@ class McpService : Service() {
server?.stop()
server = null
}
- McpPrefs(this).apply { enabled = false; offAt = 0L }
+ // Always on survives anything but the user's own Stop (which clears `enabled` itself), so a
+ // reboot or a system restart brings it back.
+ McpPrefs(this).apply { if (!alwaysOn) { enabled = false; offAt = 0L } }
statusFlow.value = statusFlow.value.copy(running = false, urls = emptyList(), offAt = 0L)
super.onDestroy()
}
- private fun goForeground() {
+ private fun goForeground(alwaysOn: Boolean) {
val nm = getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
nm.createNotificationChannel(
NotificationChannel(CHANNEL_ID, tr("AI tools on your network"), NotificationManager.IMPORTANCE_LOW)
@@ -185,7 +201,8 @@ class McpService : Service() {
this, 1, Intent(this, McpService::class.java).setAction(ACTION_STOP),
PendingIntent.FLAG_IMMUTABLE or PendingIntent.FLAG_UPDATE_CURRENT,
)
- val text = tr("Sharing your health data with paired AI tools on this network. Tap to stop.")
+ val text = if (alwaysOn) tr("Always on: paired AI tools on this network can read your health data. Tap to stop.")
+ else tr("Sharing your health data with paired AI tools on this network. Tap to stop.")
val n: Notification = NotificationCompat.Builder(this, CHANNEL_ID)
.setSmallIcon(android.R.drawable.ic_dialog_info)
.setContentTitle(tr("AI tools on your network"))
@@ -196,7 +213,9 @@ class McpService : Service() {
.setContentIntent(stop)
.addAction(0, tr("Stop"), stop)
.build()
- if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
+ if (McpConfig.usesSpecialUse(alwaysOn, Build.VERSION.SDK_INT) && Build.VERSION.SDK_INT >= Build.VERSION_CODES.UPSIDE_DOWN_CAKE) {
+ startForeground(NOTIFICATION_ID, n, ServiceInfo.FOREGROUND_SERVICE_TYPE_SPECIAL_USE)
+ } else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
startForeground(NOTIFICATION_ID, n, ServiceInfo.FOREGROUND_SERVICE_TYPE_DATA_SYNC)
} else {
startForeground(NOTIFICATION_ID, n)
@@ -213,17 +232,21 @@ class McpService : Service() {
private val statusFlow = MutableStateFlow(Status())
val status: StateFlow get() = statusFlow
- /** Turns it on for [McpPrefs.autoOffHours]. Call from the settings screen only (foreground). */
+ /**
+ * Turns it on for [McpPrefs.autoOffHours], or for good when [McpPrefs.alwaysOn]. Calling it
+ * while it runs applies a changed choice now (new off time, foreground type, stickiness).
+ * Callers: the settings screen (foreground) and [McpBootReceiver].
+ */
fun start(context: Context) {
val prefs = McpPrefs(context)
prefs.enabled = true
- prefs.offAt = System.currentTimeMillis() + prefs.autoOffHours * 3_600_000L
- statusFlow.value = Status(offAt = prefs.offAt)
+ prefs.offAt = McpConfig.offAt(System.currentTimeMillis(), prefs.alwaysOn, prefs.autoOffHours)
+ statusFlow.value = statusFlow.value.copy(offAt = prefs.offAt, unreachable = false)
ContextCompat.startForegroundService(context, Intent(context, McpService::class.java))
}
fun stop(context: Context) {
- McpPrefs(context).enabled = false
+ McpPrefs(context).apply { enabled = false; offAt = 0L }
context.stopService(Intent(context, McpService::class.java))
}
}
diff --git a/app/src/main/java/com/pulseloop/ui/screens/McpSettingsUi.kt b/app/src/main/java/com/pulseloop/ui/screens/McpSettingsUi.kt
index f69d0c96..1fe5787f 100644
--- a/app/src/main/java/com/pulseloop/ui/screens/McpSettingsUi.kt
+++ b/app/src/main/java/com/pulseloop/ui/screens/McpSettingsUi.kt
@@ -65,6 +65,25 @@ fun McpSettingsScreen(onBack: () -> Unit) {
val status by McpService.status.collectAsState()
var paired by remember { mutableStateOf(tokens.list()) }
var hours by remember { mutableIntStateOf(prefs.autoOffHours) }
+ var alwaysOn by remember { mutableStateOf(prefs.alwaysOn) }
+ var askingAlwaysOn by remember { mutableStateOf(false) }
+ // Re-read when the screen comes back from the system's battery dialog.
+ var batteryExempt by remember { mutableStateOf(isBatteryExempt(context)) }
+ androidx.lifecycle.compose.LifecycleResumeEffect(Unit) {
+ batteryExempt = isBatteryExempt(context)
+ onPauseOrDispose { }
+ }
+ // Always on that Android stopped (or refused to restart) comes back when this screen opens.
+ androidx.compose.runtime.LaunchedEffect(Unit) {
+ if (prefs.enabled && prefs.alwaysOn && !McpService.status.value.running) McpService.start(context)
+ }
+ // A changed choice applies at once while it runs: start() recomputes the off time and the
+ // service's type. While off it is simply kept for next time.
+ fun choose(always: Boolean, h: Int) {
+ alwaysOn = always; prefs.alwaysOn = always
+ if (!always) { hours = h; prefs.autoOffHours = h }
+ if (status.running || prefs.enabled) McpService.start(context)
+ }
var askingLabel by remember { mutableStateOf(false) }
var justPaired by remember { mutableStateOf?>(null) } // label to token
var revoking by remember { mutableStateOf(null) }
@@ -97,6 +116,7 @@ fun McpSettingsScreen(onBack: () -> Unit) {
}
Text(
when {
+ status.running && status.offAt == McpConfig.NEVER -> tr("On until you turn it off, including after a restart.")
status.running -> trf("On until {0}", clock(status.offAt))
starting -> tr("Starting…")
status.unreachable -> tr("Not on Wi-Fi or Tailscale, so nothing could reach it. Connect and try again.")
@@ -105,14 +125,21 @@ fun McpSettingsScreen(onBack: () -> Unit) {
style = PulseType.body,
color = if (status.unreachable && !on) PulseColors.warning else PulseColors.textSecondary,
)
- Text(tr("Turns itself off after"), style = PulseType.eyebrow, color = PulseColors.textSecondary)
+ Text(tr("Stays on for"), style = PulseType.eyebrow, color = PulseColors.textSecondary)
PulseSegmented(
- options = McpPrefs.HOURS_CHOICES.map { it to trf("{0} h", it) },
- selected = hours,
- onSelect = { h -> hours = h; prefs.autoOffHours = h },
+ options = McpPrefs.HOURS_CHOICES.map { it to trf("{0} h", it) } + (ALWAYS to tr("Always")),
+ selected = if (alwaysOn) ALWAYS else hours,
+ onSelect = { h -> if (h == ALWAYS) askingAlwaysOn = true else choose(false, h) },
)
- if (status.running) {
- Text(tr("A new time applies the next time it's turned on."), style = PulseType.label, color = PulseColors.textSecondary)
+ if (alwaysOn && !batteryExempt) {
+ Text(
+ tr("Android may pause it while the phone sleeps. Allow it to run in the background so your tools can always reach it."),
+ style = PulseType.label,
+ color = PulseColors.textSecondary,
+ )
+ PulseButton(PulseButtonStyle.Outlined, onClick = { requestBatteryExemption(context) }, modifier = Modifier.fillMaxWidth()) {
+ Text(tr("Allow background running"))
+ }
}
}
@@ -168,6 +195,25 @@ fun McpSettingsScreen(onBack: () -> Unit) {
}
}
+ if (askingAlwaysOn) {
+ AlertDialog(
+ onDismissRequest = { askingAlwaysOn = false },
+ title = { Text(tr("Keep it always on?")) },
+ text = {
+ Text(
+ tr("Paired tools on this network will be able to read your health data at any time, also after the phone restarts, until you turn it off here or tap Stop in its notification. The notification stays while it's on."),
+ style = PulseType.body,
+ )
+ },
+ confirmButton = {
+ PulseButton(PulseButtonStyle.Text, onClick = { askingAlwaysOn = false; choose(true, hours) }) { Text(tr("Keep it on")) }
+ },
+ dismissButton = {
+ PulseButton(PulseButtonStyle.Text, onClick = { askingAlwaysOn = false }) { Text(tr("Cancel")) }
+ },
+ )
+ }
+
if (askingLabel) {
var label by remember { mutableStateOf("") }
AlertDialog(
@@ -273,6 +319,24 @@ private fun McpCard(content: @Composable () -> Unit) {
private val CLOCK = DateTimeFormatter.ofPattern("HH:mm")
private val DAY = DateTimeFormatter.ofPattern("d MMM")
+/** The segmented control's key for "Always": no hour choice is 0. */
+private const val ALWAYS = 0
+
+private fun isBatteryExempt(context: Context): Boolean =
+ (context.getSystemService(Context.POWER_SERVICE) as? android.os.PowerManager)
+ ?.isIgnoringBatteryOptimizations(context.packageName) == true
+
+/** The system's own "allow in the background" dialog; the settings list if a phone lacks it. */
+private fun requestBatteryExemption(context: Context) {
+ val ask = android.content.Intent(android.provider.Settings.ACTION_REQUEST_IGNORE_BATTERY_OPTIMIZATIONS)
+ .setData(android.net.Uri.parse("package:" + context.packageName))
+ try {
+ context.startActivity(ask)
+ } catch (_: Exception) {
+ runCatching { context.startActivity(android.content.Intent(android.provider.Settings.ACTION_IGNORE_BATTERY_OPTIMIZATION_SETTINGS)) }
+ }
+}
+
private fun clock(ts: Long): String = Instant.ofEpochMilli(ts).atZone(ZoneId.systemDefault()).format(CLOCK)
private fun day(ts: Long): String = Instant.ofEpochMilli(ts).atZone(ZoneId.systemDefault()).format(DAY)
diff --git a/app/src/test/java/com/pulseloop/mcp/McpAlwaysOnTest.kt b/app/src/test/java/com/pulseloop/mcp/McpAlwaysOnTest.kt
new file mode 100644
index 00000000..e513933d
--- /dev/null
+++ b/app/src/test/java/com/pulseloop/mcp/McpAlwaysOnTest.kt
@@ -0,0 +1,34 @@
+package com.pulseloop.mcp
+
+import org.junit.Assert.assertEquals
+import org.junit.Assert.assertFalse
+import org.junit.Assert.assertTrue
+import org.junit.Test
+
+/** "Always on": its foreground-service type, its off time and when it comes back by itself. */
+class McpAlwaysOnTest {
+
+ @Test
+ fun `always on uses specialUse from Android 14, dataSync before and for timed sessions`() {
+ assertTrue(McpConfig.usesSpecialUse(alwaysOn = true, sdkInt = 34))
+ assertTrue(McpConfig.usesSpecialUse(alwaysOn = true, sdkInt = 35))
+ assertFalse(McpConfig.usesSpecialUse(alwaysOn = true, sdkInt = 33))
+ assertFalse(McpConfig.usesSpecialUse(alwaysOn = false, sdkInt = 35))
+ }
+
+ @Test
+ fun `always on never reaches its off time, a timed session does`() {
+ val now = 1_000_000L
+ assertEquals(McpConfig.NEVER, McpConfig.offAt(now, alwaysOn = true, hours = 4))
+ assertEquals(now + 4 * 3_600_000L, McpConfig.offAt(now, alwaysOn = false, hours = 4))
+ assertTrue(now < McpConfig.offAt(now, alwaysOn = true, hours = 1))
+ }
+
+ @Test
+ fun `only an always-on server left on comes back after a reboot`() {
+ assertTrue(McpConfig.restartAfterBoot(enabled = true, alwaysOn = true))
+ assertFalse(McpConfig.restartAfterBoot(enabled = true, alwaysOn = false))
+ assertFalse(McpConfig.restartAfterBoot(enabled = false, alwaysOn = true))
+ assertFalse(McpConfig.restartAfterBoot(enabled = false, alwaysOn = false))
+ }
+}
diff --git a/audits/2026-11-04-v2.14.0-mcp-always-on.md b/audits/2026-11-04-v2.14.0-mcp-always-on.md
new file mode 100644
index 00000000..0aad9b96
--- /dev/null
+++ b/audits/2026-11-04-v2.14.0-mcp-always-on.md
@@ -0,0 +1,92 @@
+# Audit: MCP "Always on" (v2.14.0)
+
+Date: 2026-11-04 · PR: see the PR that adds this file · Auditor: Claude. The four skills were
+applied by reading the code. There is no device or emulator in this session, so there are no
+screenshots.
+
+## Scope
+
+- **Settings › Connected apps › AI tools on your network:** "Turns itself off after" becomes
+ **"Stays on for"**, with the choices 1 h / 4 h / 6 or 8 h / **Always**.
+- Choosing **Always** opens a confirm dialog first.
+- While always on, a one-line note and an Outlined **"Allow background running"** button appear
+ until the phone exempts the app from battery optimisation.
+- A changed choice now applies at once. The line "A new time applies the next time it's turned on"
+ is gone.
+- **Service:**
+ - always on runs as a `specialUse` foreground service on Android 14+ (`dataSync` below that);
+ - it is `START_STICKY`;
+ - `McpBootReceiver` restarts it after a reboot or an app update;
+ - only the user's Stop ends it.
+- **New permissions:** `FOREGROUND_SERVICE_SPECIAL_USE`, `RECEIVE_BOOT_COMPLETED`,
+ `REQUEST_IGNORE_BATTERY_OPTIMIZATIONS`.
+- **No new tokens or screens.**
+
+## ux-user-flows (§13)
+
+```mermaid
+flowchart TD
+ S[Stays on for] -->|1/4/6-8 h| T[Timed: off at hh:mm]
+ S -->|Always| D{Keep it always on?}
+ D -->|Cancel| S
+ D -->|Keep it on| A[Always on · notification stays]
+ A -->|not exempt| B[Allow background running → system dialog]
+ A -->|reboot / app update| R[McpBootReceiver starts it again]
+ A -->|Stop in notification or switch| O[Off · stays off after reboot]
+ A -->|system kills it| K[START_STICKY restart, or back on next boot / screen open]
+```
+
+| # | Question | Result |
+|---|---|---|
+| 1 | Job | "My own agent can always reach my data." Pass |
+| 2 | Entries | One: the existing choice row. Pass |
+| 3 | Happy path | Tap Always, then Keep it on. Two taps, and a third for the optional battery exemption. Pass |
+| 4 | Branches | Cancel keeps the old choice. Switching back to hours applies at once. Pass |
+| 5 | States | Off, starting, on until hh:mm, always on, always on with no network (waits for one), not exempt (note and button), exempt (no note). Pass |
+| 6 | Errors | A refused background start stops quietly, and the server comes back at the next boot or when the screen opens. A refused boot start reads Off. Pass |
+| 7 | Control | Stop in the notification and the switch both end it; Revoke cuts off one tool. Pass |
+| 8 | Progress and resume | Resumes after a reboot or an update, only when it was left on. Pass |
+| 9 | Memory | The choice survives turning it off and on. It isn't in the backup, so a new phone starts off. Pass |
+| 10 | Exits | Pass |
+| 11 | Conventions | Shared segmented control, a Text-button dialog, an Outlined secondary button. Pass |
+| 12 | Speed | No added work per request. Pass |
+| 13 | Accessibility | Segments and buttons are 48dp or larger; the dialog text is plain. Pass |
+| 14 | Ethics | Explicit opt-in that says "at any time, also after the phone restarts". The ongoing notification can't be hidden while it runs. Never the default. Pass |
+| 15 | Evidence | `McpAlwaysOnTest` (type, off time, boot rule); CI |
+
+## impeccable (native audit)
+
+| Dimension | Score | Note |
+|---|---|---|
+| Accessibility | 4 | No new custom controls |
+| Performance | 4 | One idle listener; the battery exemption is the user's choice |
+| Appearance & theming | 4 | Tokens only; the note uses `label` / `textSecondary` |
+| Platform conformance | 4 | Each Android version gets the foreground-service type it permits (`specialUse` with its subtype property on 14+), START_STICKY, protected boot broadcasts, and the system's own battery dialog |
+| Adaptivity | 4 | Four short segments fit at 360dp, and "Sempre" in pt-BR is short too |
+| **Total** | **20/20** | |
+
+Findings: no P0–P3. One item needs a phone: confirm that tools still reach it with the screen off
+and the battery exemption on (Doze). The button exists for exactly that case.
+
+## graphic-design-fundamentals (§13)
+
+| Item | Result |
+|---|---|
+| Brief, concept, hierarchy | Pass: the choice sits where the old one was; the note appears only when it matters |
+| Contrast, colour | Pass: no new colour; mint stays on the selected segment and the buttons |
+| Alignment, spacing, typography | Pass: `PulseType` roles, card spacing unchanged |
+| Consistency, simplicity | Pass |
+| Production | Pass: every new `tr()` key has a pt-BR entry (script-checked); two orphaned keys removed |
+
+## less-is-more
+
+| Element | Question | Kept / cut |
+|---|---|---|
+| "A new time applies the next time…" | 3 | Cut: a change now applies at once |
+| Confirm dialog | 1 (consent) | Kept |
+| Battery note and button | 1 | Shown only while always on and not yet exempt |
+| "On until you turn it off, including after a restart." | 1 | Kept: it replaces the clock time |
+
+## Verdict
+
+Merge. There are no P0–P3 findings.
diff --git a/docs/mcp-threat-model.md b/docs/mcp-threat-model.md
index f1c3233a..b173f75e 100644
--- a/docs/mcp-threat-model.md
+++ b/docs/mcp-threat-model.md
@@ -41,7 +41,8 @@ the coach's context packet but drops its labs, postpartum, drinks and goal-plan
| Threat | Mitigation |
|---|---|
-| Left on by accident | Off by default. Never started on boot; Android doesn't restart it (`START_NOT_STICKY`). While it runs an ongoing notification says "Sharing your health data with paired AI tools on this network. Tap to stop.", and a tap stops it. It turns itself off after 1, 4 or 8 hours (default 8; Android 15 ends a `dataSync` service sooner, at its daily limit, through `onTimeout`). Stopping for any reason clears the switch. |
+| Left on by accident | Off by default. A timed session (1, 4 or 8 h; 6 h at most on Android 15+, where a `dataSync` service gets about 6 h a day) is never started on boot, Android doesn't restart it (`START_NOT_STICKY`), and stopping for any reason clears the switch. While it runs, an ongoing notification says it is sharing and a tap stops it. |
+| Always on (explicit opt-in) | Chosen only through a confirm dialog that says paired tools can read health data at any time, also after a restart. It then runs as a `specialUse` foreground service on Android 14+ (`dataSync` below), is `START_STICKY`, and `McpBootReceiver` starts it again after `BOOT_COMPLETED` or `MY_PACKAGE_REPLACED` (both protected broadcasts, so no other app can trigger them), only when the user left it on. The notification never goes away while it runs ("Always on: … Tap to stop."). Only the user's Stop, from the screen or the notification, ends it; Revoke still cuts off any one tool at once. The rest of this model is unchanged: same allowlist, tokens, private addresses, bounds. The residual risk is time: a leaked token works for as long as the server is on, so revoke a tool you no longer use (each pairing shows when it was last used). |
| Reached from the internet or over mobile data | Listens only on Wi-Fi, Ethernet, hotspot and Tailscale (`tun`) interfaces, never `rmnet`/`ccmni`, re-checked on every network change while it runs. Binds only addresses `McpNet.allowedPeer` accepts: loopback, 10/8, 172.16/12, 192.168/16, link-local, 100.64/10 (Tailscale/CGNAT), IPv6 ULA. Each connection's peer is checked again and closed before anything is read. |
| Someone else on the same Wi-Fi | Every request needs `Authorization: Bearer `. Each paired tool has its own token: 32 random bytes, base64url, shown once. Only its SHA-256 is stored, compared in constant time against every pairing. Tokens are revoked one by one. |
| A web page in a browser on the network (CSRF, DNS rebinding) | Any request with an `Origin` header is refused (403) before the token is even looked at. MCP clients don't send one; browsers do on cross-origin POSTs. The token is required anyway. |