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

@@ -1,5 +1,5 @@
import { describe, expect, it } from "vitest";
import { formatToolDurationMs, toolCallStepKey, upsertAgentStep, type AiAgentStepItem } from "@/lib/ai/aiAgentStepPresentation";
import { formatAgentToolName, formatToolDurationMs, toolCallStepKey, updateAgentStepApproval, upsertAgentStep, type AiAgentStepApproval, type AiAgentStepItem } from "@/lib/ai/aiAgentStepPresentation";
const startStep: AiAgentStepItem = {
key: "tool-call-1",
@@ -76,6 +76,38 @@ describe("aiAgentStepPresentation", () => {
});
});
describe("plugin tool approvals", () => {
const approval: AiAgentStepApproval = {
approvalId: "a1",
sessionId: "s1",
pluginName: "SSH",
pluginTool: "ssh_exec",
connectionName: "prod",
args: { command: "uptime" },
expiresAtMs: 5_000,
status: "pending",
};
it("attaches the approval to the tool card and keeps it when the call ends", () => {
const steps: AiAgentStepItem[] = [];
upsertAgentStep(steps, startStep);
expect(updateAgentStepApproval(steps, "tool-call-1", () => approval)).toBe(true);
expect(updateAgentStepApproval(steps, "tool-missing", () => approval)).toBe(false);
updateAgentStepApproval(steps, "tool-call-1", (current) => (current ? { ...current, status: "approved" } : current));
upsertAgentStep(steps, { key: "tool-call-1", labelKey: "ai.agentSteps.toolDone", tone: "success", toolName: "list_tables", toolResult: "ok", endedAtMs: 2_000 });
expect(steps).toHaveLength(1);
expect(steps[0].approval).toEqual({ ...approval, status: "approved" });
expect(steps[0].toolResult).toBe("ok");
});
it("formats plugin tool names with their provenance and leaves built-in names alone", () => {
expect(formatAgentToolName("kafka__kafka_topics_list")).toBe("kafka › kafka_topics_list");
expect(formatAgentToolName("execute_query")).toBe("execute_query");
expect(formatAgentToolName("__odd")).toBe("__odd");
expect(formatAgentToolName("odd__")).toBe("odd__");
});
});
describe("formatToolDurationMs", () => {
it("formats sub-second durations with one decimal", () => {
expect(formatToolDurationMs(799)).toBe("0.8s");
@@ -401,6 +401,38 @@ describe("aiGenerationStatus", () => {
it("falls back to the raw snake_case name for unknown tools", () => {
expect(toolLabel("mystery_tool", t)).toBe("mystery_tool");
});
it("shows plugin tools with their plugin prefix as provenance", () => {
expect(toolLabel("ssh__ssh_exec", t)).toBe("ssh › ssh_exec");
});
});
describe("plugin tool approvals", () => {
it("keep the approving tool active without changing the phase", () => {
let status = applyStatusEvent(createGenerationStatus(T0), { type: "tool_call_start", tool_call_id: "c1", tool_name: "ssh__ssh_exec", args: {} }, T0 + 1);
status = applyStatusEvent(
status,
{
type: "tool_approval_required",
approval_id: "a1",
tool_call_id: "c1",
tool_name: "ssh__ssh_exec",
plugin_id: "io.dbx.ssh",
plugin_name: "SSH",
plugin_tool: "ssh_exec",
connection_id: "s1",
connection_name: "prod",
args: { command: "uptime" },
timeout_secs: 300,
},
T0 + 2,
);
expect(status.phase).toBe("running_tool");
expect(status.activeTool?.name).toBe("ssh__ssh_exec");
status = applyStatusEvent(status, { type: "tool_approval_resolved", approval_id: "a1", tool_call_id: "c1", outcome: "approved" }, T0 + 3);
expect(status.phase).toBe("running_tool");
expect(status.lastEventAt).toBe(T0 + 3);
});
});
describe("status ticker (createStatusTicker / nextStatusTickDelay)", () => {
+5 -4
View File
@@ -784,13 +784,14 @@ export async function buildAiContext(
const maxFksPerTable = options.maxFksPerTable ?? 10;
const databaseType = aiDatabaseTypeForConnection(connection);
const { database, schema } = resolveAiDatabaseTarget(tab, connection);
const supportsMetadata = connection.db_type !== "plugin";
const tables: AiSchemaTable[] = [];
const tableKeys = new Set<string>();
let truncated = false;
let schemaScope: AiContext["schemaScope"] = "database";
let currentCollectionName: string | undefined;
if (tab.tableMeta) {
if (supportsMetadata && tab.tableMeta) {
schemaScope = "focused_table";
const s = tab.tableMeta.schema ?? "";
const tName = tab.tableMeta.tableName;
@@ -809,7 +810,7 @@ export async function buildAiContext(
truncated = tab.tableMeta.columns.length > maxColumnsPerTable;
}
for (const mention of options.mentionedTables ?? []) {
for (const mention of supportsMetadata ? (options.mentionedTables ?? []) : []) {
const key = aiTableMentionKey(mention.schema, mention.table);
if (tableKeys.has(key)) continue;
const entry = await loadMentionedTableContext(tab, connection, mention, maxColumnsPerTable, maxIndexesPerTable, maxFksPerTable).catch(() => undefined);
@@ -819,7 +820,7 @@ export async function buildAiContext(
}
// Vector databases: load collections instead of SQL tables
if (isVectorDbType(databaseType)) {
if (supportsMetadata && isVectorDbType(databaseType)) {
try {
const collections = await api.vectorListCollections(tab.connectionId, database);
@@ -854,7 +855,7 @@ export async function buildAiContext(
}
}
if (!tab.tableMeta && !["redis", "mongodb"].includes(connection.db_type) && !isVectorDbType(databaseType)) {
if (supportsMetadata && !tab.tableMeta && !["redis", "mongodb"].includes(connection.db_type) && !isVectorDbType(databaseType)) {
try {
const schemas = await loadCandidateSchemas(tab, connection);
for (const schema of schemas) {
@@ -1,7 +1,29 @@
import type { AiAgentPlan, AiAgentStep } from "@/lib/ai/aiAgentPlan";
import type { AiToolApprovalOutcome } from "@/types/pluginAiTools";
export type AiAgentStepTone = "success" | "active" | "warning" | "danger" | "muted";
/**
* Approval state of a plugin tool call that may change state. `pending` shows
* the approve/deny buttons; `submitting` is the in-flight answer; `expired`
* means the backend no longer waited when the answer arrived.
*/
export type AiAgentStepApprovalStatus = "pending" | "submitting" | "expired" | AiToolApprovalOutcome;
export interface AiAgentStepApproval {
approvalId: string;
/** Agent session that asked; the answer must go back to the same run. */
sessionId: string;
pluginName: string;
pluginTool: string;
connectionName: string;
/** Exactly the arguments DBX forwards when approved. */
args: Record<string, unknown>;
/** Wall-clock deadline after which the backend treats the call as denied. */
expiresAtMs: number;
status: AiAgentStepApprovalStatus;
}
export interface AiAgentStepItem {
key: string;
labelKey: string;
@@ -24,6 +46,8 @@ export interface AiAgentStepItem {
endedAtMs?: number;
/** Computed tool duration (endedAtMs - startedAtMs), present only when both stamps exist */
durationMs?: number;
/** Present while (and after) a plugin tool call asked the user for approval */
approval?: AiAgentStepApproval;
}
/** Backend fallback tool_call_id values that repeat across calls and must not be used as stable merge keys. */
@@ -52,6 +76,7 @@ export function upsertAgentStep(steps: AiAgentStepItem[], step: AiAgentStepItem)
if (!merged.explainData && existing.explainData) merged.explainData = existing.explainData;
if (!merged.titleKey && existing.titleKey) merged.titleKey = existing.titleKey;
if (!merged.titleParams && existing.titleParams) merged.titleParams = existing.titleParams;
if (!merged.approval && existing.approval) merged.approval = existing.approval;
if (merged.startedAtMs === undefined && existing.startedAtMs !== undefined) merged.startedAtMs = existing.startedAtMs;
if (merged.endedAtMs !== undefined && merged.startedAtMs !== undefined) {
merged.durationMs = Math.max(0, merged.endedAtMs - merged.startedAtMs);
@@ -59,6 +84,28 @@ export function upsertAgentStep(steps: AiAgentStepItem[], step: AiAgentStepItem)
steps.splice(idx, 1, merged);
}
/**
* Apply an approval change to the step keyed `toolCallKey`. Returns false when
* the card does not exist (yet), so callers can decide whether to create it.
*/
export function updateAgentStepApproval(steps: AiAgentStepItem[], toolCallKey: string, update: (approval: AiAgentStepApproval | undefined) => AiAgentStepApproval | undefined): boolean {
const idx = steps.findIndex((step) => step.key === toolCallKey);
if (idx < 0) return false;
const approval = update(steps[idx].approval);
steps.splice(idx, 1, { ...steps[idx], approval });
return true;
}
/**
* `ssh__ssh_exec` → `ssh › ssh_exec`: plugin tools carry a DBX prefix that the
* card shows as provenance; built-in tool names pass through unchanged.
*/
export function formatAgentToolName(toolName: string): string {
const separator = toolName.indexOf("__");
if (separator <= 0 || separator + 2 >= toolName.length) return toolName;
return `${toolName.slice(0, separator)} › ${toolName.slice(separator + 2)}`;
}
/**
* Format a tool duration for the step-card tail: sub-second → one decimal
* ("0.8s"); 1s–10s → one decimal ("1.2s"); ≥10s → integer ("12s").
@@ -16,6 +16,7 @@
* by `tool_call_start`/`tool_call_end`, not by `assistantMode`.
*/
import type { AgentEvent } from "@/lib/backend/tauri";
import { formatAgentToolName } from "@/lib/ai/aiAgentStepPresentation";
export interface AiGenerationStatus {
/** When `send()` set `isGenerating=true`. Elapsed time is derived from this. */
@@ -56,7 +57,7 @@ export type AiStatusTranslate = {
(key: string, named: Record<string, unknown>): string;
};
/** i18n key per agent tool name; unknown tools fall back to the raw snake_case name. */
/** i18n key per agent tool name; unknown tools fall back to the raw name (plugin tools as `prefix › tool`). */
export const STATUS_TOOL_LABEL_KEYS: Record<string, string> = {
execute_query: "ai.status.toolLabels.executeQuery",
execute_sql: "ai.status.toolLabels.executeSql",
@@ -148,7 +149,10 @@ export function applyStatusEvent(status: AiGenerationStatus, event: AgentEvent,
case "write_sql_confirmation_required":
case "production_write_blocked":
case "context_compacted":
// Only refresh lastEventAt above; do NOT change phase.
case "tool_approval_required":
case "tool_approval_resolved":
// Only refresh lastEventAt above; do NOT change phase. A pending plugin
// tool approval keeps its tool active until the call ends.
break;
case "agent_end":
case "error":
@@ -186,7 +190,7 @@ export function markCancelling(status: AiGenerationStatus, now: number): AiGener
/** Resolve a snake_case tool name through the i18n label map, falling back to the raw name. */
export function toolLabel(toolName: string, t: AiStatusTranslate): string {
const key = STATUS_TOOL_LABEL_KEYS[toolName];
return key ? t(key) : toolName;
return key ? t(key) : formatAgentToolName(toolName);
}
/** Round a duration up to whole seconds, never below 0 (guards a stale timer -1s). */