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

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -11,3 +11,4 @@ app/.DS_Store
gradle/.DS_Store
.DS_Store
.kotlin/
.claude/worktrees/
7 changes: 4 additions & 3 deletions AGENTS.md
Original file line number Diff line number Diff line change
Expand Up @@ -1160,7 +1160,8 @@ their data. Each rule fails silently if broken:
`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
switch. On Android 15+ the choices stop at 6 h and a stored 8 reads as 6
(`McpConfig.autoOffHours`): a `dataSync` service gets about 6 h a day there. The notification's tap stops it. Type `dataSync` (Android 15 ends it at its daily
limit through `onTimeout`; keep that override).
- **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.
Expand Down Expand Up @@ -1399,8 +1400,8 @@ serving, AI-estimate source); changing a number marks it `userEdited`, as a barc
source file. The tracked caps label over a card or section is `PulseType.eyebrow` (12sp,
1sp tracking, `textSecondary`) everywhere — don't hand-roll another letter-spacing.
- **Mint is the brand and the thing to tap, nothing else.** `success` (good, in range,
connected) is its own green, REM is cyan, connecting is amber. The readiness ring keeps the
brand colour on purpose: it is the headline score.
connected) is its own green, REM is cyan, connecting is amber. The readiness and activity
score rings are coloured by their band (the score's own meaning), not by the brand colour.
- **One card radius: 8dp.** Tiles and vital cards used to be 20/30dp.
- **Every button is a `PulseButton`** (`ui/components/PulseButton.kt`, v2.11.57): one composable
with a style (Filled, Tonal, Outlined, Text) that holds the design system's button rules — 52dp
Expand Down
2 changes: 2 additions & 0 deletions app/src/main/AndroidManifest.xml
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,8 @@

<!-- Self-update: fetch the GitHub release manifest/APK and install it -->
<uses-permission android:name="android.permission.INTERNET" />
<!-- mcp/McpService follows the phone's Wi-Fi/Tailscale addresses while it runs (NetworkCallback). -->
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.REQUEST_INSTALL_PACKAGES" />

<!-- Wearable settings → "Reliable background sync": asks to exempt the app from battery
Expand Down
1 change: 0 additions & 1 deletion app/src/main/assets/i18n/en-FH.json
Original file line number Diff line number Diff line change
Expand Up @@ -153,7 +153,6 @@
"Learning your normal: {0} of {1} nights.": "Learning your normal: {0} of {1} nights. Patience, damn it.",
"Learns your baseline": "Learns your baseline (give it time, damn)",
"Limited HR data available for today.": "Barely any HR data today. Where's the ring?",
"Log Meal": "Feed the Log",
"Log a drink": "Confess a drink",
"Log a drink in one tap": "Confess a drink in one tap",
"Log a few evenings with drinks and PulseLoop will compare those nights with your dry ones.": "Log a few boozy evenings and PulseLoop will compare those nights with your dry ones. The truth hurts.",
Expand Down
1 change: 0 additions & 1 deletion app/src/main/assets/i18n/pt-BR-FH.json
Original file line number Diff line number Diff line change
Expand Up @@ -153,7 +153,6 @@
"Learning your normal: {0} of {1} nights.": "Aprendendo seu normal: {0} de {1} noites. Paciência, p*rra.",
"Learns your baseline": "Aprende sua linha de base (dá um tempo, c*ramba)",
"Limited HR data available for today.": "Quase nada de dados de FC hoje. Cadê o anel?",
"Log Meal": "Alimentar o registro",
"Log a drink": "Confessar uma bebida",
"Log a drink in one tap": "Confesse uma bebida com um toque",
"Log a few evenings with drinks and PulseLoop will compare those nights with your dry ones.": "Registre algumas noites de birita e o PulseLoop vai comparar essas noites com as noites sem álcool. A verdade dói.",
Expand Down
10 changes: 9 additions & 1 deletion app/src/main/assets/i18n/pt-BR.json
Original file line number Diff line number Diff line change
Expand Up @@ -435,6 +435,8 @@
"Cost estimates aren't available for on-device or custom models.": "Estimativas de custo não estão disponíveis para modelos locais ou personalizados.",
"Could not export diagnostics.": "Não foi possível exportar os diagnósticos.",
"Could not open browser": "Não foi possível abrir o navegador",
"Couldn't add the nap. Try again.": "Não foi possível adicionar o cochilo. Tente de novo.",
"Couldn't add the workout. Try again.": "Não foi possível adicionar o treino. Tente de novo.",
"Couldn't analyse the meal. Check your connection and try again, or enter it by hand.": "Não foi possível analisar a refeição. Verifique a conexão e tente de novo, ou digite à mão.",
"Couldn't check for updates ({0}). Try again.": "Não foi possível procurar atualizações ({0}). Tente de novo.",
"Couldn't check for updates. Check your connection and try again.": "Não foi possível procurar atualizações. Verifique sua conexão e tente de novo.",
Expand Down Expand Up @@ -466,6 +468,7 @@
"Cuscuz com ovo": "Cuscuz com ovo",
"Custom model slug (vendor/model)": "Slug de modelo personalizado (fornecedor/modelo)",
"Customize": "Personalizar",
"Customize cards": "Personalizar cartões",
"Cycle": "Ciclo",
"Cycle of {0} days": "Ciclo de {0} dias",
"Cycle · day {0}": "Ciclo · dia {0}",
Expand Down Expand Up @@ -954,7 +957,6 @@
"Location": "Localização",
"Log": "Registrar",
"Log Activity": "Registrar atividade",
"Log Meal": "Registrar refeição",
"Log Past Activity": "Registrar atividade anterior",
"Log a drink": "Registrar uma bebida",
"Log a drink in one tap": "Registre uma bebida com um toque",
Expand Down Expand Up @@ -1081,6 +1083,7 @@
"NUTRITION": "NUTRIÇÃO",
"Name": "Nome",
"Name it so you'll recognise it later, like the app and the computer.": "Dê um nome que você reconheça depois, como o app e o computador.",
"Nap added": "Cochilo adicionado",
"Near baseline": "Perto da linha de base",
"Needs 5 nights in the last 2 weeks": "Precisa de 5 noites nas últimas 2 semanas",
"Needs care": "Requer atenção",
Expand Down Expand Up @@ -1945,6 +1948,7 @@
"Within a typical range for a non-fasting reading.": "Dentro da faixa típica para uma leitura sem jejum.",
"Woke up": "Acordou",
"Workout": "Treino",
"Workout added: {0}": "Treino adicionado: {0}",
"Workout history": "Histórico de treinos",
"Workout in progress": "Treino em andamento",
"Workout not found": "Treino não encontrado",
Expand Down Expand Up @@ -2027,6 +2031,8 @@
"Your usual {0}-day cycle would have ended {1} day{2} ago.": "Seu ciclo habitual de {0} dias teria terminado há {1} dia{2}.",
"Your week at a glance": "Sua semana num relance",
"Your workout is still recording. Finish it now, or keep recording?": "Seu treino ainda está sendo gravado. Finalizar agora ou continuar gravando?",
"Zoom in": "Aproximar",
"Zoom out": "Afastar",
"a {0} fits.": "cabe um(a) {0}.",
"above": "acima",
"above {0}": "acima de {0}",
Expand Down Expand Up @@ -2106,6 +2112,7 @@
"{0} asleep · woke {1} times · longest stretch {2}": "{0} dormindo · acordou {1} vezes · maior trecho {2}",
"{0} at {1}.": "{0} às {1}.",
"{0} awake during the night": "{0} acordado durante a noite",
"{0} bpm": "{0} bpm",
"{0} bpm above your usual {1}": "{0} bpm acima do seu habitual de {1}",
"{0} bpm avg": "{0} bpm média",
"{0} bpm below your usual {1}": "{0} bpm abaixo do seu habitual de {1}",
Expand Down Expand Up @@ -2148,6 +2155,7 @@
"{0} models available from {1}": "{0} modelos disponíveis de {1}",
"{0} more dry day{1} to reach {2}": "Mais {0} dia{1} sem álcool para chegar a {2}",
"{0} more — type to narrow": "Mais {0} — digite para filtrar",
"{0} ms": "{0} ms",
"{0} ms over the last 3 nights against your usual {1} ({2}%). Your body may be under extra load.": "{0} ms nas últimas 3 noites contra seu habitual de {1} ({2}%). Seu corpo pode estar sob carga extra.",
"{0} of 7 active days": "{0} de 7 dias ativos",
"{0} of exercise in the last 7 days": "{0} de exercício nos últimos 7 dias",
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -64,8 +64,8 @@ fun CoachToolTraceDisclosure(messageId: String, viewModel: CoachViewModel?) {
exit = shrinkVertically(tween(com.pulseloop.ui.theme.Motion.STANDARD_MS, easing = com.pulseloop.ui.theme.Motion.ease)),
) {
Column(
verticalArrangement = Arrangement.spacedBy(6.dp),
modifier = Modifier.padding(top = 2.dp),
verticalArrangement = Arrangement.spacedBy(8.dp),
modifier = Modifier.padding(top = 4.dp),
) {
calls.forEach { call -> ToolTraceRow(call) }
}
Expand All @@ -84,7 +84,7 @@ private fun displayLabel(call: CoachToolCallEntity): String =
@Composable
private fun ToolTraceRow(call: CoachToolCallEntity) {
val isError = call.statusRaw == "error"
Row(verticalAlignment = Alignment.Top, horizontalArrangement = Arrangement.spacedBy(6.dp)) {
Row(verticalAlignment = Alignment.Top, horizontalArrangement = Arrangement.spacedBy(8.dp)) {
Icon(
if (isError) Icons.Filled.Cancel else Icons.Filled.CheckCircle,
null,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -701,7 +701,7 @@ object HealthConnectTypeMappings {
// NutritionRecord's clinit bounds (verified from the 1.1.0 AAR): energy 0..1e8 cal; the macro
// masses (protein/carbs/fat/fiber/sugar) 0..100,000 g; sodium is a micronutrient capped at
// 100 g = 100,000 mg (and is built with Mass.milligrams, not grams). A meal comes only from the
// manual "Log Meal" dialog and is normally tiny, but a typo must not sink the whole 200-record
// manual "Log meal" dialog and is normally tiny, but a typo must not sink the whole 200-record
// chunk, so an out-of-range meal is DROPPED (never clamped), like every other guard here.

/**
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -118,11 +118,9 @@ object AccuracyReportText {
* What a coverage note says: which device was off and from when (`partly:` / `night_off:`),
* or how many hours a partly worn day was compared over (`shared:`).
*/
private fun coverageNote(note: String, ref: String): String? {
private fun coverageNote(note: String, ref: String, is24Hour: Boolean): String? {
fun device(who: String) = if (who == AccuracyScorer.WHO_RING) com.pulseloop.ui.i18n.tr("the ring") else ref
fun time(ms: String) = ms.toLongOrNull()?.let {
java.time.Instant.ofEpochMilli(it).atZone(java.time.ZoneId.systemDefault()).format(java.time.format.DateTimeFormatter.ofPattern("HH:mm"))
} ?: "?"
fun time(ms: String) = ms.toLongOrNull()?.let { com.pulseloop.ui.components.PhoneFormat.clock(is24Hour, it) } ?: "?"
return when {
note.startsWith(AccuracyScorer.NOTE_SHARED_PREFIX) -> note.removePrefix(AccuracyScorer.NOTE_SHARED_PREFIX).toLongOrNull()?.let {
com.pulseloop.ui.i18n.trf("compared over the {0} h both were on", "%.1f".format(it / 60.0))
Expand All @@ -137,8 +135,11 @@ object AccuracyReportText {
}
}

/** Why a day doesn't count, or how it was counted, for the per-day rows. */
fun dayNote(note: String?, ref: String): String? = note?.let { coverageNote(it, ref) } ?: when (note) {
/**
* Why a day doesn't count, or how it was counted, for the per-day rows. A time in it follows
* [is24Hour], which the screen reads from the phone's setting.
*/
fun dayNote(note: String?, ref: String, is24Hour: Boolean = true): String? = note?.let { coverageNote(it, ref, is24Hour) } ?: when (note) {
AccuracyScorer.NOTE_WAITING -> "waiting for $ref to deliver"
AccuracyScorer.NOTE_NOT_WORN -> "not worn on both"
AccuracyScorer.NOTE_NO_REF_NIGHT -> "no night from $ref"
Expand Down
23 changes: 23 additions & 0 deletions app/src/main/java/com/pulseloop/mcp/McpConfig.kt
Original file line number Diff line number Diff line change
Expand Up @@ -29,4 +29,27 @@ object McpConfig {
URL: $url
Header: Authorization: Bearer $token
""".trimIndent()

/**
* Android 15 (API 35) gives a `dataSync` foreground service about six hours in every 24, then
* calls `onTimeout` (which [McpService] honours by stopping). A longer auto-off can't be kept
* there, so it isn't offered, and a longer stored choice reads as the cap.
*/
const val DATA_SYNC_LIMIT_SDK = 35
const val DATA_SYNC_LIMIT_HOURS = 6

/** The auto-off lengths offered on a device running [sdkInt]; the last is the default. */
fun autoOffChoices(sdkInt: Int): List<Int> =
if (sdkInt >= DATA_SYNC_LIMIT_SDK) listOf(1, 4, DATA_SYNC_LIMIT_HOURS) else listOf(1, 4, 8)

fun defaultAutoOffHours(sdkInt: Int): Int = autoOffChoices(sdkInt).last()

/**
* A stored auto-off length as this device can honour it: capped at [DATA_SYNC_LIMIT_HOURS] on
* Android 15 and later, and the default when it isn't one of the choices offered here.
*/
fun autoOffHours(stored: Int, sdkInt: Int): Int {
val capped = if (sdkInt >= DATA_SYNC_LIMIT_SDK) stored.coerceAtMost(DATA_SYNC_LIMIT_HOURS) else stored
return capped.takeIf { it in autoOffChoices(sdkInt) } ?: defaultAutoOffHours(sdkInt)
}
}
8 changes: 5 additions & 3 deletions app/src/main/java/com/pulseloop/mcp/McpPrefs.kt
Original file line number Diff line number Diff line change
Expand Up @@ -28,8 +28,9 @@ class McpPrefs(context: Context) : McpTokenStorage {
get() = prefs.getLong(KEY_OFF_AT, 0L)
set(v) { prefs.edit().putLong(KEY_OFF_AT, v).apply() }

/** Clamped to what this Android version lets a `dataSync` service run (McpConfig.autoOffHours). */
var autoOffHours: Int
get() = prefs.getInt(KEY_HOURS, DEFAULT_HOURS).takeIf { it in HOURS_CHOICES } ?: DEFAULT_HOURS
get() = McpConfig.autoOffHours(prefs.getInt(KEY_HOURS, McpConfig.defaultAutoOffHours(SDK)), SDK)
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. */
Expand All @@ -50,8 +51,9 @@ class McpPrefs(context: Context) : McpTokenStorage {
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 SDK get() = android.os.Build.VERSION.SDK_INT
/** The auto-off lengths this device offers (1, 4 and 8 h; 6 h instead of 8 on Android 15+). */
val HOURS_CHOICES: List<Int> get() = McpConfig.autoOffChoices(SDK)
private val json = Json { ignoreUnknownKeys = true }
}
}
53 changes: 40 additions & 13 deletions app/src/main/java/com/pulseloop/mcp/McpServer.kt
Original file line number Diff line number Diff line change
Expand Up @@ -30,21 +30,48 @@ class McpServer(private val handler: McpHandler) {
fun start(addresses: List<InetAddress>, port: Int): List<InetSocketAddress> {
running = true
val bound = ArrayList<InetSocketAddress>()
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
for (a in addresses) bind(a, port)?.let { bound.add(it) }
return bound
}

/**
* Follows the phone's addresses while running (Wi-Fi joined or left, a DHCP renewal, Tailscale
* up or down): stops listening on an address the phone no longer has, starts on a new one, and
* leaves the rest alone so a tool connected through them isn't dropped. The same rule as
* [start]: only private addresses. Returns everything it listens on afterwards — empty while
* the phone is on no network of its own, until one comes back. Does nothing once stopped.
*/
@Synchronized
fun rebind(addresses: List<InetAddress>, port: Int): List<InetSocketAddress> {
if (!running) return emptyList()
val wanted = addresses.filter { McpNet.allowedPeer(it) }.distinct()
val iter = sockets.iterator()
while (iter.hasNext()) {
val s = iter.next()
if (s.inetAddress !in wanted) {
try { s.close() } catch (_: IOException) {} // its accept thread ends on the close
iter.remove()
}
sockets.add(s)
bound.add(s.localSocketAddress as InetSocketAddress)
Thread({ accept(s) }, "pulseloop-mcp-accept").apply { isDaemon = true }.start()
}
return bound
val listening = sockets.map { it.inetAddress }
for (a in wanted) if (a !in listening) bind(a, port)
return sockets.map { it.localSocketAddress as InetSocketAddress }
}

/** One listening socket on [a], with its accept thread; null when [a] is public or taken. */
private fun bind(a: InetAddress, port: Int): InetSocketAddress? {
if (!McpNet.allowedPeer(a)) return null // 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) {}
return null
}
sockets.add(s)
Thread({ accept(s) }, "pulseloop-mcp-accept").apply { isDaemon = true }.start()
return s.localSocketAddress as InetSocketAddress
}

@Synchronized
Expand Down
Loading
Loading