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
10 changes: 5 additions & 5 deletions app/src/main/java/com/pulseloop/MainActivity.kt
Original file line number Diff line number Diff line change
Expand Up @@ -111,26 +111,26 @@ class MainActivity : ComponentActivity() {
uri.getQueryParameter("error")?.takeIf { it.isNotBlank() }?.let { error ->
store.takePendingAuthState()
store.saveLastError(
if (error == "access_denied") "Strava authorization was declined." else "Strava denied authorization: $error"
if (error == "access_denied") getString(R.string.strava_auth_declined) else getString(R.string.strava_auth_denied, error)
)
return
}

// CSRF: the state we generated must come back. One-shot, cleared either way.
if (!StravaAuth.validateState(store, uri.getQueryParameter("state"))) {
store.saveLastError("Strava authorization could not be verified. Please try connecting again.")
store.saveLastError(getString(R.string.strava_auth_unverified))
return
}

// The consent screen lets the user untick "Upload your activities". Catch it here rather
// than letting every future upload fail with an opaque 401.
if (!StravaAuth.grantedScopeIncludesWrite(uri.getQueryParameter("scope"))) {
store.saveLastError("Strava did not grant upload permission. Reconnect and keep \"Upload your activities\" checked.")
store.saveLastError(getString(R.string.strava_auth_no_upload))
return
}

val code = uri.getQueryParameter("code")?.takeIf { it.isNotBlank() } ?: run {
store.saveLastError("Strava returned an unexpected authorization response.")
store.saveLastError(getString(R.string.strava_auth_unexpected))
return
}

Expand All @@ -140,7 +140,7 @@ class MainActivity : ComponentActivity() {
store.clearLastError()
} catch (e: Exception) {
// The code may have expired, or the configured secrets are wrong.
store.saveLastError("Could not complete the Strava sign-in: ${e.message ?: "unknown error"}")
store.saveLastError(getString(R.string.strava_auth_failed, e.message ?: getString(R.string.strava_unknown_error)))
}
}
}
Expand Down
1 change: 1 addition & 0 deletions app/src/main/java/com/pulseloop/PulseLoopApplication.kt
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,7 @@ class PulseLoopApplication : Application() {

override fun onCreate() {
super.onCreate()
com.pulseloop.util.L10n.init(this)
CrashLogger.install(this)
RWfitSleepJournal.init(this)
// Before any sync can read them: Bedtime tracking no longer needs the schedule (issue #126),
Expand Down
35 changes: 35 additions & 0 deletions app/src/main/java/com/pulseloop/coach/context/CoachLanguage.kt
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
package com.pulseloop.coach.context

import com.pulseloop.R
import com.pulseloop.util.L10n

/**
* The language the coach should write in: the language of the strings the app is showing.
*
* Prompts, tool schemas and tool results stay in English: the model reads English most
* reliably, and several parsers depend on exact English tokens. Only the *output language* is
* steered, by appending a directive to each system prompt that produces user-visible text
* (chat, summaries, check-in notifications, meal estimates). For English the directive is
* empty, so the prompts are byte-for-byte what they were before localization.
*
* The name comes from the `coach_language` string resource rather than from the device locale,
* so it follows whichever translation Android actually resolved. A phone set to a language the
* app has no translation for shows English UI and gets an English coach, not a coach in a
* language the rest of the app isn't speaking.
*/
object CoachLanguage {
/** English name of the app's resolved language ("Russian"), or null when it is English. */
fun languageName(): String? =
L10n.get(R.string.coach_language).trim().takeIf { it.isNotEmpty() && !it.equals("English", ignoreCase = true) }

/**
* A sentence to append to a system prompt, or "" for English. [what] names the output,
* e.g. "all replies" or "the meal name and assumptions".
*/
fun directive(what: String = "all replies"): String {
val language = languageName() ?: return ""
return "\n\nWrite $what in $language — the user's app language — even though these " +
"instructions and the data you receive are in English. Keep numbers, units and " +
"proper names as they are."
}
}
12 changes: 6 additions & 6 deletions app/src/main/java/com/pulseloop/coach/local/LocalEndpoint.kt
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
package com.pulseloop.coach.local

import com.pulseloop.R
import com.pulseloop.util.L10n
import java.net.URI

/**
Expand Down Expand Up @@ -78,13 +80,11 @@ object LocalEndpoint {

/** A short, user-facing explanation for a [Problem], for the Settings field. */
fun message(problem: Problem): String = when (problem) {
Problem.BLANK -> "Enter your server's address, e.g. http://192.168.1.50:11434"
Problem.MALFORMED -> "That doesn't look like a URL — use host:port or http://host:port"
Problem.UNSUPPORTED_SCHEME -> "Only http:// and https:// are supported."
Problem.BLANK -> L10n.get(R.string.le_blank)
Problem.MALFORMED -> L10n.get(R.string.le_malformed)
Problem.UNSUPPORTED_SCHEME -> L10n.get(R.string.le_scheme)
Problem.PUBLIC_CLEARTEXT ->
"Plain http:// is only allowed for a server on this device or your local network " +
"(an IP address, a plain hostname, or a .local / .lan / .ts.net name). " +
"Use https:// to reach one over the internet."
L10n.get(R.string.le_cleartext)
}

/**
Expand Down
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
package com.pulseloop.coach.orchestration

import com.pulseloop.R
import com.pulseloop.util.L10n
import com.pulseloop.coach.context.CoachContextPacket
import com.pulseloop.coach.schema.CoachConfidence
import com.pulseloop.coach.schema.CoachResponse
Expand All @@ -15,10 +17,10 @@ object CoachFallbacks {
/** Used after an API failure or unrepairable output. */
fun fallback(): CoachResponse = CoachResponse(
responseType = CoachResponseType.ERROR_RECOVERY,
title = "I had trouble with that",
summary = "I checked your data but couldn't finish preparing the answer. Try asking again, or narrow the question.",
dataQualityNote = "No changes were made.",
followUpChips = listOf("How am I doing today?", "Summarize my week", "What data is missing?"),
title = L10n.get(R.string.fb_trouble_title),
summary = L10n.get(R.string.fb_trouble),
dataQualityNote = L10n.get(R.string.fb_no_changes),
followUpChips = listOf(L10n.get(R.string.coach_suggest_today), L10n.get(R.string.coach_suggest_week), L10n.get(R.string.fb_chip_missing)),
confidence = CoachConfidence.LOW,
)

Expand All @@ -30,37 +32,37 @@ object CoachFallbacks {
val avgSteps = if (steps7d.isNotEmpty()) steps7d.average().toInt() else 0

val bullets = mutableListOf<String>()
if (todaySteps > 0) bullets.add("Steps today: ${todaySteps}")
if (avgSteps > 0) bullets.add("7-day average: ${avgSteps} steps/day")
if (todaySteps > 0) bullets.add(L10n.get(R.string.fb_steps_today, todaySteps))
if (avgSteps > 0) bullets.add(L10n.plural(R.plurals.fb_steps_avg, avgSteps, avgSteps))

if (bullets.isEmpty()) {
return CoachResponse(
responseType = CoachResponseType.DATA_MISSING,
title = "No activity synced yet",
summary = "I don't have today's activity from the ring yet. Sync the ring or take a measurement and I'll summarize what comes in. (The AI coach is off — add an OpenAI key in Settings to enable full coaching.)",
title = L10n.get(R.string.fb_no_activity_title),
summary = L10n.get(R.string.fb_no_activity),
dataQualityNote = packet.dataQualityWarnings.firstOrNull(),
followUpChips = listOf("Is my ring connected?", "What data is missing?"),
followUpChips = listOf(L10n.get(R.string.fb_chip_connected), L10n.get(R.string.fb_chip_missing)),
confidence = CoachConfidence.LOW,
)
}

return CoachResponse(
responseType = CoachResponseType.INSIGHT,
title = "Here's where you are today",
summary = "You're at ${todaySteps} steps so far today. The AI coach is off — add an OpenAI key in Settings for trends and tailored guidance.",
title = L10n.get(R.string.fb_today_title),
summary = L10n.plural(R.plurals.fb_today, todaySteps, todaySteps),
bullets = bullets,
dataQualityNote = packet.dataQualityWarnings.lastOrNull(),
followUpChips = listOf("How does today compare to yesterday?", "What's my heart rate trend?"),
followUpChips = listOf(L10n.get(R.string.fb_chip_compare), L10n.get(R.string.fb_chip_hr_trend)),
confidence = CoachConfidence.MEDIUM,
)
}

/** Parser failure — couldn't decode model output. */
fun parseError(): CoachResponse = CoachResponse(
responseType = CoachResponseType.ERROR_RECOVERY,
title = "Parse Error",
summary = "I had trouble formatting my response. Please try again.",
followUpChips = listOf("Try again", "Summarize my day", "What's new?"),
title = L10n.get(R.string.fb_parse_title),
summary = L10n.get(R.string.fb_parse),
followUpChips = listOf(L10n.get(R.string.action_try_again), L10n.get(R.string.fb_chip_day), L10n.get(R.string.fb_chip_new)),
confidence = CoachConfidence.LOW,
)
}
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
package com.pulseloop.coach.orchestration

import com.pulseloop.R
import com.pulseloop.util.L10n
import com.pulseloop.coach.attachments.CoachImagePayload
import com.pulseloop.coach.context.CoachContextPacket
import com.pulseloop.coach.context.CoachPromptBuilder
Expand Down Expand Up @@ -113,7 +115,7 @@ class CoachOrchestrator(
// Initial input: system + developer + recent turns + the new user message.
// Images only ever ride on user turns (system/developer/assistant stay text).
val input = mutableListOf<JsonObject>()
input.add(OpenAIRequestBuilder.message("system", CoachPromptBuilder.systemPrompt))
input.add(OpenAIRequestBuilder.message("system", CoachPromptBuilder.systemPrompt + com.pulseloop.coach.context.CoachLanguage.directive()))
input.add(OpenAIRequestBuilder.message("developer", CoachPromptBuilder.developerMessage(packet)))
for (m in recentMessages) {
val isUser = m.role == "user"
Expand Down Expand Up @@ -199,7 +201,7 @@ class CoachOrchestrator(
assistant = CoachFallbacks.parseError(), trace = trace,
pendingActions = toolContext.pendingActions.toList(),
usage = tally, modelUsed = flags.model, providerUsed = flags.providerMode.rawValue,
error = CoachTurnError(code = "Bad response", reason = e.reason))
error = CoachTurnError(code = L10n.get(R.string.cte_bad_response), reason = e.reason))
} catch (e: kotlinx.coroutines.CancellationException) {
throw e
} catch (e: Exception) {
Expand Down Expand Up @@ -228,8 +230,8 @@ class CoachOrchestrator(
if (attempts > maxFinalAttempts) {
val snippet = current.outputText.trim().take(200)
throw ParseExhausted(
"The model didn't return a valid structured answer after $maxFinalAttempts attempts." +
if (snippet.isEmpty()) "" else " It replied: “$snippet…”")
L10n.plural(R.plurals.cte_invalid_structured, maxFinalAttempts, maxFinalAttempts) +
if (snippet.isEmpty()) "" else " " + L10n.get(R.string.cte_it_replied, snippet))
}
val repair = OpenAIRequestBuilder.message("user", "Your previous output did not match the required coach_response JSON schema. Return only valid JSON for that schema now.")
current = send(client, flags, listOf(repair), emptyList(), coachResponseTextFormat, current.id)
Expand Down
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
package com.pulseloop.coach.orchestration

import com.pulseloop.R
import com.pulseloop.util.L10n
import com.pulseloop.coach.openai.ResponsesError
import kotlinx.serialization.Serializable
import kotlinx.serialization.json.Json
Expand All @@ -22,7 +24,7 @@ data class CoachTurnError(
val reason: String,
) {
/** Plain-text form stored in the message body (history/search fallback). */
val plainText: String get() = "Coach error · $code\n$reason"
val plainText: String get() = L10n.get(R.string.cte_plain, code, reason)

/** JSON form stored alongside the message so the error bubble can render
* the structured code/reason. Reuses the existing field — no schema change. */
Expand All @@ -48,19 +50,19 @@ data class CoachTurnError(
* app's `ResponsesError` cases explicitly and falls back to `message`. */
fun from(error: Throwable): CoachTurnError = when (error) {
is ResponsesError.MissingAPIKey -> CoachTurnError(
code = "No API key",
reason = "No API key is configured for the selected provider. Add one in Settings → AI Coach.")
code = L10n.get(R.string.cte_no_key),
reason = L10n.get(R.string.cte_no_key_reason))
is ResponsesError.Transport -> CoachTurnError(
code = "Network",
code = L10n.get(R.string.cte_network),
reason = transportReason(error.underlying))
is ResponsesError.Http -> CoachTurnError(
code = "HTTP ${error.status}",
reason = cleanReason(error.body, error.status))
is ResponsesError.Decoding -> CoachTurnError(code = "Response error", reason = error.msg)
is ResponsesError.Decoding -> CoachTurnError(code = L10n.get(R.string.cte_response_error), reason = error.msg)
is ResponsesError.EmptyOutput -> CoachTurnError(
code = "No output",
reason = "The model returned an empty response. Try again, or pick a different model.")
else -> CoachTurnError(code = "Error", reason = error.message ?: "Something went wrong.")
code = L10n.get(R.string.cte_no_output),
reason = L10n.get(R.string.cte_no_output_reason))
else -> CoachTurnError(code = L10n.get(R.string.dialog_error), reason = error.message ?: L10n.get(R.string.cte_generic))
}

/**
Expand All @@ -77,23 +79,19 @@ data class CoachTurnError(
return when (underlying) {
is java.net.UnknownHostException -> {
val host = hostFrom(detail)
"Couldn't look up ${host ?: "the provider"}. Your device can't resolve it right " +
"now — check your connection, and whether a VPN or a Private DNS setting is " +
"blocking it. (${detail.ifEmpty { "unknown host" }})"
L10n.get(R.string.cte_dns, host ?: L10n.get(R.string.cte_the_provider), detail.ifEmpty { "unknown host" })
}
// OkHttp reports connect and read timeouts as this same exception, and only the
// message tells them apart ("failed to connect to … after 30000ms" vs "timeout").
// The copy therefore stays neutral about which one happened, and the raw text is
// appended like every other branch so a bug report can still distinguish them.
is java.net.SocketTimeoutException ->
"The provider took too long to answer. Check your connection and try again — a " +
"VPN or a weak signal will do this. (${detail.ifEmpty { "timeout" }})"
L10n.get(R.string.cte_timeout, detail.ifEmpty { "timeout" })
is javax.net.ssl.SSLException ->
"The secure connection to the provider failed. This is usually a VPN, a proxy, " +
"or a network that intercepts traffic. (${detail.ifEmpty { "TLS error" }})"
L10n.get(R.string.cte_tls, detail.ifEmpty { "TLS error" })
is java.net.ConnectException ->
"Couldn't connect to the provider. (${detail.ifEmpty { "connection refused" }})"
else -> detail.ifEmpty { "The network request failed." }
L10n.get(R.string.cte_connect, detail.ifEmpty { "connection refused" })
else -> detail.ifEmpty { L10n.get(R.string.cte_network_failed) }
}
}

Expand Down Expand Up @@ -123,7 +121,7 @@ data class CoachTurnError(
} catch (_: Exception) {
// not JSON — fall through to the raw body
}
if (trimmed.isEmpty()) return "The provider returned HTTP $status with no details."
if (trimmed.isEmpty()) return L10n.get(R.string.cte_http_empty, status)
return trimmed.take(400)
}
}
Expand Down
Loading