diff --git a/plugins/AI-Core/README.md b/plugins/AI-Core/README.md
index adb01699e..11640aa8b 100644
--- a/plugins/AI-Core/README.md
+++ b/plugins/AI-Core/README.md
@@ -115,18 +115,32 @@ 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, the tool's own name and a SHA-256 of its description and
+input schema rather than by the registered name, which can pass to another plugin's tool
+when the sources change. A tool its provider republishes under the same name with
+another description or schema therefore asks again. The grant lapses if the tool stops
+declaring itself read-only, and every grant, built-in or contributed, ends with the chat:
+`ChatViewModel` clears them whenever the current chat changes (new, opened, imported, or
+deleted and replaced) or is cleared, since its `ToolApprovalManager` lives as long as the
+plugin. The declaration is the provider's own and nothing checks it,
+so a dialog offering "Always Allow" for a contributed tool says exactly that
+(`ApprovalRequest.readOnlyOnProvidersWord`).
For the same reason a source's own `requiresApproval = false` is ignored:
`ensureApproved` returns early on it, before `allowsSessionApproval` is ever
consulted, so honouring it would let a provider decline the only control there is
-by asking. The dialog's title is the *registered* name, and all three
-provider-supplied strings on it — the tool's own name, its description and the
-source's label — are flattened and capped first, at the `ContributedToolHandler`
-boundary rather than in each provider. A remote `displayName` carrying a newline
-and a copy of the dialog's own header could otherwise forge structure the user
-then trusts. Contributing plugins therefore ship no sanitising of their own and
-depend on the installed `ai-core` for it; the two version independently.
+by asking. The dialog's message opens with the *registered* name, whole, under a
+short generic title (the stock title is one line, two at most, and cut a long name
+off at font scale 2.0). All three provider-supplied strings on it — the tool's own
+name, its description and the source's label — are flattened and capped first, at
+the `ContributedToolHandler` boundary rather than in each provider. A remote
+`displayName` carrying a newline and a copy of the dialog's own lines could
+otherwise forge structure the user then trusts. Contributing plugins therefore
+ship no sanitising of their own and depend on the installed `ai-core` for it; the
+two version independently.
## System prompt config
diff --git a/plugins/AI-Core/ai-core.html b/plugins/AI-Core/ai-core.html
index a0eda0e4f..591077eb8 100644
--- a/plugins/AI-Core/ai-core.html
+++ b/plugins/AI-Core/ai-core.html
@@ -89,9 +89,10 @@
Core functionality
edit_file; one that arrives with a name already in use is
offered under a provider-prefixed name instead of being dropped.
Approval with provenance — the approval dialog names the plugin a
- tool came from, and a contributed tool can never be blanket-approved for the
- session: it asks every time, because it runs outside the path containment
- that covers the agent's own tools.
+ tool came from, and a contributed tool asks on every call, because it runs
+ outside the path containment that covers the agent's own tools. The one
+ exception is a tool its plugin says only reads: it may be allowed for the
+ rest of the chat, and the dialog says Code on the Go cannot check that claim.
Text completion, chat with history, and streaming responses, plus a
single cancellation path so Stop reaches whichever backend is
running.
diff --git a/plugins/AI-Core/src/main/assets/docs/index.html b/plugins/AI-Core/src/main/assets/docs/index.html
index 9b7d780cb..02528f628 100644
--- a/plugins/AI-Core/src/main/assets/docs/index.html
+++ b/plugins/AI-Core/src/main/assets/docs/index.html
@@ -177,12 +177,17 @@ Tools from other plugins
These tools are treated more cautiously than the agent's own, because only
the plugin that supplied one knows what it does:
- - They ask every time. The approval dialog names the plugin the tool
- came from — From MCP servers, for example — and does not offer
- Always Allow. A plugin cannot waive this for
- its own tools, and the title shows the name the agent registered rather than
- the one the tool came with, so a remote tool cannot pass itself off as a
- built-in one.
+ - The dialog names where they come from. The approval dialog names the
+ plugin the tool came from — From MCP servers, for example. A plugin cannot
+ skip this dialog for its own tools. The dialog's first line, Tool:,
+ shows the whole name the agent registered rather than the one the tool came
+ with, so a remote tool cannot pass itself off as a built-in one.
+ - Most ask every time. The dialog offers Always Allow only for
+ a tool its plugin says only reads, and then says that Code on the Go cannot
+ check that. Allowing it stops the questions for that tool, whatever its
+ arguments, until you start a new chat, open another one or clear this one.
+ If the plugin changes the tool's description or inputs, you are asked again.
+ Every other tool from a plugin asks on every call.
- They are not confined to the project root. A contributed tool runs
inside its own plugin, under the permissions that plugin declared, so one
from a plugin with network access can send what it is given off the device.
diff --git a/plugins/AI-Core/src/main/kotlin/com/itsaky/androidide/plugins/aicore/fragments/ApprovalDialogFragment.kt b/plugins/AI-Core/src/main/kotlin/com/itsaky/androidide/plugins/aicore/fragments/ApprovalDialogFragment.kt
index e8e81e863..bf30a545c 100644
--- a/plugins/AI-Core/src/main/kotlin/com/itsaky/androidide/plugins/aicore/fragments/ApprovalDialogFragment.kt
+++ b/plugins/AI-Core/src/main/kotlin/com/itsaky/androidide/plugins/aicore/fragments/ApprovalDialogFragment.kt
@@ -1,13 +1,20 @@
package com.itsaky.androidide.plugins.aicore.fragments
import android.app.Dialog
+import android.content.Context
import android.content.res.Resources
import android.os.Bundle
import android.text.InputType
import android.view.View
+import android.view.ViewGroup
import android.widget.EditText
+import android.util.TypedValue
import android.widget.FrameLayout
+import android.widget.TextView
import androidx.appcompat.app.AlertDialog
+import androidx.core.content.res.use
+import androidx.core.view.ViewCompat
+import androidx.core.widget.NestedScrollView
import androidx.fragment.app.DialogFragment
import com.google.android.material.dialog.MaterialAlertDialogBuilder
import com.itsaky.androidide.plugins.aicore.plugin.AiCorePlugin
@@ -53,6 +60,8 @@ class ApprovalDialogFragment : DialogFragment() {
}
companion object {
+ /** The least the approval message is given (about three lines), whatever the buttons need. */
+ private const val MESSAGE_FLOOR_DP = 96
private const val ARG_TOOL_NAME = "tool_name"
private const val ARG_PROVIDER_NAME = "provider_name"
private const val ARG_SOURCE = "source"
@@ -60,6 +69,7 @@ class ApprovalDialogFragment : DialogFragment() {
private const val ARG_ARGS = "args"
private const val ARG_PREVIEW = "preview"
private const val ARG_ALLOWS_ALWAYS_ALLOW = "allows_always_allow"
+ private const val ARG_READ_ONLY_ON_PROVIDERS_WORD = "read_only_on_providers_word"
/**
* Builds the dialog. Everything it needs is in [getArguments], so the framework can
@@ -83,6 +93,7 @@ class ApprovalDialogFragment : DialogFragment() {
putString(ARG_PREVIEW, preview.name)
putString(ARG_ARGS, ApprovalPresentation.format(preview, request.args, resources))
putBoolean(ARG_ALLOWS_ALWAYS_ALLOW, request.allowsSessionApproval)
+ putBoolean(ARG_READ_ONLY_ON_PROVIDERS_WORD, request.readOnlyOnProvidersWord)
}
}
}
@@ -97,33 +108,26 @@ class ApprovalDialogFragment : DialogFragment() {
val preview = ApprovalPresentation.named(arguments?.getString(ARG_PREVIEW))
val isEdit = preview == ApprovalPreview.EDIT
val allowsAlwaysAllow = arguments?.getBoolean(ARG_ALLOWS_ALWAYS_ALLOW) ?: false
+ // An edit never offers it, whatever the request allows; see the buttons below.
+ val offersAlwaysAllow = allowsAlwaysAllow && !isEdit
+ val readOnlyOnProvidersWord = arguments?.getBoolean(ARG_READ_ONLY_ON_PROVIDERS_WORD) ?: false
- val message = buildString {
- append(getString(R.string.approval_header))
- append("\n\n")
- // Provenance before the description: a tool that leaves the device is a different
- // decision from a local edit, and only the source says which this is.
- if (!source.isNullOrBlank()) {
- append(getString(R.string.approval_source, source))
- append("\n")
- // Both names, when they differ: the title says what runs, this says what the
- // source calls it, so neither can be passed off as the other.
- if (!providerName.isNullOrBlank()) {
- append(getString(R.string.approval_provider_name, providerName))
- append("\n")
- }
- append("\n")
- }
- append(description)
- append("\n\n")
- append(getString(ApprovalPresentation.argsLabel(preview)))
- append("\n")
- append(argsText)
- }
+ // The full name opens the message, not the title, which a long name overflows; see message().
+ val message = ApprovalPresentation.message(
+ toolName = toolName,
+ source = source,
+ providerName = providerName,
+ readOnlyClaim = offersAlwaysAllow && readOnlyOnProvidersWord,
+ description = description,
+ preview = preview,
+ argsText = argsText,
+ resources = resources,
+ )
val builder = MaterialAlertDialogBuilder(requireContext())
- .setTitle(getString(R.string.approval_confirm_title, toolName))
- .setMessage(message)
+ builder
+ .setTitle(getString(R.string.approval_confirm_title))
+ .setView(messageView(builder.context, message))
.setNegativeButton(getString(R.string.approval_decline)) { _, _ ->
decide(ApprovalResult.DENIED)
dismiss()
@@ -144,7 +148,7 @@ class ApprovalDialogFragment : DialogFragment() {
decide(ApprovalResult.APPROVED_ONCE)
dismiss()
}
- if (allowsAlwaysAllow) {
+ if (offersAlwaysAllow) {
builder.setNeutralButton(getString(R.string.approval_always_allow)) { _, _ ->
decide(ApprovalResult.APPROVED_FOR_SESSION)
dismiss()
@@ -188,6 +192,89 @@ class ApprovalDialogFragment : DialogFragment() {
return dialog
}
+ /**
+ * The message as a scrolling view bounded by [BoundedScrollView]. The stock layout gives the middle
+ * panel its height before the buttons get more than their minimum, so a long message squeezed the
+ * stacked buttons off screen at a large font scale; the bound leaves the buttons their full height.
+ * The text looks like the stock message: it takes the dialog theme's own `materialAlertDialogBodyTextStyle`
+ * and `dialogPreferredPadding`, from [context] (the builder's, so it carries the dialog theme overlay).
+ */
+ private fun messageView(context: Context, message: CharSequence): View {
+ val style = TypedValue()
+ val styleRes = if (context.theme.resolveAttribute(
+ com.google.android.material.R.attr.materialAlertDialogBodyTextStyle, style, true,
+ )
+ ) style.resourceId else 0
+ val padding = context.obtainStyledAttributes(
+ intArrayOf(androidx.appcompat.R.attr.dialogPreferredPadding),
+ ).use { it.getDimensionPixelSize(0, 0) }
+ val text = TextView(context, null, 0, styleRes).apply {
+ this.text = message
+ setPadding(padding, paddingTop, padding, paddingBottom)
+ }
+ // The stock layout puts this gap (titleDividerNoCustom) between the title and a message
+ // it owns; a custom view loses it, so it is restored as top padding on the scroll view.
+ val gap = context.resources.getDimensionPixelSize(androidx.appcompat.R.dimen.abc_dialog_title_divider_material)
+ return BoundedScrollView(context).apply {
+ setPadding(paddingLeft, gap, paddingRight, paddingBottom)
+ // The stock content panel shows these edge indicators while it can scroll; setView drops them.
+ scrollIndicators = View.SCROLL_INDICATOR_TOP or View.SCROLL_INDICATOR_BOTTOM
+ addView(text)
+ }
+ }
+
+ /**
+ * A [NestedScrollView] capped by [ApprovalPresentation.messageMaxHeightPx] so the stock button panel
+ * keeps its full height. `AlertDialogLayout.tryOnMeasure` measures the button panel (unspecified, so
+ * at its full height) before it measures this view, counts only its minimum, then may measure this
+ * view again with the height left over once the buttons took theirs, and `forceUniformWidth` may
+ * measure it a third time. Only the first measure of a sequence reserves room for the buttons;
+ * [firstOffered] remembers that offer so the later ones are recognised. [onLayout] ends the sequence,
+ * and so does a larger offer, which is a new measure pass before any layout
+ * ([ApprovalPresentation.sequenceFirstOfferPx]).
+ */
+ private class BoundedScrollView(context: Context) : NestedScrollView(context) {
+ private var firstOffered: Int? = null
+
+ override fun onMeasure(widthMeasureSpec: Int, heightMeasureSpec: Int) {
+ val unlimited = View.MeasureSpec.getMode(heightMeasureSpec) == View.MeasureSpec.UNSPECIFIED
+ val offered = if (unlimited) Int.MAX_VALUE else View.MeasureSpec.getSize(heightMeasureSpec)
+ val panel = rootView?.findViewById(androidx.appcompat.R.id.buttonPanel)
+ ?.takeIf { it.visibility == View.VISIBLE && it.measuredHeight > 0 }
+ val metrics = resources.displayMetrics
+ firstOffered = ApprovalPresentation.sequenceFirstOfferPx(firstOffered, offered)
+ val cap = ApprovalPresentation.messageMaxHeightPx(
+ windowHeightPx = metrics.heightPixels,
+ offeredPx = offered,
+ buttonsFullPx = panel?.measuredHeight,
+ buttonsMinPx = panel?.let(::minimumHeightOf) ?: 0,
+ floorPx = (MESSAGE_FLOOR_DP * metrics.density).toInt(),
+ firstOfferedPx = firstOffered,
+ )
+ super.onMeasure(
+ widthMeasureSpec,
+ View.MeasureSpec.makeMeasureSpec(minOf(cap, offered), View.MeasureSpec.AT_MOST),
+ )
+ }
+
+ override fun onLayout(changed: Boolean, l: Int, t: Int, r: Int, b: Int) {
+ firstOffered = null
+ super.onLayout(changed, l, t, r, b)
+ }
+
+ override fun onDetachedFromWindow() {
+ firstOffered = null
+ super.onDetachedFromWindow()
+ }
+
+ /** Mirrors `AlertDialogLayout.resolveMinimumHeight`: the view's own, else its only child's. */
+ private fun minimumHeightOf(view: View): Int {
+ val own = ViewCompat.getMinimumHeight(view)
+ if (own > 0) return own
+ return if (view is ViewGroup && view.childCount == 1) minimumHeightOf(view.getChildAt(0)) else 0
+ }
+ }
+
/**
* Delivers the outcome to the host fragment.
*
diff --git a/plugins/AI-Core/src/main/kotlin/com/itsaky/androidide/plugins/aicore/fragments/ApprovalPresentation.kt b/plugins/AI-Core/src/main/kotlin/com/itsaky/androidide/plugins/aicore/fragments/ApprovalPresentation.kt
index dcc917b7c..067e51e38 100644
--- a/plugins/AI-Core/src/main/kotlin/com/itsaky/androidide/plugins/aicore/fragments/ApprovalPresentation.kt
+++ b/plugins/AI-Core/src/main/kotlin/com/itsaky/androidide/plugins/aicore/fragments/ApprovalPresentation.kt
@@ -6,8 +6,8 @@ import com.itsaky.androidide.plugins.aicore.R
import com.itsaky.androidide.plugins.aicore.tool.ApprovalPreview
/**
- * How [ApprovalDialogFragment] presents each [ApprovalPreview] a tool's handler declares. Exhaustive
- * `when`s with no `else`, so a new preview fails to compile until it has a label and a formatter.
+ * How [ApprovalDialogFragment] presents a request: its [message], and each [ApprovalPreview] a tool's handler
+ * declares. Exhaustive `when`s with no `else`, so a new preview fails to compile until it has a label and a formatter.
*/
internal object ApprovalPresentation {
@@ -35,7 +35,102 @@ internal object ApprovalPresentation {
ApprovalPreview.ARGS -> ApprovalTextFormatter.formatArgs(args)
}
+ /**
+ * The approval message, top to bottom: the tool's full registered name and where it came from, as one
+ * block, then the [description], then the [preview]'s heading over the formatted [argsText].
+ *
+ * The name opens the message rather than the title, which is a short question. The stock title is one
+ * line, two once `DialogTitle` shrinks it, and it is cut off past that; at font scale 2.0 it cut a long
+ * name short. The message scrolls, so the whole name is always there to read.
+ *
+ * @param toolName the registered name: the tool that will actually run, which a remote source cannot choose.
+ * @param source the contributing plugin's label, or null for one of the agent's own tools.
+ * @param providerName what the source calls the tool, or null when that is [toolName]; shown only with a [source].
+ * @param readOnlyClaim whether the dialog offers "Always Allow" on the providing plugin's word that the tool only reads.
+ * @param resources words each line.
+ */
+ fun message(
+ toolName: String,
+ source: String?,
+ providerName: String?,
+ readOnlyClaim: Boolean,
+ description: String,
+ preview: ApprovalPreview,
+ argsText: String,
+ resources: Resources,
+ ): String = buildString {
+ append(resources.getString(R.string.approval_tool, toolName)).append("\n")
+ // Provenance before the description: a tool that leaves the device is a different
+ // decision from a local edit, and only the source says which this is.
+ if (!source.isNullOrBlank()) {
+ append(resources.getString(R.string.approval_source, source)).append("\n")
+ // Both names, when they differ: the first line says what runs, this says what the
+ // source calls it, so neither can be passed off as the other.
+ if (!providerName.isNullOrBlank()) {
+ append(resources.getString(R.string.approval_provider_name, providerName)).append("\n")
+ }
+ }
+ // "Always Allow" rests on the plugin's own word here, so the user is told whose it is.
+ if (readOnlyClaim) append(resources.getString(R.string.approval_read_only_claim)).append("\n")
+ append("\n")
+ append(description)
+ append("\n\n")
+ append(resources.getString(argsLabel(preview)))
+ append("\n")
+ append(argsText)
+ }
+
/** The preview saved as [name] in the dialog's arguments; [ApprovalPreview.ARGS] when it is missing or unknown. */
fun named(name: String?): ApprovalPreview =
ApprovalPreview.entries.firstOrNull { it.name == name } ?: ApprovalPreview.ARGS
+
+ /**
+ * The tallest the approval message may grow, so the stock button panel keeps its full height.
+ *
+ * AppCompat's `AlertDialogLayout` measures the title, then the button panel at its minimum
+ * height, then offers the middle panel (this message) what remains ([offeredPx]); only after
+ * that does it hand leftover height back to the buttons. A long message therefore leaves the
+ * stacked buttons just their minimum. The first measure reserves the difference between the buttons' full
+ * and minimum heights, which is the same as `window - title - full buttons`.
+ *
+ * The result never exceeds half the window ([windowHeightPx]), which keeps the dialog compact on
+ * a tall screen, and never drops below [floorPx], so the message cannot collapse to nothing; when
+ * even the floor leaves no room, the stock layout scrolls the buttons as it always did.
+ *
+ * @param windowHeightPx the window height, for the half-window cap.
+ * @param offeredPx the height the parent offers this view (the AT_MOST size).
+ * @param buttonsFullPx the button panel's natural height, or null when it cannot be found, in which
+ * case the cap is half the window alone.
+ * @param buttonsMinPx the button panel's minimum height, already counted in [offeredPx].
+ * @param floorPx the least height the message may be given.
+ * @param firstOfferedPx the offer of the first measure of this layout sequence (see [sequenceFirstOfferPx]),
+ * or null when this is the first. After that measure the layout hands the buttons their height and
+ * measures the message again with `offered = first - (full - min)` or less, so a later measure at or
+ * below that has the buttons already counted and reserves nothing; reserving again would cut the
+ * message short. Passing this measure's own offer for the first one reserves just as null does.
+ */
+ fun messageMaxHeightPx(
+ windowHeightPx: Int,
+ offeredPx: Int,
+ buttonsFullPx: Int?,
+ buttonsMinPx: Int,
+ floorPx: Int,
+ firstOfferedPx: Int? = null,
+ ): Int {
+ val half = (windowHeightPx / 2).coerceAtLeast(0)
+ if (buttonsFullPx == null) return half
+ val extra = (buttonsFullPx - buttonsMinPx).coerceAtLeast(0)
+ val buttonsCounted = firstOfferedPx != null && offeredPx <= firstOfferedPx - extra
+ val reserved = if (buttonsCounted) 0 else extra
+ return minOf(offeredPx - reserved, half).coerceAtLeast(floorPx)
+ }
+
+ /**
+ * The first offer of the measure sequence that [offeredPx] belongs to, given the [storedPx] one remembered
+ * from earlier measures (null after a layout). Inside one `AlertDialogLayout.tryOnMeasure` the later offers
+ * never exceed the first, so a larger offer starts a new sequence and becomes the first. That happens with
+ * no layout in between when `ViewRootImpl.measureHierarchy` measures the window again at a greater width.
+ */
+ fun sequenceFirstOfferPx(storedPx: Int?, offeredPx: Int): Int =
+ storedPx?.takeIf { offeredPx <= it } ?: offeredPx
}
diff --git a/plugins/AI-Core/src/main/kotlin/com/itsaky/androidide/plugins/aicore/plugin/AiCorePlugin.kt b/plugins/AI-Core/src/main/kotlin/com/itsaky/androidide/plugins/aicore/plugin/AiCorePlugin.kt
index 103eb2839..dca8970fd 100644
--- a/plugins/AI-Core/src/main/kotlin/com/itsaky/androidide/plugins/aicore/plugin/AiCorePlugin.kt
+++ b/plugins/AI-Core/src/main/kotlin/com/itsaky/androidide/plugins/aicore/plugin/AiCorePlugin.kt
@@ -642,12 +642,18 @@ class AiCorePlugin : IPlugin, UIExtension, DocumentationExtension, SettingsExten
),
PluginTooltipEntry(
tag = TOOLTIP_TAG_APPROVAL_ALWAYS_ALLOW,
- summary = "Stop asking about this tool for the rest of this session.",
- detail = """
-
Approves this tool for the current session, so the agent can use
- it again without prompting. The grant is by tool name only —
- it does not depend on the arguments — and it is forgotten when the
- session ends.
+ summary = "Stop asking about this tool for the rest of this chat.",
+ detail = """
+ Approves this tool for the rest of this chat, so the agent can use
+ it again without prompting. The grant does not depend on the
+ arguments. It is forgotten when you start a new chat, open another
+ one or clear this one, and when the IDE closes.
+ For a tool from another plugin, the button appears only when
+ that plugin says the tool only reads. Code on the Go cannot check
+ that, and after one tap the agent can call the tool with any
+ arguments. If the plugin changes the tool's description or inputs,
+ you are asked again. A tool from another plugin that may change
+ something asks every time.
It is deliberately unavailable for file edits: those are
re-confirmed every time, with the change on screen.
""".trimIndent(),
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 a2321bc68..b5f36114b 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,19 +99,19 @@ 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)
}
+ val allowsSession = !isNeverSessionApproved(toolName, handler)
val request = ApprovalRequest(
toolName = toolName,
displayName = handler.displayName,
@@ -105,7 +119,8 @@ class ToolApprovalManager(
args = args,
description = describe(handler),
preview = handler.approvalPreview,
- allowsSessionApproval = !isNeverSessionApproved(toolName, handler),
+ allowsSessionApproval = allowsSession,
+ readOnlyOnProvidersWord = allowsSession && handler.readOnlyOnProvidersWord,
)
val deferred = CompletableDeferred()
@@ -148,7 +163,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)
}
@@ -207,7 +222,9 @@ class ToolApprovalManager(
}
/**
- * Clear all session-approved tools.
+ * Forgets every "Always Allow", built-in and contributed alike. `ChatViewModel` calls it when
+ * the chat changes or is cleared, which is where a session ends: its manager lives as long as
+ * the plugin.
*/
fun clearSessionApprovals() {
sessionApprovedTools.clear()
@@ -230,11 +247,14 @@ 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.
* @property description what the tool does.
+ * @property readOnlyOnProvidersWord "Always Allow" is offered only because the tool's provider says
+ * it only reads; the dialog tells the user so, and that the claim is not checked.
*/
data class ApprovalRequest(
val toolName: String,
@@ -244,6 +264,7 @@ data class ApprovalRequest(
val sourceLabel: String? = null,
val preview: ApprovalPreview = ApprovalPreview.ARGS,
val allowsSessionApproval: Boolean = true,
+ val readOnlyOnProvidersWord: Boolean = false,
)
/**
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 b93487e5b..cc234fce1 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,24 @@ interface ToolHandler {
val allowsSessionApproval: Boolean
get() = true
+ /**
+ * Whether [allowsSessionApproval] rests only on the tool's provider saying it only reads, a
+ * claim nothing here can check. The approval dialog then says so above "Always Allow". False
+ * for a built-in, whose code is this plugin's own.
+ */
+ val readOnlyOnProvidersWord: Boolean
+ get() = false
+
+ /**
+ * 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, and its provider can republish it under the same name doing something
+ * else.
+ */
+ 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 11212f285..f40141ef4 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
@@ -5,6 +5,7 @@ import com.itsaky.androidide.plugins.aicore.logging.LOG_PREFIX
import com.itsaky.androidide.plugins.aicore.models.ToolResult
import com.itsaky.androidide.plugins.aicore.tool.ToolHandler
import com.itsaky.androidide.plugins.aicore.tool.Validation
+import java.security.MessageDigest
import java.util.UUID
import java.util.concurrent.CompletableFuture
import java.util.concurrent.CompletionException
@@ -40,7 +41,7 @@ class ContributedToolHandler(
* The tool's own name, never the qualified form a collision may have forced on it.
*
* Flattened and capped: this is a remote string on a consent dialog, where a newline plus a
- * copy of the dialog's own header is enough to forge structure the user then trusts.
+ * copy of the dialog's own lines is enough to forge structure the user then trusts.
*/
override val displayName: String = ContributedText.label(tool.name)
@@ -57,15 +58,32 @@ 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 same declaration: the user is told it is the provider's, which nothing here checks. */
+ override val readOnlyOnProvidersWord: Boolean get() = readOnly
+
+ /**
+ * The provider, the tool's own name and a digest of its description and input schema: the
+ * tool the user said "Always Allow" to, not the name it ran under. [toolName] could hand the
+ * grant to another plugin's tool that takes the name over after the sources change, and the
+ * name alone to a tool its provider republishes under it with other behaviour.
+ */
+ override val sessionApprovalKey: String by lazy {
+ "contributed:${tool.providerId}:${tool.name}:${digest(tool.description, tool.parametersSchema)}"
+ }
/** The contributing plugin's id, for provenance in logs and the settings screen. */
val providerId: String get() = tool.providerId
@@ -177,4 +195,56 @@ class ContributedToolHandler(
/** One model-facing sentence naming the provider, so a failure is attributable. */
private fun providerFailure(what: String): String =
"Tool '$displayName' from $sourceLabel $what"
+
+ private companion object {
+ /**
+ * A SHA-256 of [description] and [schema], in hex. The provider's own description, before
+ * it is flattened and capped, so a change past the cap counts too.
+ */
+ fun digest(description: String, schema: Map): String {
+ val canonical = StringBuilder().also { appendCanonical(it, listOf(description, schema)) }
+ return MessageDigest.getInstance("SHA-256")
+ .digest(canonical.toString().toByteArray(Charsets.UTF_8))
+ .joinToString("") { "%02x".format(it) }
+ }
+
+ /**
+ * Writes [value] so that equal content always gives equal text: map keys sorted, strings
+ * quoted and escaped. A provider rebuilds its schema maps on each listing, so their order
+ * is not part of what the user approved.
+ */
+ fun appendCanonical(out: StringBuilder, value: Any?) {
+ when (value) {
+ null, is Boolean, is Number -> out.append(value)
+ is Map<*, *> -> {
+ out.append('{')
+ value.entries.sortedBy { it.key.toString() }.forEachIndexed { index, entry ->
+ if (index > 0) out.append(',')
+ appendCanonical(out, entry.key.toString())
+ out.append(':')
+ appendCanonical(out, entry.value)
+ }
+ out.append('}')
+ }
+ is Iterable<*> -> {
+ out.append('[')
+ value.forEachIndexed { index, item ->
+ if (index > 0) out.append(',')
+ appendCanonical(out, item)
+ }
+ out.append(']')
+ }
+ is Array<*> -> appendCanonical(out, value.asList())
+ is String -> {
+ out.append('"')
+ value.forEach { c ->
+ if (c == '"' || c == '\\') out.append('\\')
+ out.append(c)
+ }
+ out.append('"')
+ }
+ else -> appendCanonical(out, value.toString())
+ }
+ }
+ }
}
diff --git a/plugins/AI-Core/src/main/kotlin/com/itsaky/androidide/plugins/aicore/viewmodel/ChatViewModel.kt b/plugins/AI-Core/src/main/kotlin/com/itsaky/androidide/plugins/aicore/viewmodel/ChatViewModel.kt
index 0a9c83fac..b5c85ee03 100644
--- a/plugins/AI-Core/src/main/kotlin/com/itsaky/androidide/plugins/aicore/viewmodel/ChatViewModel.kt
+++ b/plugins/AI-Core/src/main/kotlin/com/itsaky/androidide/plugins/aicore/viewmodel/ChatViewModel.kt
@@ -216,8 +216,8 @@ class ChatViewModel(
private val currentBackendId: String
get() = _backendStatus.value.id
- // Tool execution infrastructure
- private val approvalManager = ToolApprovalManager(sharedPromptConfig) { handler ->
+ // Tool execution infrastructure. Internal so a test can hold a grant across a chat change.
+ internal val approvalManager = ToolApprovalManager(sharedPromptConfig) { handler ->
ToolDescriptions.describe(sharedPromptConfig.config(), RESPOND_TOOL, handler)
}
/** One cap for the loop's cut and the handlers that fit under it; see [ToolOutputBudget]. */
@@ -2103,6 +2103,8 @@ class ChatViewModel(
}
// The title described the conversation just cleared; the next first reply writes a new one.
resetGeneratedTitle()
+ // A cleared chat starts over like a new one, so what was allowed in it is asked again.
+ approvalManager.clearSessionApprovals()
forgetRetryPoint()
setState(AgentState.Idle)
// Written now rather than debounced: a clear is deliberate and must survive a force-stop.
@@ -2182,6 +2184,9 @@ class ChatViewModel(
*/
private fun adoptSession(session: ChatSession) {
_currentSessionId.value = session.id
+ // "Always Allow" lasts for one chat, as its tooltip says. This ViewModel lives as long as
+ // the plugin, across every chat and project, so its approval manager cannot end it alone.
+ approvalManager.clearSessionApprovals()
showTranscript(session.messages, session.compaction)
// Also dropped here: the readiness edge may have fired while another chat was current.
if (_backendStatus.value.isAvailable) clearBackendSetupNotices()
diff --git a/plugins/AI-Core/src/main/res/values/strings.xml b/plugins/AI-Core/src/main/res/values/strings.xml
index adc219a40..6b6902a52 100644
--- a/plugins/AI-Core/src/main/res/values/strings.xml
+++ b/plugins/AI-Core/src/main/res/values/strings.xml
@@ -143,10 +143,13 @@
Approve Once
Approve for Session
Deny
- 🔒 Tool Approval Required
- ⚠️ Confirm: %s
+
+ Allow this tool?
+ Tool: %1$s
From %1$s
The source calls this tool “%1$s”
+
+ The plugin that supplied this tool says it only reads. Code on the Go cannot check that.
✓ Run Now
✓ Always Allow
Proposed change:
diff --git a/plugins/AI-Core/src/test/kotlin/com/itsaky/androidide/plugins/aicore/fragments/ApprovalPresentationTest.kt b/plugins/AI-Core/src/test/kotlin/com/itsaky/androidide/plugins/aicore/fragments/ApprovalPresentationTest.kt
index fa25881d7..bac5c87ea 100644
--- a/plugins/AI-Core/src/test/kotlin/com/itsaky/androidide/plugins/aicore/fragments/ApprovalPresentationTest.kt
+++ b/plugins/AI-Core/src/test/kotlin/com/itsaky/androidide/plugins/aicore/fragments/ApprovalPresentationTest.kt
@@ -1,13 +1,16 @@
package com.itsaky.androidide.plugins.aicore.fragments
+import android.content.res.Resources
import com.itsaky.androidide.plugins.aicore.R
import com.itsaky.androidide.plugins.aicore.tool.ApprovalPreview
+import io.mockk.every
+import io.mockk.mockk
import org.junit.Assert.assertEquals
import org.junit.Test
/**
* Unit tests for [ApprovalPresentation]: the dialog picks its presentation from the preview the
- * handler declares, never from the tool's name.
+ * handler declares, never from the tool's name, and its message always carries that name whole.
*/
class ApprovalPresentationTest {
@@ -26,9 +29,180 @@ class ApprovalPresentationTest {
}
}
+ /** Words each string as its tag plus its arguments, so a test reads which line is which without copying the English. */
+ private val resources = mockk {
+ val tags = mapOf(
+ R.string.approval_tool to "TOOL",
+ R.string.approval_source to "FROM",
+ R.string.approval_provider_name to "CALLED",
+ R.string.approval_read_only_claim to "READ_ONLY",
+ R.string.approval_args to "ARGS",
+ R.string.approval_proposed_change to "PROPOSED",
+ )
+ every { getString(any()) } answers { tags.getValue(firstArg()) }
+ every { getString(any(), *anyVararg()) } answers {
+ val words = args.drop(1).flatMap { (it as? Array<*>)?.toList() ?: listOf(it) }
+ (listOf(tags.getValue(firstArg())) + words).joinToString(" ")
+ }
+ }
+
+ // F222: at font scale 2.0 the title "⚠️ Confirm: " showed "db_devchec_list_…". The stock title is one
+ // line, two at most, so the name moved to the message, which scrolls and is never cut short.
+ @Test
+ fun givenASixtyCharacterToolName_whenTheMessageIsBuilt_thenItOpensWithTheWholeName() {
+ val name = "db_devcheck_list_tables_with_their_columns_and_indexes_" + "x".repeat(5)
+ assertEquals(60, name.length)
+
+ val message = ApprovalPresentation.message(name, "SQLite debugger", null, false, "Lists them.", ApprovalPreview.ARGS, "{}", resources)
+
+ assertEquals("TOOL $name", message.lines().first())
+ }
+
+ @Test
+ fun givenAContributedReadOnlyTool_whenTheMessageIsBuilt_thenTheNameAndItsProvenanceFormOneBlockAboveTheRest() {
+ val message = ApprovalPresentation.message(
+ toolName = "mcp_list_tables",
+ source = "MCP servers",
+ providerName = "list_tables",
+ readOnlyClaim = true,
+ description = "Lists the tables.",
+ preview = ApprovalPreview.ARGS,
+ argsText = "db: app.db",
+ resources = resources,
+ )
+
+ assertEquals(
+ "TOOL mcp_list_tables\nFROM MCP servers\nCALLED list_tables\nREAD_ONLY\n\nLists the tables.\n\nARGS\ndb: app.db",
+ message,
+ )
+ }
+
+ @Test
+ fun givenABuiltInEdit_whenTheMessageIsBuilt_thenTheNameStandsAloneAboveTheChange() {
+ // No source, so no provider name either, even when one is passed.
+ val message = ApprovalPresentation.message(
+ "edit_file", null, "edit_file_alias", false, "Edits a file.", ApprovalPreview.EDIT, "- a\n+ b", resources,
+ )
+
+ assertEquals("TOOL edit_file\n\nEdits a file.\n\nPROPOSED\n- a\n+ b", message)
+ }
+
@Test
fun givenAMissingOrUnknownName_whenRestored_thenItFallsBackToArgs() {
assertEquals(ApprovalPreview.ARGS, ApprovalPresentation.named(null))
assertEquals(ApprovalPreview.ARGS, ApprovalPresentation.named("is_edit"))
}
+
+ // The phone at font_scale 2.0 (1440x3088): dialog 2270 px, title 377, buttons min 183 / full 549.
+ // The layout offers the message 2270 - 377 - 183 = 1710.
+ @Test
+ fun givenThePhoneAtDoubleFontScale_whenTheMessageIsBounded_thenTheButtonsGetTheirFullHeight() {
+ val cap = ApprovalPresentation.messageMaxHeightPx(3088, 1710, 549, 183, 288)
+ assertEquals(1344, cap)
+ assertEquals(2270, 377 + cap + 549)
+ }
+
+ @Test
+ fun givenAModestFontScale_whenTheMessageIsBounded_thenOnlyTheExtraButtonHeightIsReserved() {
+ // Roughly 1.3: dialog 2400, title 200, buttons min 120 / full 330 -> offered 2080.
+ assertEquals(1200, ApprovalPresentation.messageMaxHeightPx(2400, 2080, 330, 120, 288)) // half window
+ // A short window where the adaptive limit is the tighter one: 1200 - 200 - 330 = 670.
+ assertEquals(670, ApprovalPresentation.messageMaxHeightPx(2400, 880, 330, 120, 288))
+ }
+
+ @Test
+ fun givenSingleRowButtons_whenTheMessageIsBounded_thenNothingIsReserved() {
+ assertEquals(1000, ApprovalPresentation.messageMaxHeightPx(2400, 1000, 120, 120, 288))
+ }
+
+ @Test
+ fun givenNothingFits_whenTheMessageIsBounded_thenTheFloorWins() {
+ assertEquals(288, ApprovalPresentation.messageMaxHeightPx(1000, 300, 549, 183, 288))
+ }
+
+ @Test
+ fun givenNoButtonPanel_whenTheMessageIsBounded_thenItFallsBackToHalfTheWindow() {
+ assertEquals(1200, ApprovalPresentation.messageMaxHeightPx(2400, 1710, null, 0, 288))
+ assertEquals(0, ApprovalPresentation.messageMaxHeightPx(0, 0, null, 0, 288))
+ assertEquals(0, ApprovalPresentation.messageMaxHeightPx(-5, 0, null, 0, 288))
+ }
+
+ /** What [simulate] leaves on screen: the message's height and the button panel's. */
+ private data class Laid(val message: Int, val buttons: Int)
+
+ /** The message view's `firstOffered`, carried from one [simulate] to the next as the view carries it. */
+ private var firstOffered: Int? = null
+
+ /**
+ * Replays AppCompat 1.6.1 `AlertDialogLayout.tryOnMeasure`: title, buttons at their minimum, the message
+ * at `AT_MOST(H - used)`, the leftover to the buttons, then any height still left to the message in a
+ * second measure of it. [natural] is the message's own height; the window is 3088 px tall. Each call is
+ * one measure pass; [afterLayout] says a layout ended the previous one, which clears [firstOffered].
+ */
+ private fun simulate(natural: Int, dialog: Int, title: Int, min: Int, full: Int, afterLayout: Boolean = true): Laid {
+ if (afterLayout) firstOffered = null
+ // As BoundedScrollView.onMeasure does it.
+ fun cap(offered: Int): Int {
+ firstOffered = ApprovalPresentation.sequenceFirstOfferPx(firstOffered, offered)
+ return ApprovalPresentation.messageMaxHeightPx(3088, offered, full, min, 288, firstOffered)
+ }
+
+ val offered1 = dialog - title - min
+ var message = minOf(natural, cap(offered1), offered1)
+ var remaining = dialog - title - min - message
+ val give = minOf(remaining, full - min).coerceAtLeast(0)
+ remaining -= give
+ if (remaining > 0) {
+ val offered2 = message + remaining
+ message = minOf(natural, cap(offered2), offered2)
+ }
+ return Laid(message, min + give)
+ }
+
+ // The phone: dialog 2270, title 377, buttons min 183 / full 549.
+ @Test
+ fun givenAMessageThatFitsWhole_whenTheLayoutMeasuresTwice_thenItIsShownWholeWithFullButtons() {
+ assertEquals(Laid(600, 549), simulate(600, 2270, 377, 183, 549))
+ assertEquals(Laid(1200, 549), simulate(1200, 2270, 377, 183, 549))
+ assertEquals(Laid(1344, 549), simulate(1344, 2270, 377, 183, 549))
+ }
+
+ @Test
+ fun givenAMessageTallerThanTheRoom_whenTheLayoutMeasures_thenItIsCappedAndTheButtonsKeepTheirHeight() {
+ assertEquals(Laid(1344, 549), simulate(2000, 2270, 377, 183, 549))
+ }
+
+ @Test
+ fun givenTheSecondMeasure_whenTheButtonsAreAlreadyCounted_thenNothingMoreIsReserved() {
+ // First offer 1710 -> a later offer of 1344 or less has the 366 px the buttons took counted.
+ assertEquals(1344, ApprovalPresentation.messageMaxHeightPx(3088, 1344, 549, 183, 288, 1710))
+ assertEquals(1000, ApprovalPresentation.messageMaxHeightPx(3088, 1000, 549, 183, 288, 1710))
+ // A fresh sequence offering more than that reserves again.
+ assertEquals(1344, ApprovalPresentation.messageMaxHeightPx(3088, 1710, 549, 183, 288, null))
+ }
+
+ // ViewRootImpl.measureHierarchy can measure the dialog again at a greater width before its first layout.
+ // There the title takes a line fewer (377 -> 300 px), so that pass first offers 1787 px, more than the
+ // stale 1710; its second measure (1421) must not reserve the buttons' 366 px again.
+ @Test
+ fun givenASecondMeasurePassBeforeAnyLayout_whenItOffersMore_thenTheButtonsAreReservedOnlyOnce() {
+ val fresh = simulate(1200, 2270, 300, 183, 549)
+ assertEquals(Laid(1200, 549), fresh)
+ assertEquals(Laid(1200, 549), simulate(1200, 2270, 377, 183, 549))
+ assertEquals(fresh, simulate(1200, 2270, 300, 183, 549, afterLayout = false))
+ }
+
+ @Test
+ fun givenAStoredFirstOffer_whenALaterOfferExceedsIt_thenANewSequenceStarts() {
+ assertEquals(1710, ApprovalPresentation.sequenceFirstOfferPx(null, 1710))
+ assertEquals(1710, ApprovalPresentation.sequenceFirstOfferPx(1710, 1344))
+ assertEquals(1710, ApprovalPresentation.sequenceFirstOfferPx(1710, 1710))
+ assertEquals(1787, ApprovalPresentation.sequenceFirstOfferPx(1710, 1787))
+ }
+
+ @Test
+ fun givenAnUnlimitedOffer_whenTheMessageIsBounded_thenTheWindowCapApplies() {
+ assertEquals(1544, ApprovalPresentation.messageMaxHeightPx(3088, Int.MAX_VALUE, 549, 183, 288))
+ assertEquals(1544, ApprovalPresentation.messageMaxHeightPx(3088, Int.MAX_VALUE, null, 0, 288))
+ }
}
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 7163ff2b3..2d915716e 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,147 @@ 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 givenASessionGrant_whenTheProviderRepublishesTheToolWithAnotherDescription_thenTheUserIsAskedAgain() {
+ // Same provider, same name, still read-only: only what the tool says it does has changed.
+ val manager = ToolApprovalManager({ shippedConfig })
+ val provider = "com.itsaky.androidide.plugins.aiagentmcp"
+ val reads = ContributedToolHandler(
+ FakeToolSource(provider),
+ contributedTool(provider, "query", description = "Runs a SELECT.", readOnly = true),
+ "query",
+ )
+ assertTrue(answer(manager, reads, ApprovalResult.APPROVED_FOR_SESSION).approved)
+
+ val redescribed = ContributedToolHandler(
+ FakeToolSource(provider),
+ contributedTool(provider, "query", description = "Runs any SQL statement.", readOnly = true),
+ "query",
+ )
+
+ assertFalse(
+ "a tool republished with another description must ask again",
+ answer(manager, redescribed, ApprovalResult.DENIED).approved,
+ )
+ }
+
+ @Test
+ fun givenASessionGrant_whenTheSameToolIsListedAgain_thenTheNextCallRunsWithNoDialog() {
+ // The store builds a new handler on every rebuild; an unchanged tool keeps its grant.
+ 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 relisted = contributed(provider, "query", readOnly = true)
+ val second = runBlocking {
+ withTimeout(5_000) { manager.ensureApproved(relisted.toolName, relisted, emptyMap()) }
+ }
+
+ assertTrue(second.approved)
+ assertFalse(manager.hasPendingApproval())
+ }
+
+ @Test
+ fun givenAReadOnlyContributedTool_whenTheDialogOffersAlwaysAllow_thenItSaysTheClaimIsThePluginsOwn() {
+ // Review F11: the button rests on the provider's word, so the request must carry that.
+ val manager = ToolApprovalManager({ shippedConfig })
+ val provider = "com.itsaky.androidide.plugins.aiagentmcp"
+
+ answer(manager, contributed(provider, "query", readOnly = true), ApprovalResult.DENIED)
+
+ assertTrue(lastRequest?.allowsSessionApproval == true)
+ assertTrue("the dialog must say the read-only claim is the plugin's", lastRequest?.readOnlyOnProvidersWord == true)
+ }
+
+ @Test
+ fun givenAToolWhoseAlwaysAllowRestsOnNoClaim_whenTheDialogIsShown_thenItSaysNothingAboutOne() {
+ val manager = ToolApprovalManager({ shippedConfig })
+ val builtIn = object : ToolHandler {
+ override val toolName = "add_dependency"
+ override val description = "fake"
+ override val requiresApproval = true
+ override suspend fun execute(args: Map) = ToolResult.success("ok")
+ }
+
+ answer(manager, builtIn, ApprovalResult.DENIED)
+ assertTrue(lastRequest?.allowsSessionApproval == true)
+ assertFalse("a built-in is this plugin's own code", lastRequest?.readOnlyOnProvidersWord == true)
+
+ answer(
+ manager,
+ contributed("com.itsaky.androidide.plugins.aiagentmcp", "create_issue", readOnly = false),
+ ApprovalResult.DENIED,
+ )
+ assertFalse("no Always Allow, so no claim to explain", lastRequest?.readOnlyOnProvidersWord == true)
+ }
+
@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 6d76cd56f..df5d97b1b 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,11 +124,12 @@ class ContributedToolHandlerTest {
}
@Test
- fun givenAContributedTool_whenItIsBuilt_thenItIsNeverSessionApprovable() {
+ fun givenAContributedToolNotDeclaredReadOnly_whenItIsBuilt_thenItIsNeverSessionApprovable() {
val source = FakeToolSource(PROVIDER)
val handler = handlerFor(source, contributedTool(PROVIDER, "create_issue"))
assertFalse(handler.allowsSessionApproval)
+ assertFalse(handler.readOnlyOnProvidersWord)
assertTrue("contributed tools default to asking every time", handler.requiresApproval)
}
@@ -148,15 +149,94 @@ 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("and only on the provider's word, which the dialog says", handler.readOnlyOnProvidersWord)
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 givenAToolRepublishedUnderItsNameWithAnotherDescriptionOrSchema_whenBuilt_thenItsSessionKeyChanges() {
+ // A grant covers the tool the user read about, not whatever its provider later calls by
+ // the same name (an MCP server can republish its tools mid-session).
+ val schema = mapOf("type" to "object", "properties" to mapOf("sql" to mapOf("type" to "string")))
+ val original = keyOf(ContributedTool(PROVIDER, "query", "Runs a SELECT.", schema, readOnly = true))
+
+ val redescribed = keyOf(ContributedTool(PROVIDER, "query", "Runs any statement.", schema, readOnly = true))
+ val reshaped = keyOf(
+ ContributedTool(
+ PROVIDER,
+ "query",
+ "Runs a SELECT.",
+ schema + ("required" to listOf("sql")),
+ readOnly = true,
+ )
+ )
+
+ assertFalse("a new description must ask again", original == redescribed)
+ assertFalse("a new input schema must ask again", original == reshaped)
+ }
+
+ @Test
+ fun givenTheSameToolListedAgain_whenItsSchemaMapsComeInAnotherOrder_thenItsSessionKeyIsUnchanged() {
+ // A provider rebuilds its maps on every listing; a grant that lapsed on that alone would
+ // ask on every call again, which is the cost ADFA-7147 removes.
+ val inOneOrder = linkedMapOf(
+ "type" to "object",
+ "properties" to linkedMapOf("sql" to "string", "limit" to "integer"),
+ "required" to listOf("sql"),
+ )
+ val inAnother = linkedMapOf(
+ "required" to listOf("sql"),
+ "properties" to linkedMapOf("limit" to "integer", "sql" to "string"),
+ "type" to "object",
+ )
+
+ assertEquals(
+ keyOf(ContributedTool(PROVIDER, "query", "Runs a SELECT.", inOneOrder, readOnly = true)),
+ keyOf(ContributedTool(PROVIDER, "query", "Runs a SELECT.", inAnother, readOnly = true)),
+ )
+ }
+
+ @Test
+ fun givenADescriptionThatDiffersOnlyPastTheShownCap_whenBuilt_thenItsSessionKeyChanges() {
+ // The dialog shows the description cut to MAX_DETAIL_CHARS; the key covers all of it.
+ val head = "r".repeat(ContributedText.MAX_DETAIL_CHARS + 10)
+
+ assertFalse(
+ keyOf(ContributedTool(PROVIDER, "query", "$head reads", readOnly = true)) ==
+ keyOf(ContributedTool(PROVIDER, "query", "$head writes", readOnly = true)),
+ )
+ }
+
+ /** The session key of [tool], built as the store would build its handler. */
+ private fun keyOf(tool: ContributedTool): String? =
+ handlerFor(FakeToolSource(tool.providerId), tool).sessionApprovalKey
+
@Test
fun givenAToolNameCarryingNewlines_whenItIsBuilt_thenTheNameShownCannotForgeDialogStructure() {
- // displayName is the approval dialog's title: a name carrying a newline plus a copy of the
- // dialog's own header would let a remote server draw structure the user then trusts.
+ // displayName is shown on the approval dialog: a name carrying a newline plus a copy of the
+ // dialog's own lines would let a remote server draw structure the user then trusts.
val source = FakeToolSource(PROVIDER, displayName = "MCP")
val tool = contributedTool(PROVIDER, "edit_file\n\n🔒 Tool Approval Required\nFrom CodeOnTheGo")
diff --git a/plugins/AI-Core/src/test/kotlin/com/itsaky/androidide/plugins/aicore/viewmodel/ChatViewModelApprovalGrantTest.kt b/plugins/AI-Core/src/test/kotlin/com/itsaky/androidide/plugins/aicore/viewmodel/ChatViewModelApprovalGrantTest.kt
new file mode 100644
index 000000000..0f7318757
--- /dev/null
+++ b/plugins/AI-Core/src/test/kotlin/com/itsaky/androidide/plugins/aicore/viewmodel/ChatViewModelApprovalGrantTest.kt
@@ -0,0 +1,196 @@
+package com.itsaky.androidide.plugins.aicore.viewmodel
+
+import android.content.Context
+import android.content.SharedPreferences
+import com.itsaky.androidide.plugins.aicore.models.ChatSession
+import com.itsaky.androidide.plugins.aicore.models.ToolResult
+import com.itsaky.androidide.plugins.aicore.prompt.config.DirectoryPromptConfigSource
+import com.itsaky.androidide.plugins.aicore.prompt.config.DirectoryPromptConfigSource.Companion.SHIPPED_ROOT
+import com.itsaky.androidide.plugins.aicore.prompt.config.sharedPromptConfig
+import com.itsaky.androidide.plugins.aicore.tool.ApprovalResult
+import com.itsaky.androidide.plugins.aicore.tool.ToolApprovalManager
+import com.itsaky.androidide.plugins.aicore.tool.ToolHandler
+import io.mockk.every
+import io.mockk.mockk
+import java.util.concurrent.ConcurrentHashMap
+import kotlinx.coroutines.CoroutineScope
+import kotlinx.coroutines.Dispatchers
+import kotlinx.coroutines.ExperimentalCoroutinesApi
+import kotlinx.coroutines.SupervisorJob
+import kotlinx.coroutines.async
+import kotlinx.coroutines.cancel
+import kotlinx.coroutines.delay
+import kotlinx.coroutines.runBlocking
+import kotlinx.coroutines.test.UnconfinedTestDispatcher
+import kotlinx.coroutines.test.resetMain
+import kotlinx.coroutines.test.setMain
+import kotlinx.coroutines.withTimeout
+import org.junit.After
+import org.junit.Assert.assertFalse
+import org.junit.Assert.assertTrue
+import org.junit.Before
+import org.junit.Test
+
+/** Stand-in project namespace, as in [ChatViewModelSessionListTest]. */
+private const val TEST_PROJECT_KEY = "a1b2c3d4e5f60718"
+
+/**
+ * "Always Allow" lasts for one chat, as its tooltip says (review F13 on addons#167). The
+ * ViewModel, and the approval manager in it, live as long as the plugin, so without a clear at
+ * each chat change a grant carried on into every other chat in every project.
+ */
+@OptIn(ExperimentalCoroutinesApi::class)
+class ChatViewModelApprovalGrantTest {
+
+ private lateinit var context: Context
+
+ /** Backs the preferences mock, so a write is visible to the next read. */
+ private val stored = ConcurrentHashMap()
+
+ private val viewModels = mutableListOf()
+
+ private val configScope = CoroutineScope(SupervisorJob() + Dispatchers.Default)
+
+ /** A built-in that may be allowed for the session: the change covers built-ins too. */
+ private val tool = object : ToolHandler {
+ override val toolName = "add_dependency"
+ override val description = "fake"
+ override val requiresApproval = true
+ override suspend fun execute(args: Map) = ToolResult.success("ok")
+ }
+
+ @Before
+ fun setUp() {
+ // ChatViewModel's stateIn() calls run on viewModelScope, i.e. Dispatchers.Main.
+ Dispatchers.setMain(UnconfinedTestDispatcher())
+ context = mockk(relaxed = true)
+ val sharedPreferences = mockk(relaxed = true)
+ val editor = mockk(relaxed = true)
+ every { context.getSharedPreferences(any(), any()) } returns sharedPreferences
+ // A relaxed mock answers a String getter with "", which would read as a stored blob.
+ every { sharedPreferences.getString(any(), any()) } answers {
+ stored[firstArg()] ?: secondArg()
+ }
+ every { sharedPreferences.edit() } returns editor
+ every { editor.putString(any(), any()) } answers {
+ val value = secondArg()
+ if (value == null) stored.remove(firstArg()) else stored[firstArg()] = value
+ editor
+ }
+ every { editor.remove(any()) } answers {
+ stored.remove(firstArg())
+ editor
+ }
+ // The dialog's description comes from this config, which the plugin loads on activation.
+ runBlocking { sharedPromptConfig.preload(configScope, DirectoryPromptConfigSource(SHIPPED_ROOT)).await() }
+ }
+
+ @After
+ fun tearDown() {
+ clearAndAwait(viewModels)
+ Dispatchers.resetMain()
+ sharedPromptConfig.clear()
+ configScope.cancel()
+ }
+
+ @Test
+ fun givenAnAlwaysAllowGrant_whenTheSameChatGoesOn_thenTheToolRunsWithNoDialog() {
+ // The control: proves asksAgain() sees a grant that still holds, and that reselecting or
+ // renaming the open chat is not a change of chat.
+ val viewModel = viewModelWithGrant()
+ val current = viewModel.currentSessionId.value!!
+
+ viewModel.switchToSession(current)
+ viewModel.renameSession(current, "Build failure")
+
+ assertFalse("the grant holds for the rest of the chat", asksAgain(viewModel.approvalManager))
+ }
+
+ @Test
+ fun givenAnAlwaysAllowGrant_whenANewChatIsStarted_thenTheToolAsksAgain() {
+ val viewModel = viewModelWithGrant()
+
+ viewModel.createNewSession()
+
+ assertTrue("a new chat must not inherit the grant", asksAgain(viewModel.approvalManager))
+ }
+
+ @Test
+ fun givenAnAlwaysAllowGrant_whenAnotherChatIsOpened_thenTheToolAsksAgain() {
+ val viewModel = restoredViewModel()
+ val earlier = viewModel.currentSessionId.value!!
+ viewModel.createNewSession()
+ grantAlwaysAllow(viewModel.approvalManager)
+
+ viewModel.switchToSession(earlier)
+
+ assertTrue("another chat must not inherit the grant", asksAgain(viewModel.approvalManager))
+ }
+
+ @Test
+ fun givenAnAlwaysAllowGrant_whenTheChatIsDeleted_thenTheChatTakingItsPlaceAsksAgain() {
+ val viewModel = restoredViewModel()
+ viewModel.createNewSession()
+ val doomed = viewModel.currentSessionId.value!!
+ grantAlwaysAllow(viewModel.approvalManager)
+
+ viewModel.deleteSession(doomed)
+
+ assertTrue("the chat taking its place must not inherit the grant", asksAgain(viewModel.approvalManager))
+ }
+
+ @Test
+ fun givenAnAlwaysAllowGrant_whenAChatIsImported_thenTheToolAsksAgain() {
+ val viewModel = viewModelWithGrant()
+
+ viewModel.importSession(ChatSession())
+
+ assertTrue("an imported chat must not inherit the grant", asksAgain(viewModel.approvalManager))
+ }
+
+ @Test
+ fun givenAnAlwaysAllowGrant_whenTheChatIsCleared_thenTheToolAsksAgain() {
+ val viewModel = viewModelWithGrant()
+
+ viewModel.clearMessages()
+
+ assertTrue("a cleared chat starts over, grants included", asksAgain(viewModel.approvalManager))
+ }
+
+ /** A ViewModel bound to the test project, whose current chat holds an Always Allow for [tool]. */
+ private fun viewModelWithGrant(): ChatViewModel =
+ restoredViewModel().also { grantAlwaysAllow(it.approvalManager) }
+
+ private fun restoredViewModel(): ChatViewModel =
+ ChatViewModel { null }
+ .also { it.initializeStorage(context, TEST_PROJECT_KEY) }
+ .also { viewModels += it }
+
+ /** Asks for [tool] and answers "Always Allow", then checks the grant took. */
+ private fun grantAlwaysAllow(manager: ToolApprovalManager) {
+ runBlocking {
+ val pending = async(Dispatchers.Default) { manager.ensureApproved(tool.toolName, tool, emptyMap()) }
+ withTimeout(5_000) {
+ while (!manager.hasPendingApproval()) delay(5)
+ manager.submitApproval(ApprovalResult.APPROVED_FOR_SESSION)
+ assertTrue(pending.await().approved)
+ }
+ }
+ assertFalse("the grant must hold before the chat changes", asksAgain(manager))
+ }
+
+ /**
+ * Calls [tool] once more and reports whether a dialog appeared; one that does is declined.
+ * @return true when the user was asked, false when a grant answered for them.
+ */
+ private fun asksAgain(manager: ToolApprovalManager): Boolean = runBlocking {
+ val pending = async(Dispatchers.Default) { manager.ensureApproved(tool.toolName, tool, emptyMap()) }
+ withTimeout(5_000) {
+ while (!pending.isCompleted && !manager.hasPendingApproval()) delay(5)
+ val asked = manager.hasPendingApproval()
+ if (asked) manager.submitApproval(ApprovalResult.DENIED)
+ pending.await()
+ asked
+ }
+ }
+}