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(agent): a model request that timed out no longer waits on the chat title too (#104)
Durganshu0b9f7cbf7e69
diff --git a/app/src/main/java/com/gotcha/agent/AgentEngine.kt b/app/src/main/java/com/gotcha/agent/AgentEngine.ktindex 14a79ed..9b2152c 100644--- a/app/src/main/java/com/gotcha/agent/AgentEngine.kt+++ b/app/src/main/java/com/gotcha/agent/AgentEngine.kt@@ -32,6 +32,7 @@ import com.gotcha.util.GotchaLogimport com.gotcha.util.HumanReadableErrorimport kotlinx.coroutines.CancellationExceptionimport kotlinx.coroutines.delay+import kotlinx.coroutines.withTimeoutOrNullimport kotlinx.serialization.json.Jsonimport kotlinx.serialization.json.JsonArrayimport kotlinx.serialization.json.JsonObject@@ -286,6 +287,14 @@ class AgentEngine(private setprivate var titleGenerationAttempted = false+ /**+ * Whether the last main-model request failed. The title request goes to the+ * same server, and saving the chat waits for it before the run is marked+ * finished, so asking a server that just timed out would hold the chat on+ * "Thinking…" for a second full API timeout (#104).+ */+ private var lastModelRequestFailed = false+/** Falls back to the truncated first user message until [generatedTitle] is set. */fun currentTitle(): String =generatedTitle ?: history.firstOrNull { it.role == "user" }?.textContent?.take(30) ?: "New Chat"@@ -307,6 +316,8 @@ class AgentEngine(*/private suspend fun generateTitleIfNeeded(llm: LLMClient) {if (titleGenerationAttempted) return+ // Not marked attempted: the next run that reaches the model titles the chat.+ if (lastModelRequestFailed) returnval firstUserText = history.firstOrNull { it.role == "user" }?.textContent?.trim()if (firstUserText.isNullOrBlank()) returntitleGenerationAttempted = true@@ -334,7 +345,11 @@ class AgentEngine())val titleModel = settings.subAgentModel.ifBlank { settings.model }- val response = llm.chat(messages = messages, temperature = 0f, modelOverride = titleModel)+ // Capped on its own: the title is a nicety, and the run is not marked+ // finished until it returns.+ val response = withTimeoutOrNull(TITLE_TIMEOUT_MS) {+ llm.chat(messages = messages, temperature = 0f, modelOverride = titleModel)+ } ?: returnChatTitle.sanitize(response.choices.firstOrNull()?.message?.textContent)?.let {generatedTitle = it}@@ -549,10 +564,11 @@ class AgentEngine(messages,ToolRegistry.toolsForAgent(agent, hiddenTools()),sessionId = promptCacheKey ?: sessionId- )+ ).also { lastModelRequestFailed = false }} catch (e: CancellationException) {throw e} catch (e: Exception) {+ lastModelRequestFailed = true// Also spoken: on a voice call an unannounced return is silence.val error = friendlyModelError(e)events.onUi(MessageKind.ERROR, error)@@ -1885,6 +1901,9 @@ class AgentEngine(private const val TAG = "Gotcha"private const val INTER_CALL_DELAY_MS = 400L+ /** Longest the best-effort chat-title request may hold up the end of a run. */+ private const val TITLE_TIMEOUT_MS = 20_000L+/** Upper bound on persisted [RunSummary]s per session (newest wins). */private const val MAX_RUN_SUMMARIES = 20diff --git a/app/src/test/java/com/gotcha/agent/AgentLoopTest.kt b/app/src/test/java/com/gotcha/agent/AgentLoopTest.ktindex f24457b..6fd8c0b 100644--- a/app/src/test/java/com/gotcha/agent/AgentLoopTest.kt+++ b/app/src/test/java/com/gotcha/agent/AgentLoopTest.kt@@ -13,6 +13,7 @@ import com.gotcha.tools.AgentModeimport com.gotcha.tools.FileResolverimport com.gotcha.tools.ScreenPerceptionimport com.gotcha.tools.ToolResult+import kotlinx.coroutines.runBlockingimport kotlinx.coroutines.test.runTestimport kotlinx.serialization.json.Jsonimport okhttp3.mockwebserver.MockResponse@@ -649,6 +650,33 @@ class AgentLoopTest {assertFalse(events.runSummaries.single().succeeded)}+ /**+ * Saving the chat at the end of a run asks the same server for a title, and the+ * run is not marked finished until that returns. After the model request has+ * just failed (a timeout, #104), asking again would hold the chat on "Thinking…"+ * for a second full timeout; the title waits for a run that reaches the model.+ */+ // runBlocking, not runTest: the title request's own timeout would expire at+ // once in runTest's virtual time while the request waits on real network I/O.+ @Test+ fun `no title is requested after the model request failed, and the next good run makes one`() = runBlocking {+ addUserMessage("Fix my wifi please")+ server.enqueue(MockResponse().setResponseCode(500).setBody("boom"))++ engine.run(AgentMode.OPERATOR)+ engine.saveCurrentSession()++ assertEquals("only the failed model request, no title request", 1, server.requestCount)+ assertEquals(null, engine.generatedTitle)++ enqueueToolCall("finish_task", """{"summary":"Done."}""")+ enqueueTextReply("Wifi fix")++ engine.run(AgentMode.OPERATOR)++ assertEquals("Wifi fix", engine.generatedTitle)+ }+@Testfun `finish_task emits a succeeded run summary`() = runTest {enqueueToolCall("finish_task", """{"summary":"All done."}""")