Skip to content

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: sanitize malformed tool-call arguments to prevent server 400 errors closes #13

Rishabh Bajpaib5c1532d9d31
diff --git a/CHANGELOG.md b/CHANGELOG.md
index dbe42fd..0fe0301 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -4,6 +4,19 @@ All notable changes to Gotcha are documented here.
## [Unreleased]
+### Fixed — Malformed tool call no longer bricks the chat (#13)
+
+- **A tool call with invalid `arguments` JSON can no longer poison a chat.** When
+ the model emits a tool call whose `arguments` aren't parseable (e.g. a cut-off
+ summary with stray `</summary>` tags), the app used to keep that raw message in
+ the history and re-send it on every later turn — and some servers 400 the whole
+ request when they see it, so every subsequent message failed too.
+- Malformed tool-call arguments are now neutralized to `{}` **before they are
+ stored or sent** (sanitized on append and again at the `LLMClient` send
+ boundary), so the chat keeps working. The model still receives the truthful
+ "Malformed tool arguments" tool result so it can retry. Sessions saved before
+ the fix self-heal on their next request.
+
### Added — `update_user_profile` agent tool (#18)
- **The agent can now keep the user's profile fresh.** A new Operator-only
diff --git a/app/src/main/java/com/gotcha/agent/AgentEngine.kt b/app/src/main/java/com/gotcha/agent/AgentEngine.kt
index e819ab2..2748805 100644
--- a/app/src/main/java/com/gotcha/agent/AgentEngine.kt
+++ b/app/src/main/java/com/gotcha/agent/AgentEngine.kt
@@ -15,6 +15,7 @@ import com.gotcha.llm.ChatMessage
import com.gotcha.llm.LLMClient
import com.gotcha.llm.ToolCall
import com.gotcha.llm.visionUserMessage
+import com.gotcha.llm.withValidToolCallArguments
import com.gotcha.tools.AgentMode
import com.gotcha.tools.AppNavigatorSession
import com.gotcha.tools.DeviceCapabilities
@@ -514,7 +515,12 @@ class AgentEngine(
return
}
- history += message
+ // Persist a sanitized copy: a tool call whose arguments aren't valid
+ // JSON would otherwise be re-sent verbatim on every later turn and
+ // make the server 400 the whole chat (issue #13). executeToolCalls
+ // below still runs the ORIGINAL calls, so the model still sees the
+ // truthful "Malformed tool arguments" result and can fix itself.
+ history += message.withValidToolCallArguments()
if (message.hasText || !message.reasoningContent.isNullOrBlank()) {
events.onUi(
MessageKind.ASSISTANT,
diff --git a/app/src/main/java/com/gotcha/llm/LLMClient.kt b/app/src/main/java/com/gotcha/llm/LLMClient.kt
index 57ea5de..158d747 100644
--- a/app/src/main/java/com/gotcha/llm/LLMClient.kt
+++ b/app/src/main/java/com/gotcha/llm/LLMClient.kt
@@ -77,7 +77,13 @@ class LLMClient(
modelOverride: String? = null
): ChatResponse {
val targetModel = modelOverride ?: model
- val cacheKey = buildCacheKey(targetModel, messages, tools)
+ // Safety net for histories that carried a malformed tool call before the
+ // append-time sanitization existed (or were restored from an old session):
+ // never transmit arguments that aren't valid JSON, or the server 400s the
+ // whole request and every later turn (issue #13). Runs before the cache
+ // key so identical (sanitized) histories share a key.
+ val sanitizedMessages = messages.map { it.withValidToolCallArguments() }
+ val cacheKey = buildCacheKey(targetModel, sanitizedMessages, tools)
if (temperature == null || temperature == 0f) {
cache.get(cacheKey)?.let { return it }
@@ -85,7 +91,7 @@ class LLMClient(
val request = ChatRequest(
model = targetModel,
- messages = messages,
+ messages = sanitizedMessages,
tools = tools.ifEmpty { null },
temperature = temperature,
promptCacheKey = sessionId
diff --git a/app/src/main/java/com/gotcha/llm/Models.kt b/app/src/main/java/com/gotcha/llm/Models.kt
index f85177b..50684c4 100644
--- a/app/src/main/java/com/gotcha/llm/Models.kt
+++ b/app/src/main/java/com/gotcha/llm/Models.kt
@@ -4,6 +4,7 @@ import kotlinx.serialization.EncodeDefault
import kotlinx.serialization.ExperimentalSerializationApi
import kotlinx.serialization.SerialName
import kotlinx.serialization.Serializable
+import kotlinx.serialization.json.Json
import kotlinx.serialization.json.JsonArray
import kotlinx.serialization.json.JsonElement
import kotlinx.serialization.json.JsonObject
@@ -164,3 +165,33 @@ data class ModelInfo(
@SerialName("provider_type")
val providerType: String? = null
)
+
+/**
+ * True when [arguments] parses as a JSON object — the shape a tool-call
+ * `arguments` string must take. Used to neutralize model-emitted tool calls
+ * whose arguments are invalid JSON: some OpenAI-compatible servers reject the
+ * whole request with HTTP 400 when history contains such a call, bricking the
+ * chat for every later message (issue #13).
+ */
+internal fun isParsableJsonObject(arguments: String): Boolean = try {
+ Json.parseToJsonElement(arguments) is JsonObject
+} catch (_: Exception) {
+ false
+}
+
+/**
+ * Copy of this message with any tool call whose `arguments` are not valid JSON
+ * replaced by `"{}"`; valid calls are left untouched. Callers persist or send
+ * this copy so a malformed call can never poison the request again.
+ */
+internal fun ChatMessage.withValidToolCallArguments(): ChatMessage {
+ val calls = toolCalls ?: return this
+ val sanitized = calls.map { call ->
+ if (isParsableJsonObject(call.function.arguments)) {
+ call
+ } else {
+ call.copy(function = call.function.copy(arguments = "{}"))
+ }
+ }
+ return copy(toolCalls = sanitized)
+}
diff --git a/app/src/main/java/com/gotcha/tools/SubAgentSession.kt b/app/src/main/java/com/gotcha/tools/SubAgentSession.kt
index 19db6bc..dd9b68e 100644
--- a/app/src/main/java/com/gotcha/tools/SubAgentSession.kt
+++ b/app/src/main/java/com/gotcha/tools/SubAgentSession.kt
@@ -9,6 +9,7 @@ import com.gotcha.connectors.ConnectorRegistry
import com.gotcha.data.Settings
import com.gotcha.llm.ChatMessage
import com.gotcha.llm.LLMClient
+import com.gotcha.llm.withValidToolCallArguments
import kotlinx.coroutines.CancellationException
import kotlinx.serialization.json.Json
import kotlinx.serialization.json.JsonObject
@@ -97,7 +98,7 @@ class SubAgentSession(
return SubAgentOutput(text, collectedSteps.toList())
}
- history.add(message)
+ history.add(message.withValidToolCallArguments())
// Check for ask_final_answer
val finalCall = toolCalls.firstOrNull { it.function.name == "ask_final_answer" }
diff --git a/app/src/test/java/com/gotcha/agent/AgentLoopTest.kt b/app/src/test/java/com/gotcha/agent/AgentLoopTest.kt
index 85c6a9d..ccfd655 100644
--- a/app/src/test/java/com/gotcha/agent/AgentLoopTest.kt
+++ b/app/src/test/java/com/gotcha/agent/AgentLoopTest.kt
@@ -5,6 +5,7 @@ import androidx.test.core.app.ApplicationProvider
import com.gotcha.data.ChatHistoryRepository
import com.gotcha.data.LlmProvider
import com.gotcha.data.Settings
+import com.gotcha.llm.ChatRequest
import com.gotcha.llm.LLMClient
import com.gotcha.testsupport.FakeAndroidKeyStore
import com.gotcha.testsupport.ShadowExternalStorageManager
@@ -13,6 +14,7 @@ import com.gotcha.tools.FileResolver
import com.gotcha.tools.ScreenPerception
import com.gotcha.tools.ToolResult
import kotlinx.coroutines.test.runTest
+import kotlinx.serialization.json.Json
import okhttp3.mockwebserver.MockResponse
import okhttp3.mockwebserver.MockWebServer
import org.junit.After
@@ -166,6 +168,38 @@ class AgentLoopTest {
assertTrue("the error was not returned to the model:\n$followUp", followUp.contains("content"))
}
+ @Test
+ fun `a malformed tool call does not poison subsequent turns (issue 13)`() = runTest {
+ // The exact shape that bricked issue #13: the model emitted a tool call
+ // whose `arguments` are not valid JSON (a cut-off summary string).
+ enqueueToolCall("finish_task", """{"summary": "cut off at the end""")
+ enqueueTextReply("Got it.")
+
+ engine.run(AgentMode.OPERATOR)
+
+ // The loop continues past the malformed call instead of aborting.
+ assertEquals("expected a follow-up turn after the malformed call", 2, server.requestCount)
+ server.takeRequest()
+ val followUpBody = server.takeRequest().body.readUtf8()
+ val sent = Json { ignoreUnknownKeys = true }.decodeFromString(ChatRequest.serializer(), followUpBody)
+
+ // The poisoned arguments were neutralized before they could be re-sent,
+ // so a strict server would not 400 the whole chat on this history.
+ val replayedArguments = sent.messages
+ .flatMap { it.toolCalls.orEmpty() }
+ .filter { it.id == "call_1" }
+ .map { it.function.arguments }
+ assertTrue("the tool call was not replayed", replayedArguments.isNotEmpty())
+ replayedArguments.forEach { assertEquals("{}", it) }
+
+ // The model still saw the truthful error text so it could recover.
+ assertTrue(
+ "the malformed-arguments error was not fed back to the model:\n$followUpBody",
+ sent.messages.any { it.role == "tool" && it.textContent.contains("Malformed tool arguments") }
+ )
+ assertEquals("Got it.", events.assistantReplies.lastOrNull())
+ }
+
@Test
fun `an empty model response surfaces an error rather than looping`() = runTest {
server.enqueue(MockResponse().setBody("""{"choices":[]}"""))
diff --git a/app/src/test/java/com/gotcha/llm/LLMClientTest.kt b/app/src/test/java/com/gotcha/llm/LLMClientTest.kt
index cf2008b..93a7f5e 100644
--- a/app/src/test/java/com/gotcha/llm/LLMClientTest.kt
+++ b/app/src/test/java/com/gotcha/llm/LLMClientTest.kt
@@ -2,6 +2,7 @@ package com.gotcha.llm
import com.gotcha.i18n.Language
import kotlinx.coroutines.test.runTest
+import kotlinx.serialization.json.Json
import kotlinx.serialization.json.JsonPrimitive
import kotlinx.serialization.json.buildJsonObject
import kotlinx.serialization.json.put
@@ -274,4 +275,52 @@ class LLMClientTest {
assertEquals(listOf("my-private-llm"), result)
}
+
+ @Test
+ fun `malformed tool-call arguments are sanitized before they leave the client`() = runTest {
+ server.enqueue(
+ MockResponse().setBody(
+ """{"choices":[{"message":{"role":"assistant","content":"ok"}}]}"""
+ ).setHeader("Content-Type", "application/json")
+ )
+
+ // The exact shape that bricked issue #13: the model cut the summary short
+ // and closed with `</summary>`/`</function>` tags inside the JSON string.
+ val poisoned = ChatMessage(
+ role = "assistant",
+ toolCalls = listOf(
+ ToolCall(
+ id = "call_poisoned",
+ function = FunctionCall(
+ "finish_task",
+ """{"summary": "रिशभ…कर सकते हैं:</summary>\n</function>\n</tool_call>"""
+ )
+ ),
+ ToolCall(
+ id = "call_fine",
+ function = FunctionCall("websearch", """{"query":"hi","numResults":5}""")
+ )
+ )
+ )
+
+ client.chat(
+ messages = listOf(
+ ChatMessage(role = "user", content = JsonPrimitive("continue")),
+ poisoned
+ )
+ )
+
+ val body = server.takeRequest().body.readUtf8()
+ val sent = Json { ignoreUnknownKeys = true }.decodeFromString(ChatRequest.serializer(), body)
+
+ val calls = sent.messages.flatMap { it.toolCalls.orEmpty() }
+ assertEquals("call_poisoned", calls[0].id)
+ assertEquals("{}", calls[0].function.arguments)
+ assertEquals("call_fine", calls[1].id)
+ assertEquals("""{"query":"hi","numResults":5}""", calls[1].function.arguments)
+ assertTrue(
+ "the malformed fragment must never leave the client:\n$body",
+ !body.contains("</summary>")
+ )
+ }
}
diff --git a/app/src/test/java/com/gotcha/llm/ModelsTest.kt b/app/src/test/java/com/gotcha/llm/ModelsTest.kt
index d2198de..cb96bf3 100644
--- a/app/src/test/java/com/gotcha/llm/ModelsTest.kt
+++ b/app/src/test/java/com/gotcha/llm/ModelsTest.kt
@@ -226,4 +226,50 @@ class ModelsTest {
assertNull(decoded.data[2].providerType)
assertNull(decoded.data[2].task)
}
+
+ // ---- malformed tool-call arguments (issue #13) ----
+
+ @Test
+ fun `isParsableJsonObject accepts objects and rejects everything else`() {
+ assertTrue(isParsableJsonObject("{}"))
+ assertTrue(isParsableJsonObject("""{"summary":"hi"}"""))
+ assertFalse(isParsableJsonObject(""))
+ assertFalse(isParsableJsonObject("not json"))
+ assertFalse(isParsableJsonObject("[1,2]"))
+ assertFalse(isParsableJsonObject("\"string\""))
+ assertFalse(isParsableJsonObject("""{"summary": "unterminated"""))
+ }
+
+ @Test
+ fun `malformed tool call arguments are replaced with an empty object`() {
+ val msg = ChatMessage(
+ role = "assistant",
+ toolCalls = listOf(
+ ToolCall(
+ id = "call_bad",
+ function = FunctionCall("finish_task", """{"summary": "unterminated""")
+ ),
+ ToolCall(
+ id = "call_ok",
+ function = FunctionCall("websearch", """{"query":"hi"}""")
+ )
+ )
+ )
+
+ val sanitized = msg.withValidToolCallArguments()
+
+ assertEquals("{}", sanitized.toolCalls!![0].function.arguments)
+ assertEquals("""{"query":"hi"}""", sanitized.toolCalls!![1].function.arguments)
+ assertEquals("call_bad", sanitized.toolCalls!![0].id)
+ // The original is untouched.
+ assertEquals("""{"summary": "unterminated""", msg.toolCalls!![0].function.arguments)
+ }
+
+ @Test
+ fun `messages without tool calls pass through unchanged`() {
+ val plain = ChatMessage(role = "user", content = JsonPrimitive("hello"))
+ val noCalls = ChatMessage(role = "assistant", content = JsonPrimitive("ok"))
+ assertEquals(plain, plain.withValidToolCallArguments())
+ assertEquals(noCalls, noCalls.withValidToolCallArguments())
+ }
}