feat(plugins): add AI tools and consent-gated data access
This commit is contained in:
71 files changed
+4613
-129
No files matched your search
@@ -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"));
|
||||
});
|
||||
});
|
||||
Reference in new issue
Block a user