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(agent): keep the working directory out of the cached prompt prefix (#121)

Durganshu778f70ca00c9
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 46024b6..f362f79 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -71,6 +71,12 @@ All notable changes to Gotcha are documented here.
won't ask twice in one task. App navigation stops at the step that needs a
permission or a Settings switch and asks once Gotcha is back on screen. It
no longer mentions the permission in passing at the end.
+- **Faster first replies in a new chat with prompt caching** (#121). Each
+ chat's folder was named near the top of what Gotcha sends the AI, so a new
+ chat, or the second message after a chat got its title, couldn't reuse the
+ cached start of the request. The folder now comes after the
+ conversation instead. Local servers such as llama-server skip reprocessing
+ thousands of tokens, and providers that discount cached input charge less.
## [1.3.0]
### Added
diff --git a/app/src/main/java/com/gotcha/agent/AgentEngine.kt b/app/src/main/java/com/gotcha/agent/AgentEngine.kt
index a0e9387..a6e35d0 100644
--- a/app/src/main/java/com/gotcha/agent/AgentEngine.kt
+++ b/app/src/main/java/com/gotcha/agent/AgentEngine.kt
@@ -579,12 +579,12 @@ class AgentEngine(
// Build message array optimized for prompt caching:
// 1. System prompt at Index 0 (instructions + static environment + connected accounts + user profile)
// 2. Conversation history (4-turn screen observation retention window)
- // 3. Current timestamp (system message at tail)
+ // 3. Working directory + current timestamp (system message at tail)
// 4. Active skills index summary (user message at tail)
val messages = buildList {
add(systemPromptMessage(agent))
addAll(cullOldObservations(trimmedHistory()))
- add(currentTimestampMessage())
+ add(runContextMessage())
addAll(activeSkillsMessages(agent))
}
val response = try {
@@ -1342,16 +1342,27 @@ class AgentEngine(
(if (scheduledRun) ScheduledTaskTool.TOOL_NAMES else emptySet())
/**
- * A separate system message carrying only the current date/time.
+ * A separate system message carrying the facts that differ per chat or per
+ * call: the working directory and the current date/time.
* Placed after the conversation history so the Index 0 static System Prompt +
- * history prefix stays in the KV cache while the timestamp is always fresh.
+ * history prefix stays in the KV cache while these stay fresh. The working
+ * directory used to sit in `<env>`; being unique to each chat (and renamed
+ * once the title arrives), it changed the prefix ahead of everything that
+ * follows, so a new chat reused almost none of the cache (issue #121).
*/
- private fun currentTimestampMessage(): ChatMessage {
+ internal fun runContextMessage(): ChatMessage {
val dateTime = java.text.SimpleDateFormat(
"EEE MMM dd yyyy, HH:mm:ss 'UTC'Z",
java.util.Locale.US
).apply { timeZone = java.util.TimeZone.getDefault() }.format(java.util.Date())
- return ChatMessage(role = "system", content = JsonPrimitive("Current date/time: $dateTime"))
+ return ChatMessage(
+ role = "system",
+ content = JsonPrimitive(
+ "Working directory: ${FileResolver.WORKING_DIR_BASE}\n" +
+ "(Relative paths in read_file/write_file/list_files resolve against the working directory.)\n" +
+ "Current date/time: $dateTime"
+ )
+ )
}
/**
@@ -1572,8 +1583,8 @@ class AgentEngine(
* Builds the environment info string with device info, agent mode,
* and service statuses (PRD §14.1).
*
- * The date/time is intentionally excluded — it is provided via
- * [currentTimestampMessage] placed after the conversation history
+ * The working directory and date/time are intentionally excluded — they are
+ * provided via [runContextMessage] placed after the conversation history
* so that this block stays fully static and the server-side KV cache
* for the [env block + history] prefix is preserved across calls.
*/
@@ -1652,8 +1663,6 @@ class AgentEngine(
)
appendLine(" VPN active: ${if (vpnActive) "yes" else "no"}")
appendLine(" App version: $versionName")
- appendLine(" Working directory: ${FileResolver.WORKING_DIR_BASE}")
- appendLine(" (Relative paths in read_file/write_file/list_files resolve against the working directory.)")
// Connector state, rebuilt every call. The active list is what lets the
// model notice a connector that appeared mid-conversation: its own
// earlier turns may say "no account is connected", and a tool quietly
diff --git a/app/src/test/java/com/gotcha/agent/PromptCacheAndTokenOptimizationTest.kt b/app/src/test/java/com/gotcha/agent/PromptCacheAndTokenOptimizationTest.kt
index f76ad94..18effd6 100644
--- a/app/src/test/java/com/gotcha/agent/PromptCacheAndTokenOptimizationTest.kt
+++ b/app/src/test/java/com/gotcha/agent/PromptCacheAndTokenOptimizationTest.kt
@@ -367,10 +367,45 @@ class PromptCacheAndTokenOptimizationTest {
@Test
fun `AgentEngine systemPromptMessage combines instructions and environment into Index 0 System message`() {
+ val msg = newEngine().systemPromptMessage(com.gotcha.tools.AgentMode.OPERATOR)
+ assertEquals("system", msg.role)
+ val text = msg.textContent
+ assertTrue("Should contain core Operator instructions", text.contains("You are Gotcha"))
+ assertTrue("Should contain env block", text.contains("<env>"))
+ assertTrue("Should contain device model info", text.contains("Device model:"))
+ }
+
+ @Test
+ fun `working directory rides in the tail context message, not the cached system prefix`() {
+ val engine = newEngine()
+ val first = "/storage/emulated/0/Gotcha/chats/First-Chat_aaaa1111"
+ val second = "/storage/emulated/0/Gotcha/chats/Second-Chat_bbbb2222"
+ try {
+ com.gotcha.tools.FileResolver.WORKING_DIR_BASE = first
+ val prefixFirst = engine.systemPromptMessage(com.gotcha.tools.AgentMode.OPERATOR).textContent
+ val tailFirst = engine.runContextMessage()
+ com.gotcha.tools.FileResolver.WORKING_DIR_BASE = second
+ val prefixSecond = engine.systemPromptMessage(com.gotcha.tools.AgentMode.OPERATOR).textContent
+ val tailSecond = engine.runContextMessage()
+
+ // Issue #121: a per-chat path in the Index 0 message broke prefix-cache reuse across chats.
+ assertFalse("Prefix must not name the working directory", prefixFirst.contains("Working directory"))
+ assertEquals("Prefix must not change with the chat's directory", prefixFirst, prefixSecond)
+ assertEquals("system", tailFirst.role)
+ assertTrue(tailFirst.textContent.contains("Working directory: $first"))
+ assertTrue(tailSecond.textContent.contains("Working directory: $second"))
+ assertTrue(tailSecond.textContent.contains("Current date/time: "))
+ } finally {
+ com.gotcha.tools.FileResolver.WORKING_DIR_BASE =
+ com.gotcha.data.GotchaStorage.root().absolutePath
+ }
+ }
+
+ private fun newEngine(): AgentEngine {
com.gotcha.testsupport.FakeAndroidKeyStore.setUp()
val context = androidx.test.core.app.ApplicationProvider.getApplicationContext<android.content.Context>()
val repository = com.gotcha.data.ChatHistoryRepository(context)
- val engine = AgentEngine(
+ return AgentEngine(
appContext = context,
events = object : AgentEvents {
override fun onUi(
@@ -392,11 +427,5 @@ class PromptCacheAndTokenOptimizationTest {
settingsProvider = { com.gotcha.data.Settings() },
clientProvider = { null }
)
- val msg = engine.systemPromptMessage(com.gotcha.tools.AgentMode.OPERATOR)
- assertEquals("system", msg.role)
- val text = msg.textContent
- assertTrue("Should contain core Operator instructions", text.contains("You are Gotcha"))
- assertTrue("Should contain env block", text.contains("<env>"))
- assertTrue("Should contain device model info", text.contains("Device model:"))
}
}