Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
16 changes: 11 additions & 5 deletions AGENTS.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
24 changes: 22 additions & 2 deletions app/src/main/AndroidManifest.xml
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,12 @@
<!-- "AI tools on your network" (mcp/McpService): the read-only MCP server runs as a dataSync
foreground service while the user has it on. docs/mcp-threat-model.md -->
<uses-permission android:name="android.permission.FOREGROUND_SERVICE_DATA_SYNC" />
<!-- MCP "Always on" (Android 14+): a specialUse foreground service has no daily limit and may
start at boot; RECEIVE_BOOT_COMPLETED brings it back after a reboot, and the battery
exemption request lets the user keep it reachable while the phone sleeps. -->
<uses-permission android:name="android.permission.FOREGROUND_SERVICE_SPECIAL_USE" />
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
<uses-permission android:name="android.permission.REQUEST_IGNORE_BATTERY_OPTIMIZATIONS" />
<uses-permission android:name="android.permission.ACTIVITY_RECOGNITION" />

<!-- Self-update: fetch the GitHub release manifest/APK and install it -->
Expand Down Expand Up @@ -169,8 +175,22 @@
only PulseLoop's settings screen starts it. docs/mcp-threat-model.md -->
<service
android:name=".mcp.McpService"
android:foregroundServiceType="dataSync"
android:exported="false" />
android:foregroundServiceType="dataSync|specialUse"
android:exported="false">
<property
android:name="android.app.PROPERTY_SPECIAL_USE_FGS_SUBTYPE"
android:value="A local network server, switched on by the user, that lets the user's own AI tools read their health data." />
</service>

<!-- Restarts the MCP server after a reboot or an update, only when the user chose Always on. -->
<receiver
android:name=".mcp.McpBootReceiver"
android:exported="true">
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED" />
<action android:name="android.intent.action.MY_PACKAGE_REPLACED" />
</intent-filter>
</receiver>

<!-- Home-screen widgets (iOS #44): three Glance app widgets + the shared configure
activity for the two configurable ones. -->
Expand Down
11 changes: 9 additions & 2 deletions app/src/main/assets/i18n/pt-BR.json
Original file line number Diff line number Diff line change
Expand Up @@ -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.",
Expand Down Expand Up @@ -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",
Expand Down Expand Up @@ -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…",
Expand Down Expand Up @@ -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.",
Expand Down Expand Up @@ -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",
Expand Down Expand Up @@ -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}",
Expand Down Expand Up @@ -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.",
Expand Down
26 changes: 26 additions & 0 deletions app/src/main/java/com/pulseloop/mcp/McpBootReceiver.kt
Original file line number Diff line number Diff line change
@@ -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
}
}
}
20 changes: 20 additions & 0 deletions app/src/main/java/com/pulseloop/mcp/McpConfig.kt
Original file line number Diff line number Diff line change
Expand Up @@ -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
}
13 changes: 12 additions & 1 deletion app/src/main/java/com/pulseloop/mcp/McpPrefs.kt
Original file line number Diff line number Diff line change
Expand Up @@ -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() }
Expand All @@ -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

Expand All @@ -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+). */
Expand Down
Loading
Loading