feat(plugins): add AI tools and consent-gated data access

This commit is contained in:
t8y2 committed 2026-09-25 01:56:26 +08:00
1 parent 1bc6f70cd8
commit 26a015cd86
71 files changed
+4613 -129

No files matched your search

@@ -5,9 +5,8 @@ import { Check, ChevronDown, ChevronRight, Folder, Search } from "@lucide/vue";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Popover, PopoverContent, PopoverTrigger } from "@/components/ui/popover";
import DatabaseIcon from "@/components/icons/DatabaseIcon.vue";
import ConnectionIcon from "@/components/icons/ConnectionIcon.vue";
import { buildConnectionPickerRows, connectionPickerSelectableRows } from "@/lib/connection/connectionPickerTree";
import { connectionIconType } from "@/lib/connection/connectionPresentation";
import { cn } from "@/lib/common/utils";
import type { ConnectionConfig, SidebarLayout } from "@/types/database";
@@ -184,7 +183,7 @@ function handleKeydown(event: KeyboardEvent) {
@click="selectConnection(row.id)"
>
<Check :class="cn('h-3.5 w-3.5 shrink-0', row.id === modelValue ? 'opacity-100' : 'opacity-0')" />
<DatabaseIcon :db-type="connectionIconType(connectionById.get(row.id))" class="h-3.5 w-3.5 shrink-0" />
<ConnectionIcon :connection="connectionById.get(row.id)" class="h-3.5 w-3.5 shrink-0" />
<span class="min-w-0 flex-1 truncate">{{ row.label }}</span>
</button>
</template>
@@ -26,6 +26,13 @@ vi.mock("@/components/icons/DatabaseIcon.vue", () => ({
}),
}));
vi.mock("@/components/plugins/PluginIcon.vue", () => ({
default: defineComponent({
props: ["pluginId", "contributionId"],
setup: (props) => () => h("span", { "data-plugin-id": props.pluginId, "data-contribution-id": props.contributionId }),
}),
}));
const mountedApps: App[] = [];
const connections: ConnectionConfig[] = [
@@ -45,12 +52,12 @@ const layout: SidebarLayout = {
order: [{ type: "group", id: "g1", children: [{ type: "connection", id: "c1" }] }],
};
async function mountPicker() {
async function mountPicker(extraConnections: ConnectionConfig[] = []) {
const container = document.createElement("div");
document.body.append(container);
const app = createApp(ConnectionTreeSelect, {
modelValue: "",
connections,
connections: [...connections, ...extraConnections],
layout,
placeholder: "Select connection",
searchPlaceholder: "Search connections",
@@ -82,6 +89,13 @@ afterEach(() => {
});
describe("ConnectionTreeSelect search collapse behavior", () => {
it("passes plugin identity and provider logo metadata to the shared icon", async () => {
await mountPicker([{ ...connections[0], id: "plugin", name: "Plugin", db_type: "plugin", plugin_id: "sample.plugin", plugin_connection_provider: "sample.connection" }]);
const icon = document.body.querySelector('[data-picker-connection="plugin"] [data-plugin-id]');
expect(icon?.getAttribute("data-plugin-id")).toBe("sample.plugin");
expect(icon?.getAttribute("data-contribution-id")).toBe("sample.connection");
});
it("ignores group clicks during search without changing the post-search state", async () => {
await mountPicker();
await setSearchText("Primary");
@@ -66,8 +66,8 @@ import { usePromptTemplateStore } from "@/stores/promptTemplateStore";
import { useUserSkillStore } from "@/stores/userSkillStore";
import { buildSelectedSkillChips, capSkillsToCharLimit, removeSkillIds, userSkillSourceOfId } from "@/lib/ai/userSkillSelection";
import { ACTIVE_SKILLS_TOTAL_MAX, type ReadUserSkill, type ReadUserSkillFailure, type UserSkillFailureReason, type UserSkillRootSettings } from "@/types/userSkills";
import { connectionIconType } from "@/lib/connection/connectionPresentation";
import DatabaseIcon from "@/components/icons/DatabaseIcon.vue";
import { supportsAiAssistantContext } from "@/lib/database/databaseFeatureSupport";
import ConnectionIcon from "@/components/icons/ConnectionIcon.vue";
import ConnectionTreeSelect from "@/components/connection/ConnectionTreeSelect.vue";
import SearchableSelect from "@/components/ui/searchable-select/SearchableSelect.vue";
import { useQueryStore } from "@/stores/queryStore";
@@ -154,11 +154,11 @@ import { buildAiAgentPlan } from "@/lib/ai/aiAgentPlan";
import { extractFirstSqlCodeBlock, extractSingleSqlCodeBlock } from "@/lib/ai/aiSqlExecutionPolicy";
import { productionContextForDatabase } from "@/lib/database/productionSafety";
import ProductionContextBadge from "@/components/common/ProductionContextBadge.vue";
import { buildAiAgentStepItems, formatToolDurationMs, toolCallStepKey, upsertAgentStep, type AiAgentStepItem, type AiAgentStepTone } from "@/lib/ai/aiAgentStepPresentation";
import { buildAiAgentStepItems, formatAgentToolName, formatToolDurationMs, toolCallStepKey, updateAgentStepApproval, upsertAgentStep, type AiAgentStepItem, type AiAgentStepTone } from "@/lib/ai/aiAgentStepPresentation";
import { createAiShikiCodeHighlighter, type AiCodeHighlighter } from "@/lib/ai/aiCodeHighlighter";
import { createAiMessageRenderer } from "@/lib/ai/aiMessageRender";
import { formatAiInlineMarkdown, handleAiMarkdownLinkClick } from "@/lib/ai/aiMarkdown";
import { aiStream, aiCancelStream, saveAiConversation, saveAiRun, saveAiRunState, loadAiConversations, loadAiRuns, deleteAiConversation, listSchemas, listTables, readUserSkills, type AiConversation, type AiRun, type AiRunStatus } from "@/lib/backend/api";
import { aiStream, aiCancelStream, resolveAiToolApproval, saveAiConversation, saveAiRun, saveAiRunState, loadAiConversations, loadAiRuns, deleteAiConversation, listSchemas, listTables, readUserSkills, type AiConversation, type AiRun, type AiRunStatus } from "@/lib/backend/api";
import type { AiMessage } from "@/lib/backend/api";
import type { AiConfigItem, AiEffortCapability, AiEffortOption, AiEffortSelection } from "@/types/ai";
import type { ConnectionConfig, QueryTab, SavedSqlFile, TableInfo } from "@/types/database";
@@ -184,6 +184,7 @@ import { buildAiAnalysisExport } from "@/lib/export/aiAnalysisExport";
import { buildAiConversationExport, type AiConversationExportFormat } from "@/lib/export/aiConversationExport";
import { buildAiConversationSearchIndex, filterAiConversationSearchIndex } from "@/lib/ai/aiConversationSearch";
import AiAttachmentCard from "@/components/editor/AiAttachmentCard.vue";
import AiToolApprovalCard from "@/components/editor/AiToolApprovalCard.vue";
import { resolveAiMessageCopyText } from "@/lib/ai/aiMessageCopy";
import { buildPluginAiRequest, pluginContextFromMessages, pluginContextText, streamPluginAiConversation, type AiPluginContext, type AiPluginConversationRequest } from "@/lib/ai/aiPluginConversation";
@@ -1780,9 +1781,11 @@ watch(
);
watch([dbSelectOptions, selectedNamespace], syncSelectedDatabases, { immediate: true });
const showAiDatabaseSelector = computed(() => !!boundConnection.value && supportsAiAssistantContext(boundConnection.value.db_type));
const showAiSchemaSelector = computed(() => {
const connection = boundConnection.value;
return !!connection && connection.db_type !== "dameng" && aiSchemaSelectionSupported(connection);
return showAiDatabaseSelector.value && !!connection && connection.db_type !== "dameng" && aiSchemaSelectionSupported(connection);
});
const aiSchemaDatabaseKey = computed(() => {
@@ -1804,7 +1807,7 @@ async function loadAiSchemas() {
}
async function loadDatabases(connection = boundConnection.value): Promise<string[]> {
if (!connection) return [];
if (!connection || !supportsAiAssistantContext(connection.db_type)) return [];
if (connection.db_type !== "dameng") {
await loadDatabaseOptions(connection.id);
return databaseOptions.value[connection.id] || [];
@@ -2103,6 +2106,21 @@ function parseExplainFromData(explainData: unknown, dbType: string): ParsedExpla
}
}
/** Sends the user's answer for a pending plugin tool approval back to the run that asked. */
async function resolveToolApproval(step: AiAgentStepItem, approved: boolean) {
const approval = step.approval;
if (!approval || approval.status !== "pending") return;
approval.status = "submitting";
try {
// The final status arrives with `tool_approval_resolved`; `false` means
// the run stopped waiting (timed out, cancelled, or app restarted).
if (!(await resolveAiToolApproval(approval.sessionId, approval.approvalId, approved))) approval.status = "expired";
} catch (error) {
approval.status = "pending";
toast(t("ai.toolApproval.answerFailed", { message: error instanceof Error ? error.message : String(error) }), 5000);
}
}
function agentEventToStep(event: AgentEvent, index: number, now: number): AiAgentStepItem | undefined {
if (event.type === "context_compacted") {
return {
@@ -2343,7 +2361,7 @@ function mentionTargetDatabase(): string {
async function loadMentionCandidates(query: string) {
const connection = boundConnection.value;
const mentionDatabase = mentionTargetDatabase();
if (pluginContext.value || !connection || !boundConnectionId.value || !mentionDatabase) return;
if (pluginContext.value || !connection || !supportsAiAssistantContext(connection.db_type) || !boundConnectionId.value || !mentionDatabase) return;
const key = mentionCacheKey(boundConnectionId.value, mentionDatabase, query);
if (mentionCache.value[key]) {
@@ -3693,6 +3711,28 @@ async function send() {
if (step) upsertAgentStep(msg.agentSteps, step);
}
}
// A plugin tool call waits for (or got) the user's approval: keep the
// state on the tool card so the answer buttons live next to the call.
if (event.type === "tool_approval_required" || event.type === "tool_approval_resolved") {
const msg = runMessages[assistantIdx];
if (msg?.agentSteps) {
const key = toolCallStepKey(event.tool_call_id, agentEvents.length - 1, "tool_call_start");
if (event.type === "tool_approval_required") {
updateAgentStepApproval(msg.agentSteps, key, () => ({
approvalId: event.approval_id,
sessionId,
pluginName: event.plugin_name,
pluginTool: event.plugin_tool,
connectionName: event.connection_name,
args: event.args ?? {},
expiresAtMs: Date.now() + event.timeout_secs * 1000,
status: "pending",
}));
} else {
updateAgentStepApproval(msg.agentSteps, key, (approval) => (approval && approval.approvalId === event.approval_id ? { ...approval, status: event.outcome } : approval));
}
}
}
if (runIsVisible()) scrollToBottom();
};
if (runPluginContext) {
@@ -5530,16 +5570,17 @@ async function openExternalUrl(url: string) {
<Loader2 v-if="step.tone === 'active' && step.toolName" class="h-3 w-3 shrink-0 animate-spin" />
<component :is="agentStepIcon(step.tone)" v-else class="h-3 w-3 shrink-0" />
<span class="font-medium">{{ t(step.labelKey) }}</span>
<span v-if="step.toolName" class="text-muted-foreground">: {{ step.toolName }}</span>
<span v-if="step.toolName" class="text-muted-foreground">: {{ formatAgentToolName(step.toolName) }}</span>
<template v-if="step.tone === 'active' && step.toolName">
<span class="ml-auto flex shrink-0 items-center gap-1">
<Loader2 class="h-3 w-3 animate-spin" />
<span>{{ t("ai.agentSteps.executing") }}</span>
<span>{{ step.approval?.status === "pending" || step.approval?.status === "submitting" ? t("ai.toolApproval.waiting") : t("ai.agentSteps.executing") }}</span>
</span>
</template>
<span v-else-if="step.durationMs !== undefined" class="ml-auto shrink-0 tabular-nums" :class="step.tone === 'danger' ? 'text-red-600 dark:text-red-400' : 'text-chart-2'">{{ formatToolDurationMs(step.durationMs) }}</span>
<ChevronRight v-if="step.toolResult || step.toolArgs?.sql" class="h-3 w-3 shrink-0 transition-transform duration-150" :class="[{ 'rotate-90': expandedSteps.has(step.key) }, !agentStepHasTail(step) ? 'ml-auto' : '']" />
</button>
<AiToolApprovalCard v-if="step.approval" :approval="step.approval" @resolve="resolveToolApproval(step, $event)" />
<div v-if="expandedSteps.has(step.key)" class="border-t border-current/10 px-2 pb-2 pt-1">
<div v-if="step.toolArgs?.sql" class="mb-1 rounded bg-background/50 px-2 py-1 font-mono text-[10px] text-foreground/80 whitespace-pre-wrap">{{ step.toolArgs.sql }}</div>
<Button v-if="step.toolName === 'explain_query' && step.toolArgs?.sql" size="sm" variant="outline" class="mb-1 h-6 gap-1 text-[10px]" @click="emit('openExplainPlan', step.toolArgs.sql as string, conversationBinding)">
@@ -5725,7 +5766,7 @@ async function openExternalUrl(url: string) {
<pre class="max-h-56 overflow-auto whitespace-pre-wrap break-all p-2 text-[11px]">{{ pluginContextText(pluginContext) }}</pre>
</details>
<template v-else-if="connectionStore.connections.length">
<DatabaseIcon v-if="boundConnection" :db-type="connectionIconType(boundConnection)" class="h-3 w-3 shrink-0" />
<ConnectionIcon v-if="boundConnection" :connection="boundConnection" class="h-3 w-3 shrink-0" />
<Server v-else class="h-3 w-3 shrink-0" />
<ConnectionTreeSelect
:model-value="boundConnectionId"
@@ -5739,7 +5780,7 @@ async function openExternalUrl(url: string) {
list-class="w-72 max-w-[calc(100vw-2rem)]"
@update:model-value="(v) => changeConnection(v)"
/>
<template v-if="boundConnection">
<template v-if="boundConnection && showAiDatabaseSelector">
<Database class="h-3 w-3 shrink-0 text-foreground/40" />
<Popover
@update:open="
@@ -0,0 +1,57 @@
<script setup lang="ts">
import { computed, ref, watch } from "vue";
import { useI18n } from "vue-i18n";
import { Check, Loader2, ShieldAlert, X } from "@lucide/vue";
import { Button } from "@/components/ui/button";
import type { AiAgentStepApproval } from "@/lib/ai/aiAgentStepPresentation";
/** Inline approval for a plugin tool call that may change state. */
const props = defineProps<{ approval: AiAgentStepApproval }>();
const emit = defineEmits<{ resolve: [approved: boolean] }>();
const { t } = useI18n();
const expired = ref(false);
watch(
() => [props.approval.status, props.approval.expiresAtMs] as const,
([status, expiresAtMs], _previous, onCleanup) => {
expired.value = expiresAtMs <= Date.now();
if (expired.value || (status !== "pending" && status !== "submitting")) return;
const timeout = setTimeout(() => {
expired.value = true;
}, expiresAtMs - Date.now());
onCleanup(() => clearTimeout(timeout));
},
{ immediate: true },
);
const argumentsText = computed(() => JSON.stringify(props.approval.args ?? {}, null, 2));
// A pending card restored from history after its deadline (or an app restart)
// has nobody waiting for the answer anymore.
const waiting = computed(() => (props.approval.status === "pending" || props.approval.status === "submitting") && !expired.value);
const displayStatus = computed(() => (props.approval.status === "pending" || props.approval.status === "submitting" ? "expired" : props.approval.status));
const expiresAt = computed(() => new Date(props.approval.expiresAtMs).toLocaleTimeString());
</script>
<template>
<div class="space-y-1.5 border-t border-current/10 px-2 pb-2 pt-1.5 text-[10px]" data-ai-tool-approval>
<div class="flex items-start gap-1.5 text-foreground">
<ShieldAlert class="mt-px h-3 w-3 shrink-0 text-amber-600 dark:text-amber-400" />
<span class="min-w-0 wrap-anywhere">{{ t("ai.toolApproval.prompt", { plugin: approval.pluginName, tool: approval.pluginTool, connection: approval.connectionName }) }}</span>
</div>
<pre class="max-h-40 overflow-auto rounded bg-background/60 px-2 py-1 font-mono text-[10px] text-foreground/80 whitespace-pre-wrap wrap-anywhere">{{ argumentsText }}</pre>
<div v-if="waiting" class="flex flex-wrap items-center gap-1.5">
<Button size="sm" class="h-6 gap-1 px-2 text-[10px]" :disabled="approval.status === 'submitting'" @click="emit('resolve', true)">
<Loader2 v-if="approval.status === 'submitting'" class="h-3 w-3 animate-spin" />
<Check v-else class="h-3 w-3" />
{{ t("ai.toolApproval.approve") }}
</Button>
<Button size="sm" variant="outline" class="h-6 gap-1 px-2 text-[10px]" :disabled="approval.status === 'submitting'" @click="emit('resolve', false)">
<X class="h-3 w-3" />
{{ t("ai.toolApproval.deny") }}
</Button>
<span class="text-muted-foreground">{{ t("ai.toolApproval.expiresAt", { time: expiresAt }) }}</span>
</div>
<div v-else class="text-muted-foreground">{{ t(`ai.toolApproval.status.${displayStatus}`) }}</div>
</div>
</template>
@@ -12,6 +12,8 @@ import i18n from "@/i18n";
import { TooltipProvider } from "@/components/ui/tooltip";
import AiAssistant from "@/components/editor/AiAssistant.vue";
import { useSettingsStore } from "@/stores/settingsStore";
import { useConnectionStore } from "@/stores/connectionStore";
import type { ConnectionConfig } from "@/types/database";
vi.mock("@/lib/backend/api", async (importOriginal) => {
const actual = await importOriginal<Record<string, unknown>>();
@@ -22,6 +24,7 @@ vi.mock("@/lib/backend/api", async (importOriginal) => {
loadAiRuns: empty,
readUserSkills: empty,
loadAiConfigs: empty,
listPlugins: empty,
loadPromptTemplates: empty,
getAiGlobalCustomInstructions: () => Promise.resolve(""),
saveAiChatSelection: () => Promise.resolve(),
@@ -35,15 +38,16 @@ afterEach(() => {
while (cleanups.length) cleanups.pop()?.();
});
async function mountPanel(aiConfigLoaded: boolean): Promise<unknown[]> {
async function mountPanel(aiConfigLoaded: boolean, connection?: ConnectionConfig) {
const pinia = createPinia();
const errors: unknown[] = [];
const app = createApp({ render: () => h(TooltipProvider, () => h(AiAssistant)) });
const app = createApp({ render: () => h(TooltipProvider, () => h(AiAssistant, { connection })) });
app.use(pinia);
app.use(i18n);
app.config.errorHandler = (error) => errors.push(error);
app.config.warnHandler = () => {};
useSettingsStore(pinia).isAiConfigLoaded = aiConfigLoaded;
if (connection) useConnectionStore(pinia).connections = [connection];
const container = document.createElement("div");
document.body.append(container);
app.mount(container);
@@ -53,15 +57,32 @@ async function mountPanel(aiConfigLoaded: boolean): Promise<unknown[]> {
});
// Let mount-time loads settle so their failures surface here too.
await new Promise((resolve) => setTimeout(resolve, 20));
return errors;
return { errors, container };
}
describe("AiAssistant mount", () => {
it("opens when the AI config was loaded before the panel mounted", async () => {
expect((await mountPanel(true)).map(String)).toEqual([]);
expect((await mountPanel(true)).errors.map(String)).toEqual([]);
});
it("opens while the AI config is still loading", async () => {
expect((await mountPanel(false)).map(String)).toEqual([]);
expect((await mountPanel(false)).errors.map(String)).toEqual([]);
});
it.each(["plugin", "etcd"] as const)("hides database and schema selectors for %s connections", async (dbType) => {
const { errors, container } = await mountPanel(true, { id: "connection", name: "Connection", db_type: dbType, plugin_id: dbType === "plugin" ? "sample.plugin" : undefined, host: "localhost", port: 22, username: "", password: "" });
expect(errors.map(String)).toEqual([]);
const row = container.querySelector("[data-ai-composer-context-row]");
expect(row?.textContent).toContain("Connection");
expect(row?.textContent).not.toContain(i18n.global.t("editor.selectDatabase"));
expect(row?.classList.contains("ai-prompt-context-row--schema")).toBe(false);
});
it("keeps database and schema selectors for PostgreSQL", async () => {
const { errors, container } = await mountPanel(true, { id: "postgres", name: "PostgreSQL", db_type: "postgres", host: "localhost", port: 5432, username: "", password: "" });
expect(errors.map(String)).toEqual([]);
const row = container.querySelector("[data-ai-composer-context-row]");
expect(row?.textContent).toContain(i18n.global.t("editor.selectDatabase"));
expect(row?.classList.contains("ai-prompt-context-row--schema")).toBe(true);
});
});
@@ -0,0 +1,55 @@
// @vitest-environment happy-dom
import { createApp, nextTick, reactive } from "vue";
import { afterEach, describe, expect, it, vi } from "vitest";
import i18n from "@/i18n";
import AiToolApprovalCard from "../AiToolApprovalCard.vue";
import type { AiAgentStepApproval } from "@/lib/ai/aiAgentStepPresentation";
const cleanups: Array<() => void> = [];
function mountCard() {
const approval = reactive<AiAgentStepApproval>({ approvalId: "approval", sessionId: "session", pluginName: "Plugin", pluginTool: "write", connectionName: "Connection", args: { target: "orders" }, expiresAtMs: Date.now() + 1000, status: "pending" });
const onResolve = vi.fn();
const container = document.createElement("div");
document.body.append(container);
const app = createApp(AiToolApprovalCard, { approval, onResolve });
app.use(i18n);
app.mount(container);
cleanups.push(() => {
app.unmount();
container.remove();
});
return { approval, onResolve, container };
}
afterEach(() => {
while (cleanups.length) cleanups.pop()?.();
vi.useRealTimers();
});
describe("AiToolApprovalCard", () => {
it("expires without another backend event and removes its answer buttons", async () => {
vi.useFakeTimers();
const { container, onResolve } = mountCard();
expect(container.querySelectorAll("button")).toHaveLength(2);
await vi.advanceTimersByTimeAsync(1001);
await nextTick();
expect(container.querySelectorAll("button")).toHaveLength(0);
expect(container.textContent).toContain(i18n.global.t("ai.toolApproval.status.expired"));
expect(onResolve).not.toHaveBeenCalled();
});
it("forwards one-time approval and disables both buttons while submitting", async () => {
const { container, approval, onResolve } = mountCard();
container.querySelector("button")?.click();
expect(onResolve).toHaveBeenCalledWith(true);
approval.status = "submitting";
await nextTick();
expect([...container.querySelectorAll("button")].every((button) => button.disabled)).toBe(true);
approval.status = "denied";
await nextTick();
expect(container.querySelectorAll("button")).toHaveLength(0);
expect(container.textContent).toContain(i18n.global.t("ai.toolApproval.status.denied"));
});
});
@@ -0,0 +1,74 @@
// @vitest-environment happy-dom
import { createApp, nextTick } from "vue";
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import ConnectionIcon from "./ConnectionIcon.vue";
import { clearPluginIconCache } from "@/lib/plugins/pluginIconResolver";
import type { ConnectionConfig } from "@/types/database";
const { listPlugins, readPluginAsset } = vi.hoisted(() => ({ listPlugins: vi.fn(), readPluginAsset: vi.fn() }));
vi.mock("@/lib/backend/api", () => ({ listPlugins, readPluginAsset }));
const cleanups: Array<() => void> = [];
const connection: ConnectionConfig = { id: "c1", name: "Connection", db_type: "mysql", host: "localhost", port: 3306, username: "", password: "" };
async function mountIcon(config?: ConnectionConfig) {
const container = document.createElement("div");
document.body.append(container);
const app = createApp(ConnectionIcon, { connection: config, class: "h-3 w-3" });
app.mount(container);
cleanups.push(() => {
app.unmount();
container.remove();
});
await new Promise((resolve) => setTimeout(resolve, 0));
await nextTick();
return container;
}
beforeEach(() => {
vi.clearAllMocks();
clearPluginIconCache();
listPlugins.mockResolvedValue([
{
manifest: {
id: "sample.plugin",
icon: "assets/plugin.svg",
contributions: [{ type: "connection-provider", id: "sample.connection", icon: "assets/connection.svg" }],
},
},
]);
readPluginAsset.mockResolvedValue({ contentType: "image/svg+xml", dataBase64: "PHN2Zy8+" });
vi.stubGlobal("URL", { ...URL, createObjectURL: () => "blob:connection-icon", revokeObjectURL: vi.fn() });
});
afterEach(() => {
while (cleanups.length) cleanups.pop()?.();
vi.unstubAllGlobals();
});
describe("ConnectionIcon", () => {
it("uses the plugin connection-provider logo and preserves sizing", async () => {
const container = await mountIcon({ ...connection, db_type: "plugin", plugin_id: "sample.plugin", plugin_connection_provider: "sample.connection" });
expect(readPluginAsset).toHaveBeenCalledWith("sample.plugin", "assets/connection.svg");
expect(container.querySelector("img")?.getAttribute("src")).toBe("blob:connection-icon");
expect(container.firstElementChild?.classList.contains("h-3")).toBe(true);
});
it("falls back to the plugin logo without a provider logo", async () => {
await mountIcon({ ...connection, db_type: "plugin", plugin_id: "sample.plugin" });
expect(readPluginAsset).toHaveBeenCalledWith("sample.plugin", "assets/plugin.svg");
});
it("keeps native database logos unchanged", async () => {
const container = await mountIcon(connection);
expect(container.querySelector("img")?.getAttribute("src")).toBe("/icons/database/mysql.svg");
expect(listPlugins).not.toHaveBeenCalled();
});
it("renders a safe fallback for missing connection metadata", async () => {
const container = await mountIcon();
expect(container.querySelector("img")?.getAttribute("src")).toBe("/icons/database/postgres.svg");
expect(listPlugins).not.toHaveBeenCalled();
});
});
@@ -0,0 +1,13 @@
<script setup lang="ts">
import DatabaseIcon from "@/components/icons/DatabaseIcon.vue";
import PluginIcon from "@/components/plugins/PluginIcon.vue";
import { connectionIconType } from "@/lib/connection/connectionPresentation";
import type { ConnectionConfig } from "@/types/database";
defineProps<{ connection?: ConnectionConfig }>();
</script>
<template>
<PluginIcon v-if="connection?.db_type === 'plugin' && connection.plugin_id" :plugin-id="connection.plugin_id" :contribution-id="connection.plugin_connection_provider" />
<DatabaseIcon v-else :db-type="connectionIconType(connection)" />
</template>
@@ -1185,8 +1185,8 @@ function openPluginResultView(pluginId: string, contributionId: string, label: s
if (!result) return;
// The tab carries the result-view contribution id, not a workbench id: the
// plugin UI is told which declared surface the user picked, and it receives a
// bounded snapshot — plugins re-query through their backend when they need the
// full or streamed result set.
// bounded snapshot — plugins that need more rows re-run the statement through
// `host.queryData` (host.data:read, with the user's consent).
const cappedRows = result.rows.slice(0, 500);
queryStore.openPluginWorkbench(pluginId, contributionId, {
title: label,
@@ -0,0 +1,163 @@
<script setup lang="ts">
import { computed, ref, watch } from "vue";
import { useI18n } from "vue-i18n";
import { Bot, Database, Loader2, ShieldCheck, TriangleAlert, X } from "@lucide/vue";
import * as api from "@/lib/backend/api";
import { Badge } from "@/components/ui/badge";
import { Button } from "@/components/ui/button";
import { Switch } from "@/components/ui/switch";
import { useToast } from "@/composables/useToast";
import type { InstalledPlugin } from "@/types/database";
import type { PluginDataGrant } from "@/types/pluginData";
import { PLUGIN_DATA_READ_PERMISSION } from "@/types/pluginData";
import type { PluginToolPreview } from "@/types/pluginAiTools";
/**
* Plugin Center controls for what a plugin may reach beyond its own UI:
* built-in AI access to its MCP tools, and the connections it may read
* through `host.data:read`. Both are off until the user turns them on.
*/
const props = defineProps<{ plugin: InstalledPlugin }>();
const { t } = useI18n();
const { toast } = useToast();
const pluginId = computed(() => props.plugin.manifest.id);
const hasBackend = computed(() => !!props.plugin.manifest.entrypoints?.backend);
const declaresDataRead = computed(() => (props.plugin.manifest.permissions || []).includes(PLUGIN_DATA_READ_PERMISSION));
const aiEnabled = ref(false);
const aiSaving = ref(false);
const preview = ref<PluginToolPreview | null>(null);
const previewLoading = ref(false);
const previewError = ref("");
const grants = ref<PluginDataGrant[]>([]);
const revoking = ref<string | null>(null);
function errorText(error: unknown): string {
return error instanceof Error ? error.message : String(error);
}
async function load() {
preview.value = null;
previewError.value = "";
grants.value = [];
const id = pluginId.value;
const [enabledIds, currentGrants] = await Promise.all([
hasBackend.value ? api.getAiPluginToolPlugins().catch(() => [] as string[]) : Promise.resolve([] as string[]),
declaresDataRead.value ? api.getPluginDataGrants(id).catch(() => [] as PluginDataGrant[]) : Promise.resolve([] as PluginDataGrant[]),
]);
// The selection may have moved on while the requests were in flight.
if (id !== pluginId.value) return;
aiEnabled.value = enabledIds.includes(id);
grants.value = currentGrants;
}
async function setAiEnabled(enabled: boolean) {
if (aiSaving.value) return;
aiSaving.value = true;
try {
const enabledIds = await api.setAiPluginToolPluginEnabled(pluginId.value, enabled);
aiEnabled.value = enabledIds.includes(pluginId.value);
} catch (error) {
toast(t("pluginPlatform.aiTools.saveFailed", { message: errorText(error) }), 5000);
} finally {
aiSaving.value = false;
}
}
async function loadPreview() {
previewLoading.value = true;
previewError.value = "";
const id = pluginId.value;
try {
const result = await api.previewPluginAiTools(id);
if (id === pluginId.value) preview.value = result;
} catch (error) {
if (id === pluginId.value) previewError.value = errorText(error);
} finally {
previewLoading.value = false;
}
}
async function revokeGrant(connectionId: string) {
revoking.value = connectionId;
try {
grants.value = await api.setPluginDataGrant(pluginId.value, connectionId, false);
} catch (error) {
toast(t("pluginPlatform.dataAccess.revokeFailed", { message: errorText(error) }), 5000);
} finally {
revoking.value = null;
}
}
watch(pluginId, () => void load(), { immediate: true });
</script>
<template>
<div v-if="hasBackend || declaresDataRead" class="space-y-3">
<section v-if="hasBackend" class="space-y-3 rounded-lg border p-4" data-plugin-ai-tools>
<div class="flex items-start justify-between gap-3">
<div class="flex min-w-0 items-start gap-2">
<Bot class="mt-0.5 size-4 shrink-0 text-primary" />
<div class="min-w-0">
<div class="text-sm font-medium">{{ t("pluginPlatform.aiTools.title") }}</div>
<p class="mt-1 text-xs leading-5 text-muted-foreground">{{ t("pluginPlatform.aiTools.description") }}</p>
</div>
</div>
<Switch :model-value="aiEnabled" :disabled="aiSaving" :aria-label="t('pluginPlatform.aiTools.title')" @update:model-value="setAiEnabled($event === true)" />
</div>
<div class="flex flex-wrap items-center gap-2">
<Button size="sm" variant="outline" class="h-7 gap-1.5 text-xs" :disabled="previewLoading" @click="loadPreview">
<Loader2 v-if="previewLoading" class="size-3.5 animate-spin" />
{{ t("pluginPlatform.aiTools.preview") }}
</Button>
<span class="text-[11px] text-muted-foreground">{{ t("pluginPlatform.aiTools.previewHint") }}</span>
</div>
<div v-if="previewError" class="flex items-start gap-2 rounded-md border border-amber-500/30 bg-amber-500/5 px-3 py-2 text-xs text-amber-800 dark:text-amber-200">
<TriangleAlert class="mt-0.5 size-3.5 shrink-0" />
<span class="min-w-0 break-words">{{ t("pluginPlatform.aiTools.previewFailed", { message: previewError }) }}</span>
</div>
<div v-else-if="preview" class="space-y-2">
<div class="text-[11px] text-muted-foreground">
{{ preview.openConnections.length ? t("pluginPlatform.aiTools.openConnections", { names: preview.openConnections.map((connection) => connection.name).join(", ") }) : t("pluginPlatform.aiTools.noOpenConnections") }}
</div>
<div v-if="!preview.tools.length" class="rounded-md border border-dashed px-3 py-2 text-xs text-muted-foreground">{{ t("pluginPlatform.aiTools.noTools") }}</div>
<ul v-else class="max-h-64 divide-y overflow-y-auto rounded-md border">
<li v-for="tool in preview.tools" :key="tool.name" class="flex items-start gap-2 px-3 py-2">
<div class="min-w-0 flex-1">
<div class="font-mono text-xs">{{ tool.name }}</div>
<div v-if="tool.description" class="mt-0.5 text-[11px] leading-4 text-muted-foreground">{{ tool.description }}</div>
</div>
<Badge v-if="tool.readOnly" variant="secondary" class="h-5 shrink-0 gap-1 px-1.5 text-[10px]"><ShieldCheck class="size-3" />{{ t("pluginPlatform.aiTools.readOnly") }}</Badge>
<Badge v-else variant="outline" class="h-5 shrink-0 border-amber-500/40 px-1.5 text-[10px] text-amber-700 dark:text-amber-300">{{ t("pluginPlatform.aiTools.needsApproval") }}</Badge>
</li>
</ul>
</div>
</section>
<section v-if="declaresDataRead" class="space-y-3 rounded-lg border p-4" data-plugin-data-access>
<div class="flex min-w-0 items-start gap-2">
<Database class="mt-0.5 size-4 shrink-0 text-primary" />
<div class="min-w-0">
<div class="text-sm font-medium">{{ t("pluginPlatform.dataAccess.title") }}</div>
<p class="mt-1 text-xs leading-5 text-muted-foreground">{{ t("pluginPlatform.dataAccess.description") }}</p>
</div>
</div>
<div v-if="!grants.length" class="rounded-md border border-dashed px-3 py-2 text-xs text-muted-foreground">{{ t("pluginPlatform.dataAccess.none") }}</div>
<ul v-else class="divide-y rounded-md border">
<li v-for="grant in grants" :key="grant.connectionId" class="flex items-center gap-2 px-3 py-2">
<div class="min-w-0 flex-1 truncate text-xs">
<span v-if="grant.connectionName">{{ grant.connectionName }}</span>
<span v-else class="text-muted-foreground">{{ t("pluginPlatform.dataAccess.missingConnection", { id: grant.connectionId }) }}</span>
</div>
<Button size="sm" variant="ghost" class="h-6 gap-1 px-2 text-xs text-destructive" :disabled="revoking === grant.connectionId" @click="revokeGrant(grant.connectionId)">
<Loader2 v-if="revoking === grant.connectionId" class="size-3 animate-spin" />
<X v-else class="size-3" />
{{ t("pluginPlatform.dataAccess.revoke") }}
</Button>
</li>
</ul>
</section>
</div>
</template>
@@ -14,6 +14,7 @@ import { Tooltip, TooltipContent, TooltipTrigger } from "@/components/ui/tooltip
import { useToast } from "@/composables/useToast";
import PluginShortcutSettings from "./PluginShortcutSettings.vue";
import PluginIcon from "@/components/plugins/PluginIcon.vue";
import PluginAiAccessSection from "@/components/plugins/PluginAiAccessSection.vue";
import * as api from "@/lib/backend/api";
import { clearPluginIconCache } from "@/lib/plugins/pluginIconResolver";
import { loadPinnedPluginIds, savePinnedPluginIds, sortPluginsPinnedFirst } from "@/lib/plugins/pluginPinning";
@@ -1354,6 +1355,8 @@ onBeforeUnmount(() => {
</div>
</div>
<PluginAiAccessSection :key="selectedDefinition.plugin.manifest.id" :plugin="selectedDefinition.plugin" />
<div v-if="connectionProviders.some((entry) => entry.plugin.manifest.id === selectedPluginId)" class="space-y-3">
<div class="flex flex-wrap gap-2">
<Button
@@ -403,6 +403,14 @@ function createBridge() {
getPlanCapabilities: (connectionId) => api.getPluginPlanCapabilities(connectionId),
explainPlan: (request) => api.getPluginEstimatedPlan(request),
getTableMetadata: (context) => api.getPluginTableMetadata(context),
// host.data:read — the bridge asks for consent per connection before the
// first query; the backend enforces the persisted grant on every call.
queryData: (pluginId, request) => api.queryPluginData(pluginId, request),
hasDataGrant: async (pluginId, connectionId) => (await api.getPluginDataGrants(pluginId)).some((grant) => grant.connectionId === connectionId),
confirmDataAccess: (_pluginId, pluginName, connectionId) => confirmPluginDataAccess(pluginName, connectionId),
grantDataAccess: async (pluginId, connectionId) => {
await api.setPluginDataGrant(pluginId, connectionId, true);
},
closeTab: () => emit("closeTab"),
saveFile: (_pluginId, request, data) => savePluginFile(request, data),
downloadFile: isTauriRuntime() ? downloadPluginFile : undefined,
@@ -442,6 +450,22 @@ function createBridge() {
};
}
/**
* Consent for `host.data:read`: names the plugin and the connection so the
* user sees exactly what is shared. An allow is persisted as a grant the
* Plugin Center can revoke; the web host asks through the browser dialog.
*/
async function confirmPluginDataAccess(pluginName: string, connectionId: string): Promise<boolean> {
const connectionName = useConnectionStore().getConfig(connectionId)?.name || connectionId;
const message = t("pluginPlatform.dataAccessConsent", { name: pluginName, connection: connectionName });
const title = t("pluginPlatform.dataAccessConsentTitle");
if (isTauriRuntime()) {
const { ask } = await import("@tauri-apps/plugin-dialog");
return (await ask(message, { title, kind: "warning" })) === true;
}
return window.confirm(`${title}\n\n${message}`);
}
/** Keep a plugin-supplied name from smuggling path separators or traversal into the save dialog. */
function safeFileName(value: string | undefined): string {
const base = (value || "").split(/[\\/]/).pop() || "";