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.

feat(settings): let the assistant change Gotcha settings with approval (#99)

Durganshu970c36da6e8d
diff --git a/CHANGELOG.md b/CHANGELOG.md
index d16e764..4f35c48 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -4,6 +4,20 @@ All notable changes to Gotcha are documented here.
## [Unreleased]
### Added
+- **The assistant can change Gotcha's settings, with your approval every
+ time** (#99). Ask it to turn off the reply chime, switch the skin, stop
+ scanning the clipboard or turn a connector off, and it proposes the change
+ through a new `update_gotcha_settings` tool. Nothing is written until you
+ approve a prompt that lists each setting with its current and new value and
+ says whether it touches privacy, notifications, permissions or device
+ control, and an approval never carries over to the next change. Only an
+ allowlist can be changed — notifications, reply and speech language, read
+ aloud, skin, proactive assistance, wake-word listening mode and sensitivity,
+ connectors and skills. API keys, sign-in, the model and run limits are out of
+ reach, and an unknown key or bad value is refused before you are asked
+ anything. Approved changes take effect at once (the skin repaints without a
+ restart), and both approvals and refusals go into the action log. Operator
+ mode only.
- **Chat personas.** The starter chips said what to ask; nothing said who to ask.
A persona row now sits under the agent selector on an empty chat — **Doctor,
Chef, Fitness Coach, Tutor, Travel Planner, Handyman** — and picking one starts
diff --git a/app/src/main/assets/app/about-gotcha.md b/app/src/main/assets/app/about-gotcha.md
index 0a3fe44..81f2d21 100644
--- a/app/src/main/assets/app/about-gotcha.md
+++ b/app/src/main/assets/app/about-gotcha.md
@@ -52,6 +52,11 @@ mid-conversation.
Calendar, To Do), Notion, and Home Assistant.
- **Skills** — bundled and community operational guidance, searchable and
injected automatically when the matching app is in front.
+- **Its own settings** — in Operator, change notification, language, read-aloud,
+ skin, proactive-assistance and wake-word listening settings, and switch
+ connectors and skills on or off, with `update_gotcha_settings`. API keys,
+ sign-in, the model, run limits and permissions are not reachable this way; the
+ user changes those in Settings.
## Where the settings are
@@ -111,8 +116,10 @@ owns it — the toggle offers to do that.
Tools are organised in capability tiers, and a permission is asked for at the
moment a tool needs it rather than up front.
-Only a few destructive actions — uninstalling an app, deleting an alarm, timer or
-calendar event, and sending an email — ask the user to confirm before running;
+Only a few actions — uninstalling an app, deleting an alarm, timer or calendar
+event, sending an email, and changing Gotcha's own settings — ask the user to
+confirm before running, every time, and a declined change leaves everything as it
+was;
everything else executes without a confirmation step. Shell commands run against
a deny-list, actions are recorded in an append-only audit log, and settings
screens that could be changed silently are marked confirm-first — the agent asks
diff --git a/app/src/main/java/com/gotcha/MainActivity.kt b/app/src/main/java/com/gotcha/MainActivity.kt
index 0ee71b9..87a8e10 100644
--- a/app/src/main/java/com/gotcha/MainActivity.kt
+++ b/app/src/main/java/com/gotcha/MainActivity.kt
@@ -167,6 +167,22 @@ class MainActivity : ComponentActivity() {
private fun Settings.appearance() = Appearance(skinId = skinId)
+ /**
+ * Repaints when the skin is written from outside the Appearance screen — the
+ * assistant's update_gotcha_settings (issue #99) — without a restart. Held in a
+ * field: SharedPreferences keeps listeners weakly.
+ */
+ private val appearanceListener =
+ android.content.SharedPreferences.OnSharedPreferenceChangeListener { _, _ -> syncAppearance() }
+
+ private fun syncAppearance() {
+ val latest = settingsRepository.load().appearance()
+ if (latest != appearance) {
+ appearance = latest
+ applyLaunchBackground()
+ }
+ }
+
/** MediaProjection consent result — stores intent for screenshot capture. */
private val mediaProjectionLauncher =
registerForActivityResult(ActivityResultContracts.StartActivityForResult()) { result ->
@@ -517,6 +533,9 @@ class MainActivity : ComponentActivity() {
override fun onStart() {
super.onStart()
chatViewModel.setForeground(true)
+ // Catch up on a change made while stopped, then follow later ones.
+ syncAppearance()
+ com.gotcha.data.settingsChangeNotifier(this).registerOnSharedPreferenceChangeListener(appearanceListener)
}
override fun onResume() {
@@ -615,6 +634,7 @@ class MainActivity : ComponentActivity() {
override fun onStop() {
super.onStop()
chatViewModel.setForeground(false)
+ com.gotcha.data.settingsChangeNotifier(this).unregisterOnSharedPreferenceChangeListener(appearanceListener)
}
@Composable
diff --git a/app/src/main/java/com/gotcha/agent/AgentEngine.kt b/app/src/main/java/com/gotcha/agent/AgentEngine.kt
index e3cc1be..b2a59b6 100644
--- a/app/src/main/java/com/gotcha/agent/AgentEngine.kt
+++ b/app/src/main/java/com/gotcha/agent/AgentEngine.kt
@@ -20,11 +20,13 @@ import com.gotcha.tools.AgentMode
import com.gotcha.tools.AppNavigatorSession
import com.gotcha.tools.DeviceCapabilities
import com.gotcha.tools.FileResolver
+import com.gotcha.tools.GotchaSettingsUpdate
import com.gotcha.tools.ScreenPerception
import com.gotcha.tools.SubAgentSession
import com.gotcha.tools.ToolExecutor
import com.gotcha.tools.ToolRegistry
import com.gotcha.tools.ToolResult
+import com.gotcha.tools.liveSettingsCatalog
import com.gotcha.ui.personaById
import com.gotcha.util.GotchaLog
import com.gotcha.util.HumanReadableError
@@ -62,6 +64,11 @@ class AgentEngine(
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,
+ /**
+ * Writes a settings change the user approved and refreshes whatever reads it;
+ * null disables update_gotcha_settings. Only ever called after a confirmation.
+ */
+ private val onUpdateGotchaSettings: (suspend (com.gotcha.tools.SettingsChangePlan) -> 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() },
@@ -631,6 +638,10 @@ class AgentEngine(
handleDeleteConfirm("CONFIRM_DELETE_CALENDAR_EVENT:", "calendar_event", call, result)
} else if (result.success && result.message.startsWith("CONFIRM_SEND_EMAIL:")) {
handleSendEmailConfirm(call, result)
+ } else if (result.success &&
+ result.message.startsWith(GotchaSettingsUpdate.CONFIRM_PREFIX)
+ ) {
+ handleSettingsUpdateConfirm(call, result)
} else {
history += ChatMessage(
role = "tool",
@@ -935,6 +946,61 @@ class AgentEngine(
}
}
+ /**
+ * Handles a tool result prefixed with CONFIRM_UPDATE_SETTINGS:base64(request).
+ *
+ * Every call asks — an earlier approval never carries over to the next change
+ * (issue #99). The dialog shows each setting's current and requested value and
+ * what the change touches; nothing is written unless the user allows it.
+ */
+ private suspend fun handleSettingsUpdateConfirm(call: ToolCall, result: ToolResult) {
+ val handler = onUpdateGotchaSettings
+ // A refusal is the user's answer, not a failure — show it like the other declines.
+ var declined = false
+ val request = GotchaSettingsUpdate.decodePayload(
+ result.message.removePrefix(GotchaSettingsUpdate.CONFIRM_PREFIX),
+ liveSettingsCatalog()
+ )
+ val outcome = when {
+ handler == null -> ToolResult.error("Changing Gotcha settings is not available here.")
+ request == null -> ToolResult.error("Failed to read the settings request. Nothing was changed.")
+ else -> {
+ val plan = GotchaSettingsUpdate.plan(request.changes, settingsProvider())
+ if (plan.changes.isEmpty()) {
+ ToolResult.ok("No change — those settings already have the requested values.")
+ } else {
+ val approved = events.awaitConfirmation(
+ listOf("update_gotcha_settings"),
+ GotchaSettingsUpdate.describe(plan, request.reason)
+ )
+ val decided = if (approved) {
+ handler(plan)
+ } else {
+ declined = true
+ ToolResult.error(
+ "The user declined the settings change; nothing was changed. " +
+ "Do not retry unless the user asks again."
+ )
+ }
+ // The call itself was logged when it returned its marker; this entry says
+ // what was asked for and the answer. Values are safe to log in full —
+ // no credential is on the allowlist.
+ toolExecutor.actionLog.record(
+ "update_gotcha_settings",
+ (if (approved) "(approved) " else "(denied) ") + plan.lines().joinToString("; "),
+ decided
+ )
+ decided
+ }
+ }
+ }
+ history += ChatMessage(role = "tool", content = JsonPrimitive(outcome.message), toolCallId = call.id)
+ events.onUi(
+ if (outcome.success || declined) MessageKind.TOOL else MessageKind.ERROR,
+ "${call.function.name}: ${outcome.message}"
+ )
+ }
+
private suspend fun handleDeleteConfirm(confirmPrefix: String, kind: String, call: ToolCall, result: ToolResult) {
val body = result.message.removePrefix(confirmPrefix)
val parts = body.split(":", limit = 2)
diff --git a/app/src/main/java/com/gotcha/agent/ChatViewModel.kt b/app/src/main/java/com/gotcha/agent/ChatViewModel.kt
index 6f3a3e2..9cf964d 100644
--- a/app/src/main/java/com/gotcha/agent/ChatViewModel.kt
+++ b/app/src/main/java/com/gotcha/agent/ChatViewModel.kt
@@ -34,6 +34,7 @@ import com.gotcha.notifications.RunOutcome
import com.gotcha.tools.AgentMode
import com.gotcha.tools.DocumentError
import com.gotcha.tools.DocumentParser
+import com.gotcha.tools.GotchaSettingsUpdate
import com.gotcha.tools.ScreenPerception
import com.gotcha.tools.ToolResult
import com.gotcha.tools.mergeProfileUpdate
@@ -293,6 +294,22 @@ class ChatViewModel(application: Application) : AndroidViewModel(application), A
"The new value will be used from the next message."
)
},
+ onUpdateGotchaSettings = { plan ->
+ // Only reached after the user approved this exact change. Apply it onto a
+ // fresh load so a concurrent write elsewhere (the Settings screen, the
+ // assistive ball) is not clobbered by the snapshot the prompt was built from.
+ settingsRepository.save(plan.applyTo(settingsRepository.load()))
+ withContext(Dispatchers.Main) {
+ // Rebuilds the cached settings the engine reads next round, and the
+ // speech engines; the skin and services follow settingsChangeNotifier.
+ refreshSettings()
+ appendEngineUi(
+ MessageKind.TOOL,
+ "Assistant changed settings: " + plan.lines().joinToString("; ") + "."
+ )
+ }
+ ToolResult.ok(GotchaSettingsUpdate.appliedMessage(plan))
+ },
// 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.kt
index 19d5d1d..69a1f30 100644
--- a/app/src/main/java/com/gotcha/service/CallSessionController.kt
+++ b/app/src/main/java/com/gotcha/service/CallSessionController.kt
@@ -23,6 +23,7 @@ import com.gotcha.llm.LLMClient
import com.gotcha.llm.visionUserMessage
import com.gotcha.tools.AgentMode
import com.gotcha.tools.Category
+import com.gotcha.tools.GotchaSettingsUpdate
import com.gotcha.tools.ToolCategories
import com.gotcha.tools.ToolResult
import com.gotcha.tools.mergeProfileUpdate
@@ -199,6 +200,11 @@ class CallSessionController(
"The new value will be used from the next message."
)
},
+ onUpdateGotchaSettings = { plan ->
+ // settingsProvider reloads every round, so the next turn already sees this.
+ settingsRepository.save(plan.applyTo(settingsRepository.load()))
+ ToolResult.ok(GotchaSettingsUpdate.appliedMessage(plan))
+ },
workingDirRoot = CALLS_WORKING_ROOT
)
newEngine.sessionId = java.util.UUID.randomUUID().toString()
diff --git a/app/src/main/java/com/gotcha/tools/GotchaSettingsUpdate.kt b/app/src/main/java/com/gotcha/tools/GotchaSettingsUpdate.kt
new file mode 100644
index 0000000..f40ecec
--- /dev/null
+++ b/app/src/main/java/com/gotcha/tools/GotchaSettingsUpdate.kt
@@ -0,0 +1,490 @@
+package com.gotcha.tools
+
+import com.gotcha.data.CompletionPreview
+import com.gotcha.data.Settings
+import com.gotcha.data.WakeWordListeningMode
+import com.gotcha.i18n.Language
+import kotlinx.serialization.json.JsonElement
+import kotlinx.serialization.json.JsonNull
+import kotlinx.serialization.json.JsonObject
+import kotlinx.serialization.json.JsonPrimitive
+import kotlinx.serialization.json.booleanOrNull
+import kotlinx.serialization.json.buildJsonObject
+import kotlinx.serialization.json.doubleOrNull
+import kotlinx.serialization.json.put
+
+/**
+ * The settings `update_gotcha_settings` may change (issue #99), and the
+ * validation that stands between the model and [com.gotcha.data.SettingsRepository].
+ *
+ * An explicit allowlist, not a key-value passthrough: every key here maps to
+ * one [Settings] field with its own parser. Credentials (API keys, the Samosa
+ * session), the model and provider, endpoints, run limits the model could use
+ * to raise its own budget, community skill hosts and the legal/onboarding
+ * state are deliberately absent — a model that could write those could undo
+ * the safety model or leak a secret. The user profile has its own tool.
+ *
+ * Kept free of Android and of the registries so the whole rule set is unit
+ * testable: the caller hands in the skins, connectors and skills that exist.
+ */
+
+/** What a setting change touches, shown on the confirmation so the user can weigh it. */
+enum class SettingImpact(val label: String) {
+ PRIVACY("privacy"),
+ NOTIFICATIONS("notifications"),
+ PERMISSIONS("permissions"),
+ DEVICE_CONTROL("device control")
+}
+
+/** The ids that exist on this install, each mapped to the name the user knows it by. */
+data class SettingsCatalog(
+ val skins: Map<String, String>,
+ val connectors: Map<String, String>,
+ val skills: Map<String, String>
+)
+
+/** One validated change. [apply] writes it; the old value is read with [describe]. */
+class SettingChange internal constructor(
+ val key: String,
+ val label: String,
+ val impacts: Set<SettingImpact>,
+ private val read: (Settings) -> String,
+ private val write: (Settings) -> Settings,
+ /** The requested value exactly as sent, so the change can be carried and re-validated. */
+ val rawValue: JsonElement
+) {
+ fun describe(settings: Settings): String = read(settings)
+ fun apply(settings: Settings): Settings = write(settings)
+}
+
+/** A change set against a known [current] state, ready to show and to apply. */
+data class SettingsChangePlan(
+ val changes: List<SettingChange>,
+ val current: Settings
+) {
+ val impacts: Set<SettingImpact> get() = changes.flatMapTo(sortedSetOf<SettingImpact>()) { it.impacts }
+
+ /** Applies every change onto [base] — the freshly loaded settings at write time. */
+ fun applyTo(base: Settings): Settings = changes.fold(base) { s, change -> change.apply(s) }
+
+ /** "Label: old → new" for each change, in request order. */
+ fun lines(): List<String> {
+ val requested = applyTo(current)
+ return changes.map { "${it.label}: ${it.describe(current)} → ${it.describe(requested)}" }
+ }
+}
+
+/** Why a request was refused. Nothing is written when this comes back. */
+class SettingsUpdateRejected(val reasons: List<String>) :
+ Exception(reasons.joinToString("; "))
+
+private fun onOff(value: Boolean) = if (value) "On" else "Off"
+
+/** A top-level key: its label, what it touches, and how to parse, read and write it. */
+// One row of the allowlist; every field is used by the parser, the prompt or the schema.
+@Suppress("LongParameterList")
+private class Spec(
+ val key: String,
+ val label: String,
+ val impacts: Set<SettingImpact>,
+ val accepts: String,
+ /** JSON Schema type, and the allowed strings for a choice — for the tool schema. */
+ val jsonType: String,
+ val choices: List<String>? = null,
+ val parse: (JsonPrimitive) -> Any?,
+ val read: (Settings) -> String,
+ val write: (Settings, Any) -> Settings
+)
+
+private fun boolSpec(
+ key: String,
+ label: String,
+ impacts: Set<SettingImpact>,
+ get: (Settings) -> Boolean,
+ set: (Settings, Boolean) -> Settings
+) = Spec(
+ key,
+ label,
+ impacts,
+ "true or false",
+ "boolean",
+ parse = { if (it.isString) null else it.booleanOrNull },
+ read = { onOff(get(it)) },
+ write = { s, v -> set(s, v as Boolean) }
+)
+
+private fun <T> choiceSpec(
+ key: String,
+ label: String,
+ impacts: Set<SettingImpact>,
+ choices: Map<String, T>,
+ display: (T) -> String,
+ get: (Settings) -> T,
+ set: (Settings, T) -> Settings
+) = Spec(
+ key, label, impacts, "one of " + choices.keys.joinToString(", "), "string", choices.keys.toList(),
+ parse = { p ->
+ if (!p.isString) {
+ null
+ } else {
+ choices.entries.firstOrNull { it.key.equals(p.content.trim(), ignoreCase = true) }?.value
+ }
+ },
+ read = { display(get(it)) },
+ write = { s, v ->
+ @Suppress("UNCHECKED_CAST")
+ set(s, v as T)
+ }
+)
+
+/** Parses `update_gotcha_settings` arguments against the allowlist. */
+object GotchaSettingsUpdate {
+
+ const val CONNECTORS_KEY = "connectors"
+ const val SKILLS_KEY = "skills"
+
+ private val languages: Map<String, String> = Language.entries.associate { it.label to it.label }
+
+ /** `voice_language` also takes this to mean "speak in the reply language" (stored blank). */
+ const val FOLLOW_REPLY_LANGUAGE = "same_as_replies"
+
+ private fun specs(catalog: SettingsCatalog): List<Spec> =
+ notificationSpecs() + voiceSpecs() + appearanceSpecs(catalog) + proactiveSpecs() + wakeWordSpecs()
+
+ private fun notificationSpecs(): List<Spec> = listOf(
+ boolSpec(
+ "reply_vibration",
+ "Vibrate when a reply arrives",
+ setOf(SettingImpact.NOTIFICATIONS),
+ { it.notifyVibrationEnabled },
+ { s, v -> s.copy(notifyVibrationEnabled = v) }
+ ),
+ boolSpec(
+ "reply_chime",
+ "Chime when a reply arrives",
+ setOf(SettingImpact.NOTIFICATIONS),
+ { it.notifyChimeEnabled },
+ { s, v -> s.copy(notifyChimeEnabled = v) }
+ ),
+ boolSpec(
+ "completion_notifications",
+ "Notify when a background task finishes",
+ setOf(SettingImpact.NOTIFICATIONS),
+ { it.chatCompletionNotificationsEnabled },
+ { s, v -> s.copy(chatCompletionNotificationsEnabled = v) }
+ ),
+ choiceSpec(
+ "completion_preview",
+ "Reply shown in the task-finished notification",
+ // FULL puts the whole reply on the lock screen.
+ setOf(SettingImpact.NOTIFICATIONS, SettingImpact.PRIVACY),
+ CompletionPreview.entries.associateBy { it.name.lowercase() },
+ { it.name.lowercase() },
+ { it.chatCompletionPreview },
+ { s, v -> s.copy(chatCompletionPreview = v) }
+ ),
+ boolSpec(
+ "server_messages",
+ "Messages from Samosa AI",
+ setOf(SettingImpact.NOTIFICATIONS),
+ { it.serverMessagesEnabled },
+ { s, v -> s.copy(serverMessagesEnabled = v) }
+ )
+ )
+
+ private fun voiceSpecs(): List<Spec> = listOf(
+ boolSpec(
+ "auto_read_replies",
+ "Read replies aloud",
+ setOf(SettingImpact.PRIVACY),
+ { it.autoReadReplies },
+ { s, v -> s.copy(autoReadReplies = v) }
+ ),
+ choiceSpec(
+ "reply_language",
+ "Reply language",
+ emptySet(),
+ languages,
+ { it },
+ { it.preferredLanguage },
+ { s, v -> s.copy(preferredLanguage = v) }
+ ),
+ choiceSpec(
+ "voice_language",
+ "Speech language",
+ emptySet(),
+ languages + (FOLLOW_REPLY_LANGUAGE to ""),
+ { it.ifBlank { "Same as replies" } },
+ { it.voiceLanguage },
+ { s, v -> s.copy(voiceLanguage = v) }
+ )
+ )
+
+ private fun appearanceSpecs(catalog: SettingsCatalog): List<Spec> = listOf(
+ choiceSpec(
+ "skin",
+ "Skin",
+ emptySet(),
+ catalog.skins.keys.associateWith { it },
+ { catalog.skins[it] ?: it },
+ { it.skinId },
+ { s, v -> s.copy(skinId = v) }
+ )
+ )
+
+ private fun proactiveSpecs(): List<Spec> = listOf(
+ boolSpec(
+ "proactive_enabled",
+ "Proactive assistance",
+ setOf(SettingImpact.PRIVACY),
+ { it.proactiveEnabled },
+ { s, v -> s.copy(proactiveEnabled = v) }
+ ),
+ boolSpec(
+ "proactive_scan_screen",
+ "Proactive: scan the screen",
+ setOf(SettingImpact.PRIVACY),
+ { it.proactiveScanScreen },
+ { s, v -> s.copy(proactiveScanScreen = v) }
+ ),
+ boolSpec(
+ "proactive_scan_clipboard",
+ "Proactive: scan the clipboard",
+ setOf(SettingImpact.PRIVACY),
+ { it.proactiveScanClipboard },
+ { s, v -> s.copy(proactiveScanClipboard = v) }
+ ),
+ boolSpec(
+ "proactive_scan_notifications",
+ "Proactive: scan notifications",
+ setOf(SettingImpact.PRIVACY, SettingImpact.NOTIFICATIONS),
+ { it.proactiveScanNotifications },
+ { s, v -> s.copy(proactiveScanNotifications = v) }
+ ),
+ boolSpec(
+ "proactive_otp_detection",
+ "Proactive: detect one-time codes",
+ setOf(SettingImpact.PRIVACY),
+ { it.proactiveOtpEnabled },
+ { s, v -> s.copy(proactiveOtpEnabled = v) }
+ ),
+ boolSpec(
+ "proactive_auto_copy_otp",
+ "Proactive: copy one-time codes automatically",
+ setOf(SettingImpact.PRIVACY),
+ { it.proactiveAutoCopyOtp },
+ { s, v -> s.copy(proactiveAutoCopyOtp = v) }
+ )
+ )
+
+ // Turning the wake word on or off stays in Settings: it needs the mic and the overlay.
+ private fun wakeWordSpecs(): List<Spec> = listOf(
+ choiceSpec(
+ "wake_word_mode",
+ "Wake word listens",
+ setOf(SettingImpact.DEVICE_CONTROL, SettingImpact.PRIVACY),
+ WakeWordListeningMode.entries.associateBy { it.name.lowercase() },
+ { it.name.lowercase() },
+ { it.wakeWordListeningMode },
+ { s, v -> s.copy(wakeWordListeningMode = v) }
+ ),
+ Spec(
+ "wake_word_sensitivity",
+ "Wake word sensitivity",
+ setOf(SettingImpact.DEVICE_CONTROL),
+ "a number from 0 to 1 (higher triggers more easily)",
+ "number",
+ parse = { p ->
+ if (p.isString) null else p.doubleOrNull?.takeIf { it in 0.0..1.0 }?.toFloat()
+ },
+ read = { "${(it.wakeWordSensitivity * 100).toInt()}%" },
+ write = { s, v -> s.copy(wakeWordSensitivity = v as Float) }
+ )
+ )
+
+ /** Every top-level key the tool accepts. */
+ fun keys(catalog: SettingsCatalog): List<String> = specs(catalog).map { it.key } + CONNECTORS_KEY + SKILLS_KEY
+
+ /**
+ * JSON Schema `properties` for the tool's `changes` object, built from the same
+ * specs that validate it so the schema can never offer a key the parser refuses.
+ */
+ fun schemaProperties(catalog: SettingsCatalog): JsonObject = buildJsonObject {
+ for (spec in specs(catalog)) {
+ put(
+ spec.key,
+ buildJsonObject {
+ put("type", spec.jsonType)
+ put("description", "${spec.label}: ${spec.accepts}.")
+ spec.choices?.let { choices ->
+ put("enum", kotlinx.serialization.json.JsonArray(choices.map(::JsonPrimitive)))
+ }
+ }
+ )
+ }
+ put(
+ CONNECTORS_KEY,
+ toggleSchema(
+ "Turn connectors on (true) or off (false), keyed by connector id: " +
+ catalog.connectors.keys.joinToString(", ") + ". Off keeps the sign-in but " +
+ "removes that connector's tools."
+ )
+ )
+ put(
+ SKILLS_KEY,
+ toggleSchema("Turn skills on (true) or off (false), keyed by skill id as search_skills reports it.")
+ )
+ }
+
+ private fun toggleSchema(description: String) = buildJsonObject {
+ put("type", "object")
+ put("description", description)
+ put("additionalProperties", buildJsonObject { put("type", "boolean") })
+ }
+
+ /**
+ * Validates [requested] — the tool's `changes` object — into a change list.
+ *
+ * All-or-nothing: one unknown key or bad value refuses the whole request, so
+ * the user is never asked to approve half of what the model meant.
+ */
+ fun parse(requested: JsonObject, catalog: SettingsCatalog): Result<List<SettingChange>> {
+ if (requested.isEmpty()) return Result.failure(SettingsUpdateRejected(listOf("no settings given")))
+ val byKey = specs(catalog).associateBy { it.key }
+ val changes = mutableListOf<SettingChange>()
+ val errors = mutableListOf<String>()
+ for ((key, value) in requested) {
+ when (key) {
+ CONNECTORS_KEY -> parseToggles(
+ key, value, catalog.connectors, "Connector",
+ setOf(SettingImpact.PRIVACY, SettingImpact.PERMISSIONS),
+ { it.disabledConnectors }, { s, v -> s.copy(disabledConnectors = v) },
+ changes, errors
+ )
+ SKILLS_KEY -> parseToggles(
+ key, value, catalog.skills, "Skill", emptySet(),
+ { it.disabledSkills }, { s, v -> s.copy(disabledSkills = v) },
+ changes, errors
+ )
+ else -> {
+ val spec = byKey[key]
+ if (spec == null) {
+ errors += "'$key' is not a setting this tool can change"
+ continue
+ }
+ val parsed = (value as? JsonPrimitive)?.takeIf { it !is JsonNull }?.let(spec.parse)
+ if (parsed == null) {
+ errors += "'$key' must be ${spec.accepts}, got $value"
+ } else {
+ changes += SettingChange(
+ key, spec.label, spec.impacts, spec.read, { s -> spec.write(s, parsed) }, value
+ )
+ }
+ }
+ }
+ }
+ return if (errors.isEmpty()) Result.success(changes) else Result.failure(SettingsUpdateRejected(errors))
+ }
+
+ /** A `{id: true|false}` object over a disabled-id set; one change per id. */
+ @Suppress("LongParameterList")
+ private fun parseToggles(
+ key: String,
+ value: JsonElement,
+ known: Map<String, String>,
+ noun: String,
+ impacts: Set<SettingImpact>,
+ get: (Settings) -> Set<String>,
+ set: (Settings, Set<String>) -> Settings,
+ changes: MutableList<SettingChange>,
+ errors: MutableList<String>
+ ) {
+ val toggles = value as? JsonObject
+ if (toggles == null || toggles.isEmpty()) {
+ errors += "'$key' must be an object of id → true (enabled) or false (disabled)"
+ return
+ }
+ for ((id, flag) in toggles) {
+ val name = known[id]
+ val enabled = (flag as? JsonPrimitive)?.takeIf { !it.isString }?.booleanOrNull
+ when {
+ name == null -> errors += "unknown ${noun.lowercase()} '$id'" +
+ if (known.isEmpty()) "" else " (known: ${known.keys.sorted().joinToString(", ")})"
+ enabled == null -> errors += "'$key.$id' must be true or false"
+ else -> changes += SettingChange(
+ "$key.$id", "$noun: $name", impacts,
+ read = { s -> if (id in get(s)) "Off" else "On" },
+ write = { s -> set(s, if (enabled) get(s) - id else get(s) + id) },
+ rawValue = flag
+ )
+ }
+ }
+ }
+
+ /**
+ * Drops the changes that would leave [current] as it is. An empty plan means
+ * there is nothing to ask the user about.
+ */
+ fun plan(changes: List<SettingChange>, current: Settings): SettingsChangePlan =
+ SettingsChangePlan(changes.filter { it.apply(current) != current }, current)
+
+ /** Rebuilds the `changes` object from a change list, to carry it across the confirmation. */
+ fun toJson(changes: List<SettingChange>): JsonObject = buildJsonObject {
+ val connectors = mutableMapOf<String, JsonElement>()
+ val skills = mutableMapOf<String, JsonElement>()
+ for (change in changes) {
+ when {
+ change.key.startsWith("$CONNECTORS_KEY.") ->
+ connectors[change.key.removePrefix("$CONNECTORS_KEY.")] = change.rawValue
+ change.key.startsWith("$SKILLS_KEY.") ->
+ skills[change.key.removePrefix("$SKILLS_KEY.")] = change.rawValue
+ else -> put(change.key, change.rawValue)
+ }
+ }
+ if (connectors.isNotEmpty()) put(CONNECTORS_KEY, JsonObject(connectors))
+ if (skills.isNotEmpty()) put(SKILLS_KEY, JsonObject(skills))
+ }
+
+ /** Marker [ToolExecutor] returns so [com.gotcha.agent.AgentEngine] asks before writing. */
+ const val CONFIRM_PREFIX = "CONFIRM_UPDATE_SETTINGS:"
+
+ /** A validated request carried across the confirmation. */
+ data class Request(val changes: List<SettingChange>, val reason: String?)
+
+ fun encodePayload(changes: List<SettingChange>, reason: String?): String {
+ val payload = buildJsonObject {
+ put("changes", toJson(changes))
+ if (!reason.isNullOrBlank()) put("reason", reason)
+ }
+ return java.util.Base64.getEncoder().encodeToString(payload.toString().toByteArray())
+ }
+
+ /**
+ * Decodes and re-validates a payload from [encodePayload]. Re-validating costs
+ * nothing and means the write never trusts the marker text on its own.
+ */
+ fun decodePayload(payload: String, catalog: SettingsCatalog): Request? = runCatching {
+ val text = String(java.util.Base64.getDecoder().decode(payload))
+ val obj = kotlinx.serialization.json.Json.parseToJsonElement(text) as JsonObject
+ val changes = parse(obj["changes"] as JsonObject, catalog).getOrThrow()
+ Request(changes, (obj["reason"] as? JsonPrimitive)?.content)
+ }.getOrNull()
+
+ /** What the model is told once an approved change is saved. */
+ fun appliedMessage(plan: SettingsChangePlan): String =
+ "The user approved and these settings are now saved: " + plan.lines().joinToString("; ") + "."
+
+ /** The confirmation text: what changes, from what to what, and what it touches. */
+ fun describe(plan: SettingsChangePlan, reason: String?): String = buildString {
+ if (!reason.isNullOrBlank()) append("Why: ").append(reason.trim()).append("\n\n")
+ append("Change these Gotcha settings:\n")
+ plan.lines().forEach { append("• ").append(it).append('\n') }
+ append('\n')
+ val impacts = plan.impacts
+ if (impacts.isEmpty()) {
+ append("Does not affect privacy, notifications, permissions or device control.")
+ } else {
+ append("Affects: ").append(impacts.joinToString(", ") { it.label }).append('.')
+ }
+ }
+}
diff --git a/app/src/main/java/com/gotcha/tools/SettingsCatalogs.kt b/app/src/main/java/com/gotcha/tools/SettingsCatalogs.kt
new file mode 100644
index 0000000..544aef6
--- /dev/null
+++ b/app/src/main/java/com/gotcha/tools/SettingsCatalogs.kt
@@ -0,0 +1,24 @@
+package com.gotcha.tools
+
+import com.gotcha.agent.skills.SkillRegistry
+import com.gotcha.connectors.ConnectorCatalog
+import com.gotcha.ui.theme.Skins
+
+/**
+ * The skins and connectors every build has, for the `update_gotcha_settings`
+ * schema. Skills are left out: they are loaded at runtime, and the schema is not.
+ */
+fun staticSettingsCatalog(): SettingsCatalog = SettingsCatalog(
+ skins = Skins.all.associate { it.id to it.label },
+ connectors = ConnectorCatalog.all.associate { it.id to it.displayName },
+ skills = emptyMap()
+)
+
+/**
+ * What [GotchaSettingsUpdate] validates ids against: the static catalog plus the
+ * skills loaded right now. Read on every call — a community skill can be
+ * imported mid-conversation.
+ */
+fun liveSettingsCatalog(): SettingsCatalog = staticSettingsCatalog().copy(
+ skills = SkillRegistry.getAllSkills().associate { it.id to it.title.ifBlank { it.id } }
+)
diff --git a/app/src/main/java/com/gotcha/tools/ToolDefinitions.kt b/app/src/main/java/com/gotcha/tools/ToolDefinitions.kt
index 0b68d12..f38f5cb 100644
--- a/app/src/main/java/com/gotcha/tools/ToolDefinitions.kt
+++ b/app/src/main/java/com/gotcha/tools/ToolDefinitions.kt
@@ -106,6 +106,33 @@ object ToolDefinitions {
}
)
+ val updateGotchaSettings = tool(
+ "update_gotcha_settings",
+ "Change Gotcha's own settings when the user asks you to — notifications, reply and " +
+ "speech language, reading replies aloud, the skin, proactive assistance, the wake " +
+ "word's listening mode and sensitivity, and turning connectors or skills on or off. " +
+ "Only the settings in `changes` can be set; API keys, sign-in, the model and " +
+ "permissions cannot, so send the user to Settings for those (about_gotcha has the " +
+ "path). The user is shown every change with its current and new value and must " +
+ "approve it, every time; if they decline, nothing changes — do not retry unless " +
+ "they ask again. Change only what the user asked for.",
+ schema {
+ putJsonObject("properties") {
+ putJsonObject("changes") {
+ put("type", "object")
+ put("description", "The settings to change and their new values. Include only these.")
+ put("properties", GotchaSettingsUpdate.schemaProperties(staticSettingsCatalog()))
+ put("additionalProperties", false)
+ }
+ putJsonObject("reason") {
+ put("type", "string")
+ put("description", "One short sentence shown to the user on the approval prompt: why.")
+ }
+ }
+ putJsonArray("required") { add("changes") }
+ }
+ )
+
val getStorageInfo = tool(
"get_storage_info",
"Report total, used and free internal storage of the device.",
@@ -2962,6 +2989,7 @@ object ToolDefinitions {
aboutSamosaAi,
aboutGotcha,
updateUserProfile,
+ updateGotchaSettings,
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.kt
index 41e79f4..692af80 100644
--- a/app/src/main/java/com/gotcha/tools/ToolExecutor.kt
+++ b/app/src/main/java/com/gotcha/tools/ToolExecutor.kt
@@ -94,7 +94,9 @@ class ToolExecutor(
private val rootTool = RootTool()
private val termuxTool = TermuxTool(appContext)
private val healthTool = HealthTool(appContext)
- private val actionLog = ActionLog(appContext)
+
+ /** The audit log; the engine also writes the answers to its confirmation prompts here. */
+ val actionLog = ActionLog(appContext)
init {
com.gotcha.connectors.ConnectorRegistry.init(appContext)
@@ -507,6 +509,21 @@ class ToolExecutor(
)
}
}
+ "update_gotcha_settings" -> {
+ val requested = args["changes"] as? JsonObject ?: return missing("changes")
+ // Validated here, before the user is asked anything: an unsupported key or
+ // bad value never reaches a prompt, let alone SettingsRepository.
+ val changes = GotchaSettingsUpdate.parse(requested, liveSettingsCatalog()).getOrElse {
+ return ToolResult.error(
+ "No settings were changed: ${it.message}. Only the settings listed in " +
+ "this tool's schema can be changed, and only to the values it lists."
+ )
+ }
+ ToolResult.ok(
+ GotchaSettingsUpdate.CONFIRM_PREFIX +
+ GotchaSettingsUpdate.encodePayload(changes, args.requireString("reason"))
+ )
+ }
"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.kt
index b5e7553..ddb62be 100644
--- a/app/src/main/java/com/gotcha/tools/ToolRegistry.kt
+++ b/app/src/main/java/com/gotcha/tools/ToolRegistry.kt
@@ -107,14 +107,16 @@ object ToolRegistry {
/**
* Full Operator tool set minus task + navigate_app (sub-agents cannot delegate
* 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.
+ * reports back with ask_final_answer instead — minus update_user_profile,
+ * whose modify-and-extend directive lives only in the top-level Operator prompt,
+ * and minus update_gotcha_settings, whose approval prompt belongs to the run the
+ * user is watching, not to a delegated one.
* Dynamic tools are included while registered; they are hidden by the
* hidden-tools mechanism when their connector is not active.
*/
val subAgentTools: Set<String>
get() = definitions.keys + dynamicSet.definitions.keys -
- setOf("task", "navigate_app", "finish_task", "update_user_profile")
+ setOf("task", "navigate_app", "finish_task", "update_user_profile", "update_gotcha_settings")
/** Tools available to the App Navigator sub-agent. */
val navigatorTools: Set<String> = setOf(
@@ -459,7 +461,7 @@ object ToolRegistry {
fun toolsForSubAgent(hiddenTools: Set<String> = emptySet()): List<ToolDefinition> {
val dynamic = dynamicSet
val allowed = definitions.keys + dynamic.definitions.keys -
- setOf("task", "navigate_app", "finish_task", "update_user_profile")
+ setOf("task", "navigate_app", "finish_task", "update_user_profile", "update_gotcha_settings")
return (definitions + dynamic.definitions)
.filterKeys { it in allowed && it !in hiddenTools }
.values.toList()
diff --git a/app/src/test/java/com/gotcha/agent/AgentPromptTest.kt b/app/src/test/java/com/gotcha/agent/AgentPromptTest.kt
index fc7c0b6..42e3afc 100644
--- a/app/src/test/java/com/gotcha/agent/AgentPromptTest.kt
+++ b/app/src/test/java/com/gotcha/agent/AgentPromptTest.kt
@@ -127,7 +127,10 @@ class AgentPromptTest {
)
assertTrue(body.contains("Respond to the user in Hindi"))
assertTrue(body.contains("Reply language: Hindi"))
- assertFalse(body.contains("German"))
+ // Only the messages: the tool schemas list every language as an allowed value.
+ val messages = kotlinx.serialization.json.Json.parseToJsonElement(body)
+ .let { it as kotlinx.serialization.json.JsonObject }["messages"].toString()
+ assertFalse(messages.contains("German"))
}
@Test
diff --git a/app/src/test/java/com/gotcha/agent/SettingsUpdateLoopTest.kt b/app/src/test/java/com/gotcha/agent/SettingsUpdateLoopTest.kt
new file mode 100644
index 0000000..40ae7d4
--- /dev/null
+++ b/app/src/test/java/com/gotcha/agent/SettingsUpdateLoopTest.kt
@@ -0,0 +1,202 @@
+package com.gotcha.agent
+
+import android.content.Context
+import androidx.test.core.app.ApplicationProvider
+import com.gotcha.data.ChatHistoryRepository
+import com.gotcha.data.LlmProvider
+import com.gotcha.data.Settings
+import com.gotcha.data.SettingsRepository
+import com.gotcha.llm.LLMClient
+import com.gotcha.testsupport.FakeAndroidKeyStore
+import com.gotcha.testsupport.ShadowExternalStorageManager
+import com.gotcha.tools.AgentMode
+import com.gotcha.tools.GotchaSettingsUpdate
+import com.gotcha.tools.ToolResult
+import kotlinx.coroutines.test.runTest
+import okhttp3.mockwebserver.MockResponse
+import okhttp3.mockwebserver.MockWebServer
+import org.junit.After
+import org.junit.Assert.assertEquals
+import org.junit.Assert.assertFalse
+import org.junit.Assert.assertTrue
+import org.junit.Before
+import org.junit.Test
+import org.junit.runner.RunWith
+import org.robolectric.RobolectricTestRunner
+import org.robolectric.annotation.Config
+import java.io.File
+
+/**
+ * `update_gotcha_settings` end to end (issue #99): model call → validation →
+ * confirmation → [SettingsRepository] → audit log, driven by a scripted server.
+ */
+@RunWith(RobolectricTestRunner::class)
+@Config(sdk = [34], shadows = [ShadowExternalStorageManager::class])
+class SettingsUpdateLoopTest {
+
+ private val context: Context = ApplicationProvider.getApplicationContext()
+
+ private lateinit var server: MockWebServer
+ private lateinit var repository: SettingsRepository
+ private lateinit var events: RecordingAgentEvents
+ private lateinit var engine: AgentEngine
+ private lateinit var workDir: File
+ private val actionLog: File get() = File(context.filesDir, "action_log.txt")
+
+ @Before
+ fun setUp() {
+ FakeAndroidKeyStore.setUp()
+ server = MockWebServer()
+ server.start()
+ workDir = File(context.filesDir, "settings-update-test").apply {
+ deleteRecursively()
+ mkdirs()
+ }
+ actionLog.delete()
+
+ repository = SettingsRepository(context)
+ repository.save(
+ Settings(
+ provider = LlmProvider.OPENAI_COMPATIBLE,
+ apiKey = "test-key",
+ baseUrl = server.url("/").toString(),
+ model = "gpt-4o",
+ maxToolRounds = 4
+ )
+ )
+
+ events = RecordingAgentEvents()
+ engine = AgentEngine(
+ appContext = context,
+ events = events,
+ historyRepository = ChatHistoryRepository(context, "settings-update-test-chats"),
+ settingsProvider = { repository.load() },
+ clientProvider = { LLMClient(apiKey = "test-key", baseUrl = server.url("/").toString()) },
+ onUpdateGotchaSettings = { plan ->
+ repository.save(plan.applyTo(repository.load()))
+ ToolResult.ok(GotchaSettingsUpdate.appliedMessage(plan))
+ },
+ workingDirRoot = workDir.absolutePath
+ )
+ engine.sessionId = "settings-update-test"
+ }
+
+ @After
+ fun tearDown() {
+ server.shutdown()
+ workDir.deleteRecursively()
+ actionLog.delete()
+ }
+
+ private fun enqueueSettingsCall(changesJson: String, id: String = "call_1") {
+ val args = """{"changes":$changesJson,"reason":"You asked."}"""
+ .replace("\\", "\\\\").replace("\"", "\\\"")
+ server.enqueue(
+ MockResponse().setBody(
+ """{"choices":[{"message":{"role":"assistant","tool_calls":[
+ {"id":"$id","type":"function",
+ "function":{"name":"update_gotcha_settings","arguments":"$args"}}]}}]}"""
+ )
+ )
+ }
+
+ private fun enqueueTextReply(text: String) {
+ server.enqueue(MockResponse().setBody("""{"choices":[{"message":{"role":"assistant","content":"$text"}}]}"""))
+ }
+
+ private fun lastRequestBody(): String {
+ var body = ""
+ repeat(server.requestCount) { body = server.takeRequest().body.readUtf8() }
+ return body
+ }
+
+ @Test
+ fun `approving saves the change through SettingsRepository and audits it`() = runTest {
+ enqueueSettingsCall("""{"reply_chime":true,"completion_preview":"full"}""")
+ enqueueTextReply("Done.")
+
+ engine.run(AgentMode.OPERATOR)
+
+ assertEquals(1, events.confirmationRequests.size)
+ val prompt = events.confirmationRequests.single()
+ assertTrue(prompt, prompt.startsWith("update_gotcha_settings:"))
+ assertTrue(prompt, prompt.contains("Chime when a reply arrives: Off → On"))
+ assertTrue(prompt, prompt.contains("Reply shown in the task-finished notification: short → full"))
+ assertTrue(prompt, prompt.contains("Affects: privacy, notifications."))
+
+ val saved = repository.load()
+ assertTrue(saved.notifyChimeEnabled)
+ assertEquals(com.gotcha.data.CompletionPreview.FULL, saved.chatCompletionPreview)
+
+ assertTrue(lastRequestBody().contains("now saved"))
+ val log = actionLog.readText()
+ assertTrue(log, log.contains("update_gotcha_settings\t(approved) Chime when a reply arrives: Off → On"))
+ }
+
+ @Test
+ fun `denying leaves every setting unchanged and tells the model`() = runTest {
+ val before = repository.load()
+ events.confirmationAnswer = false
+ enqueueSettingsCall("""{"reply_chime":true,"connectors":{"google":false}}""")
+ enqueueTextReply("Okay, left as is.")
+
+ engine.run(AgentMode.OPERATOR)
+
+ assertEquals(1, events.confirmationRequests.size)
+ assertEquals(before, repository.load())
+ assertTrue(lastRequestBody().contains("declined"))
+ val log = actionLog.readText()
+ assertTrue(log, log.contains("update_gotcha_settings\t(denied)"))
+ assertTrue(log, log.contains("\tFAIL\t"))
+ }
+
+ @Test
+ fun `every change asks again, even right after an approval`() = runTest {
+ enqueueSettingsCall("""{"reply_chime":true}""", id = "call_1")
+ enqueueSettingsCall("""{"auto_read_replies":true}""", id = "call_2")
+ enqueueTextReply("Both done.")
+
+ engine.run(AgentMode.OPERATOR)
+
+ assertEquals(2, events.confirmationRequests.size)
+ assertTrue(repository.load().notifyChimeEnabled)
+ assertTrue(repository.load().autoReadReplies)
+ }
+
+ @Test
+ fun `an invalid request is refused before any prompt and changes nothing`() = runTest {
+ val before = repository.load()
+ enqueueSettingsCall("""{"reply_chime":true,"apiKey":"sk-evil"}""")
+ enqueueTextReply("I can't change that.")
+
+ engine.run(AgentMode.OPERATOR)
+
+ assertTrue(events.confirmationRequests.isEmpty())
+ assertEquals(before, repository.load())
+ assertTrue(lastRequestBody().contains("is not a setting this tool can change"))
+ }
+
+ @Test
+ fun `a request that changes nothing does not prompt`() = runTest {
+ enqueueSettingsCall("""{"reply_vibration":true}""")
+ enqueueTextReply("Already on.")
+
+ engine.run(AgentMode.OPERATOR)
+
+ assertTrue(events.confirmationRequests.isEmpty())
+ assertTrue(lastRequestBody().contains("already have the requested values"))
+ }
+
+ @Test
+ fun `Monitor mode cannot change settings`() = runTest {
+ val before = repository.load()
+ enqueueSettingsCall("""{"reply_chime":true}""")
+ enqueueTextReply("Not in Monitor mode.")
+
+ engine.run(AgentMode.MONITOR)
+
+ assertTrue(events.confirmationRequests.isEmpty())
+ assertEquals(before, repository.load())
+ assertFalse(repository.load().notifyChimeEnabled)
+ }
+}
diff --git a/app/src/test/java/com/gotcha/tools/GotchaSettingsUpdateTest.kt b/app/src/test/java/com/gotcha/tools/GotchaSettingsUpdateTest.kt
new file mode 100644
index 0000000..ce71461
--- /dev/null
+++ b/app/src/test/java/com/gotcha/tools/GotchaSettingsUpdateTest.kt
@@ -0,0 +1,172 @@
+package com.gotcha.tools
+
+import com.gotcha.data.CompletionPreview
+import com.gotcha.data.Settings
+import com.gotcha.data.WakeWordListeningMode
+import kotlinx.serialization.json.Json
+import kotlinx.serialization.json.JsonObject
+import kotlinx.serialization.json.jsonObject
+import org.junit.Assert.assertEquals
+import org.junit.Assert.assertFalse
+import org.junit.Assert.assertNotNull
+import org.junit.Assert.assertNull
+import org.junit.Assert.assertTrue
+import org.junit.Test
+
+/**
+ * The allowlist and validation behind `update_gotcha_settings` (issue #99). Pure
+ * logic: the catalog of skins, connectors and skills is handed in.
+ */
+class GotchaSettingsUpdateTest {
+
+ private val catalog = SettingsCatalog(
+ skins = mapOf("vellum" to "Vellum", "aura" to "Aura"),
+ connectors = mapOf("google" to "Google", "notion" to "Notion"),
+ skills = mapOf("maps" to "Maps")
+ )
+
+ private val current = Settings()
+
+ private fun obj(json: String): JsonObject = Json.parseToJsonElement(json).jsonObject
+
+ private fun parse(json: String) = GotchaSettingsUpdate.parse(obj(json), catalog)
+
+ private fun rejection(json: String): String {
+ val result = parse(json)
+ assertTrue("expected a rejection for $json", result.isFailure)
+ return result.exceptionOrNull()!!.message!!
+ }
+
+ private fun applied(json: String): Settings =
+ GotchaSettingsUpdate.plan(parse(json).getOrThrow(), current).applyTo(current)
+
+ // ---- accepted values ----
+
+ @Test
+ fun `booleans, choices and numbers are applied to their fields`() {
+ val updated = applied(
+ """{"reply_chime":true,"completion_preview":"FULL","wake_word_mode":"screen_on",
+ "wake_word_sensitivity":0.4,"reply_language":"german","skin":"aura"}"""
+ )
+ assertTrue(updated.notifyChimeEnabled)
+ assertEquals(CompletionPreview.FULL, updated.chatCompletionPreview)
+ assertEquals(WakeWordListeningMode.SCREEN_ON, updated.wakeWordListeningMode)
+ assertEquals(0.4f, updated.wakeWordSensitivity, 0.0001f)
+ assertEquals("German", updated.preferredLanguage)
+ assertEquals("aura", updated.skinId)
+ }
+
+ @Test
+ fun `voice language can be set back to following the reply language`() {
+ val base = current.copy(voiceLanguage = "Hindi")
+ val changes = parse("""{"voice_language":"same_as_replies"}""").getOrThrow()
+ assertEquals("", GotchaSettingsUpdate.plan(changes, base).applyTo(base).voiceLanguage)
+ }
+
+ @Test
+ fun `connector and skill toggles edit the disabled sets`() {
+ val base = current.copy(disabledConnectors = setOf("notion"))
+ val changes = parse("""{"connectors":{"notion":true,"google":false},"skills":{"maps":false}}""").getOrThrow()
+ val updated = GotchaSettingsUpdate.plan(changes, base).applyTo(base)
+ assertEquals(setOf("google"), updated.disabledConnectors)
+ assertEquals(setOf("maps"), updated.disabledSkills)
+ }
+
+ // ---- rejected values ----
+
+ @Test
+ fun `keys outside the allowlist are refused, credentials included`() {
+ listOf("apiKey", "api_key", "samosaSessionToken", "model", "base_url", "maxToolRounds", "userName")
+ .forEach { key ->
+ assertTrue(rejection("""{"$key":"x"}""").contains("'$key' is not a setting"))
+ }
+ }
+
+ @Test
+ fun `wrong types, unknown choices and out-of-range numbers are refused`() {
+ assertTrue(rejection("""{"reply_chime":"yes"}""").contains("reply_chime"))
+ assertTrue(rejection("""{"reply_chime":"true"}""").contains("reply_chime"))
+ assertTrue(rejection("""{"completion_preview":"everything"}""").contains("completion_preview"))
+ assertTrue(rejection("""{"wake_word_sensitivity":1.5}""").contains("wake_word_sensitivity"))
+ assertTrue(rejection("""{"wake_word_sensitivity":"0.5"}""").contains("wake_word_sensitivity"))
+ assertTrue(rejection("""{"reply_language":"Klingon"}""").contains("reply_language"))
+ assertTrue(rejection("""{"skin":"neon"}""").contains("skin"))
+ assertTrue(rejection("""{"reply_chime":null}""").contains("reply_chime"))
+ }
+
+ @Test
+ fun `unknown connector or skill ids are refused`() {
+ assertTrue(rejection("""{"connectors":{"dropbox":true}}""").contains("unknown connector 'dropbox'"))
+ assertTrue(rejection("""{"skills":{"nope":true}}""").contains("unknown skill 'nope'"))
+ assertTrue(rejection("""{"connectors":{"google":"on"}}""").contains("connectors.google"))
+ assertTrue(rejection("""{"connectors":true}""").contains("connectors"))
+ }
+
+ @Test
+ fun `one bad key refuses the whole request`() {
+ val message = rejection("""{"reply_chime":true,"apiKey":"sk-123"}""")
+ assertTrue(message.contains("apiKey"))
+ // Nothing to apply: the valid half is not returned on its own.
+ assertTrue(parse("""{"reply_chime":true,"apiKey":"sk-123"}""").getOrNull() == null)
+ }
+
+ @Test
+ fun `an empty request is refused`() {
+ assertTrue(rejection("{}").contains("no settings"))
+ }
+
+ // ---- planning and the prompt ----
+
+ @Test
+ fun `changes that match the current value are dropped from the plan`() {
+ val changes = parse("""{"reply_vibration":true,"reply_chime":true}""").getOrThrow()
+ val plan = GotchaSettingsUpdate.plan(changes, current)
+ assertEquals(listOf("reply_chime"), plan.changes.map { it.key })
+ assertTrue(GotchaSettingsUpdate.plan(changes.take(1), current).changes.isEmpty())
+ }
+
+ @Test
+ fun `the prompt shows current and requested values, the reason and the impact`() {
+ val changes = parse("""{"reply_chime":true,"proactive_scan_screen":false}""").getOrThrow()
+ val text = GotchaSettingsUpdate.describe(GotchaSettingsUpdate.plan(changes, current), "You asked for a chime.")
+ assertTrue(text, text.contains("Why: You asked for a chime."))
+ assertTrue(text, text.contains("Chime when a reply arrives: Off → On"))
+ assertTrue(text, text.contains("Proactive: scan the screen: On → Off"))
+ assertTrue(text, text.contains("Affects: privacy, notifications."))
+ }
+
+ @Test
+ fun `a change touching none of the sensitive areas says so`() {
+ val changes = parse("""{"skin":"aura"}""").getOrThrow()
+ val text = GotchaSettingsUpdate.describe(GotchaSettingsUpdate.plan(changes, current), null)
+ assertTrue(text, text.contains("Skin: Vellum → Aura"))
+ assertTrue(text, text.contains("Does not affect privacy, notifications, permissions or device control."))
+ assertFalse(text, text.contains("Why:"))
+ }
+
+ @Test
+ fun `a payload survives the trip through the confirmation`() {
+ val changes = parse("""{"reply_chime":true,"connectors":{"google":false}}""").getOrThrow()
+ val request = GotchaSettingsUpdate.decodePayload(
+ GotchaSettingsUpdate.encodePayload(changes, "because"),
+ catalog
+ )
+ assertNotNull(request)
+ assertEquals(listOf("reply_chime", "connectors.google"), request!!.changes.map { it.key })
+ assertEquals("because", request.reason)
+ }
+
+ @Test
+ fun `a tampered payload is not trusted`() {
+ val forged = java.util.Base64.getEncoder()
+ .encodeToString("""{"changes":{"apiKey":"sk-evil"}}""".toByteArray())
+ assertNull(GotchaSettingsUpdate.decodePayload(forged, catalog))
+ assertNull(GotchaSettingsUpdate.decodePayload("not base64!!", catalog))
+ }
+
+ @Test
+ fun `the schema offers exactly the keys the parser accepts`() {
+ val schemaKeys = GotchaSettingsUpdate.schemaProperties(catalog).keys
+ assertEquals(GotchaSettingsUpdate.keys(catalog).toSet(), schemaKeys)
+ }
+}
diff --git a/app/src/test/java/com/gotcha/tools/ToolArgValidationTest.kt b/app/src/test/java/com/gotcha/tools/ToolArgValidationTest.kt
index a0d25ff..6a2d3bc 100644
--- a/app/src/test/java/com/gotcha/tools/ToolArgValidationTest.kt
+++ b/app/src/test/java/com/gotcha/tools/ToolArgValidationTest.kt
@@ -128,7 +128,10 @@ class ToolArgValidationTest {
* - the connector-backed tools report "X is not connected" before looking at args;
* - `set_timer` reports the domain rule ("must be at least 1 second");
* - `finish_task` ends the *top-level* turn, so the sub-agent harness this test uses
- * refuses it outright — which is the more important thing to say.
+ * refuses it outright — which is the more important thing to say;
+ * - `update_gotcha_settings` is likewise refused to sub-agents: its approval prompt
+ * belongs to the run the user is watching. `GotchaSettingsUpdateTest` and
+ * `SettingsUpdateLoopTest` cover its argument checks at the top level.
*/
val NOT_PARAMETER_NAMED = setOf(
"create_task",
@@ -139,7 +142,8 @@ class ToolArgValidationTest {
"notion_update_page",
"notion_mark_todo",
"notion_delete_item",
- "set_timer"
+ "set_timer",
+ "update_gotcha_settings"
)
}
}
diff --git a/app/src/test/resources/feature-test-coverage.json b/app/src/test/resources/feature-test-coverage.json
index c5fe76b..b5ad206 100644
--- a/app/src/test/resources/feature-test-coverage.json
+++ b/app/src/test/resources/feature-test-coverage.json
@@ -14,6 +14,15 @@
],
"notes": "merge semantics (modify-and-extend, never erase), the no-op guard, and the 250/50-word caps"
},
+ {
+ "tool": "update_gotcha_settings",
+ "tier": "ROBOLECTRIC",
+ "tests": [
+ "com.gotcha.tools.GotchaSettingsUpdateTest",
+ "com.gotcha.agent.SettingsUpdateLoopTest"
+ ],
+ "notes": "the allowlist (credentials refused), per-key validation, all-or-nothing rejection, and the loop: a prompt on every change, denial leaves settings untouched, approval saves through SettingsRepository, both audited"
+ },
{
"tool": "about_samosa_ai",
"tier": "ROBOLECTRIC",
diff --git a/docs/FEATURE_TEST_COVERAGE.md b/docs/FEATURE_TEST_COVERAGE.md
index bf8882a..507d876 100644
--- a/docs/FEATURE_TEST_COVERAGE.md
+++ b/docs/FEATURE_TEST_COVERAGE.md
@@ -14,12 +14,12 @@ Every tool the assistant can call is listed below, together with how it is verif
| Tier | Tools | What it means |
|---|---:|---|
| `UNIT` | 24 | Plain JVM unit test — no Android framework needed. |
-| `ROBOLECTRIC` | 28 | JVM test against Robolectric's Android framework, often across several API levels. |
+| `ROBOLECTRIC` | 29 | 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** | **116** | |
+| **Total** | **117** | |
-**52 of 116** tools are covered by an automated test; the remaining 64 are manual-QA-only with a recorded reason.
+**53 of 117** tools are covered by an automated test; the remaining 64 are manual-QA-only with a recorded reason.
## Foreground tools (act on the screen)
@@ -148,6 +148,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_gotcha_settings` | `ROBOLECTRIC` | `GotchaSettingsUpdateTest`, `SettingsUpdateLoopTest` — the allowlist (credentials refused), per-key validation, all-or-nothing rejection, and the loop: a prompt on every change, denial leaves settings untouched, approval saves through SettingsRepository, both audited |
| `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. |