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.
feat: add update_user_profile tool to manage durable user settings with length constraints
Rishabh Bajpai88dbf8876be1
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 06c56e8..dbe42fd 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -4,6 +4,25 @@ All notable changes to Gotcha are documented here.## [Unreleased]+### Added — `update_user_profile` agent tool (#18)++- **The agent can now keep the user's profile fresh.** A new Operator-only+ `update_user_profile` tool records durable facts the user reveals in+ conversation — a new job/role (`occupation`), background details+ (`background`) and reply preferences (`reply_style`) — straight into+ Settings ▸ Personal Info, so the knowledge isn't lost next session.+- **Modify-and-extend, never erase.** The model is instructed to pass the+ complete merged value for each field it changes, preserving prior facts and+ removing only what the user clearly outgrew; blank values are ignored so+ stored information is never wiped wholesale.+- **Stays compact.** `background` is capped at 250 words and `reply_style` at+ 50 words in-app, and a no-op guard skips writes when nothing material+ changed (keeps updates infrequent and the system prompt cache mostly stable).+- **Operator only.** Monitor keeps its read-only contract; the tool is also+ withheld from sub-agents. Works in chat and voice calls.+- A short maintenance directive in the Operator system prompt (next to+ `<user_profile>`) tells the model when to call the tool and the caps.+### Added — Collapsible Connectors cards (#20)- **Connector cards collapse by default.** The Connectors screen now shows onediff --git a/app/src/main/java/com/gotcha/agent/AgentEngine.kt b/app/src/main/java/com/gotcha/agent/AgentEngine.ktindex 7631db0..e819ab2 100644--- a/app/src/main/java/com/gotcha/agent/AgentEngine.kt+++ b/app/src/main/java/com/gotcha/agent/AgentEngine.kt@@ -57,6 +57,8 @@ class AgentEngine(private val historyRepository: ChatHistoryRepository,private val settingsProvider: () -> Settings,private val clientProvider: () -> LLMClient?,+ /** Persists agent-initiated profile changes; null disables the update_user_profile tool. */+ private val onUpdateUserProfile: (suspend (com.gotcha.tools.ProfileUpdate) -> com.gotcha.tools.ToolResult)? = null,private val workingDirRoot: String = GotchaStorage.chatsRoot().absolutePath,/** Supplies the current on-screen transcript to persist alongside history. */private val displayMessagesProvider: () -> List<UiMessage> = { emptyList() },@@ -141,6 +143,7 @@ class AgentEngine(ToolResult.ok("TASK_RESULT:$description:$stepsEncoded\n|||\n${output.finalAnswer}")}},+ onUpdateUserProfile = onUpdateUserProfile,onNavigateApp = { task ->events.onSubAgentUpdate("App Navigation", "starting…")val steps = mutableListOf<SubAgentStepUi>()@@ -1201,6 +1204,25 @@ class AgentEngine(append("</env>")append("\n\n")append(buildUserProfileString())+ // Operator-only: tells the model it may record durable personal facts. Gated here+ // (not in buildUserProfileString) so Monitor, whose contract is read-only, never+ // sees a directive to mutate settings — and the tool is withheld from it anyway.+ if (agent == AgentMode.OPERATOR) {+ append(+ "\n\nThe user profile above is maintained automatically. Whenever the user " ++ "reveals a genuinely new, durable fact about themselves — a new job or " ++ "role, a lasting background detail, or an explicit preference for how " ++ "replies are written — call update_user_profile to record it. Do not call " ++ "it for transient, one-off, or hypothetical statements, and do not call it " ++ "more than once per new fact.\n" ++ "For every field you change, pass the COMPLETE updated value. Modify and " ++ "extend what is already stored — preserve all still-true information, add " ++ "the new facts, and remove only what the user has clearly outgrown or " ++ "contradicted. Never erase prior information wholesale, and never pass a " ++ "blank value.\n" ++ "Keep the Background under 250 words and the Reply style under 50 words."+ )+ }}}diff --git a/app/src/main/java/com/gotcha/agent/ChatViewModel.kt b/app/src/main/java/com/gotcha/agent/ChatViewModel.ktindex 16eb141..7f08d9a 100644--- a/app/src/main/java/com/gotcha/agent/ChatViewModel.kt+++ b/app/src/main/java/com/gotcha/agent/ChatViewModel.kt@@ -27,6 +27,8 @@ import com.gotcha.marketing.PosterStatsBuilderimport com.gotcha.marketing.ShareCardClientimport com.gotcha.tools.AgentModeimport com.gotcha.tools.ScreenPerception+import com.gotcha.tools.ToolResult+import com.gotcha.tools.mergeProfileUpdateimport com.gotcha.ui.ConfirmationOverlayimport com.gotcha.util.HumanReadableErrorimport kotlinx.coroutines.CancellationException@@ -134,6 +136,18 @@ class ChatViewModel(application: Application) : AndroidViewModel(application), AhistoryRepository = historyRepository,settingsProvider = { settings },clientProvider = { client },+ onUpdateUserProfile = { update ->+ // Reload so a manual Personal Info edit isn't clobbered by a stale snapshot,+ // then persist and refresh the cached settings the engine reads next turn.+ val merged = mergeProfileUpdate(settingsRepository.load(), update)+ ?: return@AgentEngine ToolResult.ok("No material change — profile left as is.")+ settingsRepository.save(merged.updated)+ settings = merged.updated+ ToolResult.ok(+ "Updated " + merged.changedFields.joinToString(", ") + ". " ++ "The new value will be used from the next message."+ )+ },// Persist the ENGINE session's own data, never the viewed session's —// the user may be browsing another chat while this run continues.displayMessagesProvider = { engineTranscript },diff --git a/app/src/main/java/com/gotcha/service/CallSessionController.kt b/app/src/main/java/com/gotcha/service/CallSessionController.ktindex 9679dff..7ed034e 100644--- a/app/src/main/java/com/gotcha/service/CallSessionController.kt+++ b/app/src/main/java/com/gotcha/service/CallSessionController.kt@@ -23,6 +23,8 @@ import com.gotcha.llm.visionUserMessageimport com.gotcha.tools.AgentModeimport com.gotcha.tools.Categoryimport com.gotcha.tools.ToolCategories+import com.gotcha.tools.ToolResult+import com.gotcha.tools.mergeProfileUpdateimport com.gotcha.ui.ConfirmationOverlayimport com.gotcha.ui.ScreenReadFlashOverlayimport kotlinx.coroutines.CancellationException@@ -180,6 +182,15 @@ class CallSessionController(historyRepository = callsRepo,settingsProvider = { settingsRepository.load() },clientProvider = { buildClient() },+ onUpdateUserProfile = { update ->+ val merged = mergeProfileUpdate(settingsRepository.load(), update)+ ?: return@AgentEngine ToolResult.ok("No material change — profile left as is.")+ settingsRepository.save(merged.updated)+ ToolResult.ok(+ "Updated " + merged.changedFields.joinToString(", ") + ". " ++ "The new value will be used from the next message."+ )+ },workingDirRoot = CALLS_WORKING_ROOT)newEngine.sessionId = java.util.UUID.randomUUID().toString()diff --git a/app/src/main/java/com/gotcha/tools/ToolDefinitions.kt b/app/src/main/java/com/gotcha/tools/ToolDefinitions.ktindex 4bf153c..92e59dd 100644--- a/app/src/main/java/com/gotcha/tools/ToolDefinitions.kt+++ b/app/src/main/java/com/gotcha/tools/ToolDefinitions.kt@@ -55,6 +55,42 @@ object ToolDefinitions {schema { putJsonObject("properties") {} })+ val updateUserProfile = tool(+ "update_user_profile",+ "Update the user's stored personal profile in Settings (occupation, background, " ++ "reply style) with a durable fact they just revealed — a new job or role, a lasting " ++ "background detail, or an explicit preference for how replies are written. " ++ "Only call this for genuinely new, durable information, never for transient " ++ "statements. For each field you change, pass the COMPLETE updated value, preserving " ++ "everything already stored (modify and extend, never erase) and removing only facts " ++ "the user has clearly outgrown or contradicted. Keep background under 250 words and " ++ "reply style under 50 words. Omit any field you are not changing.",+ schema {+ putJsonObject("properties") {+ putJsonObject("occupation") {+ put("type", "string")+ put("description", "The user's current occupation or role, e.g. 'Backend engineer'.")+ }+ putJsonObject("background") {+ put("type", "string")+ put(+ "description",+ "The complete background text — preserve prior facts, add the new ones, " ++ "and keep it under 250 words."+ )+ }+ putJsonObject("reply_style") {+ put("type", "string")+ put(+ "description",+ "The complete reply-style preference — preserve prior preferences, add " ++ "the new one, and keep it under 50 words."+ )+ }+ }+ }+ )+val getStorageInfo = tool("get_storage_info","Report total, used and free internal storage of the device.",@@ -2276,6 +2312,7 @@ object ToolDefinitions {val all: List<ToolDefinition> = listOf(aboutSamosaAi,+ updateUserProfile,dialNumber, getStorageInfo, getBatteryInfo, listFiles, readFile, writeFile,openApp, setBrightness, toggleWifi, openSetting,setWallpaper, runCommand,diff --git a/app/src/main/java/com/gotcha/tools/ToolExecutor.kt b/app/src/main/java/com/gotcha/tools/ToolExecutor.ktindex f2fd4f2..5adc38f 100644--- a/app/src/main/java/com/gotcha/tools/ToolExecutor.kt+++ b/app/src/main/java/com/gotcha/tools/ToolExecutor.kt@@ -23,7 +23,8 @@ import kotlinx.serialization.json.jsonPrimitiveclass ToolExecutor(context: Context,val onTask: (suspend (description: String, prompt: String) -> ToolResult)? = null,- val onNavigateApp: (suspend (task: String) -> ToolResult)? = null+ val onNavigateApp: (suspend (task: String) -> ToolResult)? = null,+ val onUpdateUserProfile: (suspend (update: ProfileUpdate) -> ToolResult)? = null) {private companion object {@@ -378,6 +379,20 @@ class ToolExecutor(handler(description, prompt)}}+ "update_user_profile" -> {+ val handler = onUpdateUserProfile+ if (handler == null) {+ ToolResult.error("Profile updates are not configured.")+ } else {+ handler(+ ProfileUpdate(+ occupation = args.requireString("occupation"),+ background = args.requireString("background"),+ replyStyle = args.requireString("reply_style")+ )+ )+ }+ }"sleep" -> {val secs = args.requireInt("duration_seconds")?.coerceIn(1, 86400)?: return missing("duration_seconds")diff --git a/app/src/main/java/com/gotcha/tools/ToolRegistry.kt b/app/src/main/java/com/gotcha/tools/ToolRegistry.ktindex 5abddc2..3870a37 100644--- a/app/src/main/java/com/gotcha/tools/ToolRegistry.kt+++ b/app/src/main/java/com/gotcha/tools/ToolRegistry.kt@@ -59,10 +59,12 @@ object ToolRegistry {/*** Full Operator tool set minus task + navigate_app (sub-agents cannot delegate- * further) and minus finish_task, which ends the *top-level* run — a sub-agent- * reports back with ask_final_answer instead.+ * further), minus finish_task, which ends the *top-level* run — a sub-agent+ * reports back with ask_final_answer instead — and minus update_user_profile,+ * whose modify-and-extend directive lives only in the top-level Operator prompt.*/- val subAgentTools: Set<String> = definitions.keys - setOf("task", "navigate_app", "finish_task")+ val subAgentTools: Set<String> = definitions.keys -+ setOf("task", "navigate_app", "finish_task", "update_user_profile")/** Tools available to the App Navigator sub-agent. */val navigatorTools: Set<String> = setOf(diff --git a/app/src/main/java/com/gotcha/tools/UpdateUserProfile.kt b/app/src/main/java/com/gotcha/tools/UpdateUserProfile.ktnew file mode 100644index 0000000..ed74f04--- /dev/null+++ b/app/src/main/java/com/gotcha/tools/UpdateUserProfile.kt@@ -0,0 +1,88 @@+package com.gotcha.tools++import com.gotcha.data.Settings++/** New profile facts the agent recorded in `update_user_profile`. Null = field not touched. */+data class ProfileUpdate(+ val occupation: String? = null,+ val background: String? = null,+ val replyStyle: String? = null+)++/** Which fields actually changed, plus the settings to persist. Null when nothing changed. */+data class ProfileUpdateResult(+ val updated: Settings,+ val changedFields: List<String>+)++/** Word caps for the free-form profile fields, keeping the system prompt compact. */+const val BACKGROUND_MAX_WORDS = 250+const val REPLY_STYLE_MAX_WORDS = 50++private val WHITESPACE = Regex("\\s+")++/** Collapses runs of whitespace to single spaces and trims. */+internal fun normalizeProfileText(text: String): String =+ text.replace(WHITESPACE, " ").trim()++/** Word count of a normalized profile value (runs of whitespace already collapsed). */+internal fun profileWordCount(text: String): Int =+ if (text.isBlank()) 0 else text.split(" ").size++/** Hard cap: keeps the first [maxWords] words. A safety net, not the primary constraint. */+internal fun truncateProfileWords(text: String, maxWords: Int): String {+ val words = text.split(" ")+ if (words.size <= maxWords) return text+ return words.take(maxWords).joinToString(" ")+}++/**+ * Merges an agent-initiated profile update onto [current].+ *+ * Semantics:+ * - `occupation` is a single-line title: provided + non-blank replaces it.+ * - `background` and `reply_style` are modify-and-extend free text: the model passes the+ * complete merged value; this applies whitespace normalization, enforces the word caps,+ * and only persists when the value materially differs (the low-frequency guard).+ * - Blank values never erase stored information.+ *+ * Returns null when nothing material changed, so callers can skip the write.+ */+fun mergeProfileUpdate(current: Settings, update: ProfileUpdate): ProfileUpdateResult? {+ var occupation = current.userOccupation+ var background = current.userBackground+ var replyStyle = current.userResponseStyle+ val changed = mutableListOf<String>()++ update.occupation?.let { proposed ->+ val normalized = normalizeProfileText(proposed)+ if (normalized.isNotEmpty() && normalized != occupation) {+ occupation = normalized+ changed += "occupation"+ }+ }+ update.background?.let { proposed ->+ val normalized = truncateProfileWords(normalizeProfileText(proposed), BACKGROUND_MAX_WORDS)+ if (normalized.isNotEmpty() && normalized != background) {+ background = normalized+ changed += "background"+ }+ }+ update.replyStyle?.let { proposed ->+ val normalized = truncateProfileWords(normalizeProfileText(proposed), REPLY_STYLE_MAX_WORDS)+ if (normalized.isNotEmpty() && normalized != replyStyle) {+ replyStyle = normalized+ changed += "reply_style"+ }+ }++ if (changed.isEmpty()) return null+ return ProfileUpdateResult(+ updated = current.copy(+ userOccupation = occupation,+ userBackground = background,+ userResponseStyle = replyStyle+ ),+ changedFields = changed+ )+}diff --git a/app/src/test/java/com/gotcha/tools/UpdateUserProfileTest.kt b/app/src/test/java/com/gotcha/tools/UpdateUserProfileTest.ktnew file mode 100644index 0000000..f0f5be1--- /dev/null+++ b/app/src/test/java/com/gotcha/tools/UpdateUserProfileTest.kt@@ -0,0 +1,127 @@+package com.gotcha.tools++import com.gotcha.data.Settings+import org.junit.Assert.assertEquals+import org.junit.Assert.assertNull+import org.junit.Test++/**+ * The merge/cap behaviour behind the `update_user_profile` tool. Pure logic, so+ * no Robolectric needed: the settings snapshot is a plain data class.+ */+class UpdateUserProfileTest {++ private val current = Settings(+ userOccupation = "Backend engineer",+ userBackground = "Works on payments infrastructure. Uses Kotlin and Go.",+ userResponseStyle = "Keep replies short, no bullet lists."+ )++ private fun applied(update: ProfileUpdate, base: Settings = current): ProfileUpdateResult? =+ mergeProfileUpdate(base, update)++ @Test+ fun `occupation is replaced when provided`() {+ val result = applied(ProfileUpdate(occupation = "Engineering manager"))!!+ assertEquals("Engineering manager", result.updated.userOccupation)+ assertEquals(listOf("occupation"), result.changedFields)+ }++ @Test+ fun `occupation is not erased by a blank value`() {+ val result = applied(ProfileUpdate(occupation = " "))+ assertNull(result)+ assertEquals("Backend engineer", current.userOccupation)+ }++ @Test+ fun `background is extended while prior facts survive`() {+ val result = applied(+ ProfileUpdate(+ background = "Works on payments infrastructure. Uses Kotlin and Go. " ++ "Recently moved to a platform team."+ )+ )!!+ assertEquals(+ "Works on payments infrastructure. Uses Kotlin and Go. Recently moved to a platform team.",+ result.updated.userBackground+ )+ assertEquals(listOf("background"), result.changedFields)+ }++ @Test+ fun `background is capped at 250 words`() {+ val long = List(400) { "word" }.joinToString(" ")+ val result = applied(ProfileUpdate(background = long))!!+ assertEquals(250, profileWordCount(result.updated.userBackground))+ assertEquals(250, result.updated.userBackground.split(" ").size)+ }++ @Test+ fun `reply style is capped at 50 words`() {+ val long = List(120) { "word" }.joinToString(" ")+ val result = applied(ProfileUpdate(replyStyle = long))!!+ assertEquals(50, profileWordCount(result.updated.userResponseStyle))+ }++ @Test+ fun `unchanged values are a no-op`() {+ val result = applied(+ ProfileUpdate(+ occupation = current.userOccupation,+ background = current.userBackground,+ replyStyle = current.userResponseStyle+ )+ )+ assertNull(result)+ }++ @Test+ fun `whitespace is collapsed and trimmed`() {+ val result = applied(ProfileUpdate(background = " Works on payments.\n Uses Kotlin. "))!!+ assertEquals("Works on payments. Uses Kotlin.", result.updated.userBackground)+ }++ @Test+ fun `several fields update in one call`() {+ val result = applied(+ ProfileUpdate(+ occupation = "Staff engineer",+ background = "Works on payments infrastructure. Uses Kotlin and Go. Leading the billing squad.",+ replyStyle = "Keep replies short, no bullet lists. Always state the command run."+ )+ )!!+ assertEquals("Staff engineer", result.updated.userOccupation)+ assertEquals(+ "Works on payments infrastructure. Uses Kotlin and Go. Leading the billing squad.",+ result.updated.userBackground+ )+ assertEquals(+ "Keep replies short, no bullet lists. Always state the command run.",+ result.updated.userResponseStyle+ )+ assertEquals(listOf("occupation", "background", "reply_style"), result.changedFields)+ }++ @Test+ fun `a partial update touches only the provided field`() {+ val result = applied(ProfileUpdate(replyStyle = "No bullet lists."))!!+ assertEquals(current.userOccupation, result.updated.userOccupation)+ assertEquals(current.userBackground, result.updated.userBackground)+ assertEquals("No bullet lists.", result.updated.userResponseStyle)+ assertEquals(listOf("reply_style"), result.changedFields)+ }++ @Test+ fun `blank proposed background never clears the field`() {+ val result = applied(ProfileUpdate(background = "\n\n"))+ assertNull(result)+ assertEquals(current.userBackground, current.userBackground)+ }++ @Test+ fun `normalized equality counts as no change`() {+ val result = applied(ProfileUpdate(background = " Works on payments infrastructure. Uses Kotlin and Go. "))+ assertNull("whitespace-only differences are a no-op", result)+ }+}diff --git a/app/src/test/resources/feature-test-coverage.json b/app/src/test/resources/feature-test-coverage.jsonindex a9c3d5c..a778ac1 100644--- a/app/src/test/resources/feature-test-coverage.json+++ b/app/src/test/resources/feature-test-coverage.json@@ -6,6 +6,14 @@"reason": "Needs an Android Context and a system service with real device state; no JVM-tier coverage yet — scheduled for the Robolectric tier.","manualSteps": "Ask the agent to 'open the dialer with +49123456789'; confirm the dialer opens pre-filled and does NOT place the call."},+ {+ "tool": "update_user_profile",+ "tier": "UNIT",+ "tests": [+ "com.gotcha.tools.UpdateUserProfileTest"+ ],+ "notes": "merge semantics (modify-and-extend, never erase), the no-op guard, and the 250/50-word caps"+ },{"tool": "about_samosa_ai","tier": "ROBOLECTRIC",diff --git a/docs/FEATURE_TEST_COVERAGE.md b/docs/FEATURE_TEST_COVERAGE.mdindex 11ed8b7..1bbdc2e 100644--- a/docs/FEATURE_TEST_COVERAGE.md+++ b/docs/FEATURE_TEST_COVERAGE.md@@ -13,13 +13,13 @@ Every tool the assistant can call is listed below, together with how it is verif| Tier | Tools | What it means ||---|---:|---|-| `UNIT` | 23 | Plain JVM unit test — no Android framework needed. |+| `UNIT` | 24 | Plain JVM unit test — no Android framework needed. || `ROBOLECTRIC` | 18 | JVM test against Robolectric's Android framework, often across several API levels. || `INSTRUMENTED` | 0 | Runs on a real device or emulator (`app/src/androidTest`). || `MANUAL_ONLY` | 64 | No automated test — verified by hand, see the checklist below. |-| **Total** | **105** | |+| **Total** | **106** | |-**41 of 105** tools are covered by an automated test; the remaining 64 are manual-QA-only with a recorded reason.+**42 of 106** tools are covered by an automated test; the remaining 64 are manual-QA-only with a recorded reason.## Foreground tools (act on the screen)@@ -138,6 +138,7 @@ Every tool the assistant can call is listed below, together with how it is verif| `search_skills` | `MANUAL_ONLY` | Needs an Android Context and a system service with real device state; no JVM-tier coverage yet — scheduled for the Robolectric tier. || `sleep` | `MANUAL_ONLY` | Needs an Android Context and a system service with real device state; no JVM-tier coverage yet — scheduled for the Robolectric tier. || `todowrite` | `MANUAL_ONLY` | Pure UI round-trip: writes the visible todo list in the chat surface. |+| `update_user_profile` | `UNIT` | `UpdateUserProfileTest` — merge semantics (modify-and-extend, never erase), the no-op guard, and the 250/50-word caps || `webfetch` | `UNIT` | `WebFetchToolTest` — HTML-to-text extraction, truncation, error handling || `websearch` | `MANUAL_ONLY` | Performs real network I/O against a search provider; exercising it in CI would make the suite non-hermetic. |