diff --git a/plugins/AI-Core/README.md b/plugins/AI-Core/README.md index adb01699..464ea173 100644 --- a/plugins/AI-Core/README.md +++ b/plugins/AI-Core/README.md @@ -115,7 +115,12 @@ Four rules the store applies, each of which was a bug before it was a rule: Contributed tools run inside the contributing plugin, under *its* permissions, and outside the `PathGuard` containment that covers this plugin's own handlers — so the approval dialog names the source plugin, and `allowsSessionApproval` is false for -every contributed tool: "Always Allow" is downgraded to a single approval. +every contributed tool that may change something: "Always Allow" is downgraded to a +single approval. A tool its provider declares read-only (`ToolSpec.isReadOnly`) may +be allowed for the session (ADFA-7147): still one explicit approval per tool, and the +grant is keyed by provider and tool rather than by the registered name, which can pass +to another plugin's tool when the sources change. The grant lapses if the tool stops +declaring itself read-only. For the same reason a source's own `requiresApproval = false` is ignored: `ensureApproved` returns early on it, before `allowsSessionApproval` is ever diff --git a/plugins/AI-Core/src/main/kotlin/com/itsaky/androidide/plugins/aicore/tool/ToolApprovalManager.kt b/plugins/AI-Core/src/main/kotlin/com/itsaky/androidide/plugins/aicore/tool/ToolApprovalManager.kt index a2321bc6..26a48723 100644 --- a/plugins/AI-Core/src/main/kotlin/com/itsaky/androidide/plugins/aicore/tool/ToolApprovalManager.kt +++ b/plugins/AI-Core/src/main/kotlin/com/itsaky/androidide/plugins/aicore/tool/ToolApprovalManager.kt @@ -33,14 +33,16 @@ class ToolApprovalManager( /** * Built-in tools that can never be blanket-approved for the session, however the user answers. - * Session approval is keyed by tool name alone, so one tap would hand a small model unreviewed - * write access to the whole project; a destructive edit is re-confirmed every time. + * A built-in's session grant is keyed by its name alone, so one tap would hand a small model + * unreviewed write access to the whole project; a destructive edit is re-confirmed every time. */ private val neverSessionApproved = setOf("edit_file") /** * Whether a session grant may cover this call. A predicate rather than a name list because a - * plugin-contributed tool cannot be enumerated here and must be prompt-every-time. + * plugin-contributed tool cannot be enumerated here; its handler says whether it may be + * session-approved (only a tool its provider declared read-only). Checked when a grant is + * used as well as when it is made, so a tool that stops declaring itself read-only asks again. * @param toolName the tool being approved. * @param handler its handler. * @return true when "Always Allow" must be downgraded to a single approval. @@ -48,7 +50,19 @@ class ToolApprovalManager( private fun isNeverSessionApproved(toolName: String, handler: ToolHandler): Boolean = toolName in neverSessionApproved || !handler.allowsSessionApproval - // Concurrent: written from the dialog's coroutine, read from the next tool call's thread. + /** What a session grant for this call is recorded under: see [ToolHandler.sessionApprovalKey]. */ + private fun grantKey(toolName: String, handler: ToolHandler): String = + handler.sessionApprovalKey ?: toolName + + /** + * Whether an earlier "Always Allow" covers this call: granted under its [grantKey], and the + * handler may still be session-approved. + */ + private fun isSessionApproved(toolName: String, handler: ToolHandler): Boolean = + grantKey(toolName, handler) in sessionApprovedTools && !isNeverSessionApproved(toolName, handler) + + // Keys from grantKey. Concurrent: written from the dialog's coroutine, + // read from the next tool call's thread. private val sessionApprovedTools: MutableSet = ConcurrentHashMap.newKeySet() /** @@ -85,15 +99,14 @@ class ToolApprovalManager( return ApprovalResponse(approved = true) } - // Check if already approved for this session - if (sessionApprovedTools.contains(toolName)) { + if (isSessionApproved(toolName, handler)) { AgentTrace.detail("APPROVAL", "$toolName skipped=session-approved") return ApprovalResponse(approved = true) } // Locked from publishing to clearing, so a second caller waits instead of replacing it. val result = requestLock.withLock { - if (sessionApprovedTools.contains(toolName)) { + if (isSessionApproved(toolName, handler)) { AgentTrace.detail("APPROVAL", "$toolName skipped=session-approved while queued") return ApprovalResponse(approved = true) } @@ -148,7 +161,7 @@ class ToolApprovalManager( Log.d(TAG, "Approval granted (once; $toolName is never session-approved)") } else { Log.d(TAG, "Approval granted (session) for $toolName") - sessionApprovedTools.add(toolName) + sessionApprovedTools.add(grantKey(toolName, handler)) } ApprovalResponse(approved = true) } @@ -230,7 +243,8 @@ data class ApprovalResponse( /** * Pending approval request. * - * @property toolName the registered name, which is what session approval is keyed by. + * @property toolName the registered name. A session grant is keyed by the handler's + * [ToolHandler.sessionApprovalKey], or by this name when it has none (a built-in). * @property displayName the name to put on screen; the same string for a built-in. * @property sourceLabel the contributing plugin, or null for one of the agent's own tools. * @property args the arguments the tool would run with. diff --git a/plugins/AI-Core/src/main/kotlin/com/itsaky/androidide/plugins/aicore/tool/ToolHandler.kt b/plugins/AI-Core/src/main/kotlin/com/itsaky/androidide/plugins/aicore/tool/ToolHandler.kt index b93487e5..6d99519d 100644 --- a/plugins/AI-Core/src/main/kotlin/com/itsaky/androidide/plugins/aicore/tool/ToolHandler.kt +++ b/plugins/AI-Core/src/main/kotlin/com/itsaky/androidide/plugins/aicore/tool/ToolHandler.kt @@ -86,6 +86,15 @@ interface ToolHandler { val allowsSessionApproval: Boolean get() = true + /** + * What an "Always Allow" answer is recorded under, or null for the name the call was made + * under, which is what a built-in wants: its name never changes hands. A contributed tool + * overrides it, because its registered name can pass to another plugin's tool when the sources + * change mid-session. + */ + val sessionApprovalKey: String? + get() = null + /** How the approval dialog shows this tool's arguments. */ val approvalPreview: ApprovalPreview get() = ApprovalPreview.ARGS diff --git a/plugins/AI-Core/src/main/kotlin/com/itsaky/androidide/plugins/aicore/tool/sources/ContributedToolHandler.kt b/plugins/AI-Core/src/main/kotlin/com/itsaky/androidide/plugins/aicore/tool/sources/ContributedToolHandler.kt index 11212f28..92b0fbd4 100644 --- a/plugins/AI-Core/src/main/kotlin/com/itsaky/androidide/plugins/aicore/tool/sources/ContributedToolHandler.kt +++ b/plugins/AI-Core/src/main/kotlin/com/itsaky/androidide/plugins/aicore/tool/sources/ContributedToolHandler.kt @@ -57,15 +57,26 @@ class ContributedToolHandler( * A source's own `requiresApproval = false` would return from * `ToolApprovalManager.ensureApproved` before [allowsSessionApproval] below is ever consulted, * so a provider could opt out of the only control there is by asking. The declaration is kept - * on [ContributedTool] for a host-side allowlist to honour one day; nothing honours it now. + * on [ContributedTool] for a host-side allowlist to honour one day (ADFA-7147); nothing + * honours it now. */ override val requiresApproval: Boolean = true /** - * Never blanket-approved: a contributed tool runs outside the agent's path containment, so the - * approval dialog is the only control there is. + * True only for a tool its provider declared read-only (ADFA-7147). A contributed tool runs + * outside the agent's path containment, so the dialog is the only control there is: one that + * may change something is confirmed on every call. For a read-only one the user may answer + * "Always Allow", which still takes one explicit approval per tool per session. The + * declaration is the provider's own claim, so it can widen nothing beyond that one choice. */ - override val allowsSessionApproval: Boolean = false + override val allowsSessionApproval: Boolean get() = readOnly + + /** + * The provider and the tool's own name, which is what the dialog showed when the user said + * "Always Allow". [toolName] alone could hand the grant to another plugin's tool that takes + * the name over after the sources change. + */ + override val sessionApprovalKey: String = "contributed:${tool.providerId}:${tool.name}" /** The contributing plugin's id, for provenance in logs and the settings screen. */ val providerId: String get() = tool.providerId diff --git a/plugins/AI-Core/src/test/kotlin/com/itsaky/androidide/plugins/aicore/tool/ToolApprovalManagerTest.kt b/plugins/AI-Core/src/test/kotlin/com/itsaky/androidide/plugins/aicore/tool/ToolApprovalManagerTest.kt index 7163ff2b..81fe98b0 100644 --- a/plugins/AI-Core/src/test/kotlin/com/itsaky/androidide/plugins/aicore/tool/ToolApprovalManagerTest.kt +++ b/plugins/AI-Core/src/test/kotlin/com/itsaky/androidide/plugins/aicore/tool/ToolApprovalManagerTest.kt @@ -2,11 +2,15 @@ package com.itsaky.androidide.plugins.aicore.tool import com.itsaky.androidide.plugins.aicore.models.ToolResult import com.itsaky.androidide.plugins.aicore.prompt.config.DirectoryPromptConfigSource.Companion.shippedConfig +import com.itsaky.androidide.plugins.aicore.tool.sources.ContributedToolHandler +import com.itsaky.androidide.plugins.aicore.tool.sources.FakeToolSource +import com.itsaky.androidide.plugins.aicore.tool.sources.contributedTool import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.async import kotlinx.coroutines.delay import kotlinx.coroutines.runBlocking import kotlinx.coroutines.withTimeout +import org.junit.Assert.assertEquals import org.junit.Assert.assertFalse import org.junit.Assert.assertTrue import org.junit.Test @@ -46,6 +50,37 @@ class ToolApprovalManagerTest { } } + /** The request the last [answer] saw on screen. */ + private var lastRequest: ApprovalRequest? = null + + /** + * Runs [ensureApproved] for [handler] and answers its dialog with [result]. Times out when no + * dialog appears, which is how a test sees a grant cover a call it must not. + */ + private fun answer( + manager: ToolApprovalManager, + handler: ToolHandler, + result: ApprovalResult, + ): ApprovalResponse = runBlocking { + val pending = async(Dispatchers.Default) { + manager.ensureApproved(handler.toolName, handler, emptyMap()) + } + withTimeout(5_000) { + while (!manager.hasPendingApproval()) delay(5) + lastRequest = manager.currentApprovalRequest.value + manager.submitApproval(result) + pending.await() + } + } + + /** A real contributed handler, registered under the tool's own name. */ + private fun contributed(providerId: String, name: String, readOnly: Boolean) = + ContributedToolHandler( + FakeToolSource(providerId), + contributedTool(providerId, name, readOnly = readOnly), + name, + ) + @Test fun givenAToolDeclaringNoApproval_whenApprovalIsRequested_thenItRunsWithNoDialog() = runBlocking { // The handler's own declaration is the whole gate now; no name list is consulted. @@ -232,6 +267,70 @@ class ToolApprovalManagerTest { ) } + @Test + fun givenAReadOnlyContributedTool_whenApprovedForTheSession_thenTheNextCallRunsWithNoDialog() { + // ADFA-7147: one tap per read-only tool per session, instead of one per call. + val manager = ToolApprovalManager({ shippedConfig }) + val query = contributed("com.itsaky.androidide.plugins.aiagentmcp", "query", readOnly = true) + + assertTrue(answer(manager, query, ApprovalResult.APPROVED_FOR_SESSION).approved) + assertTrue("the dialog must offer Always Allow", lastRequest?.allowsSessionApproval == true) + + val second = runBlocking { + withTimeout(5_000) { manager.ensureApproved(query.toolName, query, emptyMap()) } + } + assertTrue(second.approved) + assertFalse(manager.hasPendingApproval()) + } + + @Test + fun givenAContributedToolNotDeclaredReadOnly_whenApprovedForTheSession_thenTheUserIsAskedAgain() { + val manager = ToolApprovalManager({ shippedConfig }) + val write = contributed("com.itsaky.androidide.plugins.aiagentmcp", "create_issue", readOnly = false) + + assertTrue(answer(manager, write, ApprovalResult.APPROVED_FOR_SESSION).approved) + assertFalse("the dialog must not offer Always Allow", lastRequest?.allowsSessionApproval == true) + + assertFalse( + "a tool that may change something is confirmed on every call", + answer(manager, write, ApprovalResult.DENIED).approved, + ) + } + + @Test + fun givenASessionGrant_whenAnotherPluginsReadOnlyToolTakesItsName_thenTheUserIsAskedAgain() { + // Registered names are first come, first served: once the first source goes, the second + // one's tool is published under the same name. The user approved the first plugin's tool. + val manager = ToolApprovalManager({ shippedConfig }) + val mine = contributed("com.example.one", "query", readOnly = true) + assertTrue(answer(manager, mine, ApprovalResult.APPROVED_FOR_SESSION).approved) + + val theirs = contributed("com.example.two", "query", readOnly = true) + assertEquals(mine.toolName, theirs.toolName) + + assertFalse( + "another plugin's tool must not inherit the grant", + answer(manager, theirs, ApprovalResult.DENIED).approved, + ) + } + + @Test + fun givenASessionGrant_whenTheToolStopsDeclaringReadOnly_thenTheUserIsAskedAgain() { + val manager = ToolApprovalManager({ shippedConfig }) + val provider = "com.itsaky.androidide.plugins.aiagentmcp" + assertTrue( + answer(manager, contributed(provider, "query", readOnly = true), ApprovalResult.APPROVED_FOR_SESSION) + .approved, + ) + + val nowWriting = contributed(provider, "query", readOnly = false) + + assertFalse( + "the grant lapses with the read-only declaration", + answer(manager, nowWriting, ApprovalResult.DENIED).approved, + ) + } + @Test fun givenADenial_whenApprovalIsRequested_thenItReportsTheDenial() { val manager = ToolApprovalManager({ shippedConfig }) diff --git a/plugins/AI-Core/src/test/kotlin/com/itsaky/androidide/plugins/aicore/tool/sources/ContributedToolHandlerTest.kt b/plugins/AI-Core/src/test/kotlin/com/itsaky/androidide/plugins/aicore/tool/sources/ContributedToolHandlerTest.kt index 6d76cd56..25385de6 100644 --- a/plugins/AI-Core/src/test/kotlin/com/itsaky/androidide/plugins/aicore/tool/sources/ContributedToolHandlerTest.kt +++ b/plugins/AI-Core/src/test/kotlin/com/itsaky/androidide/plugins/aicore/tool/sources/ContributedToolHandlerTest.kt @@ -124,7 +124,7 @@ class ContributedToolHandlerTest { } @Test - fun givenAContributedTool_whenItIsBuilt_thenItIsNeverSessionApprovable() { + fun givenAContributedToolNotDeclaredReadOnly_whenItIsBuilt_thenItIsNeverSessionApprovable() { val source = FakeToolSource(PROVIDER) val handler = handlerFor(source, contributedTool(PROVIDER, "create_issue")) @@ -148,11 +148,31 @@ class ContributedToolHandlerTest { val handler = ContributedToolHandler(source, tool, "searchplugin_code_search") assertTrue("a source cannot decline the approval dialog", handler.requiresApproval) - assertFalse(handler.allowsSessionApproval) + assertTrue("a read-only tool may be allowed for the session (ADFA-7147)", handler.allowsSessionApproval) assertTrue(handler.readOnly) assertFalse("a read-only tool changes nothing, whatever approval it needs", handler.mutatesProject) } + @Test + fun givenTwoProvidersToolsOfOneName_whenBuilt_thenTheirSessionKeysDiffer() { + // A session grant follows what the dialog showed, the provider and the tool's own name, + // never the registered name, which another plugin's tool can take over. + val first = ContributedToolHandler( + FakeToolSource("com.example.one"), + contributedTool("com.example.one", "query", readOnly = true), + "query", + ) + val second = ContributedToolHandler( + FakeToolSource("com.example.two"), + contributedTool("com.example.two", "query", readOnly = true), + "query", + ) + + assertEquals(first.toolName, second.toolName) + assertFalse(first.sessionApprovalKey == second.sessionApprovalKey) + assertFalse("a contributed key cannot collide with a built-in name", first.sessionApprovalKey == "query") + } + @Test fun givenAToolNameCarryingNewlines_whenItIsBuilt_thenTheNameShownCannotForgeDialogStructure() { // displayName is the approval dialog's title: a name carrying a newline plus a copy of the