diff --git a/AGENTS.md b/AGENTS.md
index fa51d7c1..8adbea12 100644
--- a/AGENTS.md
+++ b/AGENTS.md
@@ -1069,6 +1069,33 @@ because breaking it fails silently:
from `PulseLoopApplication`). Ring rows carry no device id, so a later sweep could not split
the two rings' data.
+## On-device coach: grounded, no tools, safety first
+
+**Read this before touching `coach/ondevice/` or the `ON_DEVICE` provider.** Design and as-built
+notes: `docs/on-device-model-and-mcp-plan.md`, Part 1.
+
+- **No tools and no writes on this provider.** `OnDeviceResponsesClient` never offers the
+ request's tools and never returns a function call, so no write tool or confirm card can come
+ from it; `PulseLoopApp`'s flags also turn off web search and live measurements for it. A 1B
+ model can't run the tool loop; don't wire it in "to see if it works".
+- **Safety runs before the model.** `OnDeviceSafety.route` sends crisis, emergency and
+ medicine/dose questions to fixed replies (CVV 188, SAMU 192, "ask your doctor or pharmacist")
+ without loading the model. Those replies are written in the router, not through `tr()`: no
+ voice catalog may rewrite them. New keywords go in both languages, already normalized, with a test.
+- **The reply is always a complete `coach_response`.** The client wraps the model's plain text
+ (`coachResponseJson`) so `parseFinal` accepts it on the first try. Asking the 1B model to write
+ JSON itself would spend repair rounds of slow generation and still fail.
+- **Only the coach chat may use it.** Any other `text.format` (meal estimate, lab report,
+ summary) is refused: a small model must not read a lab report or estimate a meal.
+- **The model is never in git, the APK or the backup.** It is downloaded on request, kept in
+ `noBackupFilesDir`, and re-downloadable; the data archive must not pick it up. Only the
+ provider choice (`coach_provider_mode`) rides in `ArchivedSettings`.
+- **Every download is SHA-256 checked** against the `.sha256` published beside it on the
+ pre-release, and is **Wi-Fi only by default** (`setAllowedOverMetered(false)`); mobile data is
+ the user's explicit choice.
+- **Keep `MAX_TOKENS` at the figure the file is proven with** (1280). A prompt past the window
+ crashes natively, which is why `OnDevicePrompt.fit` measures with the model's own tokenizer.
+
## Health Connect as the data source: one app, no ring, nothing back
**Read this before touching `health/source/` or the export's exclusions.** Full design:
@@ -1090,6 +1117,39 @@ and each one fails silently if broken:
It is exclusive with a paired ring: a `DeviceIdentified` turns it off.
+## MCP on your network: read-only, paired, private addresses only
+
+**Read this before touching `mcp/` or `ui/screens/McpSettingsUi.kt`.** Threat model:
+`docs/mcp-threat-model.md`. Settings › Connected apps › AI tools on your network runs an MCP
+server on the phone (port 8765, `POST /mcp`) so the user's own Claude Desktop or Cursor can read
+their data. Each rule fails silently if broken:
+
+- **The tools are an explicit allowlist** (`McpCoachTools.ALLOWLIST`), never "whatever the
+ registry holds with writes off": `ToolRegistry`'s always-on set already contains writes
+ (`log_meal`, `set_goal`, `log_drink`, `save_food_preference`, `set_drink_plan`) and a
+ cache-writing network call (`search_food_database`). Add a name only after reading its
+ implementation; `McpAllowlistTest` fails on a write name and on any coach tool nobody has
+ classified. Calls run with all three flags off and `coordinator = null`.
+- **Never a tool for** API keys, raw packets, diagnostics, lab-report PDFs or the EPDS answers.
+ `summary` reuses `CoachContextBuilder.build` but drops labs, postpartum, drinks and the goal
+ plan; keep it that way.
+- **Refusal order is part of the design**: `Origin` header → 403, then token → 401, then path and
+ method, all before a tool runs. Peers outside loopback/private/link-local/100.64/10/ULA are
+ closed before a byte is read, and nothing binds a public address or a mobile-data interface.
+- **Bounds stay**: 4 connections, 15 s, 8 KB head, 256 KB body, no chunked bodies, no JSON-RPC
+ batches, one tool call at a time.
+- **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. The notification's tap stops it. Type `dataSync` (Android 15 ends it at its daily
+ limit through `onTimeout`; keep that override).
+- **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
+ logic there rather than in the service.
+
## Every UI string goes through `tr()`, and the English text is the key
**The app speaks English and Brazilian Portuguese (Settings → Language, `ui/i18n/L10n.kt`).** There
diff --git a/app/build.gradle.kts b/app/build.gradle.kts
index bfa640f7..d5d97956 100644
--- a/app/build.gradle.kts
+++ b/app/build.gradle.kts
@@ -199,6 +199,11 @@ dependencies {
// stub, which strips the class at compile time. Full guava restores it.
implementation("com.google.guava:guava:33.3.1-android")
+ // The on-device coach (docs/on-device-model-and-mcp-plan.md, Part 1): MediaPipe LLM Inference
+ // runs a downloaded Gemma 3 1B `.task` file on the CPU. No permissions; the model itself is
+ // never in the APK. The same version Cochilo ships; LiteRT-LM waits for the Kotlin bump.
+ implementation("com.google.mediapipe:tasks-genai:0.10.35")
+
debugImplementation("androidx.compose.ui:ui-tooling")
debugImplementation("androidx.compose.ui:ui-test-manifest")
diff --git a/app/proguard-rules.pro b/app/proguard-rules.pro
index 9abf6804..42c5b630 100644
--- a/app/proguard-rules.pro
+++ b/app/proguard-rules.pro
@@ -28,3 +28,13 @@
-keepclasseswithmembers class com.pulseloop.update.** {
kotlinx.serialization.KSerializer serializer(...);
}
+
+# On-device coach (MediaPipe LLM Inference, docs/on-device-model-and-mcp-plan.md): its classes are
+# reached from native code and its options are protobuf messages, so R8 must leave them whole.
+-keep class com.google.mediapipe.** { *; }
+-dontwarn com.google.mediapipe.**
+-keep class com.google.protobuf.** { *; }
+-dontwarn com.google.protobuf.**
+# AutoValue / annotation-processing references inside MediaPipe that aren't on Android.
+-dontwarn javax.lang.model.**
+-dontwarn com.google.auto.value.**
diff --git a/app/src/main/AndroidManifest.xml b/app/src/main/AndroidManifest.xml
index 85b994ae..12e24f6a 100644
--- a/app/src/main/AndroidManifest.xml
+++ b/app/src/main/AndroidManifest.xml
@@ -33,6 +33,9 @@
missing entirely, so every workout start crashed on API 34+. -->
+
+
@@ -160,6 +163,13 @@
android:foregroundServiceType="health"
android:exported="false" />
+
+
+
ResponsesClient = { OpenAIResponsesClient(it) },
+ /** On-device only: whether the model file is on the phone. Passed in so this stays pure-JVM. */
+ onDeviceReady: Boolean = false,
+ /** On-device only: the loaded-model engine (`OnDeviceModelStore`). */
+ onDeviceEngine: OnDeviceEngine = NoOnDeviceEngine,
): Resolution = when (settings.providerMode) {
CoachProviderMode.USER_GEMINI_KEY -> {
val key = geminiKey?.takeIf { it.isNotBlank() }
@@ -74,6 +82,9 @@ object CoachClientResolver {
readTimeoutSeconds = settings.localTimeoutSeconds,
))
}
+ CoachProviderMode.ON_DEVICE ->
+ // No key and no server: the sentinel is the model file being on the phone.
+ Resolution(ON_DEVICE_KEY.takeIf { onDeviceReady }, OnDeviceResponsesClient(onDeviceEngine))
else -> {
// USER_OPENAI_KEY / OFFLINE_STUB / BACKEND_PROXY all use the OpenAI
// key + factory, mirroring the iOS resolver.
@@ -82,20 +93,36 @@ object CoachClientResolver {
}
}
+ /** The readiness sentinel of [CoachProviderMode.ON_DEVICE] when its model is on the phone. */
+ const val ON_DEVICE_KEY = "on-device"
+
+ /** Stands in when no engine was passed (JVM tests of the other providers). */
+ internal object NoOnDeviceEngine : OnDeviceEngine {
+ override suspend fun use(block: (com.pulseloop.coach.ondevice.LocalModel) -> T): T =
+ throw com.pulseloop.coach.openai.ResponsesError.Decoding(OnDeviceModelStore.NOT_READY)
+ }
+
/** Convenience overload reading the app's persisted stores. */
fun resolve(
store: CoachProviderSettingsStore,
apiKeyStore: ApiKeyStore,
openAIClientFactory: (String) -> ResponsesClient = { OpenAIResponsesClient(it) },
- ): Resolution = resolve(
- settings = store.snapshot(),
- openAIKey = apiKeyStore.apiKey,
- geminiKey = store.geminiApiKey,
- openRouterKey = store.openRouterApiKey,
- minimaxKey = store.minimaxApiKey,
- localKey = store.localApiKey,
- openAIClientFactory = openAIClientFactory,
- )
+ ): Resolution {
+ val settings = store.snapshot()
+ // Only touch the model store for the provider that uses it.
+ val onDevice = if (settings.providerMode == CoachProviderMode.ON_DEVICE) OnDeviceModelStore.get(store.appContext) else null
+ return resolve(
+ settings = settings,
+ openAIKey = apiKeyStore.apiKey,
+ geminiKey = store.geminiApiKey,
+ openRouterKey = store.openRouterApiKey,
+ minimaxKey = store.minimaxApiKey,
+ localKey = store.localApiKey,
+ openAIClientFactory = openAIClientFactory,
+ onDeviceReady = onDevice?.isReady() == true,
+ onDeviceEngine = onDevice ?: NoOnDeviceEngine,
+ )
+ }
/**
* A per-turn client factory for `CoachOrchestrator`. Gemini/OpenRouter
@@ -145,6 +172,8 @@ object CoachClientResolver {
// Reported verbatim for attribution — including blank, which is a valid llama.cpp
// setup. `CoachPricingCatalog` prices this provider at $0 regardless of the string.
CoachProviderMode.LOCAL_OPENAI_COMPAT -> settings.resolvedLocalModel
+ // Priced at $0 by `CoachPricingCatalog`, like the local server.
+ CoachProviderMode.ON_DEVICE -> ModelDownload.MODEL_SLUG
else -> openAIModel.ifEmpty { OpenAIModel.DEFAULT.slug }
}
}
diff --git a/app/src/main/java/com/pulseloop/coach/config/CoachProviderSettings.kt b/app/src/main/java/com/pulseloop/coach/config/CoachProviderSettings.kt
index d7445a51..88704bd6 100644
--- a/app/src/main/java/com/pulseloop/coach/config/CoachProviderSettings.kt
+++ b/app/src/main/java/com/pulseloop/coach/config/CoachProviderSettings.kt
@@ -5,7 +5,8 @@ package com.pulseloop.coach.config
* Where the coach's "brain" runs. `USER_OPENAI_KEY`, `USER_GEMINI_KEY` and
* `USER_OPENROUTER_KEY` are the shipping cloud providers; `BACKEND_PROXY` is
* reserved for a future public build and is treated as disabled until
- * implemented. iOS's `appleOnDevice` has no Android equivalent and is not ported.
+ * implemented. iOS's `appleOnDevice` has no Android equivalent and is not ported; Android's own
+ * on-device provider is [ON_DEVICE].
*/
enum class CoachProviderMode(val rawValue: String, val label: String) {
OFFLINE_STUB("offlineStub", "Offline"),
@@ -17,6 +18,9 @@ enum class CoachProviderMode(val rawValue: String, val label: String) {
* llama.cpp, vLLM, SGLang, LM Studio. The API key is optional here; the readiness sentinel
* is the base URL. See `docs/local-llm-coach.md`. */
LOCAL_OPENAI_COMPAT("localOpenAICompat", "Local / self-hosted"),
+ /** A small model on the phone itself (Gemma 3 1B through MediaPipe): grounded, no tools, no
+ * key. Readiness is the downloaded model file. See `docs/on-device-model-and-mcp-plan.md`. */
+ ON_DEVICE("onDevice", "On this phone"),
BACKEND_PROXY("backendProxy", "Backend proxy");
companion object {
diff --git a/app/src/main/java/com/pulseloop/coach/config/CoachProviderSettingsStore.kt b/app/src/main/java/com/pulseloop/coach/config/CoachProviderSettingsStore.kt
index 3928791f..d02dbc25 100644
--- a/app/src/main/java/com/pulseloop/coach/config/CoachProviderSettingsStore.kt
+++ b/app/src/main/java/com/pulseloop/coach/config/CoachProviderSettingsStore.kt
@@ -13,6 +13,8 @@ import androidx.security.crypto.MasterKeys
* this store only adds the new multi-provider keys alongside them.
*/
class CoachProviderSettingsStore(context: Context) {
+ /** For the on-device provider's model store (`CoachClientResolver.resolve`). */
+ val appContext: Context = context.applicationContext
private val masterKey = MasterKeys.getOrCreate(MasterKeys.AES256_GCM_SPEC)
private val prefs = EncryptedSharedPreferences.create(
"pulseloop_secure",
diff --git a/app/src/main/java/com/pulseloop/coach/config/ReasoningEfforts.kt b/app/src/main/java/com/pulseloop/coach/config/ReasoningEfforts.kt
index 3a884e78..7e574ba0 100644
--- a/app/src/main/java/com/pulseloop/coach/config/ReasoningEfforts.kt
+++ b/app/src/main/java/com/pulseloop/coach/config/ReasoningEfforts.kt
@@ -28,7 +28,9 @@ object ReasoningEfforts {
GeminiModel.entries.firstOrNull { it.slug == slug }?.reasoningEfforts ?: geminiLevels(slug)
// Neither client sends a `reasoning` field (MiniMax reasons inline; see the local
// client's header), so there is nothing to choose.
- CoachProviderMode.USER_MINIMAX_KEY, CoachProviderMode.LOCAL_OPENAI_COMPAT -> emptyList()
+ // The on-device model has no effort setting either.
+ CoachProviderMode.USER_MINIMAX_KEY, CoachProviderMode.LOCAL_OPENAI_COMPAT,
+ CoachProviderMode.ON_DEVICE -> emptyList()
// Offline / backend proxy send OpenAI requests (CoachClientResolver's fallback branch),
// and Settings shows the OpenAI picker for them.
else -> known(CoachProviderMode.USER_OPENAI_KEY, slug, live)
diff --git a/app/src/main/java/com/pulseloop/coach/ondevice/LocalModel.kt b/app/src/main/java/com/pulseloop/coach/ondevice/LocalModel.kt
new file mode 100644
index 00000000..2df8db8f
--- /dev/null
+++ b/app/src/main/java/com/pulseloop/coach/ondevice/LocalModel.kt
@@ -0,0 +1,51 @@
+package com.pulseloop.coach.ondevice
+
+import android.content.Context
+import com.google.mediapipe.tasks.genai.llminference.LlmInference
+import java.io.File
+
+/**
+ * The on-device coach's model (docs/on-device-model-and-mcp-plan.md, Part 1), copied from
+ * Cochilo's `LocalModel`. One small interface, so the runtime can change (LiteRT-LM after the
+ * Kotlin bump) without touching the coach. Everything runs on the phone; nothing is sent anywhere.
+ */
+interface LocalModel {
+ /** The model's continuation of [prompt]. Slow (seconds): call it off the main thread. */
+ fun generate(prompt: String): String
+
+ /** How many tokens [text] takes, so a prompt never overflows the model's window. */
+ fun tokens(text: String): Int
+
+ fun close()
+
+ companion object {
+ /**
+ * Prompt and answer together. 1280 is what Cochilo runs this same file with; a prompt past
+ * the model's window crashed natively there, so it stays at the proven figure.
+ */
+ const val MAX_TOKENS = 1280
+
+ /** Room kept for the answer; a prompt may use the rest and is trimmed to fit ([OnDevicePrompt.fit]). */
+ const val REPLY_TOKENS = 384
+ }
+}
+
+/** MediaPipe's LLM Inference with a `.task` model file (Gemma 3 1B int4). */
+@Suppress("DEPRECATION") // MediaPipe's LLM Inference is deprecated in favour of LiteRT-LM (a later step).
+class MediaPipeModel(context: Context, file: File) : LocalModel {
+ private val engine: LlmInference = LlmInference.createFromOptions(
+ context,
+ LlmInference.LlmInferenceOptions.builder()
+ .setModelPath(file.absolutePath)
+ .setMaxTokens(LocalModel.MAX_TOKENS)
+ // CPU: the GPU path crashes natively on some phones, and a 1B model is quick enough on CPU.
+ .setPreferredBackend(LlmInference.Backend.CPU)
+ .build(),
+ )
+
+ override fun generate(prompt: String): String = engine.generateResponse(prompt)
+
+ override fun tokens(text: String): Int = engine.sizeInTokens(text)
+
+ override fun close() = engine.close()
+}
diff --git a/app/src/main/java/com/pulseloop/coach/ondevice/ModelDownload.kt b/app/src/main/java/com/pulseloop/coach/ondevice/ModelDownload.kt
new file mode 100644
index 00000000..8c1b11fd
--- /dev/null
+++ b/app/src/main/java/com/pulseloop/coach/ondevice/ModelDownload.kt
@@ -0,0 +1,71 @@
+package com.pulseloop.coach.ondevice
+
+import java.io.File
+import java.security.MessageDigest
+
+/**
+ * Where the on-device coach's model comes from, and how what arrived is checked. Adapted from
+ * Cochilo's `ModelDownload`: the model sits on a GitHub **pre-release** (so the self-updater,
+ * which reads only full releases, never offers it), with a `sha256sum` line beside it.
+ *
+ * For now PulseLoop downloads Cochilo's published file ([REPO], [TAG]); moving to PulseLoop's own
+ * pre-release later is a change to those two constants. Pure, so it's unit-tested.
+ */
+object ModelDownload {
+ /** The repository whose pre-release holds the model. */
+ const val REPO = "gabrielbr/Cochilo"
+ const val TAG = "assistant-model-v1"
+ /** Gemma 3 1B, int4, for MediaPipe LLM Inference. */
+ const val FILE = "gemma3-1b-it-int4.task"
+ /** What Settings promises before anything moves (the file is about 555–585 MB). */
+ const val APPROX_MB = 600
+ /** Bytes the free-space check plans for: [APPROX_MB], rounded up a little. */
+ const val APPROX_BYTES = 620L * 1024 * 1024
+
+ /** The model's name on the coach screen and in Settings. A product name: not translated. */
+ const val DISPLAY_NAME = "Gemma 3 1B"
+ /** The slug a turn is attributed to (usage sheet, pricing). */
+ const val MODEL_SLUG = "gemma3-1b-on-device"
+
+ /** Below this much memory the phone isn't offered the model: loading it would starve the app. */
+ const val MIN_TOTAL_MEMORY_BYTES = 4L * 1000 * 1000 * 1000 - 400L * 1024 * 1024
+
+ /** The Gemma licence, linked before the download. */
+ const val TERMS_URL = "https://ai.google.dev/gemma/terms"
+
+ fun url(repo: String, name: String) = "https://github.com/$repo/releases/download/$TAG/$name"
+ fun modelUrl(repo: String = REPO) = url(repo, FILE)
+ fun sumUrl(repo: String = REPO) = modelUrl(repo) + ".sha256"
+
+ /**
+ * Whether a phone with [totalMemoryBytes] is offered the model. "4 GB" phones report a little
+ * under 4 GiB once the kernel takes its share, hence the margin in [MIN_TOTAL_MEMORY_BYTES].
+ * 0 (unknown) is not offered.
+ */
+ fun meetsMemoryFloor(totalMemoryBytes: Long): Boolean = totalMemoryBytes >= MIN_TOTAL_MEMORY_BYTES
+
+ /** The hash in a `sha256sum` line ("<64 hex> "), or null when it isn't one. */
+ fun parseSum(text: String): String? =
+ text.trim().split(Regex("\\s+")).firstOrNull()?.lowercase()
+ ?.takeIf { it.length == 64 && it.all { c -> c in '0'..'9' || c in 'a'..'f' } }
+
+ fun sha256(file: File): String {
+ val md = MessageDigest.getInstance("SHA-256")
+ file.inputStream().use { s ->
+ val buf = ByteArray(1 shl 20)
+ while (true) {
+ val n = s.read(buf)
+ if (n < 0) break
+ md.update(buf, 0, n)
+ }
+ }
+ return md.digest().joinToString("") { "%02x".format(it) }
+ }
+
+ /** What's wrong with a finished download, or null when it's the model we published. */
+ fun verify(file: File, expectedSha: String): ModelState.Reason? {
+ val head = file.inputStream().use { s -> ByteArray(16).also { s.read(it) } }
+ ModelFile.check(head, file.length())?.let { return it }
+ return if (sha256(file) == expectedSha.lowercase()) null else ModelState.Reason.CHECK
+ }
+}
diff --git a/app/src/main/java/com/pulseloop/coach/ondevice/ModelFile.kt b/app/src/main/java/com/pulseloop/coach/ondevice/ModelFile.kt
new file mode 100644
index 00000000..94557ed3
--- /dev/null
+++ b/app/src/main/java/com/pulseloop/coach/ondevice/ModelFile.kt
@@ -0,0 +1,63 @@
+package com.pulseloop.coach.ondevice
+
+import java.io.File
+import java.io.InputStream
+
+/** Checks on a model file before it's used, copied from Cochilo's `ModelFile`. Pure, so unit-tested. */
+object ModelFile {
+ /** A real model is hundreds of MB; anything this small was the wrong file. */
+ const val MIN_BYTES = 50L * 1024 * 1024
+
+ /**
+ * Whether the first bytes could be a model. Google's current Gemma `.task` isn't a zip, so the
+ * container isn't checked: only that it isn't text, the usual wrong file (an HTML error page,
+ * JSON, a note). A download is checked against its published SHA-256 as well, and the runtime
+ * refuses anything else it can't load.
+ */
+ fun looksLikeTask(head: ByteArray): Boolean {
+ val first = head.firstOrNull {
+ it != ' '.code.toByte() && it != '\n'.code.toByte() && it != '\r'.code.toByte() && it != '\t'.code.toByte()
+ }?.toInt()?.toChar() ?: return false
+ return first != '<' && first != '{' && first != '['
+ }
+
+ fun check(head: ByteArray, bytes: Long): ModelState.Reason? = when {
+ !looksLikeTask(head) -> ModelState.Reason.NOT_A_MODEL
+ bytes < MIN_BYTES -> ModelState.Reason.TOO_SMALL
+ else -> null
+ }
+
+ /**
+ * Whether a volume with [usableBytes] free can take a file of [fileBytes]: the file plus a
+ * [MIN_BYTES] margin, so the phone isn't left with nothing.
+ */
+ fun hasSpaceFor(fileBytes: Long, usableBytes: Long): Boolean = usableBytes >= fileBytes + MIN_BYTES
+
+ /**
+ * Copies [input] to [target] through a temporary file, reporting bytes copied; the old file
+ * stays until the copy is whole.
+ */
+ fun copy(input: InputStream, target: File, onBytes: (Long) -> Unit): Long {
+ target.parentFile?.mkdirs()
+ val tmp = File(target.parentFile, target.name + ".part")
+ var total = 0L
+ try {
+ tmp.outputStream().use { out ->
+ val buf = ByteArray(1 shl 20)
+ while (true) {
+ val n = input.read(buf)
+ if (n < 0) break
+ out.write(buf, 0, n)
+ total += n
+ onBytes(total)
+ }
+ }
+ } catch (e: Exception) {
+ tmp.delete()
+ throw e
+ }
+ if (target.exists()) target.delete()
+ if (!tmp.renameTo(target)) { tmp.delete(); error("could not move the model into place") }
+ return total
+ }
+}
diff --git a/app/src/main/java/com/pulseloop/coach/ondevice/ModelState.kt b/app/src/main/java/com/pulseloop/coach/ondevice/ModelState.kt
new file mode 100644
index 00000000..32673ee2
--- /dev/null
+++ b/app/src/main/java/com/pulseloop/coach/ondevice/ModelState.kt
@@ -0,0 +1,33 @@
+package com.pulseloop.coach.ondevice
+
+/**
+ * Where the on-device coach's model is, as Settings and the coach see it
+ * (docs/on-device-model-and-mcp-plan.md, Part 1). Adapted from Cochilo's `ModelState`. Pure, so
+ * the download and file checks that produce it are unit-tested.
+ */
+sealed interface ModelState {
+ /** Not on the phone yet. */
+ data object Absent : ModelState
+
+ /**
+ * On its way: [progress] 0..1, or null when unknown. [waitingForWifi]: queued until Wi-Fi.
+ * [copying]: a file the user chose is being copied in (not a download).
+ */
+ data class Getting(
+ val progress: Float?,
+ val waitingForWifi: Boolean = false,
+ val copying: Boolean = false,
+ ) : ModelState
+
+ /** On the phone, checked, ready to load. */
+ data class Ready(val bytes: Long) : ModelState
+
+ /** The last try failed; [reason] is shown in plain words. */
+ data class Failed(val reason: Reason) : ModelState
+
+ /**
+ * [NOT_PUBLISHED]: the model's checksum isn't on the release. [CHECK]: the file arrived, but
+ * its SHA-256 didn't match the published one.
+ */
+ enum class Reason { NOT_A_MODEL, TOO_SMALL, NO_SPACE, DOWNLOAD, NOT_PUBLISHED, CHECK, OTHER }
+}
diff --git a/app/src/main/java/com/pulseloop/coach/ondevice/OnDeviceModelStore.kt b/app/src/main/java/com/pulseloop/coach/ondevice/OnDeviceModelStore.kt
new file mode 100644
index 00000000..d7805412
--- /dev/null
+++ b/app/src/main/java/com/pulseloop/coach/ondevice/OnDeviceModelStore.kt
@@ -0,0 +1,321 @@
+package com.pulseloop.coach.ondevice
+
+import android.app.ActivityManager
+import android.app.DownloadManager
+import android.content.Context
+import android.net.Uri
+import com.pulseloop.BuildConfig
+import com.pulseloop.coach.openai.ResponsesError
+import com.pulseloop.ui.i18n.tr
+import com.pulseloop.ui.i18n.trf
+import kotlinx.coroutines.CoroutineScope
+import kotlinx.coroutines.Dispatchers
+import kotlinx.coroutines.Job
+import kotlinx.coroutines.SupervisorJob
+import kotlinx.coroutines.delay
+import kotlinx.coroutines.flow.MutableStateFlow
+import kotlinx.coroutines.flow.StateFlow
+import kotlinx.coroutines.isActive
+import kotlinx.coroutines.launch
+import kotlinx.coroutines.sync.Mutex
+import kotlinx.coroutines.sync.withLock
+import kotlinx.coroutines.withContext
+import java.io.File
+import java.net.HttpURLConnection
+import java.net.URL
+
+/**
+ * Where the on-device coach's model lives and how it gets there (docs/on-device-model-and-mcp-plan.md,
+ * Part 1), adapted from Cochilo's github-flavour `ModelSources`.
+ *
+ * - **The file lives in `noBackupFilesDir`**, so neither Android's backup nor PulseLoop's own
+ * archive (which reads Room and an allowlist of preferences) ever carries 600 MB of
+ * re-downloadable weights. It is never in git or the APK either.
+ * - **One tap downloads it** through Android's download manager, so it keeps going with the app
+ * closed, shows its progress in the system notification, resumes after a dropped connection and
+ * waits for Wi-Fi unless the user picks mobile data. The download manager can only write to
+ * the app's external files folder, so the file lands there and moves into place once its
+ * SHA-256 matches the published `.sha256`.
+ * - **A file the user already has** can be chosen instead ([import]); it is checked for size and
+ * that it isn't text, and the runtime refuses anything else it can't load.
+ * - **One engine is kept loaded** ([use]) and closed when the provider changes or the model is
+ * removed ([closeEngine], [remove]). Calls are serialized: one MediaPipe engine, one answer at a time.
+ *
+ * The requests carry nothing about the user: a GET of a public file.
+ */
+class OnDeviceModelStore private constructor(private val context: Context) : OnDeviceEngine {
+
+ /** The model, once it is on the phone and checked. */
+ val modelFile: File = File(context.noBackupFilesDir, "models/${ModelDownload.FILE}")
+
+ private val downloadDir: File? get() = context.getExternalFilesDir(null)?.let { File(it, "models") }
+ private val partial: File? get() = downloadDir?.let { File(it, PARTIAL_NAME) }
+
+ private val prefs = context.getSharedPreferences(PREFS, Context.MODE_PRIVATE)
+ private val dm: DownloadManager? = context.getSystemService(DownloadManager::class.java)
+ private val scope = CoroutineScope(SupervisorJob() + Dispatchers.IO)
+ private var watching: Job? = null
+
+ private val _state = MutableStateFlow(ModelState.Absent)
+ val state: StateFlow = _state
+
+ /** The phone's total memory, for the memory floor. 0 when Android won't say. */
+ val totalMemoryBytes: Long = runCatching {
+ ActivityManager.MemoryInfo().also { context.getSystemService(ActivityManager::class.java).getMemoryInfo(it) }.totalMem
+ }.getOrDefault(0L)
+
+ val meetsMemoryFloor: Boolean get() = ModelDownload.meetsMemoryFloor(totalMemoryBytes)
+
+ /** Serializes the engine: one load, one answer, one close at a time. */
+ private val lock = Mutex()
+ private var loaded: LocalModel? = null
+ private var lastFailure = ModelState.Reason.DOWNLOAD
+
+ init { look() }
+
+ /** Whether the model is on the phone: a cheap file check, safe on any thread. */
+ fun isReady(): Boolean = modelFile.exists() && modelFile.length() >= ModelFile.MIN_BYTES
+
+ /** Looks again at what's on the phone (the Settings sheet calls it when it opens). */
+ fun refresh() = look()
+
+ private fun look() {
+ if (_state.value is ModelState.Getting) return
+ when {
+ isReady() -> _state.value = ModelState.Ready(modelFile.length())
+ prefs.getLong(KEY_ID, -1L) >= 0 -> watch()
+ _state.value !is ModelState.Failed -> _state.value = ModelState.Absent
+ }
+ }
+
+ /** Starts the download: Wi-Fi only unless [wifiOnly] is false. */
+ fun download(wifiOnly: Boolean = true) {
+ if (_state.value is ModelState.Getting) return
+ start(wifiOnly)
+ }
+
+ /** A download waiting for Wi-Fi goes now, on any network. The download manager can't change a
+ * request's networks, so it starts again. */
+ fun useMobileData() {
+ cancelDownload()
+ _state.value = ModelState.Absent
+ start(wifiOnly = false)
+ }
+
+ /** Stops a download in progress. */
+ fun cancel() {
+ cancelDownload()
+ _state.value = if (isReady()) ModelState.Ready(modelFile.length()) else ModelState.Absent
+ }
+
+ private fun start(wifiOnly: Boolean) {
+ _state.value = ModelState.Getting(null, waitingForWifi = false)
+ scope.launch {
+ val dir = downloadDir
+ val manager = dm
+ if (dir == null || manager == null) { _state.value = ModelState.Failed(ModelState.Reason.OTHER); return@launch }
+ val sha = fetchSum() ?: run { _state.value = ModelState.Failed(lastFailure); return@launch }
+ dir.mkdirs()
+ modelFile.parentFile?.mkdirs()
+ // The download and the moved copy are on disk together for a moment.
+ val usable = minOf(dir.usableSpace, context.noBackupFilesDir.usableSpace)
+ if (!ModelFile.hasSpaceFor(ModelDownload.APPROX_BYTES * 2, usable)) {
+ _state.value = ModelState.Failed(ModelState.Reason.NO_SPACE); return@launch
+ }
+ partial?.delete()
+ val request = DownloadManager.Request(Uri.parse(ModelDownload.modelUrl()))
+ .setTitle(tr("PulseLoop coach model"))
+ .setDescription(trf("{0}, about {1} MB", ModelDownload.DISPLAY_NAME, ModelDownload.APPROX_MB))
+ .setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE)
+ .setDestinationInExternalFilesDir(context, null, "models/$PARTIAL_NAME")
+ .setAllowedOverMetered(!wifiOnly)
+ .setAllowedOverRoaming(false)
+ .addRequestHeader("User-Agent", "PulseLoop/${BuildConfig.VERSION_NAME}")
+ val id = runCatching { manager.enqueue(request) }.getOrNull()
+ if (id == null) { _state.value = ModelState.Failed(ModelState.Reason.DOWNLOAD); return@launch }
+ prefs.edit().putLong(KEY_ID, id).putString(KEY_SHA, sha).apply()
+ watch()
+ }
+ }
+
+ /** The published checksum, or null (and why, in [lastFailure]) when it can't be read. */
+ private fun fetchSum(): String? = runCatching {
+ val conn = (URL(ModelDownload.sumUrl()).openConnection() as HttpURLConnection).apply {
+ connectTimeout = 15_000; readTimeout = 15_000; instanceFollowRedirects = true
+ setRequestProperty("User-Agent", "PulseLoop/${BuildConfig.VERSION_NAME}")
+ }
+ try {
+ when (conn.responseCode) {
+ 200 -> ModelDownload.parseSum(conn.inputStream.bufferedReader().use { it.readText().take(512) })
+ .also { if (it == null) lastFailure = ModelState.Reason.NOT_PUBLISHED }
+ 404 -> { lastFailure = ModelState.Reason.NOT_PUBLISHED; null }
+ else -> { lastFailure = ModelState.Reason.DOWNLOAD; null }
+ }
+ } finally { conn.disconnect() }
+ }.getOrElse { lastFailure = ModelState.Reason.DOWNLOAD; null }
+
+ /** Follows the download manager's progress until the download ends. */
+ private fun watch() {
+ if (watching?.isActive == true) return
+ val manager = dm ?: return
+ watching = scope.launch {
+ while (isActive) {
+ val id = prefs.getLong(KEY_ID, -1L)
+ if (id < 0) return@launch
+ val row = runCatching {
+ manager.query(DownloadManager.Query().setFilterById(id))?.use { c ->
+ if (!c.moveToFirst()) null else Triple(
+ c.getInt(c.getColumnIndexOrThrow(DownloadManager.COLUMN_STATUS)),
+ c.getInt(c.getColumnIndexOrThrow(DownloadManager.COLUMN_REASON)),
+ c.getLong(c.getColumnIndexOrThrow(DownloadManager.COLUMN_BYTES_DOWNLOADED_SO_FAR)) to
+ c.getLong(c.getColumnIndexOrThrow(DownloadManager.COLUMN_TOTAL_SIZE_BYTES)),
+ )
+ }
+ }.getOrNull()
+ // Gone: cancelled from the notification.
+ if (row == null) { forget(); _state.value = ModelState.Absent; return@launch }
+ val (status, reason, sizes) = row
+ val progress = sizes.second.takeIf { it > 0 }?.let { (sizes.first.toFloat() / it).coerceIn(0f, 1f) }
+ when (status) {
+ DownloadManager.STATUS_SUCCESSFUL -> { finish(); return@launch }
+ DownloadManager.STATUS_FAILED -> {
+ forget(); partial?.delete()
+ _state.value = ModelState.Failed(
+ if (reason == DownloadManager.ERROR_INSUFFICIENT_SPACE) ModelState.Reason.NO_SPACE
+ else ModelState.Reason.DOWNLOAD,
+ )
+ return@launch
+ }
+ DownloadManager.STATUS_PAUSED -> _state.value = ModelState.Getting(
+ progress, waitingForWifi = reason == DownloadManager.PAUSED_QUEUED_FOR_WIFI,
+ )
+ else -> _state.value = ModelState.Getting(progress)
+ }
+ delay(1_000)
+ }
+ }
+ }
+
+ /** Checks the finished download against the published SHA-256, then moves it into place. */
+ private suspend fun finish() {
+ val sha = prefs.getString(KEY_SHA, null)
+ forget()
+ val file = partial
+ _state.value = ModelState.Getting(1f)
+ val problem = if (sha == null || file == null || !file.exists()) ModelState.Reason.DOWNLOAD
+ else runCatching { ModelDownload.verify(file, sha) }.getOrElse { ModelState.Reason.OTHER }
+ if (problem != null) {
+ file?.delete()
+ _state.value = ModelState.Failed(problem)
+ return
+ }
+ val placed = lock.withLock {
+ closeLoaded()
+ runCatching {
+ if (modelFile.exists()) modelFile.delete()
+ modelFile.parentFile?.mkdirs()
+ // Different volumes: a rename usually fails, so copy and delete.
+ if (!file!!.renameTo(modelFile)) {
+ file.inputStream().use { ModelFile.copy(it, modelFile) { } }
+ file.delete()
+ }
+ }.isSuccess
+ }
+ _state.value = if (placed && isReady()) ModelState.Ready(modelFile.length())
+ else { file?.delete(); ModelState.Failed(ModelState.Reason.NO_SPACE) }
+ }
+
+ private fun forget() = prefs.edit().remove(KEY_ID).apply()
+
+ private fun cancelDownload() {
+ val id = prefs.getLong(KEY_ID, -1L)
+ if (id >= 0) runCatching { dm?.remove(id) }
+ forget()
+ watching?.cancel()
+ partial?.delete()
+ }
+
+ /** Copies the model from [uri], a file the user chose (Storage Access Framework). */
+ suspend fun import(uri: Uri) = withContext(Dispatchers.IO) {
+ cancelDownload()
+ val resolver = context.contentResolver
+ val size = runCatching { resolver.openAssetFileDescriptor(uri, "r")?.use { it.length } }.getOrNull()?.takeIf { it > 0 }
+ val head = runCatching { resolver.openInputStream(uri)?.use { s -> ByteArray(16).also { s.read(it) } } }.getOrNull() ?: ByteArray(0)
+ ModelFile.check(head, size ?: Long.MAX_VALUE)?.let { _state.value = ModelState.Failed(it); return@withContext }
+ if (size != null && !ModelFile.hasSpaceFor(size, context.noBackupFilesDir.usableSpace)) {
+ _state.value = ModelState.Failed(ModelState.Reason.NO_SPACE); return@withContext
+ }
+ _state.value = ModelState.Getting(if (size != null) 0f else null, copying = true)
+ val copied = lock.withLock {
+ closeLoaded()
+ runCatching {
+ resolver.openInputStream(uri)!!.use { input ->
+ ModelFile.copy(input, modelFile) { done ->
+ if (size != null) _state.value = ModelState.Getting((done.toFloat() / size).coerceIn(0f, 1f), copying = true)
+ }
+ }
+ }
+ }
+ _state.value = copied.fold(
+ onSuccess = { bytes ->
+ if (bytes < ModelFile.MIN_BYTES) { modelFile.delete(); ModelState.Failed(ModelState.Reason.TOO_SMALL) }
+ else ModelState.Ready(bytes)
+ },
+ onFailure = { ModelState.Failed(ModelState.Reason.OTHER) },
+ )
+ }
+
+ /** Deletes the model from the phone, closing the engine first. */
+ fun remove() {
+ cancelDownload()
+ _state.value = ModelState.Absent
+ scope.launch {
+ lock.withLock {
+ closeLoaded()
+ modelFile.delete()
+ File(modelFile.parentFile, modelFile.name + ".part").delete()
+ }
+ _state.value = ModelState.Absent
+ }
+ }
+
+ // ── The engine ──────────────────────────────────────────────────────
+
+ override suspend fun use(block: (LocalModel) -> T): T = lock.withLock {
+ val model = loaded ?: run {
+ if (!isReady()) throw ResponsesError.Decoding(NOT_READY)
+ MediaPipeModel(context, modelFile).also { loaded = it }
+ }
+ block(model)
+ }
+
+ /** Frees the loaded engine (about a gigabyte of memory) once any answer in progress ends. */
+ fun closeEngine() {
+ scope.launch { lock.withLock { closeLoaded() } }
+ }
+
+ /** Only with [lock] held. */
+ private fun closeLoaded() {
+ loaded?.let { runCatching { it.close() } }
+ loaded = null
+ }
+
+ /** The coach client that answers with this phone's model. */
+ fun client(): OnDeviceResponsesClient = OnDeviceResponsesClient(engine = this)
+
+ companion object {
+ private const val PREFS = "on_device_model"
+ private const val KEY_ID = "download_id"
+ private const val KEY_SHA = "sha256"
+ private const val PARTIAL_NAME = "${ModelDownload.FILE}.download"
+
+ const val NOT_READY = "The model on this phone isn't downloaded yet. Get it in Settings → AI Coach → On this phone."
+
+ @Volatile private var instance: OnDeviceModelStore? = null
+
+ fun get(context: Context): OnDeviceModelStore =
+ instance ?: synchronized(this) {
+ instance ?: OnDeviceModelStore(context.applicationContext).also { instance = it }
+ }
+ }
+}
diff --git a/app/src/main/java/com/pulseloop/coach/ondevice/OnDevicePrompt.kt b/app/src/main/java/com/pulseloop/coach/ondevice/OnDevicePrompt.kt
new file mode 100644
index 00000000..0d35630a
--- /dev/null
+++ b/app/src/main/java/com/pulseloop/coach/ondevice/OnDevicePrompt.kt
@@ -0,0 +1,102 @@
+package com.pulseloop.coach.ondevice
+
+/**
+ * The prompt the on-device model gets, and how it is cut to fit the model's window
+ * (docs/on-device-model-and-mcp-plan.md, Part 1). Cochilo's `Grounding`, adapted: the app gathers
+ * the facts (the coach's context packet), the model only phrases the answer from them.
+ *
+ * The cloud system prompt is not sent: at about two thousand tokens it alone would overflow a
+ * 1280-token window. [instructions] restates its rules that matter without tools — never diagnose,
+ * never dose, send people to a clinician, use only the data given — in a few lines. Pure, so it's
+ * unit-tested.
+ */
+object OnDevicePrompt {
+ /** Longest question kept; a pasted essay would otherwise push out the context. */
+ const val MAX_QUESTION_CHARS = 1000
+ /** Each earlier chat message is cut to this, and at most [MAX_HISTORY] of them are kept. */
+ const val MAX_HISTORY_CHARS = 300
+ const val MAX_HISTORY = 4
+ /** Longest answer shown; past this the model wandered. */
+ const val MAX_REPLY_CHARS = 2000
+
+ /** One earlier message of the chat. [fromUser] false is the coach's own reply. */
+ data class Turn(val fromUser: Boolean, val text: String)
+
+ /** The coach's rules on this phone. [languageInstruction] is `L10n.coachInstruction()` (language and voice). */
+ fun instructions(languageInstruction: String): String = buildString {
+ append(
+ """
+You are PulseLoop Coach, running on the user's phone. Answer the user's question about their own ring data in at most 4 short paragraphs, in plain words.
+Use ONLY the facts in the context below. Use numbers exactly as they are written there. If the context doesn't answer the question, say so plainly. Never invent numbers, readings or studies.
+Never diagnose a condition. Never name a medicine, supplement or dose. For chest pain, fainting, trouble breathing, very low SpO2, or readings that stay abnormal, tell the user to see a clinician or call emergency services.
+Be warm and specific, and never judge the user's body. You can't change goals or log anything here; if asked, say they can do it in the app.
+Write plain text only: no JSON, no code, no headings.
+ """.trim(),
+ )
+ append(languageInstruction)
+ }
+
+ /** The developer message, minus its closing line about tools (there are none on this phone). */
+ fun contextFrom(developerMessage: String): String {
+ val tools = developerMessage.indexOf("Use the provided tools")
+ return (if (tools >= 0) developerMessage.substring(0, tools) else developerMessage).trim()
+ }
+
+ /** The whole prompt in Gemma's turn format. */
+ fun build(instructions: String, context: String, history: List, question: String): String = buildString {
+ append("user\n")
+ append(instructions.trim())
+ append("\n\n")
+ if (context.isNotBlank()) {
+ append("Context from the app:\n")
+ append(context.trim())
+ append("\n\n")
+ }
+ if (history.isNotEmpty()) {
+ append("Earlier in this chat:\n")
+ history.forEach { t ->
+ append(if (t.fromUser) "User: " else "Coach: ")
+ append(t.text.trim().replace(Regex("\\s+"), " ").take(MAX_HISTORY_CHARS))
+ append('\n')
+ }
+ append('\n')
+ }
+ append("Question: ")
+ append(question.trim().take(MAX_QUESTION_CHARS))
+ append("\nmodel\n")
+ }
+
+ /**
+ * The fullest prompt that [fits]: a prompt longer than the model's window crashes natively
+ * (Cochilo 0.39.1). Earlier messages go first, oldest first; then the context is cut down a
+ * quarter at a time, then dropped. The instructions and the question are always kept; null
+ * when even those two alone don't fit.
+ */
+ fun fit(instructions: String, context: String, history: List, question: String, fits: (String) -> Boolean): String? {
+ var h = history.takeLast(MAX_HISTORY)
+ var c = context.trim()
+ while (true) {
+ val prompt = build(instructions, c, h, question)
+ if (fits(prompt)) return prompt
+ when {
+ h.isNotEmpty() -> h = h.drop(1)
+ c.length > 200 -> c = c.take(c.length * 3 / 4).trimEnd() + " …"
+ c.isNotEmpty() -> c = ""
+ else -> return null
+ }
+ }
+ }
+
+ /** The model's text without turn markers, a leading label or surrounding quotes, and capped. */
+ fun clean(reply: String): String {
+ var r = reply
+ .replace("", "")
+ .replace("model", "")
+ .replace("", "")
+ .trim()
+ for (label in listOf("Answer:", "Resposta:", "Coach:")) r = r.removePrefix(label).trim()
+ r = r.trim('"').trim()
+ if (r.length > MAX_REPLY_CHARS) r = r.take(MAX_REPLY_CHARS).trimEnd() + "…"
+ return r
+ }
+}
diff --git a/app/src/main/java/com/pulseloop/coach/ondevice/OnDeviceResponsesClient.kt b/app/src/main/java/com/pulseloop/coach/ondevice/OnDeviceResponsesClient.kt
new file mode 100644
index 00000000..364e65ef
--- /dev/null
+++ b/app/src/main/java/com/pulseloop/coach/ondevice/OnDeviceResponsesClient.kt
@@ -0,0 +1,189 @@
+package com.pulseloop.coach.ondevice
+
+import com.pulseloop.coach.openai.MessageOutput
+import com.pulseloop.coach.openai.OpenAIResponse
+import com.pulseloop.coach.openai.ResponsesClient
+import com.pulseloop.coach.openai.ResponsesError
+import com.pulseloop.coach.openai.TextContent
+import com.pulseloop.coach.usage.CoachTokenUsage
+import kotlinx.coroutines.CancellationException
+import kotlinx.coroutines.Dispatchers
+import kotlinx.coroutines.withContext
+import kotlinx.serialization.json.Json
+import kotlinx.serialization.json.JsonArray
+import kotlinx.serialization.json.JsonElement
+import kotlinx.serialization.json.JsonNull
+import kotlinx.serialization.json.JsonObject
+import kotlinx.serialization.json.JsonPrimitive
+import kotlinx.serialization.json.contentOrNull
+import kotlinx.serialization.json.jsonObject
+import java.util.UUID
+
+/**
+ * The model the on-device client talks to: loaded once, used one answer at a time.
+ * [OnDeviceModelStore] is the real one; tests pass a fake.
+ */
+interface OnDeviceEngine {
+ /**
+ * Runs [block] with the loaded model, one call at a time (a MediaPipe engine is not safe to
+ * share between two generations). Throws [ResponsesError] when the model isn't on the phone.
+ */
+ suspend fun use(block: (LocalModel) -> T): T
+}
+
+/**
+ * The "On this phone" coach provider (docs/on-device-model-and-mcp-plan.md, Part 1), behind the
+ * same [ResponsesClient] interface as every cloud provider so `CoachOrchestrator` runs it
+ * unchanged. It answers grounded and without tools:
+ *
+ * - **Tools are ignored.** A 1B model can't run the tool loop, so the request's `tools` are never
+ * offered and the reply never holds a function call: the orchestrator's loop ends after one
+ * round, and no write tool or confirm card can come from this provider.
+ * - **The cloud system prompt is replaced** by [OnDevicePrompt.instructions] (its rules, shortened
+ * to fit the window), and the developer message's context packet is kept as the facts. When the
+ * prompt is too long, earlier chat messages go first, then the context is cut; the instructions
+ * and the question always stay.
+ * - **Safety comes first.** [OnDeviceSafety] checks the question before the model is loaded; a
+ * crisis, an emergency or a medicine question gets its fixed reply.
+ * - **The reply is valid `coach_response` JSON** wrapping the model's plain text ([coachResponseJson]),
+ * with every key `CoachResponseParser` requires, so `parseFinal` accepts it on the first try and
+ * never spends a repair round.
+ *
+ * Callers that ask for a different JSON schema (meal estimates, lab reports, summaries) are
+ * refused with a [ResponsesError.Decoding]: a 1B model can't be trusted to read a lab report.
+ */
+class OnDeviceResponsesClient(
+ private val engine: OnDeviceEngine,
+ private val portuguese: () -> Boolean = { com.pulseloop.ui.i18n.L10n.isPortuguese },
+ private val languageInstruction: () -> String = { com.pulseloop.ui.i18n.L10n.coachInstruction() },
+) : ResponsesClient {
+ private val json = Json { ignoreUnknownKeys = true }
+
+ /** The last answer, replayed if the orchestrator ever sends a continuation (it shouldn't: no tools, valid JSON). */
+ private var last: OpenAIResponse? = null
+
+ override suspend fun send(requestBody: ByteArray): OpenAIResponse {
+ val req = try {
+ json.parseToJsonElement(String(requestBody)).jsonObject
+ } catch (_: Exception) {
+ throw ResponsesError.Decoding("OnDeviceResponsesClient: invalid request body")
+ }
+ if (!isCoachChat(req)) throw ResponsesError.Decoding(UNSUPPORTED)
+
+ val previous = (req["previous_response_id"] as? JsonPrimitive)?.contentOrNull
+ if (previous != null) last?.let { return it }
+
+ val parsed = parseInput(req)
+ val pt = portuguese()
+
+ OnDeviceSafety.route(parsed.question, pt)?.let { route ->
+ return remember(response(coachResponseJson(route.reply, safety = true), usage = null))
+ }
+
+ val instructions = OnDevicePrompt.instructions(languageInstruction())
+ val budget = LocalModel.MAX_TOKENS - LocalModel.REPLY_TOKENS
+ val answer = try {
+ withContext(Dispatchers.Default) {
+ engine.use { model ->
+ val prompt = OnDevicePrompt.fit(instructions, parsed.context, parsed.history, parsed.question) {
+ model.tokens(it) <= budget
+ } ?: throw ResponsesError.Decoding(TOO_LONG)
+ val raw = model.generate(prompt)
+ Answer(OnDevicePrompt.clean(raw), model.tokens(prompt), model.tokens(raw))
+ }
+ }
+ } catch (e: CancellationException) {
+ throw e
+ } catch (e: ResponsesError) {
+ throw e
+ } catch (e: Throwable) {
+ // A native failure or running out of memory must end the turn with a message, not
+ // take the app down: the orchestrator only catches Exception.
+ throw ResponsesError.Decoding(FAILED + (e.message?.let { " ($it)" } ?: ""))
+ }
+ if (answer.text.isBlank()) throw ResponsesError.EmptyOutput
+ return remember(response(
+ coachResponseJson(answer.text, safety = false),
+ usage = CoachTokenUsage(inputTokens = answer.inputTokens, outputTokens = answer.outputTokens),
+ ))
+ }
+
+ private data class Answer(val text: String, val inputTokens: Int, val outputTokens: Int)
+
+ internal data class Parsed(val context: String, val history: List, val question: String)
+
+ /**
+ * The newest developer message becomes the context; system messages are dropped (replaced by
+ * the on-device instructions); user and assistant messages before the last user one are the
+ * history; the last user message is the question. Images are ignored: this model reads text.
+ */
+ internal fun parseInput(req: JsonObject): Parsed {
+ val input = (req["input"] as? JsonArray)?.mapNotNull { it as? JsonObject } ?: emptyList()
+ var context = ""
+ val chat = mutableListOf()
+ for (item in input) {
+ val role = (item["role"] as? JsonPrimitive)?.contentOrNull ?: continue
+ val text = flattenText(item["content"])
+ when (role) {
+ "developer" -> if (text.isNotBlank()) context = OnDevicePrompt.contextFrom(text)
+ "user" -> chat.add(OnDevicePrompt.Turn(fromUser = true, text = text))
+ "assistant" -> chat.add(OnDevicePrompt.Turn(fromUser = false, text = text))
+ // "system": the cloud prompt, too long for this window; OnDevicePrompt restates its rules.
+ }
+ }
+ val lastUser = chat.indexOfLast { it.fromUser }
+ val question = if (lastUser >= 0) chat[lastUser].text else ""
+ val history = if (lastUser >= 0) chat.subList(0, lastUser).filter { it.text.isNotBlank() } else emptyList()
+ return Parsed(context, history.toList(), question)
+ }
+
+ /** True for the coach chat: no `text.format`, or the `coach_response` one. */
+ internal fun isCoachChat(req: JsonObject): Boolean {
+ val format = (req["text"] as? JsonObject)?.get("format") as? JsonObject ?: return true
+ if ((format["type"] as? JsonPrimitive)?.contentOrNull != "json_schema") return true
+ return (format["name"] as? JsonPrimitive)?.contentOrNull == "coach_response"
+ }
+
+ private fun flattenText(content: JsonElement?): String {
+ if (content is JsonPrimitive && content.isString) return content.content
+ val parts = (content as? JsonArray)?.mapNotNull { it as? JsonObject } ?: return ""
+ return parts.mapNotNull { p ->
+ val type = (p["type"] as? JsonPrimitive)?.contentOrNull
+ if (type == "input_text" || type == "text") (p["text"] as? JsonPrimitive)?.contentOrNull else null
+ }.joinToString("\n")
+ }
+
+ private fun remember(r: OpenAIResponse): OpenAIResponse { last = r; return r }
+
+ private fun response(text: String, usage: CoachTokenUsage?) = OpenAIResponse(
+ id = "ondevice_" + UUID.randomUUID().toString().replace("-", "").take(16),
+ output = listOf(MessageOutput(role = "assistant", content = listOf(TextContent(text)))),
+ usage = usage,
+ )
+
+ companion object {
+ const val UNSUPPORTED =
+ "The model on this phone only answers coach questions. Reading photos, meals or lab reports needs a cloud or self-hosted coach (Settings → AI Coach)."
+ const val TOO_LONG = "That message is too long for the model on this phone. Try a shorter question."
+ const val FAILED = "The model on this phone couldn't answer. Try again, or close other apps to free memory."
+
+ /**
+ * A `coach_response` object with every key the schema lists (and so every key
+ * `CoachResponseParser` requires: response_type, title, summary, confidence), carrying
+ * [summary] as the answer. [safety] marks a fixed safety reply.
+ */
+ fun coachResponseJson(summary: String, safety: Boolean): String = JsonObject(mapOf(
+ "response_type" to JsonPrimitive(if (safety) "safety_guidance" else "insight"),
+ "title" to JsonPrimitive(""),
+ "summary" to JsonPrimitive(summary),
+ "bullets" to JsonArray(emptyList()),
+ "chart" to JsonNull,
+ "safety_note" to JsonNull,
+ "data_quality_note" to JsonNull,
+ "sources" to JsonArray(emptyList()),
+ "follow_up_chips" to JsonArray(emptyList()),
+ "actions_taken" to JsonArray(emptyList()),
+ "confidence" to JsonPrimitive(if (safety) "high" else "medium"),
+ )).toString()
+ }
+}
diff --git a/app/src/main/java/com/pulseloop/coach/ondevice/OnDeviceSafety.kt b/app/src/main/java/com/pulseloop/coach/ondevice/OnDeviceSafety.kt
new file mode 100644
index 00000000..6056bb6b
--- /dev/null
+++ b/app/src/main/java/com/pulseloop/coach/ondevice/OnDeviceSafety.kt
@@ -0,0 +1,119 @@
+package com.pulseloop.coach.ondevice
+
+import java.text.Normalizer
+
+/**
+ * Safety comes before the on-device model (docs/on-device-model-and-mcp-plan.md, Part 1, "The
+ * hard part: tools", step 3). A 1B model can't be trusted with a crisis, an emergency or a
+ * medicine question, so those get a fixed, reviewed reply and the model never sees them, as in
+ * Cochilo's Ask (`Assistant.ask`).
+ *
+ * Matching is on whole words, case- and accent-insensitive, in English and Portuguese ("remédio"
+ * and "remedio" both match). Order matters: a crisis outranks an emergency, which outranks a
+ * medicine question, so "I took too many pills to end my life" gets the crisis lines.
+ *
+ * The replies are written here, not through `tr()`: they are safety text, which no voice catalog
+ * may rewrite (AGENTS.md, "A voice is a catalog layered on a language"). Pure, so unit-tested.
+ */
+object OnDeviceSafety {
+
+ enum class Kind { CRISIS, EMERGENCY, MEDICINE }
+
+ data class Route(val kind: Kind, val reply: String)
+
+ /** The fixed reply for [question], or null when the model may answer it. */
+ fun route(question: String, portuguese: Boolean): Route? {
+ val text = normalize(question)
+ if (text.isBlank()) return null
+ val kind = when {
+ CRISIS.any { it.containsMatchIn(text) } -> Kind.CRISIS
+ EMERGENCY.any { it.containsMatchIn(text) } -> Kind.EMERGENCY
+ MEDICINE.any { it.containsMatchIn(text) } -> Kind.MEDICINE
+ else -> return null
+ }
+ return Route(kind, reply(kind, portuguese))
+ }
+
+ fun reply(kind: Kind, portuguese: Boolean): String = when (kind) {
+ Kind.CRISIS -> if (portuguese)
+ "Sinto muito que você esteja passando por isso. Você não precisa enfrentar isso sozinho. " +
+ "O CVV atende de graça, a qualquer hora, no 188 (ou em cvv.org.br). " +
+ "Se você estiver em perigo agora, ligue para o SAMU no 192 ou vá ao pronto-socorro mais próximo."
+ else
+ "I'm really sorry you're going through this. You don't have to face it alone. " +
+ "In Brazil, CVV answers for free, at any hour, on 188 (or at cvv.org.br). " +
+ "If you're in danger right now, call SAMU on 192 or go to the nearest emergency room. " +
+ "Outside Brazil, call your local emergency number."
+ Kind.EMERGENCY -> if (portuguese)
+ "Isso pode ser urgente. Com dor no peito, falta de ar ou desmaio, ligue agora para o SAMU no 192 " +
+ "ou vá ao pronto-socorro mais próximo. Não espere pelas leituras do anel."
+ else
+ "This could be urgent. For chest pain, trouble breathing or fainting, call SAMU on 192 now " +
+ "(or your local emergency number), or go to the nearest emergency room. " +
+ "Don't wait for the ring's readings."
+ Kind.MEDICINE -> if (portuguese)
+ "Eu não oriento sobre remédios, doses ou suplementos. Pergunte ao seu médico ou farmacêutico, " +
+ "que conhecem o seu histórico. Posso olhar com você os dados do seu anel, como sono, " +
+ "frequência cardíaca e atividade."
+ else
+ "I don't advise on medicines, doses or supplements. Please ask your doctor or pharmacist, " +
+ "who know your history. I can look at your ring data with you, like sleep, heart rate " +
+ "and activity."
+ }
+
+ /** Lower case, accents gone, apostrophes dropped ("can't" → "cant"), spaces collapsed. */
+ internal fun normalize(text: String): String =
+ Normalizer.normalize(text.lowercase(), Normalizer.Form.NFD)
+ .replace(Regex("\\p{M}+"), "")
+ .replace(Regex("['’`´]"), "")
+ .replace(Regex("\\s+"), " ")
+ .trim()
+
+ /**
+ * Whole-word patterns. A trailing `*` makes a stem ("suicid*" matches "suicide", "suicídio",
+ * "suicidal"). Keys are written already normalized (no accents, no apostrophes).
+ */
+ private fun patterns(vararg keys: String): List = keys.map { k ->
+ val stem = k.endsWith("*")
+ val body = Regex.escape(k.removeSuffix("*"))
+ Regex("(^|[^a-z0-9])$body" + if (stem) "" else "($|[^a-z0-9])")
+ }
+
+ private val CRISIS = patterns(
+ // English
+ "suicid*", "kill myself", "killing myself", "end my life", "ending my life", "take my life",
+ "self harm", "self-harm", "selfharm", "hurt myself", "hurting myself", "cut myself", "cutting myself",
+ "want to die", "wanna die", "dont want to live", "dont want to be alive", "no reason to live",
+ "better off dead",
+ // Portuguese
+ "me matar", "tirar minha vida", "tirar a minha vida", "acabar com a minha vida", "acabar com minha vida",
+ "quero morrer", "queria morrer", "nao quero mais viver", "nao quero viver", "me machucar", "me cortar",
+ "automutila*", "autolesao", "nao aguento mais viver", "sem motivo para viver",
+ )
+
+ private val EMERGENCY = patterns(
+ // English
+ "chest pain", "pain in my chest", "chest hurts", "chest is hurting", "chest pressure", "chest tightness",
+ "cant breathe", "cannot breathe", "can not breathe", "trouble breathing", "hard to breathe",
+ "short of breath", "shortness of breath", "fainted", "fainting", "faint", "passed out", "pass out",
+ "passing out", "emergency", "heart attack", "having a stroke", "had a stroke", "stroke symptoms",
+ // Portuguese
+ "dor no peito", "dor peito", "aperto no peito", "pressao no peito", "nao consigo respirar",
+ "falta de ar", "dificuldade para respirar", "dificuldade de respirar", "desmai*", "emergencia",
+ "infarto", "ataque cardiaco", "avc",
+ )
+
+ private val MEDICINE = patterns(
+ // English
+ "medicine*", "medication*", "meds", "pill", "pills", "tablet", "tablets", "dose", "doses", "dosage",
+ "dosing", "milligram*", "supplement*", "prescription*", "prescribe*", "drug", "drugs",
+ "ibuprofen", "paracetamol", "acetaminophen", "tylenol", "aspirin", "melatonin", "creatine",
+ "antidepressant*", "beta blocker*", "beta-blocker*", "insulin", "statin*", "antibiotic*",
+ "painkiller*", "sleeping pill*",
+ // Portuguese
+ "remedio*", "medicamento*", "medicacao", "medicacoes", "comprimido*", "pilula*", "dosagem",
+ "suplemento*", "suplementacao", "dipirona", "ibuprofeno", "melatonina", "creatina",
+ "antidepressivo*", "betabloqueador*", "insulina", "estatina*", "antibiotico*", "analgesico*",
+ "tarja preta", "receitar", "prescrever", "prescricao",
+ )
+}
diff --git a/app/src/main/java/com/pulseloop/coach/usage/CoachModelPricing.kt b/app/src/main/java/com/pulseloop/coach/usage/CoachModelPricing.kt
index aad10c25..9044578b 100644
--- a/app/src/main/java/com/pulseloop/coach/usage/CoachModelPricing.kt
+++ b/app/src/main/java/com/pulseloop/coach/usage/CoachModelPricing.kt
@@ -20,8 +20,8 @@ data class CoachModelPrice(
* longest matching key prefix, so a custom slug like `openai/gpt-5.5-preview`
* still prices off `openai/gpt-5.5`.
*
- * Unlike iOS there's no Apple on-device provider on Android, so [freeModels] only
- * carries `offline-stub`.
+ * [freeModels] carries `offline-stub` and the on-device model's slug (`ModelDownload.MODEL_SLUG`),
+ * both free on every turn.
*/
object CoachPricingCatalog {
/** Normalized-key → published list price, standard (non-batch) tier, as of
@@ -79,7 +79,7 @@ object CoachPricingCatalog {
)
/** The model strings that always cost $0 (local / scripted). */
- private val freeModels: Set = setOf("offline-stub")
+ private val freeModels: Set = setOf("offline-stub", com.pulseloop.coach.ondevice.ModelDownload.MODEL_SLUG)
/**
* Cost for a turn, given the provider that ran it. A self-hosted model costs the user nothing
@@ -91,7 +91,8 @@ object CoachPricingCatalog {
* values fall through to the catalog.
*/
fun cost(model: String, usage: CoachTokenUsage, providerRaw: String?): Double? =
- if (providerRaw == com.pulseloop.coach.config.CoachProviderMode.LOCAL_OPENAI_COMPAT.rawValue) 0.0
+ if (providerRaw == com.pulseloop.coach.config.CoachProviderMode.LOCAL_OPENAI_COMPAT.rawValue ||
+ providerRaw == com.pulseloop.coach.config.CoachProviderMode.ON_DEVICE.rawValue) 0.0
else cost(model, usage)
/** The estimated USD cost of [usage] for [model]. Returns 0 for offline
diff --git a/app/src/main/java/com/pulseloop/data/ArchivedSettings.kt b/app/src/main/java/com/pulseloop/data/ArchivedSettings.kt
index edb18664..e38ee794 100644
--- a/app/src/main/java/com/pulseloop/data/ArchivedSettings.kt
+++ b/app/src/main/java/com/pulseloop/data/ArchivedSettings.kt
@@ -44,6 +44,8 @@ object ArchivedSettings {
"rest_mode" to emptySet(),
// Whether the coach may use the lab results.
"lab_reports" to emptySet(),
+ // Never "mcp_server": the network server's switch and paired-tool tokens are device state
+ // and security material, so a restore starts off with nothing paired (docs/mcp-threat-model.md).
)
/**
diff --git a/app/src/main/java/com/pulseloop/mcp/McpCoachTools.kt b/app/src/main/java/com/pulseloop/mcp/McpCoachTools.kt
new file mode 100644
index 00000000..52b457ce
--- /dev/null
+++ b/app/src/main/java/com/pulseloop/mcp/McpCoachTools.kt
@@ -0,0 +1,80 @@
+package com.pulseloop.mcp
+
+import com.pulseloop.coach.tools.CoachFeatureFlags
+import com.pulseloop.coach.tools.ToolExecutionContext
+import com.pulseloop.coach.tools.ToolRegistry
+import kotlinx.serialization.json.JsonArray
+import kotlinx.serialization.json.JsonObject
+import kotlinx.serialization.json.JsonPrimitive
+
+/**
+ * The tools offered on the network: the coach's own read tools, listed from the same
+ * `CoachToolDef` schemas (nothing has a second definition), plus [SUMMARY].
+ *
+ * **An explicit allowlist, not "everything the read-only registry holds".** `ToolRegistry`'s
+ * always-on set already contains writes (`log_meal`, `set_goal`, `save_food_preference`,
+ * `log_drink`, `set_drink_plan`) and a network call that writes a cache (`search_food_database`),
+ * so turning `writeToolsEnabled` off is not enough. Each name below was read in its
+ * implementation and only reads Room (or, for the analysis tools, only computes over the numbers
+ * the caller passes). `McpAllowlistTest` fails if a write tool's name ever lands here.
+ *
+ * Never offered: anything that writes, sets goals, logs, deletes, queues a PendingAction, starts
+ * a live ring measurement or searches the web; the coach's API keys, raw ring packets,
+ * diagnostics, lab-report PDFs and the EPDS answers have no tool at all.
+ */
+object McpCoachTools {
+ const val SUMMARY = "summary"
+
+ val ALLOWLIST: Set = setOf(
+ // Ring data (RetrievalTools): each reads Room through the DAOs, nothing else.
+ "get_profile_context", "get_daily_summary", "get_range_summary", "get_metric_series",
+ "get_activity_sessions", "summarize_activity_session", "get_sync_status",
+ "get_data_availability", "get_sleep_summary", "get_sleep_trends",
+ "get_goal_progress", "get_recent_anomalies",
+ // Pure arithmetic over the values the caller passes (AnalysisTools): no data access at all.
+ "analyze_trend", "compare_periods", "compute_correlation", "detect_outliers", "summarize_distribution",
+ // Logged data, read only: the food log, the goal plan, the next-meal idea, agreed
+ // preferences, and drinks (which refuses while Drinks is off).
+ "get_nutrition_log", "get_goal", "suggest_next_meal", "get_food_preferences", "get_drinks",
+ )
+
+ /** The flags every network call runs with: no writes, no live measurements, no web. */
+ val FLAGS = CoachFeatureFlags(writeToolsEnabled = false, liveMeasurementsEnabled = false, webSearchEnabled = false)
+
+ private val SUMMARY_TOOL = McpTool(
+ name = SUMMARY,
+ description = "A compact picture in one call: today's activity against the goals, last night's sleep, " +
+ "the latest heart rate and SpO2, the last 7 days, the ring's sync state, and data-quality notes.",
+ inputSchema = JsonObject(mapOf(
+ "type" to JsonPrimitive("object"),
+ "properties" to JsonObject(emptyMap()),
+ "required" to JsonArray(emptyList()),
+ "additionalProperties" to JsonPrimitive(false),
+ )),
+ )
+
+ /**
+ * The table, built from [registry] (always constructed with [FLAGS] in the app) and the
+ * context the tools run with. [context] must carry `coordinator = null` and the [FLAGS].
+ */
+ fun table(
+ context: ToolExecutionContext,
+ registry: ToolRegistry = ToolRegistry(FLAGS),
+ summary: () -> String,
+ ): McpToolTable {
+ val defs = ALLOWLIST.mapNotNull { registry.tool(it) }.sortedBy { it.name }
+ val listed = defs.map { McpTool(it.name, it.description, it.parameters) } + SUMMARY_TOOL
+ return object : McpToolTable {
+ override val tools: List = listed
+
+ override fun call(name: String, argumentsJson: String): McpToolOutput? {
+ if (name == SUMMARY) return McpToolOutput(summary())
+ if (name !in ALLOWLIST) return null
+ val def = registry.tool(name) ?: return null
+ // A fresh context per call: nothing a tool queues (it shouldn't) survives the call.
+ val result = def.run(argumentsJson, context.copy(pendingActions = mutableListOf()))
+ return McpToolOutput(result.jsonString, result.isError)
+ }
+ }
+ }
+}
diff --git a/app/src/main/java/com/pulseloop/mcp/McpConfig.kt b/app/src/main/java/com/pulseloop/mcp/McpConfig.kt
new file mode 100644
index 00000000..e675c04b
--- /dev/null
+++ b/app/src/main/java/com/pulseloop/mcp/McpConfig.kt
@@ -0,0 +1,32 @@
+package com.pulseloop.mcp
+
+/**
+ * The text a person pastes into their AI tool after pairing. Plain Kotlin, JVM-tested.
+ *
+ * Claude Desktop and Cursor start MCP servers over stdio, so the ready-made entry runs
+ * [mcp-remote](https://www.npmjs.com/package/mcp-remote) as a bridge. The bearer header goes
+ * through an environment variable, as mcp-remote's README advises, because a space inside an
+ * `args` entry is mangled by some clients on Windows. `--allow-http` is needed because the
+ * phone serves plain HTTP on the local network.
+ */
+object McpConfig {
+ const val SERVER_NAME = "pulseloop"
+
+ fun stdioBridge(url: String, token: String): String = """
+ {
+ "mcpServers": {
+ "$SERVER_NAME": {
+ "command": "npx",
+ "args": ["-y", "mcp-remote", "$url", "--allow-http", "--header", "Authorization:${'$'}{PULSELOOP_AUTH}"],
+ "env": { "PULSELOOP_AUTH": "Bearer $token" }
+ }
+ }
+ }
+ """.trimIndent()
+
+ /** For clients that speak streamable HTTP themselves. */
+ fun direct(url: String, token: String): String = """
+ URL: $url
+ Header: Authorization: Bearer $token
+ """.trimIndent()
+}
diff --git a/app/src/main/java/com/pulseloop/mcp/McpHttp.kt b/app/src/main/java/com/pulseloop/mcp/McpHttp.kt
new file mode 100644
index 00000000..8be751e0
--- /dev/null
+++ b/app/src/main/java/com/pulseloop/mcp/McpHttp.kt
@@ -0,0 +1,109 @@
+package com.pulseloop.mcp
+
+import java.io.ByteArrayOutputStream
+import java.io.InputStream
+import java.io.OutputStream
+import java.util.Locale
+
+/**
+ * The little HTTP/1.1 the MCP server needs: one request per connection, a bounded head, a bounded
+ * `Content-Length` body, no chunked bodies, then `Connection: close`. Plain Kotlin, no Android
+ * imports, so it is JVM-tested (`McpHttpTest`). Ported from GMind's `McpServer.readHead/readBody`.
+ */
+object McpHttp {
+ const val MAX_HEADER = 8 * 1024
+ const val MAX_BODY = 256 * 1024
+
+ /** A request as read. Header names are lower-case. */
+ data class Request(
+ val method: String,
+ val path: String,
+ val headers: Map,
+ val body: String,
+ )
+
+ /** A reply. An empty body sends no Content-Type. */
+ data class Response(val status: Int, val body: String = "")
+
+ /** What reading produced: a request, or the status to refuse it with. */
+ sealed class Parsed {
+ data class Ok(val request: Request) : Parsed()
+ data class Refused(val status: Int) : Parsed()
+ }
+
+ fun read(input: InputStream): Parsed {
+ val head = readHead(input) ?: return Parsed.Refused(431)
+ if (head.isEmpty()) return Parsed.Refused(400)
+ val lines = head.split("\r\n")
+ val start = lines[0].split(" ")
+ if (start.size < 3 || !start[2].startsWith("HTTP/")) return Parsed.Refused(400)
+ val headers = LinkedHashMap()
+ for (i in 1 until lines.size) {
+ val colon = lines[i].indexOf(':')
+ if (colon > 0) {
+ headers[lines[i].substring(0, colon).trim().lowercase(Locale.ROOT)] = lines[i].substring(colon + 1).trim()
+ }
+ }
+ if (headers.containsKey("transfer-encoding")) return Parsed.Refused(400)
+ val length = headers["content-length"]?.let { it.toIntOrNull() ?: return Parsed.Refused(400) } ?: 0
+ if (length < 0) return Parsed.Refused(400)
+ if (length > MAX_BODY) return Parsed.Refused(413)
+ val body = readBody(input, length) ?: return Parsed.Refused(400)
+ val path = start[1].substringBefore('?')
+ return Parsed.Ok(Request(start[0], path, headers, String(body, Charsets.UTF_8)))
+ }
+
+ /** The head up to the blank line, or null when it runs past [MAX_HEADER]; "" when the client left. */
+ private fun readHead(input: InputStream): String? {
+ val head = ByteArrayOutputStream()
+ var last4 = 0
+ while (head.size() < MAX_HEADER) {
+ val b = input.read()
+ if (b < 0) return ""
+ head.write(b)
+ last4 = (last4 shl 8) or b
+ if (last4 == 0x0d0a0d0a) return String(head.toByteArray(), Charsets.ISO_8859_1).trim()
+ }
+ return null
+ }
+
+ private fun readBody(input: InputStream, length: Int): ByteArray? {
+ val body = ByteArray(length)
+ var read = 0
+ while (read < length) {
+ val n = input.read(body, read, length - read)
+ if (n < 0) return null
+ read += n
+ }
+ return body
+ }
+
+ fun reason(status: Int): String = when (status) {
+ 200 -> "OK"
+ 202 -> "Accepted"
+ 400 -> "Bad Request"
+ 401 -> "Unauthorized"
+ 403 -> "Forbidden"
+ 404 -> "Not Found"
+ 405 -> "Method Not Allowed"
+ 413 -> "Payload Too Large"
+ 431 -> "Request Header Fields Too Large"
+ 503 -> "Service Unavailable"
+ else -> "Error"
+ }
+
+ fun write(out: OutputStream, r: Response) {
+ val body = r.body.toByteArray(Charsets.UTF_8)
+ val head = StringBuilder()
+ .append("HTTP/1.1 ").append(r.status).append(' ').append(reason(r.status)).append("\r\n")
+ .append(if (body.isNotEmpty()) "Content-Type: application/json\r\n" else "")
+ .append(if (r.status == 401) "WWW-Authenticate: Bearer\r\n" else "")
+ .append(if (r.status == 405) "Allow: POST\r\n" else "")
+ .append("Content-Length: ").append(body.size).append("\r\n")
+ .append("Cache-Control: no-store\r\nConnection: close\r\n\r\n")
+ .toString()
+ out.write(head.toByteArray(Charsets.ISO_8859_1))
+ out.write(body)
+ out.flush()
+ }
+}
diff --git a/app/src/main/java/com/pulseloop/mcp/McpNet.kt b/app/src/main/java/com/pulseloop/mcp/McpNet.kt
new file mode 100644
index 00000000..46ced3e0
--- /dev/null
+++ b/app/src/main/java/com/pulseloop/mcp/McpNet.kt
@@ -0,0 +1,78 @@
+package com.pulseloop.mcp
+
+import java.net.Inet4Address
+import java.net.Inet6Address
+import java.net.InetAddress
+import java.net.InetSocketAddress
+import java.net.NetworkInterface
+import java.util.Collections
+import java.util.Locale
+
+/**
+ * Which addresses the MCP server answers and listens on. Plain Kotlin (java.net only), JVM-tested.
+ */
+object McpNet {
+ const val PORT = 8765
+
+ /**
+ * A peer we answer: loopback, your LAN (10/8, 172.16/12, 192.168/16), link-local (169.254/16,
+ * fe80::/10), Tailscale and other CGNAT (100.64/10), or IPv6 unique-local (fc00::/7).
+ * Everything else, including every public address, is refused before a byte is read.
+ */
+ fun allowedPeer(a: InetAddress?): Boolean {
+ if (a == null) return false
+ if (a.isLoopbackAddress || a.isSiteLocalAddress || a.isLinkLocalAddress) return true
+ val b = a.address
+ return when (a) {
+ is Inet4Address -> (b[0].toInt() and 0xff) == 100 && (b[1].toInt() and 0xc0) == 64
+ is Inet6Address -> {
+ // An IPv4-mapped IPv6 peer (::ffff:a.b.c.d) is judged as its IPv4 address.
+ if (isV4Mapped(b)) allowedPeer(InetAddress.getByAddress(b.copyOfRange(12, 16)))
+ else (b[0].toInt() and 0xfe) == 0xfc
+ }
+ else -> false
+ }
+ }
+
+ private fun isV4Mapped(b: ByteArray): Boolean =
+ b.size == 16 && (0 until 10).all { b[it].toInt() == 0 } && b[10].toInt() == -1 && b[11].toInt() == -1
+
+ /**
+ * This phone's addresses on your own networks: Wi-Fi, Ethernet, hotspot, and Tailscale's tunnel.
+ * Never mobile data (`rmnet`, `ccmni`), whatever address it carries.
+ */
+ fun localAddresses(): List {
+ val out = ArrayList()
+ try {
+ val interfaces = NetworkInterface.getNetworkInterfaces() ?: return out
+ for (n in Collections.list(interfaces)) {
+ val name = n.name.lowercase(Locale.ROOT)
+ val lan = name.startsWith("wlan") || name.startsWith("eth") || name.startsWith("ap") || name.startsWith("swlan")
+ val tunnel = name.startsWith("tun") // Tailscale
+ if (!n.isUp || n.isLoopback || !(lan || tunnel)) continue
+ for (a in Collections.list(n.inetAddresses)) {
+ if (a.isLoopbackAddress || !allowedPeer(a)) continue
+ // Link-local IPv6 needs a scope id that client configs can't carry: skip it.
+ if (a is Inet6Address && a.isLinkLocalAddress) continue
+ out.add(a)
+ }
+ }
+ } catch (_: Exception) { /* no network */ }
+ // IPv4 first: it is what people type and what mcp-remote handles best.
+ return out.sortedBy { if (it is Inet4Address) 0 else 1 }
+ }
+
+ /** `http://192.168.1.20:8765/mcp` (IPv6 in brackets, scope id dropped). */
+ fun url(a: InetSocketAddress): String = url(a.address, a.port)
+
+ fun url(a: InetAddress, port: Int = PORT): String {
+ var host = a.hostAddress ?: ""
+ val zone = host.indexOf('%')
+ if (zone > 0) host = host.substring(0, zone)
+ return "http://" + (if (host.contains(":")) "[$host]" else host) + ":" + port + "/mcp"
+ }
+
+ /** Tailscale hands out 100.64/10 on its tunnel; the settings page labels that address. */
+ fun isTailscale(a: InetAddress): Boolean = a is Inet4Address && allowedPeer(a) &&
+ (a.address[0].toInt() and 0xff) == 100
+}
diff --git a/app/src/main/java/com/pulseloop/mcp/McpPrefs.kt b/app/src/main/java/com/pulseloop/mcp/McpPrefs.kt
new file mode 100644
index 00000000..6bc472bb
--- /dev/null
+++ b/app/src/main/java/com/pulseloop/mcp/McpPrefs.kt
@@ -0,0 +1,57 @@
+package com.pulseloop.mcp
+
+import android.content.Context
+import android.content.SharedPreferences
+import kotlinx.serialization.builtins.ListSerializer
+import kotlinx.serialization.json.Json
+
+/**
+ * The MCP server's own preferences file, `mcp_server`: whether it may run, when it turns itself
+ * off, the auto-off length, and the paired tools (hashes only).
+ *
+ * **Not on `ArchivedSettings`' allowlist, on purpose.** The switch is device state and the
+ * pairings are security material: a backup restored on a new phone must start with the server
+ * off and nothing paired. `android:allowBackup` is off, so Android's own backup doesn't carry it
+ * either.
+ */
+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. */
+ var enabled: Boolean
+ get() = prefs.getBoolean(KEY_ENABLED, false)
+ set(v) { prefs.edit().putBoolean(KEY_ENABLED, v).apply() }
+
+ /** When the running server turns itself off (epoch ms); 0 when off. */
+ var offAt: Long
+ get() = prefs.getLong(KEY_OFF_AT, 0L)
+ set(v) { prefs.edit().putLong(KEY_OFF_AT, v).apply() }
+
+ var autoOffHours: Int
+ get() = prefs.getInt(KEY_HOURS, DEFAULT_HOURS).takeIf { it in HOURS_CHOICES } ?: DEFAULT_HOURS
+ set(v) { prefs.edit().putInt(KEY_HOURS, 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
+
+ override fun loadTools(): List = prefs.getString(KEY_TOOLS, null)
+ ?.let { runCatching { json.decodeFromString(ListSerializer(PairedTool.serializer()), it) }.getOrNull() }
+ .orEmpty()
+
+ override fun saveTools(tools: List) {
+ // commit(): a pairing must be on disk before its token is shown.
+ prefs.edit().putString(KEY_TOOLS, json.encodeToString(ListSerializer(PairedTool.serializer()), tools)).commit()
+ }
+
+ companion object {
+ const val FILE = "mcp_server"
+ private const val KEY_ENABLED = "enabled"
+ private const val KEY_OFF_AT = "offAt"
+ private const val KEY_HOURS = "autoOffHours"
+ private const val KEY_TOOLS = "pairedTools"
+ const val DEFAULT_HOURS = 8
+ val HOURS_CHOICES = listOf(1, 4, 8)
+ private val json = Json { ignoreUnknownKeys = true }
+ }
+}
diff --git a/app/src/main/java/com/pulseloop/mcp/McpProtocol.kt b/app/src/main/java/com/pulseloop/mcp/McpProtocol.kt
new file mode 100644
index 00000000..e8e1b620
--- /dev/null
+++ b/app/src/main/java/com/pulseloop/mcp/McpProtocol.kt
@@ -0,0 +1,153 @@
+package com.pulseloop.mcp
+
+import kotlinx.serialization.json.Json
+import kotlinx.serialization.json.JsonArray
+import kotlinx.serialization.json.JsonElement
+import kotlinx.serialization.json.JsonNull
+import kotlinx.serialization.json.JsonObject
+import kotlinx.serialization.json.JsonPrimitive
+import kotlinx.serialization.json.buildJsonObject
+import kotlinx.serialization.json.contentOrNull
+import kotlinx.serialization.json.put
+import java.util.concurrent.Semaphore
+import java.util.concurrent.TimeUnit
+
+/** One tool as MCP lists it. */
+data class McpTool(val name: String, val description: String, val inputSchema: JsonObject)
+
+/** What a tool call returned: text for the client, and whether it is an error. */
+data class McpToolOutput(val text: String, val isError: Boolean = false)
+
+/** The tools the server offers. Real: [McpCoachTools]; tests pass a fake. */
+interface McpToolTable {
+ val tools: List
+
+ /** Runs [name] with [argumentsJson] (a JSON object); null when there is no such tool here. */
+ fun call(name: String, argumentsJson: String): McpToolOutput?
+}
+
+/**
+ * MCP over streamable HTTP, one JSON reply per request: `POST /mcp` with one JSON-RPC 2.0 message.
+ * Refuses, in this order and before reading anything: a request with an `Origin` header (a web
+ * page), a missing or unknown bearer token, while the server is off. Then only `POST /mcp`.
+ * Methods: `initialize`, `ping`, `tools/list`, `tools/call`; notifications get 202.
+ *
+ * Plain Kotlin (no Android imports), JVM-tested (`McpHandlerTest`). Ported from GMind's
+ * `McpServer.respond`.
+ */
+class McpHandler(
+ private val table: McpToolTable,
+ private val tokens: McpTokens,
+ private val version: String,
+ private val isOn: () -> Boolean = { true },
+) {
+ /** One tool call at a time: the database and the coach's tools are shared with the app. */
+ private val calls = Semaphore(1)
+
+ fun respond(request: McpHttp.Request, now: Long = System.currentTimeMillis()): McpHttp.Response = try {
+ respondUnchecked(request, now)
+ } catch (e: Exception) {
+ json(error(JsonNull, -32603, "PulseLoop couldn't answer (${e.javaClass.simpleName})"))
+ }
+
+ private fun respondUnchecked(request: McpHttp.Request, now: Long): McpHttp.Response {
+ val h = request.headers
+ if (h.containsKey("origin")) return McpHttp.Response(403) // a web page: never
+ if (!isOn() || tokens.check(McpTokens.bearer(h["authorization"]), now) == null) return McpHttp.Response(401)
+ if (request.path != "/mcp") return McpHttp.Response(404)
+ if (request.method != "POST") return McpHttp.Response(405)
+
+ val message: JsonElement = try {
+ Json.parseToJsonElement(request.body)
+ } catch (_: Exception) {
+ return json(error(JsonNull, -32700, "Parse error"))
+ }
+ if (message !is JsonObject) return json(error(JsonNull, -32600, "One request at a time"))
+ val id = message["id"]?.takeIf { it !is JsonNull }
+ val method = (message["method"] as? JsonPrimitive)?.takeIf { it.isString }?.content
+ if (method == null) {
+ // A JSON-RPC response or result from the client: nothing to answer.
+ return if (id == null) McpHttp.Response(202) else json(error(id, -32600, "Invalid request"))
+ }
+ if (id == null) return McpHttp.Response(202) // a notification, e.g. notifications/initialized
+ val params = message["params"] as? JsonObject
+
+ return when (method) {
+ "initialize" -> json(result(id, initializeResult(params)))
+ "ping" -> json(result(id, JsonObject(emptyMap())))
+ "tools/list" -> json(result(id, buildJsonObject { put("tools", JsonArray(table.tools.map(::toolJson))) }))
+ "tools/call" -> {
+ val name = (params?.get("name") as? JsonPrimitive)?.takeIf { it.isString }?.content
+ ?: return json(error(id, -32602, "Missing tool name"))
+ val args = params?.get("arguments")
+ val argsJson = if (args is JsonObject) args.toString() else "{}"
+ json(result(id, callResult(call(name, argsJson))))
+ }
+ else -> json(error(id, -32601, "Method not found"))
+ }
+ }
+
+ private fun call(name: String, argsJson: String): McpToolOutput {
+ if (!calls.tryAcquire(CALL_WAIT_SECONDS, TimeUnit.SECONDS)) {
+ return McpToolOutput("PulseLoop is busy with another request. Try again.", isError = true)
+ }
+ return try {
+ table.call(name, argsJson)
+ ?: McpToolOutput("No such tool here. PulseLoop's tools on the network only read.", isError = true)
+ } catch (e: Exception) {
+ McpToolOutput("That tool failed (${e.javaClass.simpleName}).", isError = true)
+ } finally {
+ calls.release()
+ }
+ }
+
+ private fun initializeResult(params: JsonObject?): JsonObject {
+ val asked = (params?.get("protocolVersion") as? JsonPrimitive)?.contentOrNull
+ return buildJsonObject {
+ put("protocolVersion", if (asked != null && asked in SUPPORTED) asked else PROTOCOL)
+ put("capabilities", buildJsonObject { put("tools", buildJsonObject { put("listChanged", false) }) })
+ put("serverInfo", buildJsonObject { put("name", "PulseLoop"); put("version", version) })
+ put("instructions", INSTRUCTIONS)
+ }
+ }
+
+ companion object {
+ const val PROTOCOL = "2025-06-18"
+ val SUPPORTED = setOf("2025-06-18", "2025-03-26", "2024-11-05")
+ const val CALL_WAIT_SECONDS = 20L
+ /** Big enough for a year of daily rows; a reply past it is cut, and says so. */
+ const val MAX_TOOL_TEXT = 200_000
+
+ val INSTRUCTIONS = "PulseLoop holds this user's own health data: readings from their smart ring (steps, " +
+ "heart rate, SpO2, sleep, workouts) and what they logged in the app (meals, drinks, goals). " +
+ "Read-only: nothing here can change or delete anything. It is not a diagnostic tool: the numbers " +
+ "are estimates from a consumer wearable, not medical measurements. Don't diagnose or name " +
+ "conditions; for anything worrying, suggest the user talks to their doctor. Dates are YYYY-MM-DD " +
+ "in the user's time zone. Start with `summary` for today, last night and the week."
+
+ fun toolJson(t: McpTool): JsonObject = buildJsonObject {
+ put("name", t.name)
+ put("description", t.description)
+ put("inputSchema", t.inputSchema)
+ }
+
+ fun callResult(out: McpToolOutput): JsonObject {
+ val text = if (out.text.length > MAX_TOOL_TEXT) out.text.take(MAX_TOOL_TEXT) + "\n[cut: reply too long]" else out.text
+ return buildJsonObject {
+ put("content", JsonArray(listOf(buildJsonObject { put("type", "text"); put("text", text) })))
+ put("isError", out.isError)
+ }
+ }
+
+ private fun result(id: JsonElement, result: JsonObject) = buildJsonObject {
+ put("jsonrpc", "2.0"); put("id", id); put("result", result)
+ }
+
+ private fun error(id: JsonElement, code: Int, message: String) = buildJsonObject {
+ put("jsonrpc", "2.0"); put("id", id)
+ put("error", buildJsonObject { put("code", code); put("message", message) })
+ }
+
+ private fun json(reply: JsonObject) = McpHttp.Response(200, reply.toString())
+ }
+}
diff --git a/app/src/main/java/com/pulseloop/mcp/McpServer.kt b/app/src/main/java/com/pulseloop/mcp/McpServer.kt
new file mode 100644
index 00000000..f7531fa7
--- /dev/null
+++ b/app/src/main/java/com/pulseloop/mcp/McpServer.kt
@@ -0,0 +1,98 @@
+package com.pulseloop.mcp
+
+import java.io.BufferedInputStream
+import java.io.IOException
+import java.net.InetAddress
+import java.net.InetSocketAddress
+import java.net.ServerSocket
+import java.net.Socket
+import java.util.concurrent.ExecutorService
+import java.util.concurrent.Executors
+import java.util.concurrent.RejectedExecutionException
+import java.util.concurrent.Semaphore
+
+/**
+ * A small, bounded HTTP listener for [McpHandler]: at most [MAX_CONNECTIONS] at once, a
+ * [TIMEOUT_MS] socket timeout, one request per connection, and only on private addresses — each
+ * connection's peer is checked again before anything is read. Plain Kotlin (java.net only),
+ * JVM-tested over loopback (`McpServerSocketTest`). Ported from GMind's `McpServer`.
+ */
+class McpServer(private val handler: McpHandler) {
+ private val sockets = ArrayList()
+ private val pool: ExecutorService = Executors.newCachedThreadPool { r ->
+ Thread(r, "pulseloop-mcp").apply { isDaemon = true }
+ }
+ private val slots = Semaphore(MAX_CONNECTIONS)
+ @Volatile private var running = false
+
+ /** Listens on these addresses (each must be private); returns the ones it got. */
+ @Synchronized
+ fun start(addresses: List, port: Int): List {
+ running = true
+ val bound = ArrayList()
+ for (a in addresses) {
+ if (!McpNet.allowedPeer(a)) continue // never on a public address
+ val s = ServerSocket()
+ try {
+ s.reuseAddress = true
+ s.bind(InetSocketAddress(a, port), 8)
+ } catch (e: IOException) {
+ try { s.close() } catch (_: IOException) {}
+ continue
+ }
+ sockets.add(s)
+ bound.add(s.localSocketAddress as InetSocketAddress)
+ Thread({ accept(s) }, "pulseloop-mcp-accept").apply { isDaemon = true }.start()
+ }
+ return bound
+ }
+
+ @Synchronized
+ fun stop() {
+ running = false
+ for (s in sockets) try { s.close() } catch (_: IOException) {}
+ sockets.clear()
+ pool.shutdownNow()
+ }
+
+ fun isRunning(): Boolean = running && sockets.isNotEmpty()
+
+ private fun accept(server: ServerSocket) {
+ while (running && !server.isClosed) {
+ val socket = try { server.accept() } catch (_: IOException) { return }
+ if (!McpNet.allowedPeer(socket.inetAddress) || !slots.tryAcquire()) {
+ close(socket)
+ continue
+ }
+ try {
+ pool.execute {
+ try { serve(socket) } finally { slots.release(); close(socket) }
+ }
+ } catch (_: RejectedExecutionException) { // stopping
+ slots.release()
+ close(socket)
+ return
+ }
+ }
+ }
+
+ /** One request on one connection, then close. */
+ fun serve(socket: Socket) {
+ try {
+ socket.soTimeout = TIMEOUT_MS
+ val input = BufferedInputStream(socket.getInputStream())
+ val reply = when (val parsed = McpHttp.read(input)) {
+ is McpHttp.Parsed.Refused -> McpHttp.Response(parsed.status)
+ is McpHttp.Parsed.Ok -> handler.respond(parsed.request)
+ }
+ McpHttp.write(socket.getOutputStream(), reply)
+ } catch (_: IOException) { /* the client left or timed out */ }
+ }
+
+ private fun close(s: Socket) { try { s.close() } catch (_: IOException) {} }
+
+ companion object {
+ const val MAX_CONNECTIONS = 4
+ const val TIMEOUT_MS = 15_000
+ }
+}
diff --git a/app/src/main/java/com/pulseloop/mcp/McpService.kt b/app/src/main/java/com/pulseloop/mcp/McpService.kt
new file mode 100644
index 00000000..ed4f52e9
--- /dev/null
+++ b/app/src/main/java/com/pulseloop/mcp/McpService.kt
@@ -0,0 +1,167 @@
+package com.pulseloop.mcp
+
+import android.app.Notification
+import android.app.NotificationChannel
+import android.app.NotificationManager
+import android.app.PendingIntent
+import android.app.Service
+import android.content.Context
+import android.content.Intent
+import android.content.pm.ServiceInfo
+import android.os.Build
+import android.os.Handler
+import android.os.IBinder
+import android.os.Looper
+import androidx.core.app.NotificationCompat
+import androidx.core.content.ContextCompat
+import com.pulseloop.BuildConfig
+import com.pulseloop.coach.tools.ToolExecutionContext
+import com.pulseloop.data.PulseLoopDatabase
+import com.pulseloop.ui.i18n.tr
+import kotlinx.coroutines.flow.MutableStateFlow
+import kotlinx.coroutines.flow.StateFlow
+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.
+ *
+ * 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.
+ */
+class McpService : Service() {
+
+ data class Status(
+ val running: Boolean = false,
+ /** Where tools connect, e.g. `http://192.168.1.20:8765/mcp`; empty while off. */
+ val urls: List = emptyList(),
+ /** The last start found no Wi-Fi or Tailscale address to listen on. */
+ val unreachable: Boolean = false,
+ val offAt: Long = 0L,
+ )
+
+ private var server: McpServer? = null
+ /** Set in [onDestroy]: a start thread that loses the race must not leave a server running. */
+ private var destroyed = false
+ private val main = Handler(Looper.getMainLooper())
+ private val autoOff = Runnable { stopSelf() }
+
+ override fun onBind(intent: Intent?): IBinder? = null
+
+ override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
+ val prefs = McpPrefs(this)
+ if (intent?.action == ACTION_STOP) {
+ prefs.enabled = false
+ stopSelf()
+ return START_NOT_STICKY
+ }
+ // A foreground service must be in the foreground within seconds of starting, whatever follows.
+ goForeground()
+ val now = System.currentTimeMillis()
+ if (!prefs.isOn(now)) {
+ stopSelf()
+ return START_NOT_STICKY
+ }
+ main.removeCallbacks(autoOff)
+ 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
+ }
+
+ @Synchronized
+ private fun startServer(prefs: McpPrefs) {
+ if (server != null || destroyed) return
+ try {
+ val db = PulseLoopDatabase.getInstance(applicationContext)
+ val context = ToolExecutionContext(db = db, flags = McpCoachTools.FLAGS, coordinator = null)
+ val table = McpCoachTools.table(context) { runBlocking { McpSummary.build(db) } }
+ 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()) {
+ s.stop()
+ statusFlow.value = Status(unreachable = true)
+ main.post { stopSelf() }
+ return
+ }
+ server = s
+ statusFlow.value = Status(running = true, urls = bound.map { McpNet.url(it) }, offAt = prefs.offAt)
+ } catch (e: Exception) {
+ android.util.Log.w(TAG, "MCP server failed to start: ${e.javaClass.simpleName}")
+ main.post { stopSelf() }
+ }
+ }
+
+ /** Android 15+: the daily `dataSync` allowance ran out. Stop now, or the system crashes the app. */
+ override fun onTimeout(startId: Int, fgsType: Int) {
+ stopSelf()
+ }
+
+ override fun onDestroy() {
+ main.removeCallbacks(autoOff)
+ synchronized(this) {
+ destroyed = true
+ server?.stop()
+ server = null
+ }
+ McpPrefs(this).apply { enabled = false; offAt = 0L }
+ statusFlow.value = statusFlow.value.copy(running = false, urls = emptyList(), offAt = 0L)
+ super.onDestroy()
+ }
+
+ private fun goForeground() {
+ val nm = getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
+ nm.createNotificationChannel(
+ NotificationChannel(CHANNEL_ID, tr("AI tools on your network"), NotificationManager.IMPORTANCE_LOW)
+ .apply { description = tr("Shown while paired AI tools on your network can read your health data.") },
+ )
+ val stop = PendingIntent.getService(
+ 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 n: Notification = NotificationCompat.Builder(this, CHANNEL_ID)
+ .setSmallIcon(android.R.drawable.ic_dialog_info)
+ .setContentTitle(tr("AI tools on your network"))
+ .setContentText(text)
+ .setStyle(NotificationCompat.BigTextStyle().bigText(text))
+ .setOngoing(true)
+ .setPriority(NotificationCompat.PRIORITY_LOW)
+ .setContentIntent(stop)
+ .addAction(0, tr("Stop"), stop)
+ .build()
+ if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
+ startForeground(NOTIFICATION_ID, n, ServiceInfo.FOREGROUND_SERVICE_TYPE_DATA_SYNC)
+ } else {
+ startForeground(NOTIFICATION_ID, n)
+ }
+ }
+
+ companion object {
+ private const val TAG = "McpService"
+ const val ACTION_STOP = "com.pulseloop.MCP_STOP"
+ const val CHANNEL_ID = "mcp_server"
+ const val NOTIFICATION_ID = 2201
+
+ private val statusFlow = MutableStateFlow(Status())
+ val status: StateFlow get() = statusFlow
+
+ /** Turns it on for [McpPrefs.autoOffHours]. Call from the settings screen only (foreground). */
+ 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)
+ ContextCompat.startForegroundService(context, Intent(context, McpService::class.java))
+ }
+
+ fun stop(context: Context) {
+ McpPrefs(context).enabled = false
+ context.stopService(Intent(context, McpService::class.java))
+ }
+ }
+}
diff --git a/app/src/main/java/com/pulseloop/mcp/McpSummary.kt b/app/src/main/java/com/pulseloop/mcp/McpSummary.kt
new file mode 100644
index 00000000..7a501f09
--- /dev/null
+++ b/app/src/main/java/com/pulseloop/mcp/McpSummary.kt
@@ -0,0 +1,102 @@
+package com.pulseloop.mcp
+
+import com.pulseloop.coach.context.CoachContextBuilder
+import com.pulseloop.data.PulseLoopDatabase
+import com.pulseloop.data.entity.MeasurementEntity
+import com.pulseloop.health.accuracy.AccuracyCorrections
+import com.pulseloop.ring.MeasurementKind
+import java.time.Instant
+import java.time.LocalDate
+import java.time.ZoneId
+import java.time.format.DateTimeFormatter
+
+/**
+ * The `summary` tool: today, last night and the week as one compact text. Reuses
+ * [CoachContextBuilder.build] for the device, goals, 7-day steps and the data-quality notes the
+ * coach gets, and reads the rest the way the screens do — real rows win over demo rows
+ * (`DemoDataPolicy`), accuracy corrections applied (read-time only).
+ *
+ * Deliberately left out of the packet it reuses: labs, postpartum, drinks and the goal plan.
+ * Each has its own read tool or none, and the postpartum block is the closest thing to the EPDS
+ * the coach sees, so the network summary never carries it.
+ */
+object McpSummary {
+ private val TIME = DateTimeFormatter.ofPattern("HH:mm")
+
+ suspend fun build(db: PulseLoopDatabase, now: Long = System.currentTimeMillis(), zone: ZoneId = ZoneId.systemDefault()): String {
+ val packet = CoachContextBuilder.build(db)
+ val corrections = AccuracyCorrections.load(db)
+ val today = LocalDate.now(zone)
+ val todayStart = today.atStartOfDay(zone).toInstant().toEpochMilli()
+ val out = StringBuilder()
+
+ out.append("PulseLoop summary for ").append(today).append(" (").append(zone.id).append(")\n")
+
+ // Today
+ val goals = packet.goals
+ val act = db.activityDailyDao().byDay(todayStart)?.let(corrections::day)
+ out.append("\nToday\n")
+ if (act == null) out.append("- No activity synced yet today.\n")
+ else {
+ out.append("- Steps: ").append(act.steps).append(" of ").append(goals.stepsDaily).append(" goal\n")
+ out.append("- Distance: ").append("%.1f".format(act.distanceMeters / 1000.0)).append(" km\n")
+ out.append("- Active minutes: ").append(act.activeMinutes).append(" of ").append(goals.activeMinutesDaily).append(" goal\n")
+ if (act.calories > 0) out.append("- Calories (ring): ").append(Math.round(act.calories)).append(" kcal\n")
+ }
+ latest(db, MeasurementKind.HEART_RATE.name, now)?.let { m ->
+ out.append("- Latest heart rate: ").append(Math.round(corrections.heartRate(m.value))).append(" bpm at ").append(time(m.timestamp, zone)).append('\n')
+ }
+ latest(db, MeasurementKind.SPO2.name, now)?.let { m ->
+ out.append("- Latest SpO2: ").append(Math.round(corrections.spo2(m.value))).append("% at ").append(time(m.timestamp, zone)).append('\n')
+ }
+ packet.trends.hrResting?.let { out.append("- Resting heart rate (last 24 h, estimate): ").append(Math.round(it)).append(" bpm\n") }
+
+ // Last night and the week's nights
+ val sleepReal = db.sleepSessionDao().hasReal()
+ val nights = (if (sleepReal) db.sleepSessionDao().recentReal(7) else db.sleepSessionDao().recent(7))
+ .filter { it.date >= todayStart - 7 * DAY_MS }
+ .map(corrections::sleep)
+ out.append("\nLast night\n")
+ val last = nights.maxByOrNull { it.date }
+ if (last == null || last.date < todayStart - DAY_MS) out.append("- No sleep recorded for last night.\n")
+ else {
+ out.append("- Asleep: ").append(hm(last.totalMinutes)).append(" (goal ").append(goals.sleepHours).append(" h)\n")
+ out.append("- In bed: ").append(time(last.startAt, zone)).append("–").append(time(last.endAt, zone)).append('\n')
+ }
+
+ // The week
+ out.append("\nLast 7 days\n")
+ val steps = packet.trends.steps7d.filter { it > 0 }
+ if (steps.isEmpty()) out.append("- No step data.\n")
+ else out.append("- Steps: average ").append(Math.round(steps.average())).append(" a day over ").append(steps.size).append(" day(s)\n")
+ val asleep = nights.map { it.totalMinutes }.filter { it > 0 }
+ if (asleep.isEmpty()) out.append("- No nights recorded.\n")
+ else out.append("- Sleep: average ").append(hm(asleep.average().toInt())).append(" over ").append(asleep.size).append(" night(s)\n")
+
+ // Ring
+ val d = packet.device
+ out.append("\nRing\n")
+ out.append("- ").append(d.name ?: "Ring").append(": ").append(d.state.lowercase())
+ d.batteryPercent?.let { out.append(", battery ").append(it).append('%') }
+ out.append(", last sync ").append(d.lastSyncAt ?: "never").append('\n')
+
+ if (packet.dataQualityWarnings.isNotEmpty()) {
+ out.append("\nNotes\n")
+ packet.dataQualityWarnings.forEach { out.append("- ").append(it).append('\n') }
+ }
+ return out.toString().trimEnd()
+ }
+
+ /** The newest reading of [kind] in the last 24 h, real rows first. */
+ private suspend fun latest(db: PulseLoopDatabase, kind: String, now: Long): MeasurementEntity? {
+ val dao = db.measurementDao()
+ val rows = if (dao.hasReal(kind)) dao.rangeReal(kind, now - DAY_MS, now) else dao.range(kind, now - DAY_MS, now)
+ return rows.lastOrNull()
+ }
+
+ private fun time(ts: Long, zone: ZoneId): String = Instant.ofEpochMilli(ts).atZone(zone).format(TIME)
+
+ private fun hm(minutes: Int): String = "${minutes / 60} h ${"%02d".format(minutes % 60)} min"
+
+ private const val DAY_MS = 24 * 3600_000L
+}
diff --git a/app/src/main/java/com/pulseloop/mcp/McpTokens.kt b/app/src/main/java/com/pulseloop/mcp/McpTokens.kt
new file mode 100644
index 00000000..c2db5667
--- /dev/null
+++ b/app/src/main/java/com/pulseloop/mcp/McpTokens.kt
@@ -0,0 +1,89 @@
+package com.pulseloop.mcp
+
+import kotlinx.serialization.Serializable
+import java.security.MessageDigest
+import java.security.SecureRandom
+import java.util.Base64
+import java.util.UUID
+
+/** A paired AI tool. Only the SHA-256 of its token is kept; the token itself is shown once. */
+@Serializable
+data class PairedTool(
+ val id: String,
+ val label: String,
+ val hash: String,
+ val createdAt: Long,
+ val lastUsedAt: Long? = null,
+)
+
+/** Where pairings are kept: `McpPrefs` on the phone, a list in tests. */
+interface McpTokenStorage {
+ fun loadTools(): List
+ fun saveTools(tools: List)
+}
+
+/**
+ * Pairing for AI tools on your network: each tool gets its own random token (32 bytes,
+ * base64url), shown once and stored only as its SHA-256, compared in constant time, revocable one
+ * by one. Plain Kotlin, JVM-tested (`McpTokensTest`). Ported from GMind's `McpTokens`.
+ *
+ * Pairings are security material and device state: they never ride in the backup archive, so a
+ * restore on a new phone starts with nothing paired.
+ */
+class McpTokens(private val storage: McpTokenStorage) {
+ /** One lock for every instance in the process: the service and the settings screen each hold
+ * one over the same file, and a read-modify-write from each must not drop the other's. */
+ private val lock = LOCK
+
+ /** Pairs a tool; returns it and its token, which is never shown again. */
+ fun create(label: String?, now: Long): Pair = synchronized(lock) {
+ val secret = ByteArray(32)
+ RANDOM.nextBytes(secret)
+ val token = PREFIX + Base64.getUrlEncoder().withoutPadding().encodeToString(secret)
+ val name = label?.trim()?.takeIf { it.isNotEmpty() }?.take(MAX_LABEL) ?: DEFAULT_LABEL
+ val tool = PairedTool(id = UUID.randomUUID().toString(), label = name, hash = hash(token), createdAt = now)
+ storage.saveTools(storage.loadTools() + tool)
+ tool to token
+ }
+
+ /** The paired tool a token belongs to, or null (unknown, revoked, or malformed). */
+ fun check(token: String?, now: Long): PairedTool? = synchronized(lock) {
+ if (token == null || !token.startsWith(PREFIX) || token.length > 200) return null
+ val h = hash(token).toByteArray(Charsets.US_ASCII)
+ val tools = storage.loadTools()
+ // Compare against every pairing, in constant time, so timing says nothing about which matched.
+ var found: PairedTool? = null
+ for (t in tools) {
+ if (MessageDigest.isEqual(h, t.hash.toByteArray(Charsets.US_ASCII)) && found == null) found = t
+ }
+ val match = found ?: return null
+ // "Last used" to the minute: no need to write preferences on every request.
+ if (match.lastUsedAt == null || now - match.lastUsedAt >= 60_000L) {
+ storage.saveTools(tools.map { if (it.id == match.id) it.copy(lastUsedAt = now) else it })
+ }
+ match
+ }
+
+ fun revoke(id: String) = synchronized(lock) {
+ storage.saveTools(storage.loadTools().filterNot { it.id == id })
+ }
+
+ /** Tools still paired, newest first. */
+ fun list(): List = synchronized(lock) { storage.loadTools().sortedByDescending { it.createdAt } }
+
+ companion object {
+ const val PREFIX = "pulseloop_"
+ const val DEFAULT_LABEL = "AI tool"
+ const val MAX_LABEL = 60
+ private val RANDOM = SecureRandom()
+ private val LOCK = Any()
+
+ fun hash(token: String): String =
+ MessageDigest.getInstance("SHA-256").digest(token.toByteArray(Charsets.UTF_8))
+ .joinToString("") { "%02x".format(it.toInt() and 0xff) }
+
+ /** The token from an `Authorization: Bearer …` header, or null. */
+ fun bearer(header: String?): String? =
+ if (header != null && header.regionMatches(0, "Bearer ", 0, 7, ignoreCase = true)) header.substring(7).trim() else null
+ }
+}
diff --git a/app/src/main/java/com/pulseloop/ring/CRPSyncEngine.kt b/app/src/main/java/com/pulseloop/ring/CRPSyncEngine.kt
index eaa01b3b..6cfed99a 100644
--- a/app/src/main/java/com/pulseloop/ring/CRPSyncEngine.kt
+++ b/app/src/main/java/com/pulseloop/ring/CRPSyncEngine.kt
@@ -18,7 +18,12 @@ private const val SLEEP_BACKFILL_DAYS = 6
* into [RingDecodedEvent.HistoryMeasurement] samples (confirmed against zaggash's R11 rc2 capture);
* their multi-frame replies reassemble via the next-frame follow-up in [handle].
*/
-class CRPSyncEngine(private val writer: RingCommandWriter?) : RingSyncEngine {
+class CRPSyncEngine(
+ private val writer: RingCommandWriter?,
+ /** The phone's clock, for the 20:00 sleep-day guard. Injectable so tests don't depend on when
+ * they run: CI at 19:55–20:05 used to see the sleep queries skipped and fail. */
+ private val now: () -> java.time.Instant = { java.time.Instant.now() },
+) : RingSyncEngine {
private var profile: UserProfileValues? = null
@@ -130,7 +135,7 @@ class CRPSyncEngine(private val writer: RingCommandWriter?) : RingSyncEngine {
// decoder by the phone's when the reply lands. Straddling 20:00, the two disagree by a day
// and the night is filed a day early again — #107's bug, after #109's one-time repair has
// run. So a pass this close to 20:00 leaves sleep to the next one (~30 min later).
- if (CRPDecoder.nearSleepDayRollover(java.time.Instant.now())) return
+ if (CRPDecoder.nearSleepDayRollover(now())) return
send(CRPProtocol.queryHistorySleep())
sendSleepBackfill()
}
diff --git a/app/src/main/java/com/pulseloop/service/LabReports.kt b/app/src/main/java/com/pulseloop/service/LabReports.kt
index e200f558..e6f80412 100644
--- a/app/src/main/java/com/pulseloop/service/LabReports.kt
+++ b/app/src/main/java/com/pulseloop/service/LabReports.kt
@@ -151,6 +151,12 @@ object LabReports {
tr("Reading a report needs the coach enabled with a configured provider (Settings → AI Coach)."),
)
}
+ // The model on this phone can't read a report (its client refuses any schema but the coach's).
+ if (providerStore.providerMode == com.pulseloop.coach.config.CoachProviderMode.ON_DEVICE) {
+ return@withContext ReadResult.Failure(
+ tr("The coach on this phone can't read lab reports. Pick a cloud or self-hosted coach in Settings → AI Coach."),
+ )
+ }
val (pages, pageCount) = try {
renderPages(file)
} catch (e: Exception) {
diff --git a/app/src/main/java/com/pulseloop/ui/PulseLoopApp.kt b/app/src/main/java/com/pulseloop/ui/PulseLoopApp.kt
index a2b89fe3..f9042926 100644
--- a/app/src/main/java/com/pulseloop/ui/PulseLoopApp.kt
+++ b/app/src/main/java/com/pulseloop/ui/PulseLoopApp.kt
@@ -116,11 +116,14 @@ fun PulseLoopApp() {
val activeModel = com.pulseloop.coach.config.CoachClientResolver.activeModel(
providerSettings, apiKeyStore.model,
)
+ // The on-device model gets no tools at all (its client ignores them), and
+ // says so here too: no web search, no writes, no live ring measurements.
+ val onDevice = providerSettings.providerMode == com.pulseloop.coach.config.CoachProviderMode.ON_DEVICE
CoachFeatureFlags(
coachEnabled = apiKeyStore.coachEnabled && resolution.key != null,
- webSearchEnabled = apiKeyStore.webSearchEnabled,
+ webSearchEnabled = apiKeyStore.webSearchEnabled && !onDevice,
writeToolsEnabled = false, // safe default
- liveMeasurementsEnabled = true,
+ liveMeasurementsEnabled = !onDevice,
model = activeModel,
settings = com.pulseloop.coach.config.CoachClientResolver.coachSettings(providerSettings, activeModel),
providerMode = providerSettings.providerMode,
@@ -476,6 +479,9 @@ fun PulseLoopApp() {
// (owner choice, issue #22).
var showCoachUsage by remember { mutableStateOf(false) }
CoachHeader(
+ // Which brain answers, when it is the one on this phone.
+ subtitle = if (providerStore.providerMode == com.pulseloop.coach.config.CoachProviderMode.ON_DEVICE)
+ trf("On this phone · {0}", com.pulseloop.coach.ondevice.ModelDownload.DISPLAY_NAME) else null,
onBack = { navController.popBackStack() },
onNewChat = { coachVM.newConversation() },
onOpenUsage = { showCoachUsage = true },
@@ -794,6 +800,9 @@ fun PulseLoopApp() {
paddedComposable("settings/accuracy-check") {
AccuracyCheckSettingsScreen(onBack = { navController.popBackStack() })
}
+ paddedComposable("settings/mcp") {
+ McpSettingsScreen(onBack = { navController.popBackStack() })
+ }
paddedComposable("settings/nutrition") {
NutritionSettingsScreen(
onBack = { navController.popBackStack() },
diff --git a/app/src/main/java/com/pulseloop/ui/screens/CoachScreen.kt b/app/src/main/java/com/pulseloop/ui/screens/CoachScreen.kt
index be9d72d5..82f514de 100644
--- a/app/src/main/java/com/pulseloop/ui/screens/CoachScreen.kt
+++ b/app/src/main/java/com/pulseloop/ui/screens/CoachScreen.kt
@@ -199,7 +199,13 @@ fun CoachScreen(
* chat then scrolls under it.
*/
@Composable
-fun CoachHeader(onNewChat: () -> Unit, onOpenUsage: (() -> Unit)? = null, onBack: (() -> Unit)? = null) {
+fun CoachHeader(
+ onNewChat: () -> Unit,
+ onOpenUsage: (() -> Unit)? = null,
+ onBack: (() -> Unit)? = null,
+ /** Replaces "Using your latest ring sync", e.g. "On this phone · Gemma 3 1B". */
+ subtitle: String? = null,
+) {
Row(
Modifier
.fillMaxWidth()
@@ -230,7 +236,7 @@ fun CoachHeader(onNewChat: () -> Unit, onOpenUsage: (() -> Unit)? = null, onBack
}
Column(Modifier.weight(1f)) {
Text(tr("PulseLoop Coach"), fontSize = 16.sp, fontWeight = FontWeight.SemiBold, color = PulseColors.textPrimary)
- Text(tr("Using your latest ring sync"), fontSize = 12.sp, color = PulseColors.textMuted)
+ Text(subtitle ?: tr("Using your latest ring sync"), fontSize = 12.sp, color = PulseColors.textMuted)
}
if (onOpenUsage != null) {
RoundIconTarget(visualSize = 36.dp, onClick = onOpenUsage) {
@@ -354,7 +360,12 @@ private fun Composer(
onSend: (String, List) -> Unit,
) {
val ctx = LocalContext.current
- val imageInputEnabled = remember { com.pulseloop.coach.config.CoachProviderSettingsStore(ctx).imageInputEnabled }
+ // The model on this phone reads text only, so it offers no attach button.
+ val imageInputEnabled = remember {
+ com.pulseloop.coach.config.CoachProviderSettingsStore(ctx).let {
+ it.imageInputEnabled && it.providerMode != com.pulseloop.coach.config.CoachProviderMode.ON_DEVICE
+ }
+ }
// Staged (not yet sent) attachments — persisted to the store on pick, sent with the
// next message. Image-only sends are allowed (iOS #31).
var staged by remember { mutableStateOf(listOf()) }
diff --git a/app/src/main/java/com/pulseloop/ui/screens/CoachUsageSheet.kt b/app/src/main/java/com/pulseloop/ui/screens/CoachUsageSheet.kt
index 194e250c..fa3aea50 100644
--- a/app/src/main/java/com/pulseloop/ui/screens/CoachUsageSheet.kt
+++ b/app/src/main/java/com/pulseloop/ui/screens/CoachUsageSheet.kt
@@ -62,9 +62,9 @@ fun CoachUsageSheet(
messages.forEach { it.modelUsed?.takeIf { m -> m.isNotEmpty() }?.let(seen::add) }
if (seen.isEmpty()) listOf(fallbackModel) else seen.toList()
}
- val providerLabel = messages.firstNotNullOfOrNull { it.providerUsed }
+ val providerLabel = tr(messages.firstNotNullOfOrNull { it.providerUsed }
?.let { CoachProviderMode.fromRaw(it).label }
- ?: fallbackProviderMode.label
+ ?: fallbackProviderMode.label)
val showsCostNote = fallbackProviderMode == CoachProviderMode.OFFLINE_STUB ||
accounted.any { (it.inputTokens != null || it.outputTokens != null) && it.costUSD == null }
diff --git a/app/src/main/java/com/pulseloop/ui/screens/McpSettingsUi.kt b/app/src/main/java/com/pulseloop/ui/screens/McpSettingsUi.kt
new file mode 100644
index 00000000..f69d0c96
--- /dev/null
+++ b/app/src/main/java/com/pulseloop/ui/screens/McpSettingsUi.kt
@@ -0,0 +1,285 @@
+package com.pulseloop.ui.screens
+
+import android.content.ClipData
+import android.content.ClipboardManager
+import android.content.Context
+import android.os.PersistableBundle
+import androidx.compose.foundation.background
+import androidx.compose.foundation.layout.Arrangement
+import androidx.compose.foundation.layout.Column
+import androidx.compose.foundation.layout.Row
+import androidx.compose.foundation.layout.fillMaxWidth
+import androidx.compose.foundation.layout.heightIn
+import androidx.compose.foundation.layout.padding
+import androidx.compose.foundation.rememberScrollState
+import androidx.compose.foundation.shape.RoundedCornerShape
+import androidx.compose.foundation.text.selection.SelectionContainer
+import androidx.compose.foundation.verticalScroll
+import androidx.compose.material3.AlertDialog
+import androidx.compose.material3.OutlinedTextField
+import androidx.compose.material3.Switch
+import androidx.compose.material3.Text
+import androidx.compose.runtime.Composable
+import androidx.compose.runtime.collectAsState
+import androidx.compose.runtime.getValue
+import androidx.compose.runtime.mutableIntStateOf
+import androidx.compose.runtime.mutableStateOf
+import androidx.compose.runtime.produceState
+import androidx.compose.runtime.remember
+import androidx.compose.runtime.setValue
+import androidx.compose.ui.Alignment
+import androidx.compose.ui.Modifier
+import androidx.compose.ui.platform.LocalContext
+import androidx.compose.ui.unit.dp
+import com.pulseloop.mcp.McpConfig
+import com.pulseloop.mcp.McpNet
+import com.pulseloop.mcp.McpPrefs
+import com.pulseloop.mcp.McpService
+import com.pulseloop.mcp.McpTokens
+import com.pulseloop.mcp.PairedTool
+import com.pulseloop.ui.components.PulseButton
+import com.pulseloop.ui.components.PulseButtonStyle
+import com.pulseloop.ui.components.PulseSegmented
+import com.pulseloop.ui.components.switchRow
+import com.pulseloop.ui.i18n.tr
+import com.pulseloop.ui.i18n.trf
+import com.pulseloop.ui.theme.PulseColors
+import com.pulseloop.ui.theme.PulseType
+import kotlinx.coroutines.Dispatchers
+import kotlinx.coroutines.withContext
+import java.time.Instant
+import java.time.ZoneId
+import java.time.format.DateTimeFormatter
+
+/**
+ * Settings › Connected apps › AI tools on your network: the read-only MCP server
+ * (docs/mcp-threat-model.md). Off by default. Summary first (the switch and where to connect),
+ * then the paired tools and the one action, "Pair a tool". A token is shown once, in a dialog,
+ * with the config to paste; only its hash is kept.
+ */
+@Composable
+fun McpSettingsScreen(onBack: () -> Unit) {
+ val context = LocalContext.current
+ val prefs = remember { McpPrefs(context) }
+ val tokens = remember { McpTokens(prefs) }
+ val status by McpService.status.collectAsState()
+ var paired by remember { mutableStateOf(tokens.list()) }
+ var hours by remember { mutableIntStateOf(prefs.autoOffHours) }
+ var askingLabel by remember { mutableStateOf(false) }
+ var justPaired by remember { mutableStateOf?>(null) } // label to token
+ var revoking by remember { mutableStateOf(null) }
+
+ val starting = !status.running && status.offAt > 0L && !status.unreachable
+ val on = status.running || starting
+ // While off, the addresses it would listen on, so a config can be made before turning it on.
+ val localUrls by produceState(initialValue = emptyList(), status.running) {
+ value = withContext(Dispatchers.IO) { McpNet.localAddresses().map { a -> McpNet.url(a) } }
+ }
+ val urls = if (status.running) status.urls else localUrls
+
+ SettingsSubScreen(title = tr("AI tools on your network"), onBack = onBack) {
+ Text(
+ tr("Let AI tools on your computer, like Claude Desktop or Cursor, read your PulseLoop data over your Wi-Fi or Tailscale. They can only read: nothing can be changed or deleted."),
+ style = PulseType.body,
+ color = PulseColors.textSecondary,
+ )
+
+ McpCard {
+ Row(
+ Modifier.fillMaxWidth().switchRow(checked = on, onCheckedChange = { want ->
+ if (want) McpService.start(context) else McpService.stop(context)
+ }),
+ horizontalArrangement = Arrangement.SpaceBetween,
+ verticalAlignment = Alignment.CenterVertically,
+ ) {
+ Text(tr("Share with AI tools on this network"), style = PulseType.title, color = PulseColors.textPrimary, modifier = Modifier.weight(1f))
+ Switch(checked = on, onCheckedChange = null)
+ }
+ Text(
+ when {
+ 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.")
+ else -> tr("Off")
+ },
+ 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)
+ PulseSegmented(
+ options = McpPrefs.HOURS_CHOICES.map { it to trf("{0} h", it) },
+ selected = hours,
+ onSelect = { h -> hours = h; prefs.autoOffHours = h },
+ )
+ if (status.running) {
+ Text(tr("A new time applies the next time it's turned on."), style = PulseType.label, color = PulseColors.textSecondary)
+ }
+ }
+
+ Column(verticalArrangement = Arrangement.spacedBy(8.dp)) {
+ Text(tr("Connect to").uppercase(), style = PulseType.eyebrow, color = PulseColors.textSecondary)
+ if (urls.isEmpty()) {
+ Text(tr("Connect the phone to Wi-Fi or Tailscale to get an address."), style = PulseType.body, color = PulseColors.textSecondary)
+ } else {
+ SelectionContainer {
+ Column(verticalArrangement = Arrangement.spacedBy(4.dp)) {
+ urls.forEach { u ->
+ Text(
+ if (u.startsWith("http://100.")) trf("{0} (Tailscale)", u) else u,
+ style = PulseType.body,
+ color = PulseColors.textPrimary,
+ )
+ }
+ }
+ }
+ }
+ Text(
+ tr("Paired tools on this network can read your health data while this is on. Nothing is sent anywhere by itself."),
+ style = PulseType.body,
+ color = PulseColors.textSecondary,
+ )
+ }
+
+ Column(verticalArrangement = Arrangement.spacedBy(8.dp)) {
+ Text(tr("Paired tools").uppercase(), style = PulseType.eyebrow, color = PulseColors.textSecondary)
+ if (paired.isEmpty()) {
+ Text(tr("No tools paired yet."), style = PulseType.body, color = PulseColors.textSecondary)
+ }
+ paired.forEach { t ->
+ Row(
+ Modifier.fillMaxWidth().heightIn(min = 48.dp),
+ verticalAlignment = Alignment.CenterVertically,
+ ) {
+ Column(Modifier.weight(1f)) {
+ Text(t.label, style = PulseType.title, color = PulseColors.textPrimary)
+ Text(
+ t.lastUsedAt?.let { trf("Paired {0} · last used {1}", day(t.createdAt), day(it)) }
+ ?: trf("Paired {0} · not used yet", day(t.createdAt)),
+ style = PulseType.label,
+ color = PulseColors.textSecondary,
+ )
+ }
+ PulseButton(PulseButtonStyle.Text, onClick = { revoking = t }) { Text(tr("Revoke")) }
+ }
+ }
+ PulseButton(PulseButtonStyle.Tonal, onClick = { askingLabel = true }, modifier = Modifier.fillMaxWidth()) {
+ Text(tr("Pair a tool"))
+ }
+ }
+ }
+
+ if (askingLabel) {
+ var label by remember { mutableStateOf("") }
+ AlertDialog(
+ onDismissRequest = { askingLabel = false },
+ title = { Text(tr("Pair a tool")) },
+ text = {
+ Column(verticalArrangement = Arrangement.spacedBy(8.dp)) {
+ Text(tr("Name it so you'll recognise it later, like the app and the computer."), style = PulseType.body)
+ OutlinedTextField(
+ value = label,
+ onValueChange = { label = it.take(McpTokens.MAX_LABEL) },
+ label = { Text(tr("Name")) },
+ placeholder = { Text(tr("Claude Desktop on my laptop")) },
+ singleLine = true,
+ modifier = Modifier.fillMaxWidth(),
+ )
+ }
+ },
+ confirmButton = {
+ PulseButton(PulseButtonStyle.Text, onClick = {
+ val (tool, token) = tokens.create(label.ifBlank { tr("AI tool") }, System.currentTimeMillis())
+ paired = tokens.list()
+ askingLabel = false
+ justPaired = tool.label to token
+ }) { Text(tr("Pair")) }
+ },
+ dismissButton = {
+ PulseButton(PulseButtonStyle.Text, onClick = { askingLabel = false }) { Text(tr("Cancel")) }
+ },
+ )
+ }
+
+ justPaired?.let { (label, token) ->
+ val url = urls.firstOrNull() ?: "http://PHONE-ADDRESS:${McpNet.PORT}/mcp"
+ val bridge = McpConfig.stdioBridge(url, token)
+ val direct = McpConfig.direct(url, token)
+ AlertDialog(
+ onDismissRequest = { /* only Done closes it: the token is never shown again */ },
+ title = { Text(trf("{0} is paired", label)) },
+ text = {
+ Column(Modifier.verticalScroll(rememberScrollState()), verticalArrangement = Arrangement.spacedBy(8.dp)) {
+ Text(tr("Copy this now. It won't be shown again."), style = PulseType.body, color = PulseColors.warning)
+ SelectionContainer { Text(token, style = PulseType.body, color = PulseColors.textPrimary) }
+ PulseButton(PulseButtonStyle.Text, onClick = { copySecret(context, token) }) { Text(tr("Copy token")) }
+
+ Text(tr("Claude Desktop or Cursor").uppercase(), style = PulseType.eyebrow, color = PulseColors.textSecondary)
+ Text(
+ tr("Add this to claude_desktop_config.json or .cursor/mcp.json, then restart the app. It needs Node.js on the computer."),
+ style = PulseType.label,
+ color = PulseColors.textSecondary,
+ )
+ SelectionContainer { Text(bridge, style = PulseType.label, color = PulseColors.textPrimary) }
+ PulseButton(PulseButtonStyle.Text, onClick = { copySecret(context, bridge) }) { Text(tr("Copy config")) }
+
+ Text(tr("Tools that connect over HTTP").uppercase(), style = PulseType.eyebrow, color = PulseColors.textSecondary)
+ SelectionContainer { Text(direct, style = PulseType.label, color = PulseColors.textPrimary) }
+ PulseButton(PulseButtonStyle.Text, onClick = { copySecret(context, direct) }) { Text(tr("Copy address and header")) }
+ if (urls.isEmpty()) {
+ Text(
+ tr("Replace PHONE-ADDRESS with the phone's address once it is on Wi-Fi or Tailscale."),
+ style = PulseType.label,
+ color = PulseColors.textSecondary,
+ )
+ }
+ }
+ },
+ confirmButton = {
+ PulseButton(PulseButtonStyle.Text, onClick = { justPaired = null }) { Text(tr("Done")) }
+ },
+ )
+ }
+
+ revoking?.let { t ->
+ AlertDialog(
+ onDismissRequest = { revoking = null },
+ title = { Text(trf("Revoke {0}?", t.label)) },
+ text = { Text(tr("It won't be able to read your data any more. Pair it again to reconnect."), style = PulseType.body) },
+ confirmButton = {
+ PulseButton(PulseButtonStyle.Text, onClick = {
+ tokens.revoke(t.id)
+ paired = tokens.list()
+ revoking = null
+ }) { Text(tr("Revoke")) }
+ },
+ dismissButton = {
+ PulseButton(PulseButtonStyle.Text, onClick = { revoking = null }) { Text(tr("Cancel")) }
+ },
+ )
+ }
+}
+
+@Composable
+private fun McpCard(content: @Composable () -> Unit) {
+ Column(
+ Modifier
+ .fillMaxWidth()
+ .background(PulseColors.card, RoundedCornerShape(8.dp))
+ .padding(16.dp),
+ verticalArrangement = Arrangement.spacedBy(12.dp),
+ ) { content() }
+}
+
+private val CLOCK = DateTimeFormatter.ofPattern("HH:mm")
+private val DAY = DateTimeFormatter.ofPattern("d MMM")
+
+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)
+
+/** Copies a token or a config holding one, marked sensitive so the clipboard preview hides it. */
+private fun copySecret(context: Context, text: String) {
+ val cm = context.getSystemService(Context.CLIPBOARD_SERVICE) as ClipboardManager
+ val clip = ClipData.newPlainText("PulseLoop", text)
+ clip.description.extras = PersistableBundle().apply { putBoolean("android.content.extra.IS_SENSITIVE", true) }
+ cm.setPrimaryClip(clip)
+}
diff --git a/app/src/main/java/com/pulseloop/ui/screens/MealAnalysisSheet.kt b/app/src/main/java/com/pulseloop/ui/screens/MealAnalysisSheet.kt
index c70e616a..026b2bb2 100644
--- a/app/src/main/java/com/pulseloop/ui/screens/MealAnalysisSheet.kt
+++ b/app/src/main/java/com/pulseloop/ui/screens/MealAnalysisSheet.kt
@@ -727,6 +727,13 @@ object MealEstimator {
"You can still search the database or enter the meal manually."),
)
}
+ // The model on this phone answers coach questions only (its client refuses any other
+ // schema): say so plainly instead of a generic failure.
+ if (providerStore.providerMode == com.pulseloop.coach.config.CoachProviderMode.ON_DEVICE) {
+ return@withContext Result.Failure(
+ tr("The coach on this phone can't estimate meals. Pick a cloud or self-hosted coach in Settings → AI Coach, or enter the meal manually."),
+ )
+ }
val model = CoachClientResolver.activeModel(providerStore.snapshot(), keyStore.model)
val images = mutableListOf()
diff --git a/app/src/main/java/com/pulseloop/ui/screens/OnDeviceModelUi.kt b/app/src/main/java/com/pulseloop/ui/screens/OnDeviceModelUi.kt
new file mode 100644
index 00000000..563ac8c4
--- /dev/null
+++ b/app/src/main/java/com/pulseloop/ui/screens/OnDeviceModelUi.kt
@@ -0,0 +1,178 @@
+package com.pulseloop.ui.screens
+
+import android.content.Intent
+import android.net.Uri
+import androidx.activity.compose.rememberLauncherForActivityResult
+import androidx.activity.result.contract.ActivityResultContracts
+import androidx.compose.foundation.layout.Arrangement
+import androidx.compose.foundation.layout.Column
+import androidx.compose.foundation.layout.fillMaxWidth
+import androidx.compose.foundation.layout.height
+import androidx.compose.foundation.layout.padding
+import androidx.compose.material3.LinearProgressIndicator
+import androidx.compose.material3.Text
+import androidx.compose.runtime.Composable
+import androidx.compose.runtime.LaunchedEffect
+import androidx.compose.runtime.collectAsState
+import androidx.compose.runtime.getValue
+import androidx.compose.runtime.remember
+import androidx.compose.runtime.rememberCoroutineScope
+import androidx.compose.ui.Modifier
+import androidx.compose.ui.platform.LocalContext
+import androidx.compose.ui.text.font.FontWeight
+import androidx.compose.ui.unit.dp
+import androidx.compose.ui.unit.sp
+import com.pulseloop.coach.ondevice.ModelDownload
+import com.pulseloop.coach.ondevice.ModelState
+import com.pulseloop.coach.ondevice.OnDeviceModelStore
+import com.pulseloop.ui.components.PulseButton
+import com.pulseloop.ui.components.PulseButtonStyle
+import com.pulseloop.ui.i18n.tr
+import com.pulseloop.ui.i18n.trf
+import com.pulseloop.ui.theme.PulseColors
+import kotlinx.coroutines.launch
+
+/**
+ * Settings › AI Coach › "On this phone" (docs/on-device-model-and-mcp-plan.md, Part 1, "What the
+ * person sees"). Shown under the provider picker when that provider is chosen.
+ *
+ * Flow: what it is → the size before anything moves → Download (Wi-Fi only) or "Download now on
+ * mobile data" → progress with Cancel (and a switch to mobile data while it waits for Wi-Fi) →
+ * Ready, with Remove. "Choose a file instead" copies a model the user already has. A failure says
+ * why in plain words and offers the same actions again. Below the memory floor nothing is offered,
+ * and the line says why.
+ *
+ * One primary action at a time, Tonal (this is a pushed screen; the Actions button is the screen's
+ * only filled accent); everything else is a Text button.
+ */
+@Composable
+fun OnDeviceModelSection() {
+ val context = LocalContext.current
+ val store = remember { OnDeviceModelStore.get(context) }
+ val state by store.state.collectAsState()
+ val scope = rememberCoroutineScope()
+ LaunchedEffect(Unit) { store.refresh() }
+
+ val pickFile = rememberLauncherForActivityResult(ActivityResultContracts.OpenDocument()) { uri ->
+ if (uri != null) scope.launch { store.import(uri) }
+ }
+ val openTerms = {
+ runCatching { context.startActivity(Intent(Intent.ACTION_VIEW, Uri.parse(ModelDownload.TERMS_URL))) }
+ Unit
+ }
+
+ Column(Modifier.fillMaxWidth(), verticalArrangement = Arrangement.spacedBy(8.dp)) {
+ Text(
+ tr("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."),
+ fontSize = 14.sp, color = PulseColors.textSecondary,
+ )
+
+ val current = state
+ // Below the floor the model would starve the phone: say why, and offer nothing to start.
+ if (!store.meetsMemoryFloor && current !is ModelState.Ready) {
+ Text(
+ trf(
+ "Not offered on this phone: it has {0} GB of memory, and the model needs about 4 GB to run without slowing everything down.",
+ "%.1f".format(store.totalMemoryBytes / 1_000_000_000.0),
+ ),
+ fontSize = 14.sp, color = PulseColors.textPrimary,
+ )
+ } else {
+ ModelControls(store, current, onPickFile = { pickFile.launch(arrayOf("*/*")) })
+ }
+ PulseButton(PulseButtonStyle.Text, onClick = openTerms) { Text(tr("Gemma Terms of Use")) }
+ }
+}
+
+/** The status, the progress and the one or two actions that fit [current]. */
+@Composable
+private fun ModelControls(store: OnDeviceModelStore, current: ModelState, onPickFile: () -> Unit) {
+ Column(Modifier.fillMaxWidth(), verticalArrangement = Arrangement.spacedBy(8.dp)) {
+ Text(statusLine(current), fontSize = 16.sp, fontWeight = FontWeight.SemiBold, color = statusColor(current))
+
+ when (current) {
+ is ModelState.Getting -> {
+ val p = current.progress
+ if (p != null) {
+ LinearProgressIndicator(
+ progress = { p },
+ modifier = Modifier.fillMaxWidth().height(8.dp),
+ color = PulseColors.info,
+ trackColor = PulseColors.cardSoft,
+ )
+ } else {
+ LinearProgressIndicator(
+ modifier = Modifier.fillMaxWidth().height(8.dp),
+ color = PulseColors.info,
+ trackColor = PulseColors.cardSoft,
+ )
+ }
+ if (current.waitingForWifi) {
+ PulseButton(PulseButtonStyle.Tonal, onClick = { store.useMobileData() }, modifier = Modifier.fillMaxWidth()) {
+ Text(tr("Download now on mobile data"))
+ }
+ }
+ if (!current.copying) {
+ PulseButton(PulseButtonStyle.Text, onClick = { store.cancel() }) { Text(tr("Cancel")) }
+ }
+ }
+ is ModelState.Ready -> {
+ PulseButton(PulseButtonStyle.Text, onClick = { store.remove() }) {
+ Text(trf("Remove the model (frees {0} MB)", current.bytes / 1_000_000))
+ }
+ }
+ ModelState.Absent, is ModelState.Failed -> {
+ Text(
+ trf("{0}, about {1} MB. Downloads on Wi-Fi only, unless you choose mobile data.",
+ ModelDownload.DISPLAY_NAME, ModelDownload.APPROX_MB),
+ fontSize = 14.sp, color = PulseColors.textSecondary,
+ )
+ PulseButton(PulseButtonStyle.Tonal, onClick = { store.download(wifiOnly = true) }, modifier = Modifier.fillMaxWidth()) {
+ Text(trf("Download ({0} MB)", ModelDownload.APPROX_MB))
+ }
+ PulseButton(PulseButtonStyle.Text, onClick = { store.download(wifiOnly = false) }) {
+ Text(tr("Download now on mobile data"))
+ }
+ PulseButton(PulseButtonStyle.Text, onClick = onPickFile) {
+ Text(tr("Choose a file instead"))
+ }
+ Text(
+ tr("Downloading means you accept Google's Gemma Terms of Use."),
+ fontSize = 12.sp, color = PulseColors.textMuted,
+ modifier = Modifier.padding(top = 4.dp),
+ )
+ }
+ }
+ }
+}
+
+private fun statusLine(state: ModelState): String = when (state) {
+ ModelState.Absent -> tr("Not downloaded yet")
+ is ModelState.Getting -> {
+ val pct = state.progress?.let { (it * 100).toInt() }
+ when {
+ state.copying -> if (pct != null) trf("Copying the file… {0}%", pct) else tr("Copying the file…")
+ state.waitingForWifi -> tr("Waiting for Wi-Fi")
+ pct == null -> tr("Starting the download…")
+ pct >= 100 -> tr("Checking the download…")
+ else -> trf("Downloading… {0}%", pct)
+ }
+ }
+ is ModelState.Ready -> trf("Ready · {0}", ModelDownload.DISPLAY_NAME)
+ is ModelState.Failed -> when (state.reason) {
+ ModelState.Reason.NOT_A_MODEL -> tr("That file isn't a model. Choose the .task file.")
+ ModelState.Reason.TOO_SMALL -> tr("That file is too small to be the model.")
+ ModelState.Reason.NO_SPACE -> trf("Not enough free space. Free about {0} MB and try again.", ModelDownload.APPROX_MB * 2)
+ ModelState.Reason.DOWNLOAD -> tr("The download didn't finish. Check your connection and try again.")
+ ModelState.Reason.NOT_PUBLISHED -> tr("The model isn't available to download right now. Try again later.")
+ ModelState.Reason.CHECK -> tr("The download didn't match its published checksum, so it was deleted. Try again.")
+ ModelState.Reason.OTHER -> tr("Something went wrong. Try again.")
+ }
+}
+
+private fun statusColor(state: ModelState) = when (state) {
+ is ModelState.Ready -> PulseColors.success
+ is ModelState.Failed -> PulseColors.danger
+ else -> PulseColors.textPrimary
+}
diff --git a/app/src/main/java/com/pulseloop/ui/screens/SettingsScreen.kt b/app/src/main/java/com/pulseloop/ui/screens/SettingsScreen.kt
index 89695561..1a0b58fa 100644
--- a/app/src/main/java/com/pulseloop/ui/screens/SettingsScreen.kt
+++ b/app/src/main/java/com/pulseloop/ui/screens/SettingsScreen.kt
@@ -77,12 +77,14 @@ fun SettingsScreen(
CoachProviderMode.LOCAL_OPENAI_COMPAT ->
providerStore.localModel.ifBlank { tr("Local") }
CoachProviderMode.BACKEND_PROXY -> tr("Backend proxy")
+ CoachProviderMode.ON_DEVICE -> tr("On this phone")
else -> keyStore.model
}
val openCheck by remember(db) { db.accuracyDao().openFlow() }.collectAsState(initial = null)
// The tabs no longer carry the "Adjusted by your accuracy check" caption; this row is
// where the user sees that corrections are on, and the screen behind it lists them.
val accuracyCorrections = rememberAccuracyCorrections()
+ val mcpStatus by com.pulseloop.mcp.McpService.status.collectAsState()
val accuracyTrailing = openCheck?.let { c ->
if (c.state == com.pulseloop.data.entity.AccuracyCheckEntity.STATE_RUNNING) {
val (day, total) = AccuracyUiText.dayOf(c)
@@ -202,6 +204,9 @@ fun SettingsScreen(
SettingsRowItem(Icons.Filled.Verified, PulseColors.info, tr("Accuracy check"), accuracyTrailing) {
navigate("settings/accuracy-check")
},
+ SettingsRowItem(Icons.Filled.Wifi, PulseColors.info, tr("AI tools on your network"), if (mcpStatus.running) tr("On") else null) {
+ navigate("settings/mcp")
+ },
),
)
diff --git a/app/src/main/java/com/pulseloop/ui/screens/SettingsSubScreens.kt b/app/src/main/java/com/pulseloop/ui/screens/SettingsSubScreens.kt
index e71799dd..f2093303 100644
--- a/app/src/main/java/com/pulseloop/ui/screens/SettingsSubScreens.kt
+++ b/app/src/main/java/com/pulseloop/ui/screens/SettingsSubScreens.kt
@@ -226,11 +226,19 @@ fun CoachSettingsScreen(onBack: () -> Unit) {
// not a key, so the old key-only check told a correctly-configured user their
// "API key" was missing.
val isLocal = providerStore.providerMode == CoachProviderMode.LOCAL_OPENAI_COMPAT
- val ready = if (isLocal) providerStore.hasLocalBaseUrl else keyStore.apiKey.isNotBlank()
+ val isOnDevice = providerStore.providerMode == CoachProviderMode.ON_DEVICE
+ val onDeviceState by com.pulseloop.coach.ondevice.OnDeviceModelStore.get(context).state.collectAsState()
+ val ready = when {
+ isOnDevice -> onDeviceState is com.pulseloop.coach.ondevice.ModelState.Ready
+ isLocal -> providerStore.hasLocalBaseUrl
+ else -> keyStore.apiKey.isNotBlank()
+ }
val activeModel = if (isLocal) providerStore.localModel.ifBlank { "local server" }
+ else if (isOnDevice) trf("On this phone · {0}", com.pulseloop.coach.ondevice.ModelDownload.DISPLAY_NAME)
else selectedModel
Text(
if (coachEnabled && ready) trf("Active — {0}", activeModel)
+ else if (coachEnabled && isOnDevice) tr("Model download needed")
else if (coachEnabled && isLocal) tr("Server address needed")
else if (coachEnabled) tr("API key needed")
else tr("Disabled"),
@@ -313,6 +321,7 @@ fun CoachSettingsScreen(onBack: () -> Unit) {
CoachProviderMode.USER_OPENROUTER_KEY to "OpenRouter (100+ models)",
CoachProviderMode.USER_MINIMAX_KEY to "MiniMax",
CoachProviderMode.LOCAL_OPENAI_COMPAT to "Local / self-hosted (no key needed)",
+ CoachProviderMode.ON_DEVICE to tr("On this phone (no key, works offline)"),
)
val providerLabel = providerOptions.firstOrNull { it.first == providerMode }?.second ?: tr("OpenAI")
@@ -328,7 +337,12 @@ fun CoachSettingsScreen(onBack: () -> Unit) {
providerOptions.forEach { (mode, label) ->
DropdownMenuItem(
text = { Text(label) },
- onClick = { providerMode = mode; providerStore.providerMode = mode; providerExpanded = false },
+ onClick = {
+ // Leaving the on-device model frees the memory its engine holds.
+ if (providerMode == CoachProviderMode.ON_DEVICE && mode != CoachProviderMode.ON_DEVICE)
+ com.pulseloop.coach.ondevice.OnDeviceModelStore.get(context).closeEngine()
+ providerMode = mode; providerStore.providerMode = mode; providerExpanded = false
+ },
)
}
}
@@ -706,6 +720,8 @@ fun CoachSettingsScreen(onBack: () -> Unit) {
modifier = Modifier.padding(top = 4.dp),
)
}
+ // The model on this phone: its download, its file, its licence (OnDeviceModelUi.kt).
+ CoachProviderMode.ON_DEVICE -> OnDeviceModelSection()
else -> {
// OpenAI (and legacy modes): the model picker + key field.
CoachModelPicker(
@@ -724,12 +740,14 @@ fun CoachSettingsScreen(onBack: () -> Unit) {
)
}
}
- Spacer(Modifier.height(4.dp))
- Text(
- tr("Stored securely in Android Keystore. Never leaves your device except to call the model. Provider changes apply from your next message."),
- style = MaterialTheme.typography.bodySmall,
- color = MaterialTheme.colorScheme.onSurfaceVariant,
- )
+ if (providerMode != CoachProviderMode.ON_DEVICE) {
+ Spacer(Modifier.height(4.dp))
+ Text(
+ tr("Stored securely in Android Keystore. Never leaves your device except to call the model. Provider changes apply from your next message."),
+ style = MaterialTheme.typography.bodySmall,
+ color = MaterialTheme.colorScheme.onSurfaceVariant,
+ )
+ }
// Reasoning effort / Gemini thinking level (iOS #140). The levels differ per model
// (GPT-6 Sol rejects None, DeepSeek has no Medium), so the picker lists only what
@@ -738,6 +756,7 @@ fun CoachSettingsScreen(onBack: () -> Unit) {
val effortProvider = if (providerMode in setOf(
CoachProviderMode.USER_GEMINI_KEY, CoachProviderMode.USER_OPENROUTER_KEY,
CoachProviderMode.USER_MINIMAX_KEY, CoachProviderMode.LOCAL_OPENAI_COMPAT,
+ CoachProviderMode.ON_DEVICE,
)) providerMode else CoachProviderMode.USER_OPENAI_KEY
val effortModel = when (effortProvider) {
CoachProviderMode.USER_GEMINI_KEY -> geminiModel
@@ -757,8 +776,11 @@ fun CoachSettingsScreen(onBack: () -> Unit) {
) { providerStore.reasoningEffort = it.takeIf { s -> s != "default" }; reasoningEffort = providerStore.reasoningEffort }
}
+ // The model on this phone reads text, runs no tools and writes nothing, so
+ // image, web-search, write and measurement switches don't apply to it.
+ val toolsApply = providerMode != CoachProviderMode.ON_DEVICE
// Image attachments (iOS #31): gates the attach button in the coach chat.
- Row(Modifier.fillMaxWidth()
+ if (toolsApply) Row(Modifier.fillMaxWidth()
.switchRow(checked = imageInput, onCheckedChange = { imageInput = it; providerStore.imageInputEnabled = it }), horizontalArrangement = Arrangement.SpaceBetween, verticalAlignment = Alignment.CenterVertically) {
Column(Modifier.weight(1f)) {
Text(tr("Image attachments"))
@@ -772,7 +794,7 @@ fun CoachSettingsScreen(onBack: () -> Unit) {
// Tool toggles. Neither MiniMax's compat endpoint nor any self-hosted engine
// has a hosted web search, so hide the toggle for both (each client drops the
// tool anyway — this is the UI half).
- if (providerMode != CoachProviderMode.USER_MINIMAX_KEY &&
+ if (toolsApply && providerMode != CoachProviderMode.USER_MINIMAX_KEY &&
providerMode != CoachProviderMode.LOCAL_OPENAI_COMPAT) {
Row(Modifier.fillMaxWidth()
.switchRow(checked = webSearch, onCheckedChange = {
@@ -785,7 +807,7 @@ fun CoachSettingsScreen(onBack: () -> Unit) {
Switch(checked = webSearch, onCheckedChange = null)
}
}
- Row(Modifier.fillMaxWidth()
+ if (toolsApply) Row(Modifier.fillMaxWidth()
.switchRow(checked = writeTools, onCheckedChange = {
writeTools = it; keyStore.writeToolsEnabled = it
}), horizontalArrangement = Arrangement.SpaceBetween, verticalAlignment = Alignment.CenterVertically) {
@@ -795,7 +817,7 @@ fun CoachSettingsScreen(onBack: () -> Unit) {
}
Switch(checked = writeTools, onCheckedChange = null)
}
- Row(Modifier.fillMaxWidth()
+ if (toolsApply) Row(Modifier.fillMaxWidth()
.switchRow(checked = liveMeasurements, onCheckedChange = {
liveMeasurements = it; keyStore.liveMeasurementsEnabled = it
}), horizontalArrangement = Arrangement.SpaceBetween, verticalAlignment = Alignment.CenterVertically) {
diff --git a/app/src/test/java/com/pulseloop/coach/ondevice/ModelDownloadTest.kt b/app/src/test/java/com/pulseloop/coach/ondevice/ModelDownloadTest.kt
new file mode 100644
index 00000000..657abd08
--- /dev/null
+++ b/app/src/test/java/com/pulseloop/coach/ondevice/ModelDownloadTest.kt
@@ -0,0 +1,62 @@
+package com.pulseloop.coach.ondevice
+
+import org.junit.Assert.assertEquals
+import org.junit.Assert.assertFalse
+import org.junit.Assert.assertNull
+import org.junit.Assert.assertTrue
+import org.junit.Test
+import java.io.File
+
+/** Copied from Cochilo's ModelDownloadTest, adapted to PulseLoop's constants. */
+class ModelDownloadTest {
+ @Test fun urls_point_at_the_prerelease() {
+ assertEquals(
+ "https://github.com/gabrielbr/Cochilo/releases/download/assistant-model-v1/gemma3-1b-it-int4.task",
+ ModelDownload.modelUrl(),
+ )
+ assertTrue(ModelDownload.sumUrl().endsWith(".task.sha256"))
+ // Moving to PulseLoop's own pre-release is a change of repository only.
+ assertEquals(
+ "https://github.com/gabrielbr/PulseLoopAndroid/releases/download/assistant-model-v1/gemma3-1b-it-int4.task",
+ ModelDownload.modelUrl("gabrielbr/PulseLoopAndroid"),
+ )
+ }
+
+ @Test fun reads_a_sha256sum_line_and_refuses_anything_else() {
+ val h = "a".repeat(64)
+ assertEquals(h, ModelDownload.parseSum("$h gemma3-1b-it-int4.task\n"))
+ assertEquals(h, ModelDownload.parseSum(h.uppercase()))
+ assertNull(ModelDownload.parseSum("Not Found"))
+ assertNull(ModelDownload.parseSum(""))
+ assertNull(ModelDownload.parseSum(""))
+ assertNull(ModelDownload.parseSum("a".repeat(63)))
+ }
+
+ @Test fun verify_checks_the_header_the_size_and_the_hash() {
+ val f = File.createTempFile("model", ".task")
+ try {
+ f.writeBytes(byteArrayOf('P'.code.toByte(), 'K'.code.toByte()) + ByteArray(10))
+ assertEquals(ModelState.Reason.TOO_SMALL, ModelDownload.verify(f, ModelDownload.sha256(f)))
+ f.writeBytes("Not Found".toByteArray())
+ assertEquals(ModelState.Reason.NOT_A_MODEL, ModelDownload.verify(f, ModelDownload.sha256(f)))
+ assertFalse(ModelDownload.sha256(f) == "0".repeat(64))
+ } finally { f.delete() }
+ }
+
+ @Test fun sha256_matches_a_known_digest() {
+ val f = File.createTempFile("abc", ".txt")
+ try {
+ f.writeText("abc")
+ assertEquals("ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad", ModelDownload.sha256(f))
+ } finally { f.delete() }
+ }
+
+ @Test fun the_memory_floor_takes_a_4_gb_phone_and_refuses_a_3_gb_one() {
+ val gib = 1024L * 1024 * 1024
+ // A "4 GB" phone reports a little under 4 GiB once the kernel takes its share.
+ assertTrue(ModelDownload.meetsMemoryFloor(3_700_000_000L))
+ assertTrue(ModelDownload.meetsMemoryFloor(8 * gib))
+ assertFalse(ModelDownload.meetsMemoryFloor(3 * gib))
+ assertFalse(ModelDownload.meetsMemoryFloor(0))
+ }
+}
diff --git a/app/src/test/java/com/pulseloop/coach/ondevice/ModelFileTest.kt b/app/src/test/java/com/pulseloop/coach/ondevice/ModelFileTest.kt
new file mode 100644
index 00000000..37c7af3f
--- /dev/null
+++ b/app/src/test/java/com/pulseloop/coach/ondevice/ModelFileTest.kt
@@ -0,0 +1,49 @@
+package com.pulseloop.coach.ondevice
+
+import org.junit.Assert.assertEquals
+import org.junit.Assert.assertFalse
+import org.junit.Assert.assertNull
+import org.junit.Assert.assertTrue
+import org.junit.Test
+import java.io.ByteArrayInputStream
+import java.io.File
+import java.nio.file.Files
+
+/** Copied from Cochilo's ModelFileTest (the `.task` parts), plus the free-space rule. */
+class ModelFileTest {
+ private val zip = byteArrayOf('P'.code.toByte(), 'K'.code.toByte())
+
+ @Test fun only_a_task_file_of_a_real_size_is_taken() {
+ assertNull(ModelFile.check(zip, 600L * 1024 * 1024))
+ // Google's current Gemma .task isn't a zip: a binary header is fine.
+ assertNull(ModelFile.check(byteArrayOf(0x1C, 0x00, 0x00, 0x00, 'T'.code.toByte()), 600L * 1024 * 1024))
+ assertEquals(ModelState.Reason.NOT_A_MODEL, ModelFile.check("{}".toByteArray(), 600L * 1024 * 1024))
+ assertEquals(ModelState.Reason.NOT_A_MODEL, ModelFile.check(" ".toByteArray(), 600L * 1024 * 1024))
+ assertEquals(ModelState.Reason.TOO_SMALL, ModelFile.check(zip, 1024))
+ assertFalse(ModelFile.looksLikeTask(ByteArray(0)))
+ }
+
+ @Test fun the_copy_lands_whole_and_reports_progress() {
+ val dir = Files.createTempDirectory("ondevice").toFile()
+ try {
+ val target = File(dir, "models/assistant.task")
+ val data = ByteArray(3 * (1 shl 20) + 7) { it.toByte() }
+ val seen = mutableListOf()
+ val n = ModelFile.copy(ByteArrayInputStream(data), target) { seen += it }
+ assertEquals(data.size.toLong(), n)
+ assertTrue(target.readBytes().contentEquals(data))
+ assertEquals(data.size.toLong(), seen.last())
+ assertFalse(File(target.parentFile, "assistant.task.part").exists())
+ // A second copy replaces the first.
+ val again = ByteArray(10) { 1 }
+ ModelFile.copy(ByteArrayInputStream(again), target) { }
+ assertTrue(target.readBytes().contentEquals(again))
+ } finally { dir.deleteRecursively() }
+ }
+
+ @Test fun free_space_keeps_a_margin() {
+ val mb = 1024L * 1024
+ assertTrue(ModelFile.hasSpaceFor(600 * mb, 700 * mb))
+ assertFalse(ModelFile.hasSpaceFor(600 * mb, 620 * mb))
+ }
+}
diff --git a/app/src/test/java/com/pulseloop/coach/ondevice/OnDevicePromptTest.kt b/app/src/test/java/com/pulseloop/coach/ondevice/OnDevicePromptTest.kt
new file mode 100644
index 00000000..362ec2a6
--- /dev/null
+++ b/app/src/test/java/com/pulseloop/coach/ondevice/OnDevicePromptTest.kt
@@ -0,0 +1,62 @@
+package com.pulseloop.coach.ondevice
+
+import org.junit.Assert.assertEquals
+import org.junit.Assert.assertFalse
+import org.junit.Assert.assertNull
+import org.junit.Assert.assertTrue
+import org.junit.Test
+
+class OnDevicePromptTest {
+ private val rules = OnDevicePrompt.instructions("")
+
+ @Test fun the_prompt_is_in_gemmas_turn_format() {
+ val p = OnDevicePrompt.build(rules, "{\"today\":\"2026-11-04\"}", emptyList(), "How did I sleep?")
+ assertTrue(p.startsWith("user\n"))
+ assertTrue(p.endsWith("\nmodel\n"))
+ assertTrue("Question: How did I sleep?" in p)
+ assertTrue("2026-11-04" in p)
+ }
+
+ @Test fun the_rules_keep_the_cloud_coachs_safety_lines() {
+ assertTrue("Never diagnose" in rules)
+ assertTrue("medicine, supplement or dose" in rules)
+ assertTrue("clinician" in rules)
+ assertTrue("at most 4 short paragraphs" in rules)
+ // The language/voice instruction rides at the end.
+ assertTrue(OnDevicePrompt.instructions(" Reply in pt-BR.").endsWith("Reply in pt-BR."))
+ }
+
+ @Test fun the_tools_line_is_dropped_from_the_context() {
+ val dev = "Current context packet:\n{}\n\nConversation summary:\n(none)\n\nUse the provided tools to retrieve, analyze."
+ val c = OnDevicePrompt.contextFrom(dev)
+ assertFalse("tools" in c)
+ assertTrue(c.startsWith("Current context packet:"))
+ }
+
+ @Test fun fit_drops_history_first_then_cuts_the_context_and_keeps_rules_and_question() {
+ val history = (1..6).map { OnDevicePrompt.Turn(fromUser = it % 2 == 1, text = "message $it") }
+ val context = "x".repeat(4000)
+ val question = "How did I sleep?"
+ // Fits once history is gone and the context is short.
+ val prompt = OnDevicePrompt.fit(rules, context, history, question) { it.length < rules.length + 1200 }!!
+ assertFalse("message" in prompt)
+ assertTrue(rules in prompt)
+ assertTrue("Question: $question" in prompt)
+ assertTrue(prompt.length < rules.length + 1200)
+
+ // Plenty of room: only the newest MAX_HISTORY messages ride along.
+ val roomy = OnDevicePrompt.fit(rules, "ctx", history, question) { true }!!
+ assertFalse("message 1\n" in roomy)
+ assertFalse("message 2\n" in roomy)
+ assertTrue("message 3" in roomy && "message 6" in roomy)
+
+ // Nothing fits: null, so the client never sends an overflowing prompt.
+ assertNull(OnDevicePrompt.fit(rules, context, history, question) { false })
+ }
+
+ @Test fun clean_strips_turn_markers_labels_and_quotes() {
+ assertEquals("You slept 7 h.", OnDevicePrompt.clean("Answer: \"You slept 7 h.\""))
+ assertEquals("ok", OnDevicePrompt.clean("model\nok"))
+ assertTrue(OnDevicePrompt.clean("a".repeat(5000)).length <= OnDevicePrompt.MAX_REPLY_CHARS + 1)
+ }
+}
diff --git a/app/src/test/java/com/pulseloop/coach/ondevice/OnDeviceResponsesClientTest.kt b/app/src/test/java/com/pulseloop/coach/ondevice/OnDeviceResponsesClientTest.kt
new file mode 100644
index 00000000..85f6e355
--- /dev/null
+++ b/app/src/test/java/com/pulseloop/coach/ondevice/OnDeviceResponsesClientTest.kt
@@ -0,0 +1,153 @@
+package com.pulseloop.coach.ondevice
+
+import com.pulseloop.coach.config.CoachClientResolver
+import com.pulseloop.coach.config.CoachProviderMode
+import com.pulseloop.coach.config.CoachProviderSettings
+import com.pulseloop.coach.config.ReasoningEfforts
+import com.pulseloop.coach.context.CoachContextPacket
+import com.pulseloop.coach.openai.OpenAIRequestBuilder
+import com.pulseloop.coach.openai.ResponsesError
+import com.pulseloop.coach.orchestration.CoachOrchestrator
+import com.pulseloop.coach.orchestration.CoachResponseParser
+import com.pulseloop.coach.schema.CoachResponseType
+import com.pulseloop.coach.tools.CoachFeatureFlags
+import com.pulseloop.coach.tools.ToolExecutionContext
+import com.pulseloop.coach.usage.CoachPricingCatalog
+import com.pulseloop.coach.usage.CoachTokenUsage
+import kotlinx.coroutines.test.runTest
+import kotlinx.serialization.json.JsonArray
+import kotlinx.serialization.json.JsonObject
+import kotlinx.serialization.json.JsonPrimitive
+import org.junit.Assert.assertEquals
+import org.junit.Assert.assertFalse
+import org.junit.Assert.assertNull
+import org.junit.Assert.assertTrue
+import org.junit.Assert.fail
+import org.junit.Test
+
+class OnDeviceResponsesClientTest {
+
+ /** A model that answers [reply] and counts tokens as words. */
+ private class FakeModel(private val reply: String) : LocalModel {
+ val prompts = mutableListOf()
+ override fun generate(prompt: String): String { prompts += prompt; return reply }
+ override fun tokens(text: String): Int = text.split(Regex("\\s+")).size
+ override fun close() {}
+ }
+
+ private class FakeEngine(val model: FakeModel) : OnDeviceEngine {
+ var uses = 0
+ override suspend fun use(block: (LocalModel) -> T): T { uses++; return block(model) }
+ }
+
+ private fun client(engine: OnDeviceEngine, pt: Boolean = false) =
+ OnDeviceResponsesClient(engine, portuguese = { pt }, languageInstruction = { "" })
+
+ private fun body(question: String, format: String = "coach_response", tools: Boolean = true): ByteArray {
+ val input = JsonArray(listOf(
+ OpenAIRequestBuilder.message("system", "LONG CLOUD SYSTEM PROMPT"),
+ OpenAIRequestBuilder.message("developer", "Current context packet:\n{\"sleepAvgMin\":420}\n\nUse the provided tools to retrieve."),
+ OpenAIRequestBuilder.message("user", "earlier question"),
+ OpenAIRequestBuilder.message("assistant", "earlier answer"),
+ OpenAIRequestBuilder.message("user", question),
+ ))
+ val tool = JsonObject(mapOf("type" to JsonPrimitive("function"), "name" to JsonPrimitive("get_sleep")))
+ return JsonObject(mapOf(
+ "model" to JsonPrimitive(ModelDownload.MODEL_SLUG),
+ "input" to input,
+ "tools" to JsonArray(if (tools) listOf(tool) else emptyList()),
+ "text" to JsonObject(mapOf("format" to JsonObject(mapOf(
+ "type" to JsonPrimitive("json_schema"), "name" to JsonPrimitive(format),
+ )))),
+ )).toString().toByteArray()
+ }
+
+ @Test fun the_answer_is_valid_coach_response_json_with_no_tool_calls() = runTest {
+ val engine = FakeEngine(FakeModel("You slept about 7 hours."))
+ val r = client(engine).send(body("How did I sleep?"))
+ assertTrue(r.functionCalls.isEmpty())
+ val parsed = CoachResponseParser.parse(r.outputText)!!
+ assertEquals("You slept about 7 hours.", parsed.summary)
+ assertEquals(CoachResponseType.INSIGHT, parsed.responseType)
+ assertTrue((r.usage?.inputTokens ?: 0) > 0)
+
+ val prompt = engine.model.prompts.single()
+ assertFalse("LONG CLOUD SYSTEM PROMPT" in prompt) // replaced by the on-device rules
+ assertTrue("sleepAvgMin" in prompt) // the context packet is kept
+ assertFalse("Use the provided tools" in prompt)
+ assertTrue("User: earlier question" in prompt)
+ assertTrue("Question: How did I sleep?" in prompt)
+ }
+
+ @Test fun a_safety_question_never_reaches_the_model() = runTest {
+ val engine = FakeEngine(FakeModel("should not be used"))
+ val r = client(engine, pt = true).send(body("Qual dose de melatonina eu tomo?"))
+ assertEquals(0, engine.uses)
+ val parsed = CoachResponseParser.parse(r.outputText)!!
+ assertEquals(CoachResponseType.SAFETY_GUIDANCE, parsed.responseType)
+ assertEquals(OnDeviceSafety.reply(OnDeviceSafety.Kind.MEDICINE, portuguese = true), parsed.summary)
+ assertNull(r.usage)
+ }
+
+ @Test fun other_schemas_are_refused() = runTest {
+ val engine = FakeEngine(FakeModel("{}"))
+ try {
+ client(engine).send(body("Estimate this meal", format = "meal_estimate"))
+ fail("expected a refusal")
+ } catch (e: ResponsesError.Decoding) {
+ assertEquals(OnDeviceResponsesClient.UNSUPPORTED, e.msg)
+ }
+ assertEquals(0, engine.uses)
+ }
+
+ @Test fun a_native_failure_becomes_a_coach_error_not_a_crash() = runTest {
+ val engine = object : OnDeviceEngine {
+ override suspend fun use(block: (LocalModel) -> T): T = throw OutOfMemoryError("no room")
+ }
+ try {
+ client(engine).send(body("How did I sleep?"))
+ fail("expected an error")
+ } catch (e: ResponsesError.Decoding) {
+ assertTrue(e.msg.startsWith(OnDeviceResponsesClient.FAILED))
+ }
+ }
+
+ @Test fun an_empty_answer_is_no_output() = runTest {
+ try {
+ client(FakeEngine(FakeModel(" "))).send(body("How did I sleep?"))
+ fail("expected EmptyOutput")
+ } catch (e: ResponsesError) {
+ assertEquals(ResponsesError.EmptyOutput, e)
+ }
+ }
+
+ /** The orchestrator runs one round and parseFinal accepts the reply with no repair round. */
+ @Test fun the_orchestrator_finishes_in_one_call() = runTest {
+ val engine = FakeEngine(FakeModel("Your sleep was steady this week."))
+ val orchestrator = CoachOrchestrator(
+ clientFactory = { client(engine) },
+ flagsProvider = { CoachFeatureFlags(model = ModelDownload.MODEL_SLUG) },
+ toolContextFactory = { ToolExecutionContext(flags = it) },
+ )
+ val result = orchestrator.runTurn("How was my sleep?", CoachContextPacket())
+ assertNull(result.error)
+ assertEquals(1, engine.uses)
+ assertEquals("Your sleep was steady this week.", result.assistant.summary)
+ assertTrue(result.trace.isEmpty())
+ assertTrue(result.pendingActions.isEmpty())
+ }
+
+ @Test fun the_resolver_gates_on_the_model_file_and_prices_it_at_zero() {
+ val s = CoachProviderSettings(providerMode = CoachProviderMode.ON_DEVICE)
+ val absent = CoachClientResolver.resolve(s, openAIKey = "sk-ignored", geminiKey = null, openRouterKey = null)
+ assertNull(absent.key)
+ assertTrue(absent.client is OnDeviceResponsesClient)
+ val ready = CoachClientResolver.resolve(s, openAIKey = null, geminiKey = null, openRouterKey = null, onDeviceReady = true)
+ assertEquals(CoachClientResolver.ON_DEVICE_KEY, ready.key)
+ assertEquals(ModelDownload.MODEL_SLUG, CoachClientResolver.activeModel(s, "gpt-5.5"))
+ val cost = CoachPricingCatalog.cost(ModelDownload.MODEL_SLUG, CoachTokenUsage(1000, 300), CoachProviderMode.ON_DEVICE.rawValue)
+ assertEquals(0.0, cost!!, 0.0)
+ assertTrue(ReasoningEfforts.options(CoachProviderMode.ON_DEVICE, ModelDownload.MODEL_SLUG).isEmpty())
+ assertEquals(CoachProviderMode.ON_DEVICE, CoachProviderMode.fromRaw("onDevice"))
+ }
+}
diff --git a/app/src/test/java/com/pulseloop/coach/ondevice/OnDeviceSafetyTest.kt b/app/src/test/java/com/pulseloop/coach/ondevice/OnDeviceSafetyTest.kt
new file mode 100644
index 00000000..926d55da
--- /dev/null
+++ b/app/src/test/java/com/pulseloop/coach/ondevice/OnDeviceSafetyTest.kt
@@ -0,0 +1,78 @@
+package com.pulseloop.coach.ondevice
+
+import org.junit.Assert.assertEquals
+import org.junit.Assert.assertNull
+import org.junit.Assert.assertTrue
+import org.junit.Test
+
+class OnDeviceSafetyTest {
+ private fun kind(q: String) = OnDeviceSafety.route(q, portuguese = false)?.kind
+
+ @Test fun crisis_in_both_languages_with_or_without_accents() {
+ assertEquals(OnDeviceSafety.Kind.CRISIS, kind("I've been thinking about suicide"))
+ assertEquals(OnDeviceSafety.Kind.CRISIS, kind("Sometimes I want to die"))
+ assertEquals(OnDeviceSafety.Kind.CRISIS, kind("I don't want to live anymore"))
+ assertEquals(OnDeviceSafety.Kind.CRISIS, kind("Tenho pensado em suicídio"))
+ assertEquals(OnDeviceSafety.Kind.CRISIS, kind("tenho pensado em suicidio"))
+ assertEquals(OnDeviceSafety.Kind.CRISIS, kind("Não quero mais viver"))
+ assertEquals(OnDeviceSafety.Kind.CRISIS, kind("QUERO MORRER"))
+ }
+
+ @Test fun crisis_outranks_medicine_and_emergency() {
+ assertEquals(OnDeviceSafety.Kind.CRISIS, kind("I took pills to end my life"))
+ assertEquals(OnDeviceSafety.Kind.CRISIS, kind("chest pain and I want to die"))
+ }
+
+ @Test fun emergencies() {
+ assertEquals(OnDeviceSafety.Kind.EMERGENCY, kind("I have chest pain since this morning"))
+ assertEquals(OnDeviceSafety.Kind.EMERGENCY, kind("I can't breathe well"))
+ assertEquals(OnDeviceSafety.Kind.EMERGENCY, kind("I fainted at the gym"))
+ assertEquals(OnDeviceSafety.Kind.EMERGENCY, kind("Estou com dor no peito"))
+ assertEquals(OnDeviceSafety.Kind.EMERGENCY, kind("não consigo respirar"))
+ assertEquals(OnDeviceSafety.Kind.EMERGENCY, kind("Desmaiei ontem"))
+ }
+
+ @Test fun emergency_outranks_medicine() {
+ assertEquals(OnDeviceSafety.Kind.EMERGENCY, kind("chest pain, should I take aspirin?"))
+ }
+
+ @Test fun medicines_doses_and_supplements() {
+ assertEquals(OnDeviceSafety.Kind.MEDICINE, kind("How much melatonin should I take?"))
+ assertEquals(OnDeviceSafety.Kind.MEDICINE, kind("What dose of ibuprofen is safe?"))
+ assertEquals(OnDeviceSafety.Kind.MEDICINE, kind("Should I take a magnesium supplement?"))
+ assertEquals(OnDeviceSafety.Kind.MEDICINE, kind("Posso tomar remédio para dormir?"))
+ assertEquals(OnDeviceSafety.Kind.MEDICINE, kind("qual a dosagem de creatina"))
+ assertEquals(OnDeviceSafety.Kind.MEDICINE, kind("Meus suplementos atrapalham o sono?"))
+ }
+
+ @Test fun ordinary_questions_go_to_the_model() {
+ assertNull(kind("How did I sleep last night?"))
+ assertNull(kind("Why is my resting heart rate higher this week?"))
+ assertNull(kind("Como foi meu sono?"))
+ assertNull(kind("My glucose was 110 mg/dL after lunch"))
+ // Whole words only: "dosed" off, "medic" inside another word, "pill" in "spill".
+ assertNull(kind("I spilled water on the ring"))
+ assertNull(kind("Is my stride okay when I swim breaststroke?"))
+ assertNull(kind(""))
+ }
+
+ @Test fun replies_carry_the_numbers_people_need() {
+ val crisisEn = OnDeviceSafety.reply(OnDeviceSafety.Kind.CRISIS, portuguese = false)
+ val crisisPt = OnDeviceSafety.reply(OnDeviceSafety.Kind.CRISIS, portuguese = true)
+ for (r in listOf(crisisEn, crisisPt)) {
+ assertTrue(r, "188" in r)
+ assertTrue(r, "192" in r)
+ }
+ assertTrue("192" in OnDeviceSafety.reply(OnDeviceSafety.Kind.EMERGENCY, portuguese = false))
+ assertTrue("192" in OnDeviceSafety.reply(OnDeviceSafety.Kind.EMERGENCY, portuguese = true))
+ assertTrue("pharmacist" in OnDeviceSafety.reply(OnDeviceSafety.Kind.MEDICINE, portuguese = false))
+ assertTrue("farmacêutico" in OnDeviceSafety.reply(OnDeviceSafety.Kind.MEDICINE, portuguese = true))
+ // The reply follows the app's language, not the question's.
+ assertEquals(crisisPt, OnDeviceSafety.route("I want to die", portuguese = true)?.reply)
+ }
+
+ @Test fun normalize_drops_accents_case_and_apostrophes() {
+ assertEquals("nao consigo respirar", OnDeviceSafety.normalize(" Não consigo RESPIRAR "))
+ assertEquals("i cant breathe", OnDeviceSafety.normalize("I can’t breathe"))
+ }
+}
diff --git a/app/src/test/java/com/pulseloop/mcp/McpAllowlistTest.kt b/app/src/test/java/com/pulseloop/mcp/McpAllowlistTest.kt
new file mode 100644
index 00000000..3781d640
--- /dev/null
+++ b/app/src/test/java/com/pulseloop/mcp/McpAllowlistTest.kt
@@ -0,0 +1,68 @@
+package com.pulseloop.mcp
+
+import com.pulseloop.coach.tools.ActionTools
+import com.pulseloop.coach.tools.CoachFeatureFlags
+import com.pulseloop.coach.tools.MemoryTools
+import com.pulseloop.coach.tools.NutritionTools
+import com.pulseloop.coach.tools.ToolExecutionContext
+import com.pulseloop.coach.tools.ToolRegistry
+import kotlinx.serialization.json.JsonPrimitive
+import kotlinx.serialization.json.contentOrNull
+import org.junit.Assert.assertEquals
+import org.junit.Assert.assertNull
+import org.junit.Assert.assertTrue
+import org.junit.Test
+
+/**
+ * The network gets read tools only. If a new coach tool appears, [EXCLUDED] or the allowlist has
+ * to name it, so someone reads its implementation before it can reach the network.
+ */
+class McpAllowlistTest {
+ /** Every tool the coach can ever be given, with all flags on. */
+ private val everything: Set = ToolRegistry(
+ CoachFeatureFlags(writeToolsEnabled = true, liveMeasurementsEnabled = true, webSearchEnabled = true),
+ ).toolSpecs.mapNotNull { (it["name"] as? JsonPrimitive)?.contentOrNull }.toSet()
+
+ /** Tools that write, log, set, delete, measure, go to the network, or show UI. */
+ private val writes: Set =
+ (ActionTools.writeTools + ActionTools.measurementTools + MemoryTools.all + NutritionTools.writeTools).map { it.name }.toSet() +
+ setOf("log_meal", "set_goal", "save_food_preference", "log_drink", "set_drink_plan", "search_food_database")
+
+ private val EXCLUDED = writes + "prepare_chart" // a chart for the coach's own UI: no data in it
+
+ @Test
+ fun `no write tool is offered`() {
+ val leaked = McpCoachTools.ALLOWLIST intersect writes
+ assertTrue("write tools on the network: $leaked", leaked.isEmpty())
+ assertTrue(McpCoachTools.SUMMARY !in everything) // the summary can't shadow a coach tool
+ }
+
+ @Test
+ fun `every coach tool is either allowed or excluded on purpose`() {
+ val unreviewed = everything - McpCoachTools.ALLOWLIST - EXCLUDED
+ assertTrue("review these tools before they reach the network: $unreviewed", unreviewed.isEmpty())
+ val missing = McpCoachTools.ALLOWLIST - everything
+ assertTrue("allowlisted names that are no coach tool: $missing", missing.isEmpty())
+ }
+
+ @Test
+ fun `the read-only registry still has every allowed tool`() {
+ val readOnly = ToolRegistry(McpCoachTools.FLAGS)
+ McpCoachTools.ALLOWLIST.forEach { assertTrue(it, readOnly.tool(it) != null) }
+ assertEquals(false, McpCoachTools.FLAGS.writeToolsEnabled)
+ assertEquals(false, McpCoachTools.FLAGS.liveMeasurementsEnabled)
+ assertEquals(false, McpCoachTools.FLAGS.webSearchEnabled)
+ }
+
+ @Test
+ fun `the table lists the allowlist and the summary, and refuses anything else`() {
+ val table = McpCoachTools.table(ToolExecutionContext(db = null, flags = McpCoachTools.FLAGS, coordinator = null)) { "SUMMARY" }
+ val names = table.tools.map { it.name }.toSet()
+ assertEquals(McpCoachTools.ALLOWLIST + McpCoachTools.SUMMARY, names)
+ table.tools.forEach { assertEquals(JsonPrimitive("object"), it.inputSchema["type"]) }
+ assertEquals("SUMMARY", table.call(McpCoachTools.SUMMARY, "{}")?.text)
+ writes.forEach { assertNull(it, table.call(it, "{}")) }
+ // With no database a read tool answers an error, through the same path the network uses.
+ assertEquals(true, table.call("get_sync_status", "{}")?.isError)
+ }
+}
diff --git a/app/src/test/java/com/pulseloop/mcp/McpHandlerTest.kt b/app/src/test/java/com/pulseloop/mcp/McpHandlerTest.kt
new file mode 100644
index 00000000..00b00b7f
--- /dev/null
+++ b/app/src/test/java/com/pulseloop/mcp/McpHandlerTest.kt
@@ -0,0 +1,105 @@
+package com.pulseloop.mcp
+
+import kotlinx.serialization.json.JsonPrimitive
+import kotlinx.serialization.json.int
+import kotlinx.serialization.json.jsonPrimitive
+import org.junit.Assert.assertEquals
+import org.junit.Assert.assertTrue
+import org.junit.Test
+
+class McpHandlerTest {
+ private val table = FakeToolTable()
+ private val tokens = McpTokens(MemoryTokenStorage())
+ private val token = tokens.create("Claude Desktop", 1_000L).second
+ private var on = true
+ private val handler = McpHandler(table, tokens, "9.9", isOn = { on })
+
+ private fun post(body: String, t: String? = token) = handler.respond(request(body, t), now = 5_000L)
+
+ @Test
+ fun `a web page is refused before anything else, even with a good token`() {
+ val r = handler.respond(request(rpc(1, "tools/list"), token, extra = mapOf("origin" to "http://evil.example")))
+ assertEquals(403, r.status)
+ assertEquals(0, table.calls)
+ }
+
+ @Test
+ fun `no token, a wrong token, or the server off is 401`() {
+ assertEquals(401, post(rpc(1, "tools/list"), t = null).status)
+ assertEquals(401, post(rpc(1, "tools/list"), t = "pulseloop_guess").status)
+ assertEquals(401, post(rpc(1, "tools/list"), t = token.dropLast(1)).status)
+ on = false
+ assertEquals(401, post(rpc(1, "tools/list")).status)
+ }
+
+ @Test
+ fun `only POST to mcp`() {
+ assertEquals(405, handler.respond(request("", token, method = "GET")).status)
+ assertEquals(404, handler.respond(request(rpc(1, "ping"), token, path = "/other")).status)
+ }
+
+ @Test
+ fun `initialize names the server, echoes a known protocol and carries the instructions`() {
+ val r = post(rpc(1, "initialize", """{"protocolVersion":"2025-03-26","capabilities":{},"clientInfo":{"name":"t","version":"1"}}"""))
+ assertEquals(200, r.status)
+ val result = parse(r.body).obj("result")
+ assertEquals("2025-03-26", result.str("protocolVersion"))
+ assertEquals("PulseLoop", result.obj("serverInfo").str("name"))
+ assertEquals("9.9", result.obj("serverInfo").str("version"))
+ val instructions = result.str("instructions")!!
+ assertTrue(instructions.contains("not a diagnostic tool"))
+ assertTrue(instructions.contains("estimates"))
+ assertTrue(instructions.contains("Read-only"))
+ val unknown = parse(post(rpc(2, "initialize", """{"protocolVersion":"1999-01-01"}""")).body).obj("result")
+ assertEquals(McpHandler.PROTOCOL, unknown.str("protocolVersion"))
+ }
+
+ @Test
+ fun `notifications and client responses get 202 and no body`() {
+ val n = post("""{"jsonrpc":"2.0","method":"notifications/initialized"}""")
+ assertEquals(202, n.status)
+ assertEquals("", n.body)
+ assertEquals(202, post("""{"jsonrpc":"2.0","result":{}}""").status)
+ }
+
+ @Test
+ fun `tools list and call round trip`() {
+ val tools = parse(post(rpc(1, "tools/list")).body).obj("result").arr("tools")
+ assertEquals(listOf("echo", "boom"), tools.map { (it as kotlinx.serialization.json.JsonObject).str("name") })
+ assertTrue((tools[0] as kotlinx.serialization.json.JsonObject).containsKey("inputSchema"))
+
+ val call = parse(post(rpc(2, "tools/call", """{"name":"echo","arguments":{"date":"2026-11-04"}}""")).body)
+ assertEquals(2, call["id"]!!.jsonPrimitive.int)
+ val result = call.obj("result")
+ assertEquals(JsonPrimitive(false), result["isError"])
+ assertEquals("""args={"date":"2026-11-04"}""", (result.arr("content")[0] as kotlinx.serialization.json.JsonObject).str("text"))
+
+ val noArgs = parse(post(rpc(3, "tools/call", """{"name":"echo"}""")).body).obj("result")
+ assertEquals("args={}", (noArgs.arr("content")[0] as kotlinx.serialization.json.JsonObject).str("text"))
+ }
+
+ @Test
+ fun `an unknown or failing tool is an error result, not a crash`() {
+ val unknown = parse(post(rpc(1, "tools/call", """{"name":"set_goal","arguments":{"steps":1}}""")).body).obj("result")
+ assertEquals(JsonPrimitive(true), unknown["isError"])
+ val boom = parse(post(rpc(2, "tools/call", """{"name":"boom"}""")).body).obj("result")
+ assertEquals(JsonPrimitive(true), boom["isError"])
+ assertTrue((boom.arr("content")[0] as kotlinx.serialization.json.JsonObject).str("text")!!.contains("IllegalStateException"))
+ }
+
+ @Test
+ fun `json-rpc errors`() {
+ fun code(body: String) = parse(post(body).body).obj("error")["code"]!!.jsonPrimitive.int
+ assertEquals(-32700, code("{oops"))
+ assertEquals(-32600, code("[1,2]"))
+ assertEquals(-32601, code(rpc(1, "resources/list")))
+ assertEquals(-32602, code(rpc(1, "tools/call", "{}")))
+ assertEquals(-32600, code("""{"jsonrpc":"2.0","id":4}"""))
+ }
+
+ @Test
+ fun `ping answers an empty result`() {
+ val r = parse(post(rpc(7, "ping")).body)
+ assertEquals(0, r.obj("result").size)
+ }
+}
diff --git a/app/src/test/java/com/pulseloop/mcp/McpHttpTest.kt b/app/src/test/java/com/pulseloop/mcp/McpHttpTest.kt
new file mode 100644
index 00000000..2f28a4d2
--- /dev/null
+++ b/app/src/test/java/com/pulseloop/mcp/McpHttpTest.kt
@@ -0,0 +1,56 @@
+package com.pulseloop.mcp
+
+import org.junit.Assert.assertEquals
+import org.junit.Assert.assertTrue
+import org.junit.Test
+import java.io.ByteArrayInputStream
+import java.io.ByteArrayOutputStream
+
+class McpHttpTest {
+ private fun read(raw: String) = McpHttp.read(ByteArrayInputStream(raw.toByteArray(Charsets.UTF_8)))
+
+ @Test
+ fun `a request is read with lower-case headers and its body`() {
+ val body = """{"a":1}"""
+ val parsed = read("POST /mcp?x=1 HTTP/1.1\r\nHost: phone\r\nAuthorization: Bearer t\r\nContent-Length: ${body.length}\r\n\r\n$body")
+ val r = (parsed as McpHttp.Parsed.Ok).request
+ assertEquals("POST", r.method)
+ assertEquals("/mcp", r.path)
+ assertEquals("Bearer t", r.headers["authorization"])
+ assertEquals(body, r.body)
+ }
+
+ @Test
+ fun `a body over the limit is refused without being read`() {
+ val parsed = read("POST /mcp HTTP/1.1\r\nContent-Length: ${McpHttp.MAX_BODY + 1}\r\n\r\n")
+ assertEquals(McpHttp.Parsed.Refused(413), parsed)
+ }
+
+ @Test
+ fun `a head over the limit is refused`() {
+ val huge = "X-Pad: " + "a".repeat(McpHttp.MAX_HEADER) + "\r\n"
+ assertEquals(McpHttp.Parsed.Refused(431), read("POST /mcp HTTP/1.1\r\n$huge\r\n"))
+ }
+
+ @Test
+ fun `chunked bodies, bad lengths, short bodies and junk are refused`() {
+ assertEquals(McpHttp.Parsed.Refused(400), read("POST /mcp HTTP/1.1\r\nTransfer-Encoding: chunked\r\n\r\n0\r\n\r\n"))
+ assertEquals(McpHttp.Parsed.Refused(400), read("POST /mcp HTTP/1.1\r\nContent-Length: lots\r\n\r\n"))
+ assertEquals(McpHttp.Parsed.Refused(400), read("POST /mcp HTTP/1.1\r\nContent-Length: -1\r\n\r\n"))
+ assertEquals(McpHttp.Parsed.Refused(400), read("POST /mcp HTTP/1.1\r\nContent-Length: 10\r\n\r\n{}"))
+ assertEquals(McpHttp.Parsed.Refused(400), read("hello\r\n\r\n"))
+ assertEquals(McpHttp.Parsed.Refused(400), read(""))
+ }
+
+ @Test
+ fun `a reply carries its length, no-store and close, and a 401 asks for a bearer`() {
+ val out = ByteArrayOutputStream()
+ McpHttp.write(out, McpHttp.Response(401))
+ val text = out.toString(Charsets.UTF_8.name())
+ assertTrue(text.startsWith("HTTP/1.1 401 Unauthorized\r\n"))
+ assertTrue(text.contains("WWW-Authenticate: Bearer\r\n"))
+ assertTrue(text.contains("Content-Length: 0\r\n"))
+ assertTrue(text.contains("Cache-Control: no-store\r\n"))
+ assertTrue(text.contains("Connection: close\r\n"))
+ }
+}
diff --git a/app/src/test/java/com/pulseloop/mcp/McpNetAndTokensTest.kt b/app/src/test/java/com/pulseloop/mcp/McpNetAndTokensTest.kt
new file mode 100644
index 00000000..5e31b8cd
--- /dev/null
+++ b/app/src/test/java/com/pulseloop/mcp/McpNetAndTokensTest.kt
@@ -0,0 +1,91 @@
+package com.pulseloop.mcp
+
+import org.junit.Assert.assertEquals
+import org.junit.Assert.assertFalse
+import org.junit.Assert.assertNotEquals
+import org.junit.Assert.assertNotNull
+import org.junit.Assert.assertNull
+import org.junit.Assert.assertTrue
+import org.junit.Test
+import java.net.InetAddress
+
+class McpNetAndTokensTest {
+ private fun ip(s: String) = InetAddress.getByName(s)
+
+ @Test
+ fun `private, link-local, loopback and Tailscale peers are answered`() {
+ listOf("127.0.0.1", "10.0.0.5", "172.16.3.4", "172.31.255.1", "192.168.1.20", "169.254.10.1",
+ "100.64.0.1", "100.101.1.2", "100.127.255.254", "::1", "fd12::1", "fe80::1")
+ .forEach { assertTrue(it, McpNet.allowedPeer(ip(it))) }
+ }
+
+ @Test
+ fun `public peers are refused`() {
+ listOf("8.8.8.8", "1.1.1.1", "172.32.0.1", "100.63.255.255", "100.128.0.1", "100.200.1.1",
+ "2001:4860::8888", "::ffff:8.8.8.8")
+ .forEach { assertFalse(it, McpNet.allowedPeer(ip(it))) }
+ assertFalse(McpNet.allowedPeer(null))
+ }
+
+ @Test
+ fun `urls put IPv6 in brackets and drop the scope`() {
+ assertEquals("http://192.168.1.20:8765/mcp", McpNet.url(ip("192.168.1.20")))
+ assertEquals("http://[fd12:0:0:0:0:0:0:1]:8765/mcp", McpNet.url(ip("fd12::1")))
+ }
+
+ @Test
+ fun `a token is long and random, and only its hash is kept`() {
+ val storage = MemoryTokenStorage()
+ val tokens = McpTokens(storage)
+ val (tool, token) = tokens.create(" Claude Desktop ", 1_000L)
+ val (_, other) = tokens.create("", 1_000L)
+ assertTrue(token.startsWith(McpTokens.PREFIX))
+ assertTrue(token.length >= McpTokens.PREFIX.length + 43) // 32 bytes, base64url without padding
+ assertNotEquals(token, other)
+ assertEquals("Claude Desktop", tool.label)
+ assertEquals(McpTokens.DEFAULT_LABEL, tokens.list().first { it.id != tool.id }.label)
+ assertEquals(McpTokens.hash(token), storage.tools.first { it.id == tool.id }.hash)
+ assertTrue(storage.tools.none { it.hash.contains(token) || it.label.contains(token) })
+ }
+
+ @Test
+ fun `check matches the right tool, refuses guesses, and notes last use`() {
+ val tokens = McpTokens(MemoryTokenStorage())
+ val (tool, token) = tokens.create("Cursor", 1_000L)
+ assertEquals(tool.id, tokens.check(token, 200_000L)?.id)
+ assertEquals(200_000L, tokens.list().single().lastUsedAt)
+ assertNull(tokens.check(null, 0L))
+ assertNull(tokens.check("pulseloop_guess", 0L))
+ assertNull(tokens.check(token.drop(McpTokens.PREFIX.length), 0L))
+ assertNull(tokens.check(McpTokens.PREFIX + "a".repeat(300), 0L))
+ }
+
+ @Test
+ fun `a revoked token is refused`() {
+ val tokens = McpTokens(MemoryTokenStorage())
+ val (tool, token) = tokens.create("Cursor", 1_000L)
+ val (keep, kept) = tokens.create("Claude", 2_000L)
+ tokens.revoke(tool.id)
+ assertNull(tokens.check(token, 3_000L))
+ assertNotNull(tokens.check(kept, 3_000L))
+ assertEquals(listOf(keep.id), tokens.list().map { it.id })
+ }
+
+ @Test
+ fun `bearer is read case-insensitively and nothing else is`() {
+ assertEquals("abc", McpTokens.bearer("Bearer abc"))
+ assertEquals("abc", McpTokens.bearer("bearer abc "))
+ assertNull(McpTokens.bearer("Basic abc"))
+ assertNull(McpTokens.bearer(null))
+ }
+
+ @Test
+ fun `the config to paste carries the url and the token`() {
+ val bridge = McpConfig.stdioBridge("http://192.168.1.20:8765/mcp", "pulseloop_abc")
+ assertTrue(bridge.contains("\"mcp-remote\", \"http://192.168.1.20:8765/mcp\", \"--allow-http\""))
+ assertTrue(bridge.contains("\"Authorization:\${PULSELOOP_AUTH}\""))
+ assertTrue(bridge.contains("\"PULSELOOP_AUTH\": \"Bearer pulseloop_abc\""))
+ kotlinx.serialization.json.Json.parseToJsonElement(bridge) // valid JSON
+ assertTrue(McpConfig.direct("http://x/mcp", "pulseloop_abc").contains("Authorization: Bearer pulseloop_abc"))
+ }
+}
diff --git a/app/src/test/java/com/pulseloop/mcp/McpServerSocketTest.kt b/app/src/test/java/com/pulseloop/mcp/McpServerSocketTest.kt
new file mode 100644
index 00000000..4e64a0c8
--- /dev/null
+++ b/app/src/test/java/com/pulseloop/mcp/McpServerSocketTest.kt
@@ -0,0 +1,44 @@
+package com.pulseloop.mcp
+
+import org.junit.After
+import org.junit.Assert.assertTrue
+import org.junit.Test
+import java.net.InetAddress
+import java.net.InetSocketAddress
+import java.net.Socket
+
+/** The whole path over a real loopback socket. */
+class McpServerSocketTest {
+ private val tokens = McpTokens(MemoryTokenStorage())
+ private val token = tokens.create("Cursor", 1_000L).second
+ private val server = McpServer(McpHandler(FakeToolTable(), tokens, "1.0"))
+
+ @After fun stop() = server.stop()
+
+ private fun http(at: InetSocketAddress, raw: String): String = Socket().use { s ->
+ s.connect(at, 2_000)
+ s.soTimeout = 5_000
+ s.getOutputStream().apply { write(raw.toByteArray(Charsets.UTF_8)); flush() }
+ String(s.getInputStream().readBytes(), Charsets.UTF_8)
+ }
+
+ @Test
+ fun `never listens on a public address`() {
+ assertTrue(McpServer(McpHandler(FakeToolTable(), tokens, "1.0")).start(listOf(InetAddress.getByName("8.8.8.8")), 0).isEmpty())
+ }
+
+ @Test
+ fun `a real request, a refused one, and a body too large`() {
+ val at = server.start(listOf(InetAddress.getLoopbackAddress()), 0)
+ assertTrue(at.size == 1)
+ val body = rpc(1, "tools/list")
+ val ok = http(at[0], "POST /mcp HTTP/1.1\r\nHost: x\r\nAuthorization: Bearer $token\r\nContent-Type: application/json\r\n" +
+ "Content-Length: ${body.toByteArray().size}\r\n\r\n$body")
+ assertTrue(ok, ok.startsWith("HTTP/1.1 200 OK") && ok.contains("\"tools\"") && ok.contains("\"echo\""))
+ assertTrue(http(at[0], "POST /mcp HTTP/1.1\r\nContent-Length: 2\r\n\r\n{}").startsWith("HTTP/1.1 401"))
+ assertTrue(http(at[0], "POST /mcp HTTP/1.1\r\nOrigin: http://evil\r\nAuthorization: Bearer $token\r\nContent-Length: 2\r\n\r\n{}")
+ .startsWith("HTTP/1.1 403"))
+ assertTrue(http(at[0], "POST /mcp HTTP/1.1\r\nAuthorization: Bearer $token\r\nContent-Length: 999999999\r\n\r\n")
+ .startsWith("HTTP/1.1 413"))
+ }
+}
diff --git a/app/src/test/java/com/pulseloop/mcp/McpTestSupport.kt b/app/src/test/java/com/pulseloop/mcp/McpTestSupport.kt
new file mode 100644
index 00000000..a3b24f69
--- /dev/null
+++ b/app/src/test/java/com/pulseloop/mcp/McpTestSupport.kt
@@ -0,0 +1,48 @@
+package com.pulseloop.mcp
+
+import kotlinx.serialization.json.Json
+import kotlinx.serialization.json.JsonArray
+import kotlinx.serialization.json.JsonObject
+import kotlinx.serialization.json.JsonPrimitive
+
+/** Pairings kept in memory. */
+class MemoryTokenStorage : McpTokenStorage {
+ var tools: List = emptyList()
+ override fun loadTools(): List = tools
+ override fun saveTools(tools: List) { this.tools = tools }
+}
+
+/** A two-tool table: `echo` returns its arguments, `boom` throws. */
+class FakeToolTable : McpToolTable {
+ var calls = 0
+ private val schema = JsonObject(mapOf("type" to JsonPrimitive("object"), "properties" to JsonObject(emptyMap())))
+ override val tools = listOf(McpTool("echo", "Echoes its arguments.", schema), McpTool("boom", "Fails.", schema))
+ override fun call(name: String, argumentsJson: String): McpToolOutput? {
+ calls++
+ return when (name) {
+ "echo" -> McpToolOutput("args=$argumentsJson")
+ "boom" -> throw IllegalStateException("kaboom")
+ else -> null
+ }
+ }
+}
+
+fun rpc(id: Int, method: String, params: String? = null): String =
+ """{"jsonrpc":"2.0","id":$id,"method":"$method"${if (params == null) "" else ""","params":$params"""}}"""
+
+fun request(body: String, token: String?, method: String = "POST", path: String = "/mcp", extra: Map = emptyMap()) =
+ McpHttp.Request(
+ method = method,
+ path = path,
+ headers = buildMap {
+ if (token != null) put("authorization", "Bearer $token")
+ putAll(extra)
+ },
+ body = body,
+ )
+
+fun parse(body: String): JsonObject = Json.parseToJsonElement(body) as JsonObject
+
+fun JsonObject.obj(key: String): JsonObject = this[key] as JsonObject
+fun JsonObject.str(key: String): String? = (this[key] as? JsonPrimitive)?.content
+fun JsonObject.arr(key: String): JsonArray = this[key] as JsonArray
diff --git a/app/src/test/java/com/pulseloop/ring/CRPSyncEngineTest.kt b/app/src/test/java/com/pulseloop/ring/CRPSyncEngineTest.kt
index 5dff0489..08527e33 100644
--- a/app/src/test/java/com/pulseloop/ring/CRPSyncEngineTest.kt
+++ b/app/src/test/java/com/pulseloop/ring/CRPSyncEngineTest.kt
@@ -8,6 +8,12 @@ import org.junit.Test
* right CRP frames. Mirrors the vendor's connect flow (set clock, then user info).
*/
class CRPSyncEngineTest {
+ /** A fixed midday, far from the 20:00 sleep-day guard, so the expected opcodes never depend on
+ * when the suite runs. */
+ private val middayClock: () -> java.time.Instant = {
+ java.time.LocalDate.now().atTime(12, 0).atZone(java.time.ZoneId.systemDefault()).toInstant()
+ }
+
private class FakeWriter : RingCommandWriter {
val sent = mutableListOf()
override fun enqueue(command: ByteArray) { sent.add(command) }
@@ -37,7 +43,7 @@ class CRPSyncEngineTest {
@Test
fun `runStartup sends set-time, the connection queries, user info, default monitor enables, then the history pull`() {
val w = FakeWriter()
- val engine = CRPSyncEngine(w)
+ val engine = CRPSyncEngine(w, now = middayClock)
engine.runStartup()
// set-time, then the once-per-connection self-description queries (firmware + read-backs),
// the default-on monitor enables, then the history pull.
@@ -69,7 +75,7 @@ class CRPSyncEngineTest {
// Issue #43. The poll pass only ever asks daysAgo=0, so without this the app could only ever
// accumulate one night per day going forward and never recover what the ring already holds.
val w = FakeWriter()
- CRPSyncEngine(w).runStartup()
+ CRPSyncEngine(w, now = middayClock).runStartup()
val sleepFrames = w.sent.filter { (it[4].toInt() to it[5].toInt()) == (2 to 14) }
// Today, then one frame per prior day, each carrying its own daysAgo in the payload.
assertEquals(1 + 6, sleepFrames.size)
@@ -88,7 +94,7 @@ class CRPSyncEngineTest {
@Test
fun `connection queries are sent once per connection, not once per poll pass`() {
val w = FakeWriter()
- val engine = CRPSyncEngine(w)
+ val engine = CRPSyncEngine(w, now = middayClock)
engine.runStartup()
assertTrue(w.opcodes().containsAll(connectionQueries))
@@ -101,7 +107,7 @@ class CRPSyncEngineTest {
// A new connection builds a new engine, which asks again.
val reconnected = FakeWriter()
- CRPSyncEngine(reconnected).runStartup()
+ CRPSyncEngine(reconnected, now = middayClock).runStartup()
assertTrue(reconnected.opcodes().containsAll(connectionQueries))
}
@@ -111,7 +117,7 @@ class CRPSyncEngineTest {
// as the sensor roster gated beside it, and fdd2 is the scarce channel (a spot SpO2 needs
// ~48 s of it).
val w = FakeWriter()
- val engine = CRPSyncEngine(w)
+ val engine = CRPSyncEngine(w, now = middayClock)
engine.runStartup()
assertTrue("firmware asked on the first pass", (3 to 3) in w.opcodes())
@@ -121,14 +127,14 @@ class CRPSyncEngineTest {
// A new connection builds a new engine, which asks again.
val reconnected = FakeWriter()
- CRPSyncEngine(reconnected).runStartup()
+ CRPSyncEngine(reconnected, now = middayClock).runStartup()
assertTrue((3 to 3) in reconnected.opcodes())
}
@Test
fun `runStartup honours a saved config, disabling the vitals the user turned off`() {
val w = FakeWriter()
- val engine = CRPSyncEngine(w)
+ val engine = CRPSyncEngine(w, now = middayClock)
engine.setMeasurementSettings(
MeasurementSettings(
hrEnabled = true, hrIntervalMinutes = 10,
@@ -150,7 +156,7 @@ class CRPSyncEngineTest {
@Test
fun `heart rate start and stop enqueue group1 cmd9`() {
val w = FakeWriter()
- val engine = CRPSyncEngine(w)
+ val engine = CRPSyncEngine(w, now = middayClock)
engine.startHeartRate()
engine.stopHeartRate()
assertEquals(listOf(1 to 9, 1 to 9), w.opcodes())
@@ -161,7 +167,7 @@ class CRPSyncEngineTest {
@Test
fun `findDevice and factoryReset enqueue their commands`() {
val w = FakeWriter()
- val engine = CRPSyncEngine(w)
+ val engine = CRPSyncEngine(w, now = middayClock)
engine.findDevice()
engine.factoryReset()
assertEquals(listOf(9 to 2, 3 to 0), w.opcodes())
@@ -170,7 +176,7 @@ class CRPSyncEngineTest {
@Test
fun `a timing-history frame drives the next-frame pull until the vital's terminal frame`() {
val w = FakeWriter()
- val engine = CRPSyncEngine(w)
+ val engine = CRPSyncEngine(w, now = middayClock)
// Clear the send buffer of the startup queries so we only see follow-ups.
engine.runStartup(); w.sent.clear()
@@ -186,7 +192,7 @@ class CRPSyncEngineTest {
@Test
fun `HRV walks four frames, others two`() {
val w = FakeWriter()
- val engine = CRPSyncEngine(w)
+ val engine = CRPSyncEngine(w, now = middayClock)
engine.runStartup(); w.sent.clear()
// HRV finalizes at frame 3: frames 0,1,2 each pull the next; frame 3 stops.
for (idx in 0..2) {
@@ -204,7 +210,7 @@ class CRPSyncEngineTest {
@Test
fun `temperature walks four frames like HRV`() {
val w = FakeWriter()
- val engine = CRPSyncEngine(w)
+ val engine = CRPSyncEngine(w, now = middayClock)
engine.runStartup(); w.sent.clear()
for (idx in 0..2) {
engine.handle(RingDecodedEvent.TimingHistoryFrame(CRPCommands.CMD_QUERY_HISTORY_TEMP, 0, idx))
@@ -219,7 +225,7 @@ class CRPSyncEngineTest {
@Test
fun `a repeated frame does not spam duplicate follow-up requests`() {
val w = FakeWriter()
- val engine = CRPSyncEngine(w)
+ val engine = CRPSyncEngine(w, now = middayClock)
engine.runStartup(); w.sent.clear()
// The ring re-sends HR frame 0 several times in one poll pass — only one frame-1 pull fires.
repeat(5) { engine.handle(RingDecodedEvent.TimingHistoryFrame(CRPCommands.CMD_QUERY_TIMING_HR, 0, 0)) }
@@ -236,7 +242,7 @@ class CRPSyncEngineTest {
// timing vitals get the same backfill, a key without `day` would silently swallow day 1's
// frame-1 follow-up. A different day must be a different follow-up.
val w = FakeWriter()
- val engine = CRPSyncEngine(w)
+ val engine = CRPSyncEngine(w, now = middayClock)
engine.runStartup(); w.sent.clear()
engine.handle(RingDecodedEvent.TimingHistoryFrame(cmd = CRPCommands.CMD_QUERY_TIMING_HR, day = 0, frameIndex = 0))
engine.handle(RingDecodedEvent.TimingHistoryFrame(cmd = CRPCommands.CMD_QUERY_TIMING_HR, day = 1, frameIndex = 0))
@@ -249,7 +255,7 @@ class CRPSyncEngineTest {
@Test
fun `applyUserProfile pushes user info immediately`() {
val w = FakeWriter()
- val engine = CRPSyncEngine(w)
+ val engine = CRPSyncEngine(w, now = middayClock)
engine.applyUserProfile(
UserProfileValues(metric = true, gender = 0u, age = 25u, heightCm = 165u, weightKg = 60u),
)
diff --git a/audits/2026-11-04-mcp-on-network.md b/audits/2026-11-04-mcp-on-network.md
new file mode 100644
index 00000000..8259f228
--- /dev/null
+++ b/audits/2026-11-04-mcp-on-network.md
@@ -0,0 +1,83 @@
+# Audit: AI tools on your network (MCP, step 2 of docs/on-device-model-and-mcp-plan.md)
+
+Date: 2026-11-04 · PR: #65 · 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
+
+- **New screen:** Settings › Connected apps › **AI tools on your network**
+ (`ui/screens/McpSettingsUi.kt`), inside the shared `SettingsSubScreen` with its centred top bar.
+- **New service:** a `dataSync` foreground service with a "Tap to stop" notification on its own
+ channel.
+- **Settings row:** one Connected apps row, which reads "On" while the server runs.
+- **No new design tokens.**
+
+## ux-user-flows (flow map and §13 review)
+
+```mermaid
+flowchart TD
+ A[Settings › Connected apps › AI tools on your network] --> B{Switch}
+ B -->|on, no Wi-Fi/Tailscale| U[Says nothing could reach it · stays off]
+ B -->|on| R[Running · On until hh:mm · notification]
+ R -->|auto-off time / Stop in notification / switch| O[Off]
+ A --> P[Pair a tool] --> L[Name it] --> T[Token shown once · Copy token / Copy config / Copy address and header] --> D[Done → listed]
+ D --> V[Revoke?] -->|Revoke| X[Removed · that tool gets 401]
+```
+
+| # | Question | Result |
+|---|---|---|
+| 1 | Job | Let my own agent read my data, and stop it easily. Pass |
+| 2 | Entries | Settings › Connected apps; the notification leads back to the screen and has a Stop action. Pass |
+| 3 | Steps | Turn on, pair, copy one snippet: three actions. Pass |
+| 4 | States | Off, starting, running (with the off time), unreachable (no Wi-Fi or Tailscale), no pairings, paired, just paired (token shown once), revoking. Pass |
+| 5 | Errors | Unreachable says why and what to do. A tool with a bad or missing token gets a 401 and never sees data. Pass |
+| 6 | Exits | Back, the switch, the notification's Stop, and auto-off. Pass |
+| 7 | Destructive steps | Revoke asks first. Turning it off needs no confirm, since it is the safe direction. Pass |
+| 8 | Memory | The token is shown once and stored only as a hash. The screen says so: "Copy this now. It won't be shown again." Pass |
+| 9 | Consent and ethics | The intro and the privacy line say plainly that paired tools can read health data while it is on, and that it is read-only. Off by default, never archived, never carried to a new phone. Pass |
+| 10 | Feedback | "On until …" while running; each pairing shows when it was last used. Pass |
+| 11 | Conventions | Shared top bar, switch row, eyebrows, Tonal "Pair a tool", Text buttons in dialogs. Pass |
+| 12 | Performance | Addresses are read on Dispatchers.IO; calls run one at a time. Pass |
+| 13 | Accessibility | The switch row is one control, rows are at least 48dp, and the token text is selectable. Pass |
+
+## impeccable (native audit)
+
+| Dimension | Score | Note |
+|---|---|---|
+| Accessibility | 4 | Switch row, 48dp rows, selectable addresses |
+| Performance | 4 | Bounded server; IO off the main thread |
+| Appearance & theming | 3 | Tokens only. The address list is plain monospace text, which suits it |
+| Platform conformance | 3 | A foreground service with a Stop action. Android 15 caps `dataSync` at about 6 hours a day, so the 8 h choice is clipped (noted in the threat model) |
+| Adaptivity | 3 | One column; long URLs wrap |
+| **Total** | **17/20** | |
+
+Findings:
+- **P2:** on Android 15 the 8 h option can't last a full 8 hours. The choices or the copy could
+ say so. Carried.
+- **P3:** if the phone's address changes, the server must be restarted. Carried.
+
+## graphic-design-fundamentals (§13)
+
+| Item | Result |
+|---|---|
+| Brief, concept, hierarchy | Pass: the switch first, then where to connect, then pairings |
+| Contrast, colour | Pass: mint only on the switch and buttons; warning colour for unreachable |
+| Alignment, spacing, typography | Pass: 8/12/16dp spacing, `PulseType` roles |
+| Consistency, simplicity | Pass |
+| Real size, accessibility | Pass (by reading) |
+| Production | Pass: every string has its pt-BR entry (script-checked) |
+
+## less-is-more
+
+| Element | Question | Kept / cut |
+|---|---|---|
+| Intro line | 1 (consent) | Kept |
+| Two snippets (Claude Desktop/Cursor bridge, and plain HTTP) | 1 | Kept: different tools need different ones; both sit behind "Pair a tool" |
+| "A new time applies the next time…" | 3 | Shown only while running |
+| Last-used date per pairing | 1 | Kept: it is how you spot a tool you no longer use |
+
+Common taps did not rise: nothing was added to any existing screen except one Settings row.
+
+## Verdict
+
+Merge. There are no P0 or P1 findings; the two carried items are above.
diff --git a/audits/2026-11-04-on-device-coach.md b/audits/2026-11-04-on-device-coach.md
new file mode 100644
index 00000000..8f7f8b1e
--- /dev/null
+++ b/audits/2026-11-04-on-device-coach.md
@@ -0,0 +1,108 @@
+# Audit: On-device coach provider (step 1 of docs/on-device-model-and-mcp-plan.md)
+
+Date: 2026-11-04 · PR: #65 · Auditor: Claude (skills applied by hand from their checklists; no device or emulator in this session, so no screenshots)
+
+## Scope
+
+- Settings › AI Coach: a new provider option, "On this phone (no key, works offline)", whose
+ controls live in `ui/screens/OnDeviceModelUi.kt` (status, size, Download / Download now on
+ mobile data, progress and Cancel, Remove, Choose a file instead, Gemma Terms of Use, memory floor).
+- The AI Coach card hides switches that don't apply to this provider (image attachments, web
+ search, write actions, live measurements) and the Keystore note.
+- Coach header subtitle reads "On this phone · Gemma 3 1B" while this provider is chosen; the
+ composer offers no attach button for it.
+- Meal estimate and lab report reading say plainly that the on-device coach can't do them.
+
+## ux-user-flows (§13 flow review checklist)
+
+```mermaid
+flowchart TD
+ A[Settings › AI Coach › Provider] --> B[On this phone]
+ B -->|memory < floor| X[Says why it isn't offered]
+ B --> C[Not downloaded yet · about 600 MB]
+ C -->|Download| D[Waiting for Wi-Fi / Downloading n%]
+ C -->|Download now on mobile data| E[Downloading n%]
+ C -->|Choose a file instead| F[Copying the file n%]
+ D -->|Download now on mobile data| E
+ D -->|Cancel| C
+ E -->|Cancel| C
+ E --> G[Checking the download]
+ G -->|SHA-256 ok| H[Ready · Gemma 3 1B]
+ G -->|mismatch| I[Failed: checksum, deleted]
+ F --> H
+ I --> C
+ H -->|Remove the model| C
+```
+
+| # | Question | Result |
+|---|---|---|
+| 1 | Job | Get a coach that answers on the phone, with no key, then forget about it. |
+| 2 | Entries | Settings › AI Coach › Provider; the coach's "Model download needed" status points there. |
+| 3 | Happy path | Pick provider → Download → (Wi-Fi) → Ready. Two taps. |
+| 4 | Branches | Mobile data now; choose a file; below the memory floor. |
+| 5 | States | Absent, waiting for Wi-Fi, downloading, copying, checking, ready, failed (7 reasons). |
+| 6 | Errors | Each failure reason has its own plain line and offers the same actions again. |
+| 7 | Control | Cancel at any time during a download; Remove frees the space; the download manager's notification can cancel too. |
+| 8 | Progress and resume | Percent and bar; the download manager resumes after the app closes or the link drops, and the screen picks the download back up. |
+| 9 | Memory | The size is stated before anything moves; no need to remember anything. |
+| 10 | Exits | Back; switching provider frees the loaded engine. |
+| 11 | Conventions | Android download manager notification; SAF file picker. |
+| 12 | Speed | Answers take seconds on CPU; said up front ("slower and simpler than a cloud coach"). |
+| 13 | Accessibility | Every action is a PulseButton (≥ 52 dp); status is text, not colour alone. |
+| 14 | Ethics | Wi-Fi only by default; Gemma licence linked before download; nothing leaves the phone. |
+| 15 | Evidence | Mirrors Cochilo's shipped sheet. Not yet tried on the owner's phone. |
+
+Issues: none critical. Polish: the Keystore note is now hidden for this provider only; fine.
+
+## graphic-design-fundamentals (§13 checklist)
+
+| # | Question | Result |
+|---|---|---|
+| 1 | Brief | One section inside the existing AI Coach card. |
+| 2 | Concept | Status first, one primary action, the rest as text buttons. |
+| 3 | Hierarchy | Status line 16 sp SemiBold; explanations 14 sp secondary; licence note 12 sp muted. |
+| 4 | Contrast | `textPrimary` / `textSecondary` on the card; failure in `danger`, ready in `success`. |
+| 5 | Alignment and grid | Single column, full-width primary button, 8 dp rhythm. |
+| 6 | Spacing | 4 / 8 dp only. |
+| 7 | Typography | 12 / 14 / 16 sp from `PulseType.SCALE`. |
+| 8 | Colour | Mint only on buttons (the tappable thing); the progress bar uses `info`. |
+| 9 | Consistency | Same card, dropdown and button styles as the other providers. |
+| 10 | Simplicity | At most one Tonal button visible at a time. |
+| 11 | Real-size test | Not run (no device); pt-BR labels can wrap, buttons have no fixed height. |
+| 12 | Accessibility and ergonomics | Targets ≥ 48 dp; reachable one-handed in the card. |
+| 13 | Production | No new tokens or assets. |
+
+## impeccable (audit, native / Android)
+
+| # | Dimension | Score | Key finding |
+|---|---|---|---|
+| 1 | Accessibility | 3 | Text states; no icon-only controls. Progress bar has no spoken value beyond the status text above it. |
+| 2 | Performance | 3 | Status is a StateFlow; the 600 MB engine loads on first question and is closed on provider change or Remove. |
+| 3 | Appearance & theming | 4 | Tokens only; dark theme like the rest. |
+| 4 | Platform conformance | 4 | DownloadManager, SAF, no storage permission. |
+| 5 | Adaptivity | 3 | Single column; not checked in landscape on a device. |
+| | **Total** | **17/20** | |
+
+Findings: P2 — speed and memory on real phones are unmeasured (try first on the owner's phone).
+P3 — the canvas board for AI Coach needs the new option (see PR description).
+
+## less-is-more
+
+| Element | Question (1–5) | Kept / moved / merged / removed, and where |
+|---|---|---|
+| Intro line | 1: says what it is and what it can't do | Kept, one sentence pair. |
+| Size line | 2: needed before a 600 MB download | Kept, merged with "Wi-Fi only". |
+| Mobile-data choice | 3: needed when no Wi-Fi | Kept as a Text button, not a switch. |
+| Choose a file | 4: rare | Kept as a Text button below. |
+| Image / web / write / live switches | 5: don't apply | Removed for this provider. |
+
+| Dimension | 0–4 |
+|---|---|
+| Elements per screen, compared with before | 3 (four switches hidden, one section added) |
+| Duplicates left | 4 |
+| Text to read when tired | 3 |
+| Taps on the common actions (must not rise) | 4 (other providers unchanged) |
+
+## Evidence
+
+No device in this session: no screenshots, `check_tokens.py` / `drift.py` not run (no token changed).
diff --git a/docs/mcp-threat-model.md b/docs/mcp-threat-model.md
new file mode 100644
index 00000000..d15a459f
--- /dev/null
+++ b/docs/mcp-threat-model.md
@@ -0,0 +1,70 @@
+# AI tools on your network (MCP): threat model
+
+PulseLoop can answer AI tools on the user's own network, such as Claude Desktop or Cursor on a
+laptop, over the Model Context Protocol (streamable HTTP, `POST /mcp`, JSON-RPC 2.0, protocol
+`2025-06-18`). This note covers what that exposes and what limits it. It is a port of GMind's
+design (`nottheomiaiapp/docs/MCP-THREAT-MODEL.md`), adapted to health data.
+
+Code: `app/src/main/java/com/pulseloop/mcp/` (`McpHttp`, `McpNet`, `McpTokens`, `McpProtocol`,
+`McpServer`, `McpCoachTools`, `McpSummary`, `McpService`, `McpPrefs`), the screen in
+`ui/screens/McpSettingsUi.kt` (Settings › Connected apps › AI tools on your network), and the
+tests in `app/src/test/java/com/pulseloop/mcp/`.
+
+## What it exposes
+
+The coach's own read tools, listed from the same `CoachToolDef` schemas, plus `summary`:
+
+- ring data: `get_profile_context`, `get_daily_summary`, `get_range_summary`, `get_metric_series`,
+ `get_activity_sessions`, `summarize_activity_session`, `get_sync_status`,
+ `get_data_availability`, `get_sleep_summary`, `get_sleep_trends`, `get_goal_progress`,
+ `get_recent_anomalies`;
+- arithmetic over numbers the caller sends: `analyze_trend`, `compare_periods`,
+ `compute_correlation`, `detect_outliers`, `summarize_distribution`;
+- logged data: `get_nutrition_log`, `get_goal`, `suggest_next_meal`, `get_food_preferences`,
+ `get_drinks` (refuses while Drinks is off);
+- `summary`: today, last night, the latest heart rate and SpO2, the last 7 days, the ring's state
+ and the coach's data-quality notes, as text.
+
+Those can return the user's health data: steps, heart rate, SpO2, sleep, workouts, meals, drinks,
+goals, profile name and age. **Anyone holding a valid token and able to reach the phone can read
+that while the server is on.** That is the asset to protect.
+
+**Never offered**, by an explicit allowlist (`McpCoachTools.ALLOWLIST`), not by flags alone: every
+tool that writes, logs, sets a goal, deletes, queues a confirmation, starts a live ring
+measurement or searches the web (`log_meal`, `set_goal`, `save_food_preference`, `log_drink`,
+`set_drink_plan`, `save_memory`, `log_user_note`, the activity and meal edit/delete tools,
+`trigger_measurement`, `search_food_database`). There is no tool at all for the coach's API keys,
+raw ring packets, diagnostics, lab reports or their PDFs, or the EPDS answers. `summary` reuses
+the coach's context packet but drops its labs, postpartum, drinks and goal-plan blocks.
+
+## What limits it
+
+| 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. |
+| Reached from the internet or over mobile data | Listens only on Wi-Fi, Ethernet, hotspot and Tailscale (`tun`) interfaces, never `rmnet`/`ccmni`. 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. |
+| Changing or deleting data | Only allowlisted read tools are listed or callable, and they run with `CoachFeatureFlags(writeToolsEnabled = false, liveMeasurementsEnabled = false, webSearchEnabled = false)` and `coordinator = null`, so even a misrouted call has no ring to talk to. `McpAllowlistTest` fails if a write tool's name reaches the allowlist, or if a new coach tool appears that nobody has classified. |
+| Exhausting the phone | At most 4 connections at once, a 15 s socket timeout, 8 KB of headers, a 256 KB body, no chunked bodies, one request per connection, one JSON-RPC message per request (no batches), one tool call at a time (a 20 s wait, then "busy"), replies cut at 200 KB. |
+| Another app on the phone starting it | `McpService` is `exported="false"`; only PulseLoop's settings screen starts it. Its loopback address is still reachable by other apps on the phone, but they need a token too. |
+| A restore carrying a pairing to another phone | The switch and the pairings live in their own preferences file, `mcp_server`, which is not on `ArchivedSettings`' allowlist; `android:allowBackup` is off. A restore starts with the server off and nothing paired. |
+| A token leaking through the clipboard | Copies are marked sensitive (`android.content.extra.IS_SENSITIVE`), which hides the clipboard preview on Android 13+. |
+| Plain HTTP on the LAN | The traffic is readable on the local network. Use Tailscale (encrypted) on networks you don't trust, or keep it off. The token gates access; it doesn't hide the replies. |
+| The agent over-reading the numbers | The `initialize` result's `instructions` say this is the user's own data from a consumer ring, read-only, not a diagnostic tool, that the numbers are estimates, and to send anything worrying to a doctor. |
+
+## Residual risks
+
+- **A leaked token** gives read access from the network while the server is on, until it is
+ revoked in Settings › Connected apps › AI tools on your network.
+- **Untrusted Wi-Fi** (cafés, hotels): other people there can read the plain-HTTP traffic,
+ including the token. Turn it off there, or use Tailscale.
+- **The paired tool** sees what it asks for, and its own data policy then applies to that health
+ data. A cloud-backed assistant sends it to its provider.
+- **The address can change.** The server binds the addresses it found at start; after a Wi-Fi
+ change it must be turned off and on again.
+- **The notification can be hidden.** If notifications are denied, Android 13+ still runs the
+ service but may not show its card; the switch on the settings screen still shows the truth.
+- **Readings may be demo rows.** The tools read what the screens read (real rows win once the
+ ring has synced; before that, demo data). `summary` carries the coach's "this is demo data"
+ note when that applies.
diff --git a/docs/on-device-model-and-mcp-plan.md b/docs/on-device-model-and-mcp-plan.md
new file mode 100644
index 00000000..a213fc2a
--- /dev/null
+++ b/docs/on-device-model-and-mcp-plan.md
@@ -0,0 +1,193 @@
+# On-device coach model, and MCP for your own agent
+
+The owner's request (2026-11-04): a model that runs **on the phone** as a coach option, beside the
+cloud providers and the self-hosted server; and **MCP**, so people can use PulseLoop's data with
+their own agent. GMind and Cochilo already have both pieces, so this plan reuses what they proved
+rather than inventing a third way.
+
+## What already exists here
+
+- **Cloud providers:** OpenAI, Gemini, OpenRouter and MiniMax, each with the user's own key.
+- **`LOCAL_OPENAI_COMPAT`:** any OpenAI-compatible server the user runs (Ollama, LM Studio,
+ llama.cpp, vLLM, SGLang), on the same Wi-Fi or over Tailscale (`docs/local-llm-coach.md`). It
+ runs on *another* computer, not on the phone.
+- **The coach is tool-driven:** `CoachOrchestrator` gives the model `ToolRegistry`'s tools
+ (`CoachToolDef`: a name, a JSON schema, a handler) and loops up to 15 rounds. Write tools sit
+ behind `CoachFeatureFlags.writeToolsEnabled`, and changes the user must confirm go through
+ `PendingAction`.
+
+## Part 1: a model on the phone
+
+### How the sibling apps do it
+
+| | Cochilo | GMind |
+|---|---|---|
+| Runtime | **LiteRT-LM** 0.16.1 for `.litertlm`, plus **MediaPipe LLM Inference** (`tasks-genai` 0.10.35) for `.task`, behind one `LocalModel` interface; the file's magic bytes pick which | **llama.cpp**, built from a pinned commit into its own `libgmind-llama.so` (JNI, CPU, streaming); **Gemini Nano** through ML Kit where Android offers it |
+| Model | Gemma 3 1B int4 (about 600 MB); Gemma 3n E2B (about 3.5 GB) on 8 GB phones | Qwen2.5 1.5B Q4_K_M (1.1 GB) |
+| Delivery | Downloaded on request from a **pre-release** of its own repo (`assistant-model-v1`), checked against the published SHA-256, Wi-Fi only unless the person chooses otherwise; a Play asset pack in the Play build | Downloaded on request, size and SHA-256 checked, kept in no-backup storage |
+| How it answers | Never the source of truth: the app computes the facts, the model only phrases them (`Grounding.kt`), and safety questions get fixed replies before the model sees them | Retrieval first (`LocalPrompt`): the app finds the sources, the model writes from them. A JSON grammar for tools, because small models handle tool use poorly |
+| Build cost | Two Gradle dependencies; Kotlin moved to 2.2.21 for LiteRT-LM | An NDK build pipeline, a pinned llama.cpp, ELF audits, host JNI tests |
+
+### Options for PulseLoop
+
+1. **LiteRT-LM / MediaPipe with Gemma (Cochilo's way). Recommended.** It costs two Gradle
+ dependencies and no NDK work. Google maintains both runtimes, and Cochilo already ships them.
+ The model is already published and hash-checked on Cochilo's `assistant-model-v1` pre-release,
+ so PulseLoop can start from those files and move to its own pre-release later with the same
+ workflow.
+2. **llama.cpp (GMind's way).** It runs any GGUF model (Qwen, Llama, Phi), but needs GMind's
+ whole native build pipeline. That is worth it only if a model outside Gemma's family proves
+ clearly better at health coaching.
+3. **Gemini Nano (ML Kit GenAI).** It needs no download, but only some phones have it, it is
+ closed source, and it isn't on the Pixel 9a. It could be a bonus later, never the only path.
+
+**Recommendation: option 1.** Gemma 3 1B goes on every phone, and Gemma 3n E2B on phones with
+8 GB of memory, behind Cochilo's `LocalModel` interface, copied with its tests.
+
+### The hard part: tools
+
+A 1B model can't run the coach's 15-round tool loop reliably, and a 3n can only sometimes. So the
+on-device coach answers like Cochilo, **grounded, without tools**:
+
+1. **The app gathers the facts first.** `CoachContextBuilder` already builds the per-turn packet:
+ today, last night, the vitals, the goals and the warnings. For the question asked, the app also
+ runs the read-only tools that obviously apply (sleep, heart, activity, nutrition), picked by
+ keyword, and adds their results as compact text, as GMind's `LocalPrompt` does.
+2. **The model only phrases the answer**, in at most a few short paragraphs, in the app's
+ language. The rules are those of the cloud coach's system prompt, shortened: it never
+ diagnoses, never doses, and sends people to a clinician.
+3. **Safety comes before the model.** Crisis, medication, pregnancy, postpartum and lab-diagnosis
+ questions get the reviewed replies the app already has, and the model never sees them.
+4. **No write tools and no confirm cards** on this provider. Goals, meals and workouts are still
+ changed from the app, or with a cloud or self-hosted coach.
+
+The coach screen says which brain answered ("On this phone · Gemma 3 1B"), and that nothing left
+the phone.
+
+### What the person sees
+
+- **Settings › AI Coach › "On this phone"**, a new provider beside the others.
+- **Download** shows the model's size before anything moves (Wi-Fi only unless they tap "Download
+ now on mobile data"), with progress and Cancel, using Android's download manager. Remove frees
+ the space. The Gemma licence is linked in the sheet.
+- On a phone below the memory floor (about 4 GB), the option says why it isn't offered.
+
+### Build steps
+
+1. Add `tasks-genai` and the `LocalModel` interface, with `MediaPipeModel`.
+2. Add `ModelDownload` and `ModelFile`, copied with their tests.
+3. Add `CoachProviderMode.ON_DEVICE` and an `OnDeviceCoach` that does the grounded prompt and
+ the safety routing.
+4. Add the Settings row and the download sheet, with all four design skills and an audit.
+5. **Later:** bump Kotlin (2.0.21 → 2.2.x), KSP and Room (2.6.1 → 2.7.x) for LiteRT-LM and Gemma
+ 3n, as Cochilo did in 0.55.0. This is a separate PR, because it touches the whole build.
+
+### As built (step 1, 2026-11-04)
+
+MediaPipe only; LiteRT-LM and Gemma 3n wait for the Kotlin bump (step 3).
+
+- **Runtime:** `com.google.mediapipe:tasks-genai:0.10.35`, CPU backend, one engine kept loaded
+ (`coach/ondevice/LocalModel.kt`, `MediaPipeModel`, `MAX_TOKENS` 1280 with 384 kept for the
+ answer, as Cochilo runs the same file). R8 keeps `com.google.mediapipe.**` and protobuf
+ (`proguard-rules.pro`).
+- **The file:** `gemma3-1b-it-int4.task` from Cochilo's `assistant-model-v1` pre-release
+ (`ModelDownload.REPO` / `TAG`, so moving it to PulseLoop's own pre-release is two constants),
+ checked against the `.sha256` beside it, at least 50 MB and not text (`ModelFile`). It lands
+ in the app's external files folder (the only place Android's download manager can write
+ without a permission) and moves into `noBackupFilesDir/models/` once checked
+ (`OnDeviceModelStore`). Wi-Fi only unless the user taps "Download now on mobile data". A file
+ the user already has can be chosen instead (Storage Access Framework → `ModelFile.copy`).
+- **The provider:** `CoachProviderMode.ON_DEVICE` ("onDevice"). `CoachClientResolver` returns
+ `OnDeviceResponsesClient` with the sentinel `"on-device"` only when the file is on the phone;
+ the model slug is `gemma3-1b-on-device`, priced at $0.
+- **How a turn runs:** the orchestrator is unchanged. `OnDeviceResponsesClient` ignores the
+ tools, replaces the cloud system prompt with `OnDevicePrompt.instructions` (its safety rules,
+ shortened, plus `L10n.coachInstruction()`), keeps the developer message's context packet, and
+ cuts the prompt to the window (earlier messages first, then the context; instructions and
+ question always stay). It answers in Gemma's turn format and wraps the plain-text answer in a
+ complete `coach_response` object, so the tool loop ends after one call and `parseFinal` accepts
+ it without a repair round. Any other schema (meal estimate, lab report, summary) is refused;
+ the meal and lab screens say so plainly.
+- **Safety first:** `OnDeviceSafety` routes crisis (CVV 188, SAMU 192), emergency (SAMU 192) and
+ medicine/dose/supplement questions to fixed replies before the model is loaded, in English and
+ Portuguese, accent-insensitive.
+- **Off on this provider:** web search, write tools, live measurements, image attachments.
+- **Not built yet:** the keyword-picked read-only tool results (step 1 of "The hard part"), and
+ routing pregnancy, postpartum and lab-diagnosis questions to their reviewed replies.
+
+## Part 2: MCP, so people can use their data with their own agent
+
+### How GMind does it
+
+GMind has two surfaces:
+
+- **On your network:** an opt-in, **read-only** MCP server on the phone (`McpServer`,
+ `McpService`, `McpTokens`). It speaks MCP's streamable HTTP (`POST /mcp`, JSON-RPC 2.0,
+ protocol `2025-06-18`) on port 8765, so Claude Desktop, Cursor and others on the same Wi-Fi or
+ Tailscale can call GMind's lookup tools. Every request needs that tool's own pairing token.
+ Requests from non-private addresses, or with an `Origin` header (a web page), are refused before
+ anything is read. Connections, timeouts and body sizes are bounded. A foreground service keeps
+ it alive while it is on. It has its own threat model (`docs/MCP-THREAT-MODEL.md`).
+- **Anywhere:** an encrypted mirror on the person's own free Cloudflare Worker (`mcp-mirror/`).
+ It stores only ciphertext, has a 30-day lease, and serves Claude on the web and phone.
+
+### For PulseLoop
+
+**Phase A (recommended first): the on-network server, GMind's way.**
+
+- **Tools:** the coach's own read-only tools from `ToolRegistry`, plus one `summary` tool (today,
+ last night and the week in one reply), so an agent gets a useful picture in one call. They are
+ listed from the same `CoachToolDef` schemas, so nothing has a second definition.
+ - **Never offered:** write tools, live ring measurements, the coach's API keys, raw ring
+ packets, or lab-report PDFs.
+- **Pairing:** Settings › Connected apps › **"AI tools on your network"**, off by default. Each
+ agent gets its own token (shown once, revocable), and the connection's address and a ready-made
+ config are copied for Claude Desktop or Cursor.
+- **Limits:** only private and Tailscale addresses; no `Origin` header; bounded body size,
+ connections and time. A foreground notification shows while it runs, and it turns off by
+ itself after a set time (default 8 hours).
+- **Privacy:** the readings are health data, so each pairing says what the agent will be able to
+ read, and the coach's rules travel in the server's `instructions` (it is not a diagnosis tool).
+ The server ignores the demo-data switch: an agent gets what the screens show.
+
+**As built (Phase A, step 2).** Package `app/src/main/java/com/pulseloop/mcp/`, screen
+`ui/screens/McpSettingsUi.kt` (route `settings/mcp`, one row under Connected apps), threat model
+`docs/mcp-threat-model.md`, rules in AGENTS.md "MCP on your network".
+
+- **Tools:** an explicit allowlist of 22 coach read tools (`McpCoachTools.ALLOWLIST`) plus
+ `summary`. The registry's always-on set turned out to hold writes too (`log_meal`, `set_goal`,
+ `log_drink`, `set_drink_plan`, `save_food_preference`) and `search_food_database` writes a cache
+ and goes to the network, so the flags alone were not enough. `prepare_chart` is left out: it
+ carries no data. `summary` reuses `CoachContextBuilder.build` without its labs, postpartum,
+ drinks and goal-plan blocks.
+- **Pure JVM core:** `McpHttp` (parse/write, limits), `McpNet` (address rules, URLs), `McpTokens`
+ (32-byte base64url tokens, `pulseloop_` prefix, SHA-256 only, constant-time check),
+ `McpHandler` (JSON-RPC: `initialize`, `ping`, `tools/list`, `tools/call`, 202 for
+ notifications, one tool call at a time), `McpServer` (sockets). Tested in
+ `app/src/test/java/com/pulseloop/mcp/`, including a real loopback round trip.
+- **Android:** `McpService`, a `dataSync` foreground service with its own channel and a
+ tap-to-stop notification; auto-off after 1, 4 or 8 hours (default 8). On Android 15 the system
+ caps `dataSync` at about 6 hours a day, so the 8-hour choice ends there (`onTimeout`).
+ `McpPrefs` keeps the switch and the pairings in `mcp_server`, which is not archived.
+- **Connecting:** the pairing dialog shows the token once with a Claude Desktop / Cursor entry
+ (`npx -y mcp-remote --allow-http --header Authorization:${PULSELOOP_AUTH}`, the bearer in
+ `env`) and the plain URL and header for clients that speak HTTP.
+- **Not done here:** the design canvas board, the flow-map card and the four-skill audit for the
+ new screen; the pt-BR catalog entries (listed in the PR for the catalog owner).
+
+**Phase B (owner's call): an encrypted mirror, so Claude anywhere can read it.** This is GMind's
+Worker, with the same push, lease and delete behaviour. It would put a copy of health data, even
+encrypted, on a server outside the phone, so it is the owner's decision. It would also be opt-in,
+with summaries and no raw rows.
+
+## Order and size
+
+| Step | What | Size |
+|---|---|---|
+| 1 | On-device coach: MediaPipe + Gemma 3 1B, grounded, download sheet | Medium |
+| 2 | MCP on your network: server, tokens, Settings row, threat model doc | Medium |
+| 3 | Kotlin/KSP/Room bump → LiteRT-LM + Gemma 3n on 8 GB phones | Medium (build-wide) |
+| 4 | Encrypted MCP mirror for Claude anywhere | Owner's call |
+
+None of this can be checked here on a phone. CI compiles and runs the unit tests, but speed,
+memory and answer quality on the owner's phone are the first thing to try after each release.