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

+19
View File
@@ -217,3 +217,22 @@ describe("AI schema selector visibility", () => {
expect(resolveAiDatabaseTarget(queryTab("app", "public"), postgres)).toEqual({ database: "app", schema: "public" });
});
});
describe("Plugin AI context", () => {
beforeEach(() => vi.clearAllMocks());
it.each([false, true])("skips database metadata even with stale table context: %s", async (withTable) => {
const connection: ConnectionConfig = { ...postgresConnection(), db_type: "plugin", plugin_id: "sample.plugin" };
const tab = { ...queryTab("stale-db", "public"), connectionId: connection.id, tableMeta: withTable ? { schema: "public", tableName: "stale_table", columns: [] } : undefined };
const context = await buildAiContext(tab, connection, { mentionedTables: [{ schema: "public", table: "stale_mention" }], sqlFiles: [{ name: "notes.sql", content: "SELECT 1" }] });
expect(context.databaseType).toBe("plugin");
expect(context.connectionName).toBe(connection.name);
expect(context.tables).toEqual([]);
expect(context.truncated).toBe(false);
expect(context.sqlFiles).toEqual([{ name: "notes.sql", content: "SELECT 1" }]);
expect(apiMock.listTables).not.toHaveBeenCalled();
expect(apiMock.getColumns).not.toHaveBeenCalled();
expect(apiMock.listIndexes).not.toHaveBeenCalled();
expect(apiMock.listForeignKeys).not.toHaveBeenCalled();
});
});
@@ -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). */
+7
View File
@@ -282,6 +282,9 @@ export const buildExplainSql = forward("buildExplainSql");
export const getExplainInfo = forward("getExplainInfo");
export const getPluginPlanCapabilities = forward("getPluginPlanCapabilities");
export const getPluginEstimatedPlan = forward("getPluginEstimatedPlan");
export const queryPluginData = forward("queryPluginData");
export const getPluginDataGrants = forward("getPluginDataGrants");
export const setPluginDataGrant = forward("setPluginDataGrant");
export const buildCreateUserSql = forward("buildCreateUserSql");
export const buildDroppedFilePreviewSql = forward("buildDroppedFilePreviewSql");
export const buildTableSelectSql = forward("buildTableSelectSql");
@@ -345,6 +348,10 @@ export const aiComplete = forward("aiComplete");
export const aiStream = forward("aiStream");
export const aiAgentStream = forward("aiAgentStream");
export const aiCancelStream = forward("aiCancelStream");
export const resolveAiToolApproval = forward("resolveAiToolApproval");
export const getAiPluginToolPlugins = forward("getAiPluginToolPlugins");
export const setAiPluginToolPluginEnabled = forward("setAiPluginToolPluginEnabled");
export const previewPluginAiTools = forward("previewPluginAiTools");
export const aiTestConnection = forward("aiTestConnection");
export const aiListModels = forward("aiListModels");
export const aiResolveModelEffort = forward("aiResolveModelEffort");
+37
View File
@@ -198,6 +198,8 @@ import type {
} from "@/lib/backend/tauri";
import type { QueryEditability } from "@/lib/sql/sqlAnalysis";
import type { PluginTableMetadata, PluginTableMetadataRequest } from "@/types/pluginSchemaMetadata";
import type { PluginDataGrant, PluginDataQueryRequest, PluginDataQueryResult } from "@/types/pluginData";
import type { PluginToolPreview } from "@/types/pluginAiTools";
import type { CsvQuoteMode } from "@/lib/export/csvQuoteMode";
import type { MigrationPreflight, MigrationReport } from "./migration";
export type { MigrationPreflight, MigrationReport } from "./migration";
@@ -1680,6 +1682,22 @@ export async function getPluginEstimatedPlan(request: PluginPlanRequest): Promis
return post<PluginPlanResult>("/api/query/plugin-estimated-plan", request);
}
/**
* Plugin Host API (`host.data:read`): one read-only statement on a connection
* the user granted to `pluginId`. The backend enforces permission, grant, and gate.
*/
export async function queryPluginData(pluginId: string, request: PluginDataQueryRequest): Promise<PluginDataQueryResult> {
return post<PluginDataQueryResult>("/api/plugin/data/query", { pluginId, request });
}
export async function getPluginDataGrants(pluginId: string): Promise<PluginDataGrant[]> {
return post<PluginDataGrant[]>("/api/plugin/data/grants", { pluginId });
}
export async function setPluginDataGrant(pluginId: string, connectionId: string, granted: boolean): Promise<PluginDataGrant[]> {
return post<PluginDataGrant[]>("/api/plugin/data/grant", { pluginId, connectionId, granted });
}
export async function buildDroppedFilePreviewSql(options: DroppedFilePreviewSqlOptions): Promise<string | undefined> {
const result = await post<string | null>("/api/query/build-dropped-file-preview-sql", { options });
return result ?? undefined;
@@ -1981,6 +1999,25 @@ export async function aiCancelStream(sessionId: string): Promise<boolean> {
return post("/api/ai/cancel-stream", { sessionId });
}
/** Answers a pending plugin tool approval of the agent run `sessionId`; false when nothing was waiting. */
export async function resolveAiToolApproval(sessionId: string, approvalId: string, approved: boolean): Promise<boolean> {
return post("/api/ai/tool-approval", { sessionId, approvalId, approved });
}
/** Plugin ids whose MCP tools the built-in AI agent may call. */
export async function getAiPluginToolPlugins(): Promise<string[]> {
return get("/api/ai/plugin-tools/plugins");
}
export async function setAiPluginToolPluginEnabled(pluginId: string, enabled: boolean): Promise<string[]> {
return post("/api/ai/plugin-tools/plugins", { pluginId, enabled });
}
/** Tools the built-in AI would get from a plugin (may start its sidecar). */
export async function previewPluginAiTools(pluginId: string): Promise<PluginToolPreview> {
return post("/api/ai/plugin-tools/preview", { pluginId });
}
export async function aiTestConnection(config: AiConfig): Promise<AiTestConnectionResult> {
return post("/api/ai/test-connection", { config });
}
+53
View File
@@ -25,6 +25,8 @@ import { collectBrowserSupportInfo } from "@/lib/app/supportInfo";
// for this module's own signatures (a re-export does not bind local names).
import type { PluginPlanCapabilities, PluginPlanRequest, PluginPlanResult } from "@/types/pluginPlan";
import type { PluginTableMetadata, PluginTableMetadataRequest } from "@/types/pluginSchemaMetadata";
import type { PluginDataGrant, PluginDataQueryRequest, PluginDataQueryResult } from "@/types/pluginData";
import type { AiToolApprovalOutcome, PluginToolPreview } from "@/types/pluginAiTools";
function invoke<T>(command: string, args?: Record<string, unknown>): Promise<T> {
assertUpdateAllowsCommand(command);
@@ -600,6 +602,22 @@ export type AgentEvent =
tool_name: string;
args: Record<string, unknown>;
}
| {
/** A plugin tool call that may change state waits for the user's approval; the run is paused. */
type: "tool_approval_required";
approval_id: string;
tool_call_id: string;
tool_name: string;
plugin_id: string;
plugin_name: string;
plugin_tool: string;
connection_id: string;
connection_name: string;
/** Exactly the arguments DBX forwards if the user approves. */
args: Record<string, unknown>;
timeout_secs: number;
}
| { type: "tool_approval_resolved"; approval_id: string; tool_call_id: string; outcome: AiToolApprovalOutcome }
| {
type: "tool_call_end";
tool_call_id: string;
@@ -716,6 +734,25 @@ export async function aiCancelStream(sessionId: string): Promise<boolean> {
return invoke("ai_cancel_stream", { sessionId });
}
/** Answers a pending plugin tool approval of the agent run `sessionId`; false when nothing was waiting. */
export async function resolveAiToolApproval(sessionId: string, approvalId: string, approved: boolean): Promise<boolean> {
return invoke("ai_resolve_tool_approval", { sessionId, approvalId, approved });
}
/** Plugin ids whose MCP tools the built-in AI agent may call. */
export async function getAiPluginToolPlugins(): Promise<string[]> {
return invoke("get_ai_plugin_tool_plugins");
}
export async function setAiPluginToolPluginEnabled(pluginId: string, enabled: boolean): Promise<string[]> {
return invoke("set_ai_plugin_tool_plugin_enabled", { pluginId, enabled });
}
/** Tools the built-in AI would get from a plugin (may start its sidecar). */
export async function previewPluginAiTools(pluginId: string): Promise<PluginToolPreview> {
return invoke("preview_plugin_ai_tools", { pluginId });
}
export async function saveAiConfigs(configs: AiConfigItem[]): Promise<void> {
return invoke("save_ai_configs", { configs });
}
@@ -1932,6 +1969,22 @@ export async function getPluginEstimatedPlan(request: PluginPlanRequest): Promis
return invoke<PluginPlanResult>("get_plugin_estimated_plan", { request });
}
/**
* Plugin Host API (`host.data:read`): one read-only statement on a connection
* the user granted to `pluginId`. The backend enforces permission, grant, and gate.
*/
export async function queryPluginData(pluginId: string, request: PluginDataQueryRequest): Promise<PluginDataQueryResult> {
return invoke<PluginDataQueryResult>("query_plugin_data", { pluginId, request });
}
export async function getPluginDataGrants(pluginId: string): Promise<PluginDataGrant[]> {
return invoke<PluginDataGrant[]>("get_plugin_data_grants", { pluginId });
}
export async function setPluginDataGrant(pluginId: string, connectionId: string, granted: boolean): Promise<PluginDataGrant[]> {
return invoke<PluginDataGrant[]>("set_plugin_data_grant", { pluginId, connectionId, granted });
}
export async function buildDroppedFilePreviewSql(options: DroppedFilePreviewSqlOptions): Promise<string | undefined> {
const result = await invoke<string | null>("build_dropped_file_preview_sql", {
options,
+122 -1
View File
@@ -1,6 +1,6 @@
import { describe, expect, it, vi } from "vitest";
import { reactive, readonly } from "vue";
import { PLUGIN_CLIPBOARD_AUDIT_CAPACITY, PluginHostBridge, clipboardReadGateAllows, createClipboardReadGate, pluginSandboxDocument, pluginSdkSource, recordClipboardRead } from "./pluginHostBridge";
import { MAX_CONCURRENT_PLUGIN_DATA_QUERIES, PLUGIN_CLIPBOARD_AUDIT_CAPACITY, PluginHostBridge, clipboardReadGateAllows, createClipboardReadGate, pluginSandboxDocument, pluginSdkSource, recordClipboardRead } from "./pluginHostBridge";
import type { InstalledPlugin, PluginResultViewContribution, PluginWorkbenchContribution } from "@/types/database";
function plugin(permissions: string[] = [], contributions: InstalledPlugin["manifest"]["contributions"] = []): InstalledPlugin {
@@ -1170,6 +1170,127 @@ describe("PluginHostBridge", () => {
return bridge.clipboardAudit.map((entry) => entry.outcome);
}
function dataApi(overrides: Record<string, unknown> = {}) {
return {
invoke: vi.fn(),
notify: vi.fn(),
sendBinary: vi.fn(),
readAsset: vi.fn(),
queryData: vi.fn().mockResolvedValue({ dbType: "postgres", columns: [{ name: "id" }], rows: [[1]], truncated: false, elapsedMs: 3 }),
hasDataGrant: vi.fn().mockResolvedValue(false),
confirmDataAccess: vi.fn().mockResolvedValue(true),
grantDataAccess: vi.fn().mockResolvedValue(undefined),
...overrides,
};
}
function dataHarness(permissions: string[], api: ReturnType<typeof dataApi>) {
const messages: unknown[] = [];
const target = { postMessage: (message: unknown) => messages.push(message) } as unknown as Window;
const bridge = new PluginHostBridge(plugin(permissions), workbench, {}, () => target, api);
const query = async (id: string, params: unknown) => {
bridge.handleWindowMessage({ source: target, data: { source: "dbx-plugin", version: 1, type: "request", id, method: "host.queryData", params } } as MessageEvent);
await vi.waitFor(() => expect(messages.some((message) => (message as { id?: string }).id === id)).toBe(true));
return messages.find((message) => (message as { id?: string }).id === id) as { result?: unknown; error?: string };
};
return { bridge, messages, query };
}
it("serves host.queryData only with host.data:read and after the user's consent", async () => {
const withoutPermission = dataHarness([], dataApi());
expect(await withoutPermission.query("no-permission", { connectionId: "conn-1", sql: "SELECT 1" })).toMatchObject({ error: "Plugin has not declared permission 'host.data:read'" });
const api = dataApi();
const { query } = dataHarness(["host.data:read"], api);
const first = await query("first", { connectionId: " conn-1 ", sql: " SELECT id FROM users ", maxRows: 99_999, database: " " });
expect(first).toMatchObject({ result: { rows: [[1]] } });
expect(api.confirmDataAccess).toHaveBeenCalledWith("sample", expect.any(String), "conn-1");
expect(api.grantDataAccess).toHaveBeenCalledWith("sample", "conn-1");
// Bound to the owning plugin, trimmed, and pre-clamped to the host row cap.
expect(api.queryData).toHaveBeenCalledWith("sample", { connectionId: "conn-1", sql: "SELECT id FROM users", maxRows: 5_000 });
// The consent is remembered for this connection; another connection asks again.
await query("second", { connectionId: "conn-1", sql: "SELECT 2" });
expect(api.confirmDataAccess).toHaveBeenCalledTimes(1);
expect(api.hasDataGrant).toHaveBeenCalledTimes(1);
await query("other-connection", { connectionId: "conn-2", sql: "SELECT 3" });
expect(api.confirmDataAccess).toHaveBeenCalledTimes(2);
});
it("skips the prompt for an existing grant and asks again after the backend reports a revocation", async () => {
const api = dataApi({
hasDataGrant: vi.fn().mockResolvedValue(true),
queryData: vi
.fn()
.mockResolvedValueOnce({ dbType: "mysql", columns: [], rows: [], truncated: false, elapsedMs: 1 })
.mockRejectedValueOnce(new Error("PLUGIN_DATA_ACCESS_NOT_GRANTED: the user has not granted this plugin access to the connection"))
.mockResolvedValue({ dbType: "mysql", columns: [], rows: [], truncated: false, elapsedMs: 1 }),
});
const { query } = dataHarness(["host.data:read"], api);
await query("granted", { connectionId: "conn-1", sql: "SELECT 1" });
expect(api.confirmDataAccess).not.toHaveBeenCalled();
expect(await query("revoked", { connectionId: "conn-1", sql: "SELECT 1" })).toMatchObject({ error: expect.stringContaining("PLUGIN_DATA_ACCESS_NOT_GRANTED") });
await query("after-revoke", { connectionId: "conn-1", sql: "SELECT 1" });
expect(api.hasDataGrant).toHaveBeenCalledTimes(2);
});
it("remembers a declined data access and never queries without consent", async () => {
const api = dataApi({ confirmDataAccess: vi.fn().mockResolvedValue(false) });
const { query } = dataHarness(["host.data:read"], api);
expect(await query("declined", { connectionId: "conn-1", sql: "SELECT 1" })).toMatchObject({ error: "Data access to this connection was denied" });
expect(await query("declined-again", { connectionId: "conn-1", sql: "SELECT 1" })).toMatchObject({ error: "Data access to this connection was denied for this plugin session" });
expect(api.confirmDataAccess).toHaveBeenCalledTimes(1);
expect(api.grantDataAccess).not.toHaveBeenCalled();
expect(api.queryData).not.toHaveBeenCalled();
// A host without a consent surface denies instead of granting silently.
const noSurface = dataApi({ confirmDataAccess: undefined });
const { query: queryWithoutSurface } = dataHarness(["host.data:read"], noSurface);
expect(await queryWithoutSurface("no-surface", { connectionId: "conn-1", sql: "SELECT 1" })).toMatchObject({ error: "Data access to this connection was denied" });
expect(noSurface.queryData).not.toHaveBeenCalled();
});
it("caps concurrent data queries per bridge so a plugin cannot occupy the shared pool", async () => {
const pending: Array<(value: unknown) => void> = [];
const api = dataApi({
hasDataGrant: vi.fn().mockResolvedValue(true),
queryData: vi.fn().mockImplementation(() => new Promise((resolve) => pending.push(resolve))),
});
const { bridge, messages } = dataHarness(["host.data:read"], api);
const target = (bridge as unknown as { targetWindow: () => Window }).targetWindow();
const start = (id: string) => bridge.handleWindowMessage({ source: target, data: { source: "dbx-plugin", version: 1, type: "request", id, method: "host.queryData", params: { connectionId: "conn-1", sql: "SELECT 1" } } } as MessageEvent);
for (let index = 0; index < MAX_CONCURRENT_PLUGIN_DATA_QUERIES; index += 1) start(`running-${index}`);
await vi.waitFor(() => expect(api.queryData).toHaveBeenCalledTimes(MAX_CONCURRENT_PLUGIN_DATA_QUERIES));
start("over-limit");
await vi.waitFor(() => expect(messages.some((message) => (message as { id?: string }).id === "over-limit")).toBe(true));
expect(messages.find((message) => (message as { id?: string }).id === "over-limit")).toMatchObject({ error: expect.stringContaining("data queries may run at once") });
// A finished query frees its slot.
pending.shift()?.({ dbType: "postgres", columns: [], rows: [], truncated: false, elapsedMs: 1 });
await vi.waitFor(() => expect(messages.some((message) => (message as { id?: string }).id === "running-0")).toBe(true));
start("after-slot");
await vi.waitFor(() => expect(api.queryData).toHaveBeenCalledTimes(MAX_CONCURRENT_PLUGIN_DATA_QUERIES + 1));
});
it("rejects malformed data requests and advertises dataApi only with a complete consent surface", async () => {
const api = dataApi();
const { query, bridge, messages } = dataHarness(["host.data:read"], api);
expect(await query("no-sql", { connectionId: "conn-1" })).toMatchObject({ error: "host.queryData requires sql" });
expect(await query("blank-sql", { connectionId: "conn-1", sql: " " })).toMatchObject({ error: "host.queryData requires a non-empty sql" });
expect(await query("no-connection", { sql: "SELECT 1" })).toMatchObject({ error: "connectionId must be a string" });
expect(await query("huge-sql", { connectionId: "conn-1", sql: "x".repeat(100_001) })).toMatchObject({ error: "sql must be at most 100000 characters" });
expect(api.queryData).not.toHaveBeenCalled();
bridge.sendInit();
const init = messages.find((message) => (message as { type?: string }).type === "init") as { capabilities?: Record<string, boolean> };
expect(init.capabilities?.dataApi).toBe(true);
const partial = dataHarness(["host.data:read"], dataApi({ grantDataAccess: undefined }));
partial.bridge.sendInit();
const partialInit = partial.messages.find((message) => (message as { type?: string }).type === "init") as { capabilities?: Record<string, boolean> };
expect(partialInit.capabilities?.dataApi).toBe(false);
});
it("denies clipboard reads on hosts without a consent surface and rate-limits repeated reads", async () => {
const messages: unknown[] = [];
const target = { postMessage: (message: unknown) => messages.push(message) } as unknown as Window;
@@ -3,6 +3,7 @@ import { clonePluginData, snapshotPluginWorkbenchContext } from "./pluginData";
import { MAX_PLUGIN_PLAN_SQL_CHARS, MAX_PLUGIN_PLAN_TIMEOUT_MS, PLUGIN_PLAN_PERMISSION, type PluginPlanCapabilities, type PluginPlanRequest, type PluginPlanResult } from "@/types/pluginPlan";
import { createPluginAiConversation, type AiPluginConversationRequest } from "@/lib/ai/aiPluginConversation";
import { MAX_PLUGIN_SCHEMA_METADATA_NAME_CHARS, PLUGIN_SCHEMA_METADATA_CAPABILITY, PLUGIN_SCHEMA_METADATA_PERMISSION, type PluginTableContext, type PluginTableMetadata } from "@/types/pluginSchemaMetadata";
import { MAX_PLUGIN_DATA_MAX_ROWS, MAX_PLUGIN_DATA_NAME_CHARS, MAX_PLUGIN_DATA_SQL_CHARS, MAX_PLUGIN_DATA_TIMEOUT_MS, PLUGIN_DATA_ACCESS_NOT_GRANTED, PLUGIN_DATA_CAPABILITY, PLUGIN_DATA_READ_PERMISSION, type PluginDataQueryRequest, type PluginDataQueryResult } from "@/types/pluginData";
const PLUGIN_MESSAGE_SOURCE = "dbx-plugin";
const HOST_MESSAGE_SOURCE = "dbx-host";
@@ -14,6 +15,12 @@ const MAX_BRIDGE_BINARY_BYTES = 8 * 1024 * 1024;
const MAX_BRIDGE_SAVE_BYTES = 512 * 1024 * 1024;
// Mirrors MAX_PLUGIN_PLAN_NAME_CHARS in crates/dbx-core/src/query/plugin_plan.rs.
const MAX_PLUGIN_PLAN_IDENTIFIER_CHARS = 256;
/**
* In-flight `host.queryData` calls per bridge. Plugin queries share the
* connection pool with the user's own tabs, so a runaway plugin must not be
* able to occupy it.
*/
export const MAX_CONCURRENT_PLUGIN_DATA_QUERIES = 4;
// Clipboard reads are the one permission that hands environment data (the
// system clipboard) to plugin code with no user interaction on each call, so
@@ -160,6 +167,22 @@ export interface PluginHostBridgeApi {
explainPlan?(request: PluginPlanRequest): Promise<PluginPlanResult>;
/** Read-only table schema metadata over an already-open Host connection. */
getTableMetadata?(context: PluginTableContext): Promise<PluginTableMetadata>;
/**
* One read-only SQL statement on a connection the user granted to the
* plugin (`host.data:read`). The backend re-checks the permission, the
* grant, the open connection, and the read-only statement gate.
*/
queryData?(pluginId: string, request: PluginDataQueryRequest): Promise<PluginDataQueryResult>;
/** Whether the user already granted `pluginId` data access to `connectionId`. */
hasDataGrant?(pluginId: string, connectionId: string): Promise<boolean>;
/**
* Asks the user whether `pluginId` may read `connectionId`. Resolves true to
* allow; the bridge then persists the grant through `grantDataAccess`. A
* host without a consent surface must omit it so the bridge denies.
*/
confirmDataAccess?(pluginId: string, pluginName: string, connectionId: string): Promise<boolean> | boolean;
/** Persists the grant the user just allowed. */
grantDataAccess?(pluginId: string, connectionId: string): Promise<void>;
closeTab?(): Promise<void> | void;
/** Persist plugin bytes through the host's native save dialog. Resolves null when the user cancels. */
saveFile?(pluginId: string, request: PluginSaveFileRequest, data: Uint8Array): Promise<PluginSaveFileResult | null>;
@@ -217,6 +240,16 @@ export class PluginHostBridge {
private theme?: PluginBridgeTheme;
/** Consent + audit + rate state for clipboard reads; lives for the bridge lifetime. */
private clipboardReadGate = createClipboardReadGate();
/**
* Data-access answers for this bridge lifetime, per connection. A denial is
* remembered so a plugin cannot re-prompt in a loop; an iframe reload builds
* a new bridge and may ask again. Grants live in the backend; this only
* spares a lookup per query.
*/
private dataAccess = new Map<string, "granted" | "denied">();
/** One consent prompt per connection at a time; concurrent queries share it. */
private pendingDataAccess = new Map<string, Promise<void>>();
private inFlightDataQueries = 0;
/** Bounded audit trail of this session's clipboard read attempts (oldest first). */
get clipboardAudit(): readonly PluginClipboardAuditEntry[] {
@@ -364,6 +397,7 @@ export class PluginHostBridge {
downloadFile: !!this.api.downloadFile,
planApi: !!this.api.getPlanCapabilities && !!this.api.explainPlan,
[PLUGIN_SCHEMA_METADATA_CAPABILITY]: !!this.api.getTableMetadata,
[PLUGIN_DATA_CAPABILITY]: !!this.api.queryData && !!this.api.hasDataGrant && !!this.api.confirmDataAccess && !!this.api.grantDataAccess,
storage: !!this.api.storageGet && !!this.api.storageSet && !!this.api.storageDelete,
ai: !!this.api.openAiConversation,
// Additive with the same "absence means unsupported" contract: an older
@@ -528,6 +562,26 @@ export class PluginHostBridge {
if (!this.api.getTableMetadata) throw new Error("Host schema metadata API is unavailable");
return this.api.getTableMetadata(requirePluginTableContext(requireRecord(params, "host.getTableMetadata params")));
}
if (method === "host.queryData") {
this.requirePermission(PLUGIN_DATA_READ_PERMISSION);
if (!this.api.queryData) throw new Error("Host data API is unavailable");
const request = requirePluginDataQueryRequest(requireRecord(params, "host.queryData params"));
await this.ensureDataAccess(request.connectionId);
if (this.inFlightDataQueries >= MAX_CONCURRENT_PLUGIN_DATA_QUERIES) {
throw new Error(`At most ${MAX_CONCURRENT_PLUGIN_DATA_QUERIES} data queries may run at once; wait for one to finish`);
}
this.inFlightDataQueries += 1;
try {
return await this.api.queryData(this.plugin.manifest.id, request);
} catch (error) {
// The grant was revoked while this workbench stayed open: forget the
// cached answer so the next query asks the user again.
if ((error instanceof Error ? error.message : String(error)).includes(PLUGIN_DATA_ACCESS_NOT_GRANTED)) this.dataAccess.delete(request.connectionId);
throw error;
} finally {
this.inFlightDataQueries -= 1;
}
}
if (method === "host.saveFile") {
const input = isRecord(params) ? params : {};
// The sandboxed iframe cannot trigger downloads (WKWebView cancels blob
@@ -659,6 +713,35 @@ export class PluginHostBridge {
if (!this.hasPermission(permission)) throw new Error(`Plugin has not declared permission '${permission}'`);
}
/** Resolves once the user allowed this plugin to read `connectionId`; rejects on denial. */
private async ensureDataAccess(connectionId: string): Promise<void> {
const known = this.dataAccess.get(connectionId);
if (known === "granted") return;
if (known === "denied") throw new Error("Data access to this connection was denied for this plugin session");
let pending = this.pendingDataAccess.get(connectionId);
if (!pending) {
pending = this.requestDataAccess(connectionId).finally(() => this.pendingDataAccess.delete(connectionId));
this.pendingDataAccess.set(connectionId, pending);
}
await pending;
}
private async requestDataAccess(connectionId: string): Promise<void> {
const pluginId = this.plugin.manifest.id;
if (this.api.hasDataGrant && (await this.api.hasDataGrant(pluginId, connectionId))) {
this.dataAccess.set(connectionId, "granted");
return;
}
// A host that cannot ask denies; it never grants silently.
const allowed = this.api.confirmDataAccess && this.api.grantDataAccess ? (await this.api.confirmDataAccess(pluginId, this.plugin.manifest.name, connectionId)) === true : false;
if (!allowed || !this.api.grantDataAccess) {
this.dataAccess.set(connectionId, "denied");
throw new Error("Data access to this connection was denied");
}
await this.api.grantDataAccess(pluginId, connectionId);
this.dataAccess.set(connectionId, "granted");
}
private hasPermission(permission: string): boolean {
return (this.plugin.manifest.permissions || []).includes(permission);
}
@@ -977,6 +1060,9 @@ export function pluginSdkSource(initialTheme?: PluginBridgeTheme): string {
explainPlan: (planRequest) => request('host.explainPlan', planRequest),
// Read-only metadata; the host enforces the permission and open-session gate.
getTableMetadata: (tableContext) => request('host.getTableMetadata', tableContext),
// One read-only statement on a connection the user granted to this
// plugin (host.data:read); the first query per connection asks the user.
queryData: (dataRequest) => request('host.queryData', dataRequest),
saveFile: (options = {}, data) => {
if (data === undefined) return request('host.saveFile', options);
if (typeof data === 'string') return request('host.saveFile', { ...(options || {}), dataBase64: data });
@@ -1189,6 +1275,42 @@ function requirePluginPlanRequest(input: Record<string, unknown>): PluginPlanReq
return request;
}
/**
* Validates one `host.queryData` request: a connection reference, optional
* scope, one SQL text, and optional bounds. The backend re-checks every bound
* and owns the read-only decision; this only refuses malformed input early.
*/
function requirePluginDataQueryRequest(input: Record<string, unknown>): PluginDataQueryRequest {
if (typeof input.sql !== "string") throw new Error("host.queryData requires sql");
const sql = input.sql.trim();
if (!sql) throw new Error("host.queryData requires a non-empty sql");
if (sql.length > MAX_PLUGIN_DATA_SQL_CHARS) throw new Error(`sql must be at most ${MAX_PLUGIN_DATA_SQL_CHARS} characters`);
const request: PluginDataQueryRequest = { connectionId: requirePluginDataName(input.connectionId, "connectionId"), sql };
for (const key of ["database", "schema"] as const) {
const value = input[key];
if (value === undefined || value === null) continue;
if (typeof value !== "string") throw new Error(`${key} must be a string`);
if (value.trim()) request[key] = requirePluginDataName(value, key);
}
if (input.maxRows !== undefined && input.maxRows !== null) {
if (typeof input.maxRows !== "number" || !Number.isFinite(input.maxRows)) throw new Error("maxRows must be a number");
request.maxRows = Math.min(MAX_PLUGIN_DATA_MAX_ROWS, Math.max(1, Math.floor(input.maxRows)));
}
if (input.timeoutMs !== undefined && input.timeoutMs !== null) {
if (typeof input.timeoutMs !== "number" || !Number.isFinite(input.timeoutMs)) throw new Error("timeoutMs must be a number");
request.timeoutMs = Math.min(MAX_PLUGIN_DATA_TIMEOUT_MS, Math.max(1, Math.round(input.timeoutMs)));
}
return request;
}
function requirePluginDataName(value: unknown, label: string): string {
if (typeof value !== "string") throw new Error(`${label} must be a string`);
const name = value.trim();
if (!name) throw new Error(`${label} must not be empty`);
if (Array.from(name).length > MAX_PLUGIN_DATA_NAME_CHARS) throw new Error(`${label} must be at most ${MAX_PLUGIN_DATA_NAME_CHARS} characters`);
return name;
}
/** Pre-clamps to the host ceiling; the backend additionally clamps to the connection's own timeout. */
function clampPluginPlanTimeout(value: unknown): number {
if (typeof value !== "number" || !Number.isFinite(value)) throw new Error("timeoutMs must be a number");