Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 6 additions & 1 deletion plugins/AI-Core/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -33,22 +33,36 @@ 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.
*/
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<String> = ConcurrentHashMap.newKeySet()

/**
Expand Down Expand Up @@ -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)
}
Expand Down Expand Up @@ -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))

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

MINOR: a session grant outlives the chat session, and the dialog tooltip promises otherwise.

The defect is partly outside this diff: clearSessionApprovals() (line 225) has no caller anywhere in plugins/AI-Core, and ChatViewModel.createNewSession, switchToSession and importSession never clear it. So "Always Allow" lasts for the whole ChatViewModel, across every chat in the project. The tooltip text in AiCorePlugin.kt (~line 644) says the grant is "by tool name only" and "forgotten when the session ends", which no longer matches for contributed tools (keyed by provider and tool) and is not true for chats. Built-ins already behave this way, so it is MINOR, but this PR newly extends the lifetime to plugin-run tools, and the README and PR description both say "per session".

Either call clearSessionApprovals() when the chat session changes, or word the README and tooltip as "until the IDE closes this chat panel".

}
ApprovalResponse(approved = true)
}
Expand Down Expand Up @@ -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.
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

IMPORTANT: "Always Allow" now rests on a read-only claim the user is never shown and nothing in the host checks.

readOnly is copied from the provider's ToolSpec.isReadOnly (ToolSourceRegistryImpl:168). The dialog (ApprovalDialogFragment) prints the source label, description and args, but nothing says "read-only" or that this is the provider's own declaration, so the user cannot weigh what the Always Allow button is asking of them. A read-only-declared tool still runs outside PathGuard and may read project files or reach the network. After one tap, a prompt-injected model can call it with any arguments, because the grant ignores args (the dialog's own tooltip says so). Before this change a provider could not buy that by declaring a flag.

This is the reversal the ticket says AI-Core's owner decides, so it needs that decision on record before merge. If it goes ahead, have the dialog say the tool is declared read-only by the plugin, and tell the user the grant covers every argument.


/**
* 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}"

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

MINOR: the grant key is provider and tool name only, so it does not cover what the user approved (description, schema, read-only flag).

The user taps Always Allow on query from provider P, having read one description and one schema. P (or an MCP server behind it, via notifyToolsChanged) republishes query with a different description and schema and still isReadOnly = true. The new ContributedToolHandler produces the same key, so it runs with no dialog. The PR's "key by what the dialog showed" reasoning stops at the name. It is MINOR because the provider is already trusted for its own tools and this needs a mid-session redefinition, which no current in-repo provider does.

Fold a hash of description and parameters schema into the key, so a changed tool asks again. The comment above (what the dialog showed) is also loose: the dialog title is the registered toolName, not tool.name.


/** The contributing plugin's id, for provenance in logs and the settings screen. */
val providerId: String get() = tool.providerId
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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.
Expand Down Expand Up @@ -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 })
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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"))

Expand All @@ -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
Expand Down
Loading