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(connectors): user enable/disable + hide tools nothing can serve
Durganshu Mishradb582613fa74
diff --git a/app/src/main/java/com/gotcha/agent/AgentEngine.kt b/app/src/main/java/com/gotcha/agent/AgentEngine.ktindex 4e4869e..b006371 100644--- a/app/src/main/java/com/gotcha/agent/AgentEngine.kt+++ b/app/src/main/java/com/gotcha/agent/AgentEngine.kt@@ -4,6 +4,7 @@ import android.content.Contextimport android.util.Logimport com.gotcha.agent.skills.SkillPromptBuilderimport com.gotcha.agent.skills.SkillRegistry+import com.gotcha.connectors.ConnectorRegistryimport com.gotcha.data.ChatHistoryRepositoryimport com.gotcha.data.ChatSessionimport com.gotcha.data.GotchaStorage@@ -381,7 +382,11 @@ class AgentEngine(addAll(activeSkillsMessages())}val response = try {- llm.chat(messages, ToolRegistry.toolsForAgent(agent), sessionId = sessionId)+ llm.chat(+ messages,+ ToolRegistry.toolsForAgent(agent, hiddenConnectorTools()),+ sessionId = sessionId+ )} catch (e: CancellationException) {throw e} catch (e: Exception) {@@ -796,9 +801,22 @@ class AgentEngine(} catch (_: Exception) {return ToolResult.error("Malformed tool arguments: ${call.function.arguments.take(200)}")}- return toolExecutor.execute(call.function.name, args, agent)+ return toolExecutor.execute(+ call.function.name,+ args,+ agent,+ hiddenTools = hiddenConnectorTools()+ )}+ /**+ * Tools withheld this turn because every connector that could serve them is+ * disconnected or switched off. Recomputed per call — the user can connect or+ * toggle a connector mid-conversation.+ */+ private fun hiddenConnectorTools(): Set<String> =+ ConnectorRegistry.hiddenToolNames(settings.disabledConnectors)+/*** Environment block sent as the first system message.* Fully static within a session — no volatile fields like timestamps.@@ -981,6 +999,18 @@ class AgentEngine(appendLine(" (Relative paths in read_file/write_file/list_files resolve against the working directory.)")appendLine(" Preferred language: ${settings.preferredLanguage}")appendLine(" Preferred currency: ${settings.preferredCurrency}")+ // Discovery hint for connectors the user has never set up. Costs ~20+ // tokens and is the only way the model can suggest connecting Notion+ // or To Do, whose tools are hidden and which — unlike email — have no+ // no-connector fallback tool. Connectors that are configured but+ // switched off are omitted: the user already decided.+ val unconfigured = ConnectorRegistry.unconfigured()+ if (unconfigured.isNotEmpty()) {+ appendLine(+ " Connectors available to set up (drawer menu ▸ Connectors): " ++ unconfigured.joinToString(", ") { it.displayName }+ )+ }append("</env>")}}diff --git a/app/src/main/java/com/gotcha/connectors/Connector.kt b/app/src/main/java/com/gotcha/connectors/Connector.ktindex cd4ef7e..4b6650c 100644--- a/app/src/main/java/com/gotcha/connectors/Connector.kt+++ b/app/src/main/java/com/gotcha/connectors/Connector.kt@@ -20,9 +20,24 @@ interface Connector {/** Names of the tools that depend on this connector (shown on its card). */val toolNames: Set<String>+ /**+ * The static half of this connector: which tools it owns outright, and which+ * agents may use them. See [ConnectorSpec] for why it lives apart from the+ * instance.+ */+ val spec: ConnectorSpec+/** True when credentials are stored and the connector is usable. */fun isConnected(): Boolean+ /**+ * True when the connector is both connected and not switched off by the user.+ * Tool exposure keys off this, not [isConnected]: a disabled connector keeps+ * its credentials (so re-enabling needs no re-auth) but contributes no tools.+ */+ fun isActive(disabledConnectors: Set<String>): Boolean =+ isConnected() && id !in disabledConnectors+/** Short status line for the Settings card (e.g. "Connected as [email protected]"). */fun statusLine(): Stringdiff --git a/app/src/main/java/com/gotcha/connectors/ConnectorCatalog.kt b/app/src/main/java/com/gotcha/connectors/ConnectorCatalog.ktnew file mode 100644index 0000000..7d695d7--- /dev/null+++ b/app/src/main/java/com/gotcha/connectors/ConnectorCatalog.kt@@ -0,0 +1,111 @@+package com.gotcha.connectors++import com.gotcha.tools.AgentMode++/**+ * Context-free description of a connector: which tools depend on it, which of+ * those only read, and which agents may use them.+ *+ * Split out of [Connector] deliberately. Tool gating and the Monitor tool set+ * have to be derivable without constructing connectors — constructing one needs+ * a Context and touches the encrypted credential store, which neither+ * [com.gotcha.tools.ToolRegistry] nor its unit tests can do.+ */+data class ConnectorSpec(+ /** Matches [Connector.id] — the credential-store key. */+ val id: String,+ val displayName: String,+ /**+ * Tools that have no non-connector implementation, and are therefore hidden+ * from the model while every owning connector is inactive.+ *+ * Deliberately narrower than [Connector.toolNames] (what the Settings card+ * lists): `list_calendar_events` and `create_calendar_event` are owned by+ * Google/Microsoft for remote accounts but fall back to the device calendar+ * via CalendarContract, so they must stay exposed with no connector at all.+ */+ val ownedToolNames: Set<String>,+ /** Subset of [ownedToolNames] that only reads — the slice Monitor may call. */+ val readOnlyToolNames: Set<String> = emptySet(),+ /** Agents allowed to use this connector's tools. */+ val agents: Set<AgentMode> = setOf(AgentMode.MONITOR, AgentMode.OPERATOR)+)++/**+ * The static half of the connector registry. [ConnectorRegistry] owns the live+ * instances and their connection state; this owns what each connector *would*+ * contribute, which is fixed at compile time.+ */+object ConnectorCatalog {++ private val MAIL_TOOLS = setOf("list_emails", "read_email", "send_email", "mark_email_read")+ private val MAIL_READ_TOOLS = setOf("list_emails", "read_email")++ val IMAP = ConnectorSpec(+ id = "imap",+ displayName = "Email (IMAP)",+ ownedToolNames = MAIL_TOOLS,+ readOnlyToolNames = MAIL_READ_TOOLS+ )++ val GOOGLE = ConnectorSpec(+ id = "google",+ displayName = "Google (BYO OAuth)",+ // check_availability is the one calendar tool with no CalendarContract+ // implementation — free/busy needs a remote account.+ ownedToolNames = MAIL_TOOLS + "check_availability",+ readOnlyToolNames = MAIL_READ_TOOLS + "check_availability"+ )++ val MICROSOFT = ConnectorSpec(+ id = "microsoft",+ displayName = "Microsoft (Outlook, Calendar, To Do)",+ ownedToolNames = MAIL_TOOLS + setOf(+ "check_availability",+ "list_tasks",+ "create_task",+ "complete_task"+ ),+ readOnlyToolNames = MAIL_READ_TOOLS + setOf("check_availability", "list_tasks")+ )++ val NOTION = ConnectorSpec(+ id = "notion",+ displayName = "Notion",+ ownedToolNames = setOf(+ "notion_search",+ "notion_read_page",+ "notion_create_page",+ "notion_append_to_page"+ ),+ readOnlyToolNames = setOf("notion_search", "notion_read_page")+ )++ val all: List<ConnectorSpec> = listOf(IMAP, GOOGLE, MICROSOFT, NOTION)++ fun byId(id: String): ConnectorSpec? = all.firstOrNull { it.id == id }++ /** Every tool that depends on at least one connector. */+ val allOwnedTools: Set<String> = all.flatMapTo(mutableSetOf()) { it.ownedToolNames }++ /** Connector-owned tools Monitor may call, contributed to ToolRegistry.monitorTools. */+ val monitorTools: Set<String> = all+ .filter { AgentMode.MONITOR in it.agents }+ .flatMapTo(mutableSetOf()) { it.readOnlyToolNames }++ /**+ * Tools to hide given the ids of the currently active connectors.+ *+ * Exposure is per-tool, not per-connector: `list_emails` is owned by IMAP,+ * Google and Microsoft, so it survives as long as *any* of them is active.+ */+ fun hiddenTools(activeIds: Set<String>): Set<String> {+ val exposed = all+ .filter { it.id in activeIds }+ .flatMapTo(mutableSetOf()) { it.ownedToolNames }+ return allOwnedTools - exposed+ }++ /** Connectors that own [tool] — used to explain what to connect. */+ fun ownersOf(tool: String): List<ConnectorSpec> = all.filter { tool in it.ownedToolNames }+}diff --git a/app/src/main/java/com/gotcha/connectors/ConnectorRegistry.kt b/app/src/main/java/com/gotcha/connectors/ConnectorRegistry.ktindex 1c38c38..e0f0798 100644--- a/app/src/main/java/com/gotcha/connectors/ConnectorRegistry.kt+++ b/app/src/main/java/com/gotcha/connectors/ConnectorRegistry.kt@@ -66,6 +66,27 @@ object ConnectorRegistry {fun byId(id: String): Connector? = connectors.firstOrNull { it.id == id }+ /** Ids of connectors that are connected and not switched off by the user. */+ fun activeIds(disabledConnectors: Set<String>): Set<String> =+ connectors.filter { it.isActive(disabledConnectors) }.mapTo(mutableSetOf()) { it.id }++ /**+ * Tool names to withhold from the model right now, because every connector+ * that could serve them is disconnected or disabled. Falls back to hiding+ * all connector-owned tools before [init] runs — nothing can serve them at+ * that point either.+ */+ fun hiddenToolNames(disabledConnectors: Set<String>): Set<String> =+ ConnectorCatalog.hiddenTools(activeIds(disabledConnectors))++ /**+ * Connectors the user has never set up, for the one-line discovery hint in+ * the agent's environment block. Deliberately excludes connectors that are+ * configured but switched off: that was the user's choice, and re-offering+ * it every turn would be nagging.+ */+ fun unconfigured(): List<Connector> = connectors.filterNot { it.isConnected() }+/** Email tool router (null before [init]). Used by the send-confirmation flow. */fun email(): EmailTools? = emailToolsdiff --git a/app/src/main/java/com/gotcha/connectors/google/GoogleConnector.kt b/app/src/main/java/com/gotcha/connectors/google/GoogleConnector.ktindex 9007917..3eb9fca 100644--- a/app/src/main/java/com/gotcha/connectors/google/GoogleConnector.kt+++ b/app/src/main/java/com/gotcha/connectors/google/GoogleConnector.kt@@ -75,6 +75,7 @@ class GoogleConnector("check_availability")override val idPrefix = "gmail"+ override val spec = com.gotcha.connectors.ConnectorCatalog.GOOGLE@Volatileprivate var credentials: GoogleCredentials? = store.loadRaw(id)?.let { blob ->diff --git a/app/src/main/java/com/gotcha/connectors/imap/ImapConnector.kt b/app/src/main/java/com/gotcha/connectors/imap/ImapConnector.ktindex a283d33..c70b828 100644--- a/app/src/main/java/com/gotcha/connectors/imap/ImapConnector.kt+++ b/app/src/main/java/com/gotcha/connectors/imap/ImapConnector.kt@@ -75,6 +75,7 @@ class ImapConnector(override val toolNames =setOf("list_emails", "read_email", "send_email", "mark_email_read")override val idPrefix = "imap"+ override val spec = com.gotcha.connectors.ConnectorCatalog.IMAPprivate val json = Json { ignoreUnknownKeys = true }private var cachedStore: Store? = nulldiff --git a/app/src/main/java/com/gotcha/connectors/microsoft/MicrosoftConnector.kt b/app/src/main/java/com/gotcha/connectors/microsoft/MicrosoftConnector.ktindex 4769109..7df7aec 100644--- a/app/src/main/java/com/gotcha/connectors/microsoft/MicrosoftConnector.kt+++ b/app/src/main/java/com/gotcha/connectors/microsoft/MicrosoftConnector.kt@@ -87,6 +87,7 @@ class MicrosoftConnector("complete_task")override val idPrefix = "ms"+ override val spec = com.gotcha.connectors.ConnectorCatalog.MICROSOFT@Volatileprivate var credentials: MicrosoftCredentials? = store.loadRaw(id)?.let { blob ->diff --git a/app/src/main/java/com/gotcha/connectors/notion/NotionConnector.kt b/app/src/main/java/com/gotcha/connectors/notion/NotionConnector.ktindex dd28d5c..18cfd5a 100644--- a/app/src/main/java/com/gotcha/connectors/notion/NotionConnector.kt+++ b/app/src/main/java/com/gotcha/connectors/notion/NotionConnector.kt@@ -45,6 +45,7 @@ class NotionConnector("notion_create_page","notion_append_to_page")+ override val spec = com.gotcha.connectors.ConnectorCatalog.NOTION@Volatileprivate var credentials: NotionCredentials? = store.loadRaw(id)?.let { blob ->diff --git a/app/src/main/java/com/gotcha/data/SettingsRepository.kt b/app/src/main/java/com/gotcha/data/SettingsRepository.ktindex c3fe7f9..b158f9b 100644--- a/app/src/main/java/com/gotcha/data/SettingsRepository.kt+++ b/app/src/main/java/com/gotcha/data/SettingsRepository.kt@@ -45,6 +45,12 @@ data class Settings(val assistiveBallEnabled: Boolean = false,val themeMode: ThemeMode = ThemeMode.SYSTEM,val disabledSkills: Set<String> = emptySet(),+ /**+ * Ids of connectors the user switched off. Credentials survive (re-enabling+ * needs no re-auth), but the connector contributes no tools and its skills+ * stop being injected.+ */+ val disabledConnectors: Set<String> = emptySet(),// Proactive Assistance Settingsval proactiveEnabled: Boolean = true,val proactiveScanScreen: Boolean = true,@@ -166,6 +172,9 @@ class SettingsRepository(context: Context) {)}+ private fun stringSet(key: String, default: Set<String> = emptySet()): Set<String> =+ prefs.getStringSet(key, default) ?: default+fun load(): Settings = Settings(provider = LlmProvider.fromName(prefs.getString(KEY_PROVIDER, null)),apiKey = prefs.getString(KEY_API_KEY, "") ?: "",@@ -200,18 +209,18 @@ class SettingsRepository(context: Context) {themeMode = runCatching {ThemeMode.valueOf(prefs.getString(KEY_THEME_MODE, "SYSTEM") ?: "SYSTEM")}.getOrDefault(ThemeMode.SYSTEM),- disabledSkills = prefs.getStringSet(KEY_DISABLED_SKILLS, emptySet()) ?: emptySet(),+ disabledSkills = stringSet(KEY_DISABLED_SKILLS),+ disabledConnectors = stringSet(KEY_DISABLED_CONNECTORS),proactiveEnabled = prefs.getBoolean(KEY_PROACTIVE_ENABLED, true),proactiveScanScreen = prefs.getBoolean(KEY_PROACTIVE_SCAN_SCREEN, true),proactiveScanClipboard = prefs.getBoolean(KEY_PROACTIVE_SCAN_CLIPBOARD, true),proactiveScanNotifications = prefs.getBoolean(KEY_PROACTIVE_SCAN_NOTIFICATIONS, true),proactiveOtpEnabled = prefs.getBoolean(KEY_PROACTIVE_OTP_ENABLED, true),proactiveAutoCopyOtp = prefs.getBoolean(KEY_PROACTIVE_AUTO_COPY_OTP, true),- proactiveAppBlacklist = prefs.getStringSet(KEY_PROACTIVE_BLACKLIST, emptySet()) ?: emptySet(),+ proactiveAppBlacklist = stringSet(KEY_PROACTIVE_BLACKLIST),preferredLanguage = prefs.getString(KEY_PREFERRED_LANGUAGE, "English") ?: "English",preferredCurrency = prefs.getString(KEY_PREFERRED_CURRENCY, "USD") ?: "USD",- communitySkillHosts = prefs.getStringSet(KEY_COMMUNITY_SKILL_HOSTS, defaultCommunitySkillHosts)- ?: defaultCommunitySkillHosts+ communitySkillHosts = stringSet(KEY_COMMUNITY_SKILL_HOSTS, defaultCommunitySkillHosts))fun save(settings: Settings) {@@ -243,6 +252,7 @@ class SettingsRepository(context: Context) {.putBoolean(KEY_ASSISTIVE_BALL, settings.assistiveBallEnabled).putString(KEY_THEME_MODE, settings.themeMode.name).putStringSet(KEY_DISABLED_SKILLS, settings.disabledSkills)+ .putStringSet(KEY_DISABLED_CONNECTORS, settings.disabledConnectors).putBoolean(KEY_PROACTIVE_ENABLED, settings.proactiveEnabled).putBoolean(KEY_PROACTIVE_SCAN_SCREEN, settings.proactiveScanScreen).putBoolean(KEY_PROACTIVE_SCAN_CLIPBOARD, settings.proactiveScanClipboard)@@ -300,6 +310,7 @@ class SettingsRepository(context: Context) {const val KEY_ASSISTIVE_BALL = "assistive_ball_enabled"const val KEY_THEME_MODE = "theme_mode"const val KEY_DISABLED_SKILLS = "disabled_skills"+ const val KEY_DISABLED_CONNECTORS = "disabled_connectors"const val KEY_PROACTIVE_ENABLED = "proactive_enabled"const val KEY_PROACTIVE_SCAN_SCREEN = "proactive_scan_screen"const val KEY_PROACTIVE_SCAN_CLIPBOARD = "proactive_scan_clipboard"diff --git a/app/src/main/java/com/gotcha/tools/SubAgentSession.kt b/app/src/main/java/com/gotcha/tools/SubAgentSession.ktindex e805a33..6561256 100644--- a/app/src/main/java/com/gotcha/tools/SubAgentSession.kt+++ b/app/src/main/java/com/gotcha/tools/SubAgentSession.kt@@ -4,6 +4,7 @@ import android.content.Contextimport android.util.Logimport com.gotcha.agent.skills.SkillPromptBuilderimport com.gotcha.agent.skills.SkillRegistry+import com.gotcha.connectors.ConnectorRegistryimport com.gotcha.data.Settingsimport com.gotcha.llm.ChatMessageimport com.gotcha.llm.LLMClient@@ -51,7 +52,10 @@ class SubAgentSession(val history = initialHistory()val maxRounds = settings.maxToolRounds- val subAgentTools = ToolRegistry.toolsForSubAgent()+ // Sub-agents inherit the parent's connector gating: no point paying for+ // schemas of tools nothing can serve, once per round, again.+ val hiddenTools = ConnectorRegistry.hiddenToolNames(settings.disabledConnectors)+ val subAgentTools = ToolRegistry.toolsForSubAgent(hiddenTools)for (round in 0 until maxRounds) {Log.d(TAG, "Sub-agent round ${round + 1}/$maxRounds")@@ -125,7 +129,13 @@ class SubAgentSession(}val result = try {- toolExecutor.execute(call.function.name, args, AgentMode.OPERATOR, isSubAgent = true)+ toolExecutor.execute(+ call.function.name,+ args,+ AgentMode.OPERATOR,+ isSubAgent = true,+ hiddenTools = hiddenTools+ )} catch (e: CancellationException) {throw e} catch (e: Throwable) {diff --git a/app/src/main/java/com/gotcha/tools/ToolExecutor.kt b/app/src/main/java/com/gotcha/tools/ToolExecutor.ktindex 6c7760d..a1d53ab 100644--- a/app/src/main/java/com/gotcha/tools/ToolExecutor.kt+++ b/app/src/main/java/com/gotcha/tools/ToolExecutor.kt@@ -77,11 +77,20 @@ class ToolExecutor(name: String,args: JsonObject,agent: AgentMode = AgentMode.OPERATOR,- isSubAgent: Boolean = false+ isSubAgent: Boolean = false,+ /**+ * Connector-owned tools withheld from the model this turn. Callers on the+ * model path pass these so a hallucinated call is refused with an+ * actionable message instead of reaching a router that cannot serve it.+ */+ hiddenTools: Set<String> = emptySet()): ToolResult {if (!ToolRegistry.contains(name)) {return ToolResult.error("Unknown tool '$name'. Only the fixed tool catalog is available.")}+ if (name in hiddenTools) {+ return ToolResult.error(connectorUnavailableMessage(name))+ }if (!isSubAgent && !ToolRegistry.isAllowedForAgent(name, agent)) {return ToolResult.error("This action is not available in ${agent.name} mode. " +@@ -492,6 +501,19 @@ class ToolExecutor(}}+ /** Names the connectors that would make [name] work, so the model can steer the user. */+ private fun connectorUnavailableMessage(name: String): String {+ val owners = com.gotcha.connectors.ConnectorCatalog.ownersOf(name)+ .joinToString(" or ") { it.displayName }+ val suffix = if (owners.isBlank()) {+ "The connector it needs is not set up."+ } else {+ "It needs $owners, which is not connected or is switched off."+ }+ return "Tool '$name' is unavailable. $suffix " ++ "Tell the user to set it up in the drawer menu ▸ Connectors; do not retry."+ }+private fun JsonObject.requireString(key: String): String? =this[key]?.jsonPrimitive?.takeIf { it.isString || it.content.isNotEmpty() }?.contentdiff --git a/app/src/main/java/com/gotcha/tools/ToolRegistry.kt b/app/src/main/java/com/gotcha/tools/ToolRegistry.ktindex 7b708e6..a840f06 100644--- a/app/src/main/java/com/gotcha/tools/ToolRegistry.kt+++ b/app/src/main/java/com/gotcha/tools/ToolRegistry.kt@@ -1,5 +1,6 @@package com.gotcha.tools+import com.gotcha.connectors.ConnectorCatalogimport com.gotcha.llm.FunctionDefinitionimport com.gotcha.llm.ToolDefinitionimport kotlinx.serialization.json.add@@ -27,9 +28,15 @@ object ToolRegistry {"delete_timer")- val monitorTools: Set<String> = setOf(+ /**+ * Read-only tools that belong to no connector. The connector-owned half of+ * the Monitor set is contributed by [ConnectorCatalog] so the two can never+ * drift — adding a connector read tool in one place used to require+ * remembering to add it here too.+ */+ private val baseMonitorTools: Set<String> = setOf("dial_number", "read_call_log", "find_contact", "read_recent_sms",- "list_calendar_events", "check_availability",+ "list_calendar_events","get_storage_info", "get_battery_info", "get_location", "get_volume","get_audio_recording_status","get_app_usage", "get_data_usage",@@ -42,13 +49,12 @@ object ToolRegistry {"get_clipboard","read_screen", "read_notifications","check_root", "search_skills",- "list_emails", "read_email",- "list_tasks",- "notion_search", "notion_read_page","get_health_summary", "get_health_records","get_now_playing")+ val monitorTools: Set<String> = baseMonitorTools + ConnectorCatalog.monitorTools+/** Full Operator tool set minus task + navigate_app (sub-agents cannot delegate further). */val subAgentTools: Set<String> = definitions.keys - setOf("task", "navigate_app")@@ -317,20 +323,40 @@ object ToolRegistry {fun isDestructive(name: String): Boolean = name in destructiveTools- fun isAllowedForAgent(name: String, agent: AgentMode): Boolean = when (agent) {- AgentMode.MONITOR -> name in monitorTools- AgentMode.OPERATOR -> name in operatorTools+ fun isAllowedForAgent(+ name: String,+ agent: AgentMode,+ hiddenTools: Set<String> = emptySet()+ ): Boolean {+ if (name in hiddenTools) return false+ return when (agent) {+ AgentMode.MONITOR -> name in monitorTools+ AgentMode.OPERATOR -> name in operatorTools+ }}- fun isAllowedForSubAgent(name: String): Boolean = name in subAgentTools+ fun isAllowedForSubAgent(name: String, hiddenTools: Set<String> = emptySet()): Boolean =+ name !in hiddenTools && name in subAgentTools- fun toolsForAgent(agent: AgentMode): List<ToolDefinition> = when (agent) {- AgentMode.MONITOR -> definitions.filterKeys { it in monitorTools }.values.toList()- AgentMode.OPERATOR -> definitions.values.toList()+ /**+ * Tool schemas to send for [agent], minus [hiddenTools] — connector-owned+ * tools nothing can currently serve. Withholding them is both a token saving+ * and a correctness fix: the model can no longer spend a round calling a tool+ * whose only possible reply is "not connected".+ */+ fun toolsForAgent(+ agent: AgentMode,+ hiddenTools: Set<String> = emptySet()+ ): List<ToolDefinition> {+ val allowed = when (agent) {+ AgentMode.MONITOR -> monitorTools+ AgentMode.OPERATOR -> operatorTools+ }+ return definitions.filterKeys { it in allowed && it !in hiddenTools }.values.toList()}- fun toolsForSubAgent(): List<ToolDefinition> =- definitions.filterKeys { it in subAgentTools }.values.toList()+ fun toolsForSubAgent(hiddenTools: Set<String> = emptySet()): List<ToolDefinition> =+ definitions.filterKeys { it in subAgentTools && it !in hiddenTools }.values.toList()fun toolsForNavigator(): List<ToolDefinition> =navigatorTools.mapNotNull { navigatorDefinitions[it] }diff --git a/app/src/main/java/com/gotcha/ui/ConnectorCards.kt b/app/src/main/java/com/gotcha/ui/ConnectorCards.ktindex cc8e3a0..20b7762 100644--- a/app/src/main/java/com/gotcha/ui/ConnectorCards.kt+++ b/app/src/main/java/com/gotcha/ui/ConnectorCards.kt@@ -2,12 +2,14 @@ package com.gotcha.uiimport androidx.compose.foundation.layout.Arrangementimport androidx.compose.foundation.layout.Column+import androidx.compose.foundation.layout.Rowimport androidx.compose.foundation.layout.fillMaxWidthimport androidx.compose.foundation.text.KeyboardOptionsimport androidx.compose.material3.Buttonimport androidx.compose.material3.MaterialThemeimport androidx.compose.material3.OutlinedButtonimport androidx.compose.material3.OutlinedTextField+import androidx.compose.material3.Switchimport androidx.compose.material3.Textimport androidx.compose.material3.TextButtonimport androidx.compose.runtime.Composable@@ -17,6 +19,7 @@ import androidx.compose.runtime.mutableStateOfimport androidx.compose.runtime.rememberimport androidx.compose.runtime.rememberCoroutineScopeimport androidx.compose.runtime.setValue+import androidx.compose.ui.Alignmentimport androidx.compose.ui.Modifierimport androidx.compose.ui.text.font.FontWeightimport androidx.compose.ui.text.input.PasswordVisualTransformation@@ -51,6 +54,33 @@ private fun CardHeader(title: String, status: String, blurb: String?, steps: Lis}}+/**+ * The enable/disable switch, shown only once a connector is connected. Distinct+ * from Disconnect: switching off keeps the credentials (re-enabling needs no+ * re-auth) but withholds the connector's tools and skills from the assistant.+ */+@Composable+private fun EnabledRow(enabled: Boolean, onEnabledChange: (Boolean) -> Unit) {+ Row(+ verticalAlignment = Alignment.CenterVertically,+ horizontalArrangement = Arrangement.SpaceBetween,+ modifier = Modifier.fillMaxWidth()+ ) {+ Column(modifier = Modifier.weight(1f)) {+ Text("Enabled", style = MaterialTheme.typography.bodyMedium)+ Text(+ if (enabled) {+ "The assistant can use this connector's tools."+ } else {+ "Switched off — tools hidden, sign-in kept."+ },+ style = MaterialTheme.typography.bodySmall+ )+ }+ Switch(checked = enabled, onCheckedChange = onEnabledChange)+ }+}+@Composablefun TokenConnectorCard(title: String,@@ -60,6 +90,10 @@ fun TokenConnectorCard(/** Performs the connect (may hit the network) and returns the status message to show. */onConnect: suspend () -> String,onDisconnect: () -> Unit,+ /** Current enable state; only meaningful once connected. */+ enabled: Boolean = true,+ /** Null hides the enable switch entirely. */+ onEnabledChange: ((Boolean) -> Unit)? = null,blurb: String? = null,steps: List<String> = emptyList(),canConnect: () -> Boolean = { fields.all { it.value.isNotBlank() } },@@ -105,6 +139,7 @@ fun TokenConnectorCard(modifier = Modifier.fillMaxWidth()) { Text(if (busy) "Connecting…" else "Connect") }} else {+ if (onEnabledChange != null) EnabledRow(enabled, onEnabledChange)OutlinedButton(onClick = {onDisconnect()@@ -130,6 +165,10 @@ fun OAuthConnectorCard(initialClientSecret: String?,flow: OAuthConnectFlow,onDisconnect: () -> Unit,+ /** Current enable state; only meaningful once connected. */+ enabled: Boolean = true,+ /** Null hides the enable switch entirely. */+ onEnabledChange: ((Boolean) -> Unit)? = null,blurb: String? = null,steps: List<String> = emptyList(),extraFields: @Composable () -> Unit = {}@@ -222,6 +261,7 @@ fun OAuthConnectorCard() { Text("Finish sign-in with pasted URL") }}} else {+ if (onEnabledChange != null) EnabledRow(enabled, onEnabledChange)OutlinedButton(onClick = {onDisconnect()diff --git a/app/src/main/java/com/gotcha/ui/ConnectorsSection.kt b/app/src/main/java/com/gotcha/ui/ConnectorsSection.ktindex 2ae0fa4..cf9c54a 100644--- a/app/src/main/java/com/gotcha/ui/ConnectorsSection.kt+++ b/app/src/main/java/com/gotcha/ui/ConnectorsSection.kt@@ -29,6 +29,7 @@ import com.gotcha.connectors.imap.ImapCredentialsimport com.gotcha.connectors.microsoft.MicrosoftConnectorimport com.gotcha.connectors.notion.NotionConnectorimport com.gotcha.connectors.oauth.OAuthConnectFlow+import com.gotcha.data.SettingsRepository/*** The body of the Connectors screen: one card per connector, built from the two@@ -47,19 +48,32 @@ fun ConnectorsSection() {val microsoft = remember(registry) { registry.byId("microsoft") as MicrosoftConnector }val notion = remember(registry) { registry.byId("notion") as NotionConnector }+ // The one piece of connector state that is *not* a credential, so it lives in+ // Settings rather than the connector's own encrypted blob.+ val settingsRepo = remember(context) { SettingsRepository(context) }+ var disabled by remember { mutableStateOf(settingsRepo.load().disabledConnectors) }+ fun setEnabled(id: String, enabled: Boolean) {+ disabled = if (enabled) disabled - id else disabled + id+ settingsRepo.save(settingsRepo.load().copy(disabledConnectors = disabled))+ }+Column(verticalArrangement = Arrangement.spacedBy(16.dp)) {- ImapCard(imap)+ ImapCard(imap, "imap" !in disabled) { setEnabled("imap", it) }HorizontalDivider(thickness = 1.dp)- GoogleCard(google)+ GoogleCard(google, "google" !in disabled) { setEnabled("google", it) }HorizontalDivider(thickness = 1.dp)- MicrosoftCard(microsoft)+ MicrosoftCard(microsoft, "microsoft" !in disabled) { setEnabled("microsoft", it) }HorizontalDivider(thickness = 1.dp)- NotionCard(notion)+ NotionCard(notion, "notion" !in disabled) { setEnabled("notion", it) }}}@Composable-private fun NotionCard(notion: NotionConnector) {+private fun NotionCard(+ notion: NotionConnector,+ enabled: Boolean,+ onEnabledChange: (Boolean) -> Unit+) {val token = rememberTokenField("Internal integration token", "", secret = true)TokenConnectorCard(@@ -77,12 +91,18 @@ private fun NotionCard(notion: NotionConnector) {"add the integration. Pages that are not shared stay invisible to it."),onConnect = { notion.connect(token.value) },- onDisconnect = notion::disconnect+ onDisconnect = notion::disconnect,+ enabled = enabled,+ onEnabledChange = onEnabledChange)}@Composable-private fun ImapCard(imap: ImapConnector) {+private fun ImapCard(+ imap: ImapConnector,+ enabled: Boolean,+ onEnabledChange: (Boolean) -> Unit+) {val saved = imap.credentials()val email = rememberTokenField("Email address", saved?.email ?: "", keyboard = KeyboardType.Email)val appPassword = rememberTokenField("App password", "", secret = true)@@ -125,12 +145,18 @@ private fun ImapCard(imap: ImapConnector) {)"Saved. Credentials are verified on first use."},- onDisconnect = imap::disconnect+ onDisconnect = imap::disconnect,+ enabled = enabled,+ onEnabledChange = onEnabledChange)}@Composable-private fun GoogleCard(google: GoogleConnector) {+private fun GoogleCard(+ google: GoogleConnector,+ enabled: Boolean,+ onEnabledChange: (Boolean) -> Unit+) {val context = LocalContext.current// Which Google services to request consent for. Adding one later needs a reconnect,// because the refresh token only carries the scopes granted at consent time.@@ -164,6 +190,8 @@ private fun GoogleCard(google: GoogleConnector) {initialClientSecret = google.credentials()?.clientSecret ?: "",flow = flow,onDisconnect = google::disconnect,+ enabled = enabled,+ onEnabledChange = onEnabledChange,blurb = "Full read/write Gmail and Google Calendar access using your own Google Cloud " +"OAuth client — no shared app, no verification wait.",steps = listOf(@@ -194,7 +222,11 @@ private fun GoogleCard(google: GoogleConnector) {}@Composable-private fun MicrosoftCard(microsoft: MicrosoftConnector) {+private fun MicrosoftCard(+ microsoft: MicrosoftConnector,+ enabled: Boolean,+ onEnabledChange: (Boolean) -> Unit+) {val context = LocalContext.current// "common" covers personal and work accounts; a tenant id/domain locks it to one org.var tenant by remember {@@ -219,6 +251,8 @@ private fun MicrosoftCard(microsoft: MicrosoftConnector) {initialClientSecret = null,flow = flow,onDisconnect = microsoft::disconnect,+ enabled = enabled,+ onEnabledChange = onEnabledChange,blurb = "Outlook mail, calendar and To Do using your own Entra app registration. " +"One sign-in covers all three.",steps = listOf(diff --git a/app/src/test/java/com/gotcha/connectors/ConnectorGatingTest.kt b/app/src/test/java/com/gotcha/connectors/ConnectorGatingTest.ktnew file mode 100644index 0000000..f6c94a1--- /dev/null+++ b/app/src/test/java/com/gotcha/connectors/ConnectorGatingTest.kt@@ -0,0 +1,180 @@+package com.gotcha.connectors++import com.gotcha.tools.AgentMode+import com.gotcha.tools.ToolRegistry+import org.junit.Assert.assertEquals+import org.junit.Assert.assertFalse+import org.junit.Assert.assertTrue+import org.junit.Test++/**+ * Connector-driven tool gating. Exercises [ConnectorCatalog] directly rather+ * than live connectors — that is the whole point of splitting the spec out of+ * [Connector]: the rules are testable without a Context or a credential store.+ */+class ConnectorGatingTest {++ private val mailTools = setOf("list_emails", "read_email", "send_email", "mark_email_read")++ @Test+ fun `nothing active hides every connector-owned tool`() {+ val hidden = ConnectorCatalog.hiddenTools(emptySet())+ assertEquals(ConnectorCatalog.allOwnedTools, hidden)+ assertTrue(mailTools.all { it in hidden })+ assertTrue("notion_search" in hidden)+ assertTrue("list_tasks" in hidden)+ assertTrue("check_availability" in hidden)+ }++ @Test+ fun `mail tools survive when any one mail backend is active`() {+ // Exposure is per-tool, not per-connector: turning Gmail off while IMAP+ // is connected must not take email away.+ listOf("imap", "google", "microsoft").forEach { id ->+ val hidden = ConnectorCatalog.hiddenTools(setOf(id))+ assertTrue("$id should expose mail tools", mailTools.none { it in hidden })+ }+ }++ @Test+ fun `disabling one mail backend keeps the others exposed`() {+ val hidden = ConnectorCatalog.hiddenTools(setOf("imap"))+ assertTrue(mailTools.none { it in hidden })+ // IMAP owns no tasks or Notion, so those stay hidden.+ assertTrue("list_tasks" in hidden)+ assertTrue("notion_search" in hidden)+ }++ @Test+ fun `check_availability needs google or microsoft, not imap`() {+ assertTrue("check_availability" in ConnectorCatalog.hiddenTools(setOf("imap")))+ assertFalse("check_availability" in ConnectorCatalog.hiddenTools(setOf("google")))+ assertFalse("check_availability" in ConnectorCatalog.hiddenTools(setOf("microsoft")))+ }++ @Test+ fun `device-backed calendar tools are never connector-owned`() {+ // They fall back to CalendarContract, so they must stay exposed with no+ // connector at all. delete and edit never leave ToolExecutor's device path.+ listOf(+ "list_calendar_events",+ "create_calendar_event",+ "edit_calendar_event",+ "delete_calendar_event"+ ).forEach {+ assertFalse("$it must not be gated", it in ConnectorCatalog.allOwnedTools)+ }+ }++ @Test+ fun `compose_email is never gated so the agent keeps a no-connector fallback`() {+ assertFalse("compose_email" in ConnectorCatalog.allOwnedTools)+ }++ @Test+ fun `every owned tool exists in the catalog and every read tool is owned`() {+ ConnectorCatalog.allOwnedTools.forEach {+ assertTrue("unknown tool $it", ToolRegistry.contains(it))+ }+ ConnectorCatalog.all.forEach { spec ->+ assertTrue(+ "${spec.id} read tools must be a subset of its owned tools",+ spec.ownedToolNames.containsAll(spec.readOnlyToolNames)+ )+ }+ }++ @Test+ fun `monitor tool set includes connector read tools and excludes their writes`() {+ assertTrue("list_emails" in ToolRegistry.monitorTools)+ assertTrue("read_email" in ToolRegistry.monitorTools)+ assertTrue("notion_search" in ToolRegistry.monitorTools)+ assertTrue("list_tasks" in ToolRegistry.monitorTools)+ assertFalse("send_email" in ToolRegistry.monitorTools)+ assertFalse("notion_create_page" in ToolRegistry.monitorTools)+ assertFalse("create_task" in ToolRegistry.monitorTools)+ }++ @Test+ fun `hidden tools are dropped from the operator schema list`() {+ val hidden = ConnectorCatalog.hiddenTools(emptySet())+ val exposed = ToolRegistry.toolsForAgent(AgentMode.OPERATOR, hidden)+ .map { it.function.name }+ .toSet()+ assertTrue(hidden.none { it in exposed })+ // Everything else survives.+ assertEquals(+ ToolRegistry.allDefinitions().size - hidden.size,+ exposed.size+ )+ assertTrue("compose_email" in exposed)+ }++ @Test+ fun `hidden tools are dropped for monitor and sub-agents too`() {+ val hidden = ConnectorCatalog.hiddenTools(emptySet())+ assertTrue(+ ToolRegistry.toolsForAgent(AgentMode.MONITOR, hidden)+ .none { it.function.name in hidden }+ )+ assertTrue(+ ToolRegistry.toolsForSubAgent(hidden).none { it.function.name in hidden }+ )+ }++ @Test+ fun `hidden tools are refused by the permission check`() {+ val hidden = setOf("list_emails")+ assertFalse(ToolRegistry.isAllowedForAgent("list_emails", AgentMode.OPERATOR, hidden))+ assertFalse(ToolRegistry.isAllowedForSubAgent("list_emails", hidden))+ // Unaffected without the gate.+ assertTrue(ToolRegistry.isAllowedForAgent("list_emails", AgentMode.OPERATOR))+ }++ private class FakeConnector(+ override val spec: ConnectorSpec,+ private val connected: Boolean+ ) : Connector {+ override val id = spec.id+ override val displayName = spec.displayName+ override val description = ""+ override val toolNames = spec.ownedToolNames+ override fun isConnected() = connected+ override fun statusLine() = ""+ override fun disconnect() = Unit+ }++ @Test+ fun `a disabled connector is inactive but stays connected`() {+ val notion = FakeConnector(ConnectorCatalog.NOTION, connected = true)+ assertTrue(notion.isActive(emptySet()))+ assertFalse(notion.isActive(setOf("notion")))+ // Credentials are untouched — re-enabling must not need a re-auth.+ assertTrue(notion.isConnected())+ }++ @Test+ fun `a disconnected connector is inactive regardless of the disabled set`() {+ val notion = FakeConnector(ConnectorCatalog.NOTION, connected = false)+ assertFalse(notion.isActive(emptySet()))+ assertFalse(notion.isActive(setOf("notion")))+ }++ @Test+ fun `catalog ids match the connector ids the registry uses`() {+ assertEquals(+ setOf("imap", "google", "microsoft", "notion"),+ ConnectorCatalog.all.map { it.id }.toSet()+ )+ }++ @Test+ fun `ownersOf names the connectors that would unblock a tool`() {+ assertEquals(+ setOf("imap", "google", "microsoft"),+ ConnectorCatalog.ownersOf("list_emails").map { it.id }.toSet()+ )+ assertEquals(listOf("notion"), ConnectorCatalog.ownersOf("notion_search").map { it.id })+ assertTrue(ConnectorCatalog.ownersOf("read_file").isEmpty())+ }+}