Your phone, on your command. Gotcha is world's first fully on-device AI copilot for Android that turns natural language into real device actions — safely.
fix(llm): model requests time out after 3 minutes of silence by default (#104)
Durganshu8cdf0bd4f685
diff --git a/app/src/main/assets/app/about-gotcha.md b/app/src/main/assets/app/about-gotcha.mdindex 10410bc..73dc1de 100644--- a/app/src/main/assets/app/about-gotcha.md+++ b/app/src/main/assets/app/about-gotcha.md@@ -67,7 +67,7 @@ Everything below is reached from **Settings** in the navigation drawer.| Personal Info | Name, occupation, background, reply style, location, preferred currency and language || Language | App display language, AI reply language, voice language, STT language || AI | Hub for the two pages below |-| AI > AI Configuration | LLM provider, API key, Base URL, main and navigator models, API timeout, max context tokens, max tool rounds, max repeated tool calls, max navigation tool calls, max consecutive delegations, cache and debug-screenshot clearing |+| AI > AI Configuration | LLM provider, API key, Base URL, main and navigator models, API timeout (default 180 seconds; 0 never times out), max context tokens, max tool rounds, max repeated tool calls, max navigation tool calls, max consecutive delegations, cache and debug-screenshot clearing || AI > Speech (TTS / STT) | TTS and STT provider, base URL, key and model, voice selection, podcast host voices, auto-read replies aloud, transcription language override || Permissions | Every runtime and special-access permission, grouped: Communications, Contacts, Calendar, Media & Storage, Location, Device Control, Notifications, System Access, Health || Termux (Linux shell) | Guided setup for the Linux shell used by `run_termux_command` and audio conversion |diff --git a/app/src/main/java/com/gotcha/agent/AgentEngine.kt b/app/src/main/java/com/gotcha/agent/AgentEngine.ktindex a3d1c3a..14a79ed 100644--- a/app/src/main/java/com/gotcha/agent/AgentEngine.kt+++ b/app/src/main/java/com/gotcha/agent/AgentEngine.kt@@ -38,6 +38,7 @@ import kotlinx.serialization.json.JsonObjectimport kotlinx.serialization.json.JsonPrimitiveimport kotlinx.serialization.json.contentOrNullimport kotlinx.serialization.json.jsonPrimitive+import java.net.SocketTimeoutException/** Outcome of the sensitive-action confirmation step. */private enum class ConfirmDecision { APPROVED, DENIED, TIMED_OUT }@@ -48,6 +49,18 @@ private val WHITESPACE = Regex("\\s+")/** Maps API/network failures to a short, user-readable message. */internal fun friendlyAgentError(e: Exception): String = HumanReadableError.format(e)+/** Shown when the model server sends nothing back within the API timeout (#104). */+internal const val MODEL_TIMEOUT_MESSAGE =+ "The model didn't respond in time. Try again, or raise the API timeout in Settings → AI → AI Configuration."++/**+ * [friendlyAgentError] for a failed model request. A timeout here means the model+ * never answered, which the generic network wording ("try a smaller request")+ * does not say; the generic one stays for speech-to-text and the rest.+ */+internal fun friendlyModelError(e: Exception): String =+ if (e is SocketTimeoutException) MODEL_TIMEOUT_MESSAGE else friendlyAgentError(e)+/*** The core agent loop, extracted from ChatViewModel so it can run both inside* the in-app chat (ViewModel host) and inside a background service (voice-call@@ -541,7 +554,7 @@ class AgentEngine(throw e} catch (e: Exception) {// Also spoken: on a voice call an unannounced return is silence.- val error = friendlyAgentError(e)+ val error = friendlyModelError(e)events.onUi(MessageKind.ERROR, error)events.onAssistantReply(error)emitRunSummary(error, succeeded = false)diff --git a/app/src/main/java/com/gotcha/data/SettingsRepository.kt b/app/src/main/java/com/gotcha/data/SettingsRepository.ktindex b950d51..fb0a813 100644--- a/app/src/main/java/com/gotcha/data/SettingsRepository.kt+++ b/app/src/main/java/com/gotcha/data/SettingsRepository.kt@@ -49,6 +49,13 @@ enum class WakeWordListeningMode {*/const val DEFAULT_MAX_CONTEXT_TOKENS = 256_000+/**+ * How long a model request may go without the server sending anything, in+ * seconds, for a fresh install. Requests are not streamed, so this has to cover+ * the model writing its whole reply (#104). 0 means never time out.+ */+const val DEFAULT_API_TIMEOUT_SECONDS = 180L+/** Daily tip time for a fresh install: 10:00, in minutes after midnight. */const val DEFAULT_DAILY_TIP_MINUTE = 10 * 60@@ -87,6 +94,23 @@ internal fun liftMaxContextTokens(stored: Int, alreadyLifted: Boolean): MaxConteelse -> MaxContextTokensLift(stored, writeBack = false)}+/** What the one-shot API-timeout lift decided: the value to use, and whether to store it. */+internal data class ApiTimeoutLift(val value: Long, val writeBack: Boolean)++/**+ * Decides whether a stored API timeout should be lifted to [DEFAULT_API_TIMEOUT_SECONDS].+ *+ * 0 ("never time out") was the old default, so a stored 0 cannot be told apart+ * from never having chosen; it is lifted once, while [alreadyLifted] is false.+ * Any other value was typed in and is kept, and so is a 0 set after the lift.+ * Pure for the same reason as [liftMaxContextTokens].+ */+internal fun liftApiTimeout(stored: Long, alreadyLifted: Boolean): ApiTimeoutLift = when {+ alreadyLifted -> ApiTimeoutLift(stored, writeBack = false)+ stored == 0L -> ApiTimeoutLift(DEFAULT_API_TIMEOUT_SECONDS, writeBack = true)+ else -> ApiTimeoutLift(stored, writeBack = false)+}+data class Settings(// Which LLM backend is active. Defaults to the Samosa AI flow.val provider: LlmProvider = LlmProvider.SAMOSA_AI,@@ -112,7 +136,7 @@ data class Settings(*/val maxConsecutiveDelegations: Int = 3,val maxContextTokens: Int = DEFAULT_MAX_CONTEXT_TOKENS,- val apiTimeoutSeconds: Long = 0L,+ val apiTimeoutSeconds: Long = DEFAULT_API_TIMEOUT_SECONDS,// TTS / STT settingsval ttsProvider: AudioProvider = AudioProvider.ANDROID,val ttsApiBaseUrl: String = "",@@ -536,6 +560,28 @@ class SettingsRepository(context: Context) : SettingsStore {return lift.value}+ /**+ * The stored API timeout, with 0 lifted to [DEFAULT_API_TIMEOUT_SECONDS] the+ * first time this build loads settings (#104). 0 used to be the default, and+ * with it a model server that never replied left the chat on "Thinking…"+ * forever. Like [resolvedMaxContextTokens], it runs once, tracked by its own+ * flag, so a user can set 0 again afterwards and keep it.+ */+ private fun resolvedApiTimeoutSeconds(): Long {+ val alreadyLifted = prefs.getBoolean(KEY_API_TIMEOUT_LIFTED, false)+ val lift = liftApiTimeout(+ stored = prefs.getLong(KEY_API_TIMEOUT, DEFAULT_API_TIMEOUT_SECONDS),+ alreadyLifted = alreadyLifted+ )+ if (!alreadyLifted) {+ prefs.edit().apply {+ putBoolean(KEY_API_TIMEOUT_LIFTED, true)+ if (lift.writeBack) putLong(KEY_API_TIMEOUT, lift.value)+ }.apply()+ }+ return lift.value+ }+override fun load(): Settings = Settings(provider = LlmProvider.fromName(prefs.getString(KEY_PROVIDER, null)),apiKey = string(KEY_API_KEY),@@ -550,7 +596,7 @@ class SettingsRepository(context: Context) : SettingsStore {maxNavigationToolCalls = prefs.getInt(KEY_MAX_NAVIGATION_TOOL_CALLS, 30),maxConsecutiveDelegations = prefs.getInt(KEY_MAX_CONSECUTIVE_DELEGATIONS, 3),maxContextTokens = resolvedMaxContextTokens(),- apiTimeoutSeconds = prefs.getLong(KEY_API_TIMEOUT, 0L),+ apiTimeoutSeconds = resolvedApiTimeoutSeconds(),ttsProvider = runCatching {AudioProvider.valueOf(string(KEY_TTS_PROVIDER, "ANDROID"))}.getOrDefault(AudioProvider.ANDROID),@@ -775,6 +821,9 @@ class SettingsRepository(context: Context) : SettingsStore {/** Whether the one-shot 70k -> 256k lift has already run. */const val KEY_MAX_CONTEXT_TOKENS_RAISED = "max_context_tokens_raised"const val KEY_API_TIMEOUT = "api_timeout"++ /** Whether the one-shot 0 -> [DEFAULT_API_TIMEOUT_SECONDS] lift has already run (#104). */+ const val KEY_API_TIMEOUT_LIFTED = "api_timeout_lifted"const val KEY_TTS_PROVIDER = "tts_provider"const val KEY_TTS_API_URL = "tts_api_url"const val KEY_TTS_API_KEY = "tts_api_key"diff --git a/app/src/main/java/com/gotcha/llm/LLMClient.kt b/app/src/main/java/com/gotcha/llm/LLMClient.ktindex 1dcd29e..9fbb5bd 100644--- a/app/src/main/java/com/gotcha/llm/LLMClient.kt+++ b/app/src/main/java/com/gotcha/llm/LLMClient.kt@@ -4,6 +4,7 @@ import android.content.Contextimport com.gotcha.BuildConfigimport com.gotcha.audio.AudioModelimport com.gotcha.audio.ModelCategory+import com.gotcha.data.DEFAULT_API_TIMEOUT_SECONDSimport com.gotcha.i18n.Languageimport com.jakewharton.retrofit2.converter.kotlinx.serialization.asConverterFactoryimport kotlinx.serialization.builtins.ListSerializer@@ -13,13 +14,39 @@ import okhttp3.OkHttpClientimport okhttp3.logging.HttpLoggingInterceptorimport retrofit2.Retrofitimport java.security.MessageDigest+import java.util.concurrent.TimeUnit++/** Longest a connection to the model server may take to open, however long the API timeout is. */+private const val MAX_CONNECT_TIMEOUT_SECONDS = 15L++/** OkHttp timeouts, in seconds, for one API timeout setting. 0 means no timeout. */+internal data class LlmTimeouts(val connectSeconds: Long, val readSeconds: Long, val writeSeconds: Long)++/**+ * Splits the user's API timeout into OkHttp's timeouts (#104).+ *+ * Read and write are gaps between bytes, not a cap on the whole request, so a+ * reply that keeps arriving is never cut off; there is deliberately no call+ * timeout. Connecting never needs minutes, so it is capped at+ * [MAX_CONNECT_TIMEOUT_SECONDS]. 0 is the user asking for no timeout at all and+ * is passed through to every one of them.+ */+internal fun llmTimeouts(apiTimeoutSeconds: Long): LlmTimeouts {+ val timeout = apiTimeoutSeconds.coerceAtLeast(0L)+ if (timeout == 0L) return LlmTimeouts(0L, 0L, 0L)+ return LlmTimeouts(+ connectSeconds = timeout.coerceAtMost(MAX_CONNECT_TIMEOUT_SECONDS),+ readSeconds = timeout,+ writeSeconds = timeout+ )+}class LLMClient(private val apiKey: String,private val baseUrl: String,private val model: String = "chai-small",context: Context? = null,- private val apiTimeoutSeconds: Long = 0L,+ private val apiTimeoutSeconds: Long = DEFAULT_API_TIMEOUT_SECONDS,private val cache: LLMCache = LLMCache(context),/*** Invoked when the server responds 401 (e.g. an expired/blacklisted Samosa@@ -48,10 +75,11 @@ class LLMClient(redactHeader("Authorization")}+ val timeouts = llmTimeouts(apiTimeoutSeconds)val okHttpClient = OkHttpClient.Builder()- .connectTimeout(apiTimeoutSeconds, java.util.concurrent.TimeUnit.SECONDS)- .readTimeout(apiTimeoutSeconds, java.util.concurrent.TimeUnit.SECONDS)- .writeTimeout(apiTimeoutSeconds, java.util.concurrent.TimeUnit.SECONDS)+ .connectTimeout(timeouts.connectSeconds, TimeUnit.SECONDS)+ .readTimeout(timeouts.readSeconds, TimeUnit.SECONDS)+ .writeTimeout(timeouts.writeSeconds, TimeUnit.SECONDS).addInterceptor { chain ->val builder = chain.request().newBuilder().addHeader("Authorization", "Bearer $apiKey")diff --git a/app/src/main/java/com/gotcha/ui/AiConfigScreen.kt b/app/src/main/java/com/gotcha/ui/AiConfigScreen.ktindex 7feb631..f54c06b 100644--- a/app/src/main/java/com/gotcha/ui/AiConfigScreen.kt+++ b/app/src/main/java/com/gotcha/ui/AiConfigScreen.kt@@ -24,6 +24,7 @@ import androidx.compose.ui.platform.testTagimport androidx.compose.ui.text.input.KeyboardTypeimport androidx.compose.ui.text.input.PasswordVisualTransformationimport androidx.compose.ui.text.input.VisualTransformation+import com.gotcha.data.DEFAULT_API_TIMEOUT_SECONDSimport com.gotcha.data.DEFAULT_MAX_CONTEXT_TOKENSimport com.gotcha.data.LlmProviderimport com.gotcha.data.Settings@@ -137,7 +138,7 @@ fun AiConfigScreen(maxNavigationToolCalls = maxNavigationToolCalls.toIntOrNull()?.takeIf { it > 0 } ?: 30,maxConsecutiveDelegations = maxConsecutiveDelegations.toIntOrNull()?.takeIf { it > 0 } ?: 3,maxContextTokens = maxContextTokens.toIntOrNull()?.takeIf { it > 0 } ?: DEFAULT_MAX_CONTEXT_TOKENS,- apiTimeoutSeconds = apiTimeoutSeconds.toLongOrNull()?.takeIf { it >= 0 } ?: 0L+ apiTimeoutSeconds = apiTimeoutSeconds.toLongOrNull()?.takeIf { it >= 0 } ?: DEFAULT_API_TIMEOUT_SECONDS)/**@@ -492,7 +493,10 @@ fun AiConfigScreen(OutlinedTextField(value = apiTimeoutSeconds,onValueChange = { apiTimeoutSeconds = it },- label = { Text("API Timeout (seconds, 0 for infinite)") },+ label = { Text("API timeout (seconds)") },+ supportingText = {+ Text("Default $DEFAULT_API_TIMEOUT_SECONDS. 0 = never time out (not recommended).")+ },singleLine = true,keyboardOptions = KeyboardOptions(keyboardType = KeyboardType.Number),modifier = Modifier.fillMaxWidth().settingsField("settings_api_timeout")diff --git a/app/src/test/java/com/gotcha/agent/FriendlyModelErrorTest.kt b/app/src/test/java/com/gotcha/agent/FriendlyModelErrorTest.ktnew file mode 100644index 0000000..0f5e5a1--- /dev/null+++ b/app/src/test/java/com/gotcha/agent/FriendlyModelErrorTest.kt@@ -0,0 +1,22 @@+package com.gotcha.agent++import org.junit.Assert.assertEquals+import org.junit.Assert.assertTrue+import org.junit.Test+import java.net.SocketTimeoutException+import java.net.UnknownHostException++class FriendlyModelErrorTest {++ /** A model server that never answers ends the run with this, not a network hint (#104). */+ @Test+ fun `a timeout says the model did not respond in time`() {+ assertEquals(MODEL_TIMEOUT_MESSAGE, friendlyModelError(SocketTimeoutException("timeout")))+ }++ @Test+ fun `other failures keep the generic wording`() {+ val message = friendlyModelError(UnknownHostException("api.openai.com"))+ assertTrue(message, message.contains("Cannot connect to server"))+ }+}diff --git a/app/src/test/java/com/gotcha/data/ApiTimeoutLiftTest.kt b/app/src/test/java/com/gotcha/data/ApiTimeoutLiftTest.ktnew file mode 100644index 0000000..427ef4c--- /dev/null+++ b/app/src/test/java/com/gotcha/data/ApiTimeoutLiftTest.kt@@ -0,0 +1,52 @@+package com.gotcha.data++import org.junit.Assert.assertEquals+import org.junit.Assert.assertFalse+import org.junit.Assert.assertTrue+import org.junit.Test++/**+ * 0 ("never time out") was the old default, so an update alone leaves every+ * existing install waiting forever on a model server that never replies (#104).+ * This lift is what moves them, once; same reasoning as [MaxContextTokensLiftTest].+ */+class ApiTimeoutLiftTest {++ @Test+ fun `an install still on the old default of 0 is lifted and the new value stored`() {+ val lift = liftApiTimeout(stored = 0L, alreadyLifted = false)+ assertEquals(DEFAULT_API_TIMEOUT_SECONDS, lift.value)+ assertTrue("the lifted value has to be persisted, not just returned", lift.writeBack)+ }++ /** A fresh install never wrote the key, so the read already returns the default. */+ @Test+ fun `a fresh install is left alone`() {+ val lift = liftApiTimeout(stored = DEFAULT_API_TIMEOUT_SECONDS, alreadyLifted = false)+ assertEquals(DEFAULT_API_TIMEOUT_SECONDS, lift.value)+ assertFalse(lift.writeBack)+ }++ /** The point of the one-shot flag: "no timeout" chosen after the lift is kept. */+ @Test+ fun `0 chosen after the lift has run is kept`() {+ val lift = liftApiTimeout(stored = 0L, alreadyLifted = true)+ assertEquals(0L, lift.value)+ assertFalse(lift.writeBack)+ }++ /** A typed-in timeout is a decision, and survives even on the run where the lift fires. */+ @Test+ fun `a hand-set timeout is never rewritten`() {+ listOf(30L, 600L).forEach { stored ->+ val lift = liftApiTimeout(stored = stored, alreadyLifted = false)+ assertEquals(stored, lift.value)+ assertFalse(lift.writeBack)+ }+ }++ @Test+ fun `a fresh Settings times out by default`() {+ assertEquals(DEFAULT_API_TIMEOUT_SECONDS, Settings().apiTimeoutSeconds)+ }+}diff --git a/app/src/test/java/com/gotcha/llm/LLMClientTest.kt b/app/src/test/java/com/gotcha/llm/LLMClientTest.ktindex 93a7f5e..93b117a 100644--- a/app/src/test/java/com/gotcha/llm/LLMClientTest.kt+++ b/app/src/test/java/com/gotcha/llm/LLMClientTest.kt@@ -8,11 +8,15 @@ import kotlinx.serialization.json.buildJsonObjectimport kotlinx.serialization.json.putimport okhttp3.mockwebserver.MockResponseimport okhttp3.mockwebserver.MockWebServer+import okhttp3.mockwebserver.SocketPolicyimport org.junit.Afterimport org.junit.Assert.assertEqualsimport org.junit.Assert.assertTrue+import org.junit.Assert.failimport org.junit.Beforeimport org.junit.Test+import java.net.SocketTimeoutException+import java.util.concurrent.TimeUnitclass LLMClientTest {@@ -323,4 +327,48 @@ class LLMClientTest {!body.contains("</summary>"))}++ /** A server that accepts the request and never answers must end the call, not hang it (#104). */+ @Test+ fun `a server that never responds times out`() = runTest {+ server.enqueue(MockResponse().setSocketPolicy(SocketPolicy.NO_RESPONSE))+ val shortTimeout = LLMClient(+ apiKey = "test-key",+ baseUrl = server.url("/").toString(),+ apiTimeoutSeconds = 1L+ )+ try {+ shortTimeout.chat(listOf(ChatMessage(role = "user", content = JsonPrimitive("Hello?"))))+ fail("expected the request to time out")+ } catch (_: SocketTimeoutException) {+ // expected+ }+ }++ /**+ * The timeout is a gap between bytes, not a cap on the whole request: a reply+ * that takes longer than the timeout overall but keeps arriving is not cut off.+ */+ @Test+ fun `a slow reply that keeps arriving is not cut off`() = runTest {+ server.enqueue(+ MockResponse()+ .setBody("""{"choices":[{"message":{"role":"assistant","content":"slow but steady"}}]}""")+ .throttleBody(32, 400, TimeUnit.MILLISECONDS)+ )+ val shortTimeout = LLMClient(+ apiKey = "test-key",+ baseUrl = server.url("/").toString(),+ apiTimeoutSeconds = 1L+ )+ val response = shortTimeout.chat(listOf(ChatMessage(role = "user", content = JsonPrimitive("Take your time"))))+ assertEquals("slow but steady", response.choices.first().message.textContent)+ }++ @Test+ fun `the API timeout is split into OkHttp timeouts`() {+ assertEquals(LlmTimeouts(15L, 180L, 180L), llmTimeouts(180L))+ assertEquals(LlmTimeouts(5L, 5L, 5L), llmTimeouts(5L))+ assertEquals("0 is the user asking for no timeout", LlmTimeouts(0L, 0L, 0L), llmTimeouts(0L))+ }}