feat(ai): add plugin recommendations and agent context

This commit is contained in:
二丫讲梵 authored and t8y2 committed 2026-09-27 12:04:09 +08:00
1 parent 1b6017b9c5
commit e6edd02bbe
43 files changed
+1210 -118

No files matched your search

+8 -1
View File
@@ -1,6 +1,6 @@
import { describe, expect, it, vi } from "vitest";
import * as api from "@/lib/backend/api";
import { AGENT_ACTIONS, ASK_ACTIONS, buildAgentRequest, isValidActionForMode, type AiAction, type AiContext } from "@/lib/ai/ai";
import { AGENT_ACTIONS, ASK_ACTIONS, buildAgentRequest, buildSystemPrompt, isValidActionForMode, type AiAction, type AiContext } from "@/lib/ai/ai";
import { INTENT_CLASSIFY_MAX_TEXT_CHARS, actionForIntent, classifyIntentByLlm, intentCandidatesForMode, parseClassifierAction, requestsExplicitExecution, routeIntent, routeIntentByRules, type AiIntent, type AiIntentRouteInput } from "@/lib/ai/aiIntentRouter";
import type { AiConfig } from "@/stores/settingsStore";
@@ -428,6 +428,13 @@ describe("routeIntent (two-stage entry point)", () => {
});
describe("'auto' never reaches the transport layer", () => {
it("builds plugin Agent prompts that require live tools", () => {
const request = buildAgentRequest({ config, action: "general", mode: "agent", instruction: "检查当前集群", context: context({ databaseType: "plugin", connectionName: "orb", database: "" }) });
expect(request.messages[request.messages.length - 1]?.content).toBe("检查当前集群");
expect(buildSystemPrompt("general", context({ databaseType: "plugin", connectionName: "orb", database: "" }), "agent")).toContain("live data");
expect(buildSystemPrompt("general", context({ databaseType: "plugin", connectionName: "orb", database: "" }), "agent")).not.toContain("返回 SQL");
});
it("keeps the concrete action tables free of 'auto'", () => {
expect(ASK_ACTIONS).not.toContain("auto");
expect(AGENT_ACTIONS).not.toContain("auto");
@@ -1,5 +1,5 @@
import { describe, expect, it, vi } from "vitest";
import { buildPluginAiRequest, createPluginAiConversation, pluginContextFromMessages, streamPluginAiConversation } from "../aiPluginConversation";
import { buildPluginAiRequest, createPluginAiConversation, pluginComposerConnectionLabel, pluginContextConnectionId, pluginContextFromMessages, streamPluginAiConversation } from "../aiPluginConversation";
import type { AiConfig } from "@/types/ai";
import type { AgentEvent } from "@/lib/backend/tauri";
@@ -7,6 +7,19 @@ const identity = { id: "market", name: "Market Watch" };
const input = () => ({ title: "AAPL", prompt: "Analyse risks", context: { quotes: [{ symbol: "AAPL", price: 100, currency: "USD" }], snapshotId: "snap-1" } });
describe("plugin conversations in DBX AI", () => {
it("keeps the composer label on the connection instead of the recommendation title", () => {
const context = createPluginAiConversation(identity, input()).context;
expect(pluginComposerConnectionLabel(context, "orb", "Saved connection")).toBe("orb");
expect(pluginComposerConnectionLabel(context, undefined, "Saved connection")).toBe("Saved connection");
expect(pluginComposerConnectionLabel(context)).toBe("Market Watch");
});
it("reads an optional connection id from the plugin snapshot without requiring it", () => {
const context = createPluginAiConversation(identity, { ...input(), context: { connectionId: "conn-orb" } }).context;
expect(pluginContextConnectionId(context)).toBe("conn-orb");
expect(pluginContextConnectionId(createPluginAiConversation(identity, input()).context)).toBeUndefined();
});
it("binds the host identity and freezes a data snapshot without auto-sending by default", () => {
const request = input();
const opened = createPluginAiConversation(identity, { ...request, pluginId: "other-plugin", pluginName: "spoof" });
@@ -16,6 +29,16 @@ describe("plugin conversations in DBX AI", () => {
expect(opened).not.toHaveProperty("apiKey");
});
it("keeps legacy opens in snapshot Ask mode and accepts explicit Agent mode", () => {
const legacy = createPluginAiConversation(identity, input());
expect(legacy.mode).toBeUndefined();
expect(legacy.context.mode).toBeUndefined();
const live = createPluginAiConversation(identity, { ...input(), mode: "agent" });
expect(live.mode).toBe("agent");
expect(live.context.mode).toBe("agent");
expect(() => createPluginAiConversation(identity, { ...input(), mode: "invalid" })).toThrow();
});
it.each([{ title: "" }, { prompt: "" }, { context: [] }, { send: "true" }, { context: { callback: () => {} } }, { context: { big: "x".repeat(2 * 1024 * 1024) } }])("rejects malformed or oversized requests", (override) => {
expect(() => createPluginAiConversation(identity, { ...input(), ...override })).toThrow();
});
+17
View File
@@ -286,6 +286,9 @@ export async function runAgentStream(input: AiRequestInput, history: api.AiMessa
}
export function buildUserPrompt(action: AiAction, context: AiContext, instruction: string, isZh: boolean): string {
if (context.databaseType === "plugin") {
return instruction.trim() || (isZh ? "(无额外说明)" : "(No extra instruction provided.)");
}
const userRequest = instruction.trim() || (isZh ? "(无额外说明)" : "(No extra instruction provided.)");
const attachedTextData = formatAttachedTextData(context, isZh);
if (isVectorDbType(context.databaseType) || context.databaseType === "redis") {
@@ -325,6 +328,20 @@ function attachmentSafetyInstruction(isZh: boolean): string {
}
export function buildSystemPrompt(action: AiAction, context: AiContext, mode: AiAssistantMode = "ask", custom?: CustomPromptContext): string {
if (context.databaseType === "plugin") {
const isZh = isChineseLocale(currentLocale());
return [
isZh ? "你是 DBX 中连接插件的实时 Agent。" : "You are DBX's live Agent for a connected plugin.",
isZh
? "必须优先调用当前插件提供的工具获取实时数据,再基于工具结果回答。不要把历史上下文快照当作当前状态,也不要在没有工具结果时声称已经查询过资源。"
: "Always call the connected plugin's tools first to obtain live data. Do not treat historical context snapshots as current state or claim that a resource was queried without tool results.",
isZh ? "工具调用遵循工具定义和现有确认策略;如果没有可用工具,明确告知用户当前连接未提供实时查询能力。" : "Follow the tool definitions and the existing approval policy. If no tool is available, tell the user that this connection does not provide live query capability.",
...buildCustomInstructionLines(custom, isZh),
`Connection: ${context.connectionName}`,
]
.filter(Boolean)
.join("\n\n");
}
if (isVectorDbType(context.databaseType)) {
return buildVectorSystemPrompt(context, mode, custom);
}
@@ -1,6 +1,6 @@
import type { InjectionKey } from "vue";
import { snapshotPluginWorkbenchContext } from "@/lib/plugins/pluginData";
import type { AiConfig } from "@/types/ai";
import type { AiAssistantMode, AiConfig } from "@/types/ai";
import type { AiCompletionRequest, AiMessage, AiStreamChunk, AgentEvent } from "@/lib/backend/tauri";
/** Data owned by a conversation, independent of the currently selected DBX tab. */
@@ -10,12 +10,16 @@ export interface AiPluginContext {
title: string;
capturedAt: string;
data: Record<string, unknown>;
/** Persisted so reopening a live recommendation conversation keeps Agent mode. */
mode?: AiAssistantMode;
}
export interface AiPluginConversationRequest {
context: AiPluginContext;
prompt: string;
send: boolean;
/** Legacy plugin calls stay on snapshot Ask mode unless they opt into live Agent mode. */
mode?: AiAssistantMode;
}
export const OPEN_PLUGIN_AI_CONVERSATION: InjectionKey<(request: AiPluginConversationRequest) => Promise<void>> = Symbol("open-plugin-ai-conversation");
@@ -27,6 +31,7 @@ export function createPluginAiConversation(plugin: { id: string; name: string },
if (typeof input.prompt !== "string" || !input.prompt.trim() || input.prompt.length > 32000) throw new Error("AI conversation prompt must contain 1–32000 characters");
if (!input.context || typeof input.context !== "object" || Array.isArray(input.context)) throw new Error("AI conversation context must be an object");
if (input.send !== undefined && typeof input.send !== "boolean") throw new Error("AI conversation send must be a boolean");
if (input.mode !== undefined && input.mode !== "ask" && input.mode !== "agent") throw new Error("AI conversation mode must be ask or agent");
return {
context: {
pluginId: plugin.id,
@@ -34,9 +39,11 @@ export function createPluginAiConversation(plugin: { id: string; name: string },
title: input.title.trim(),
capturedAt: new Date().toISOString(),
data: snapshotPluginWorkbenchContext(input.context as Record<string, unknown>),
...(input.mode === undefined ? {} : { mode: input.mode }),
},
prompt: input.prompt.trim(),
send: input.send === true,
...(input.mode === undefined ? {} : { mode: input.mode }),
};
}
@@ -48,6 +55,25 @@ export function pluginContextText(context: AiPluginContext): string {
return `${context.pluginName} · ${context.title}\n${context.capturedAt}\n\n${JSON.stringify(context.data, null, 2)}`;
}
/** A plugin may include the DBX connection id in its snapshot context. */
export function pluginContextConnectionId(context: AiPluginContext): string | undefined {
const value = context.data.connectionId;
return typeof value === "string" && value.trim() ? value : undefined;
}
/**
* Label shown in the AI composer for a plugin-backed conversation.
*
* The plugin title describes the request and can change for every
* recommendation. The composer is bound to a connection instead, so prefer
* the resolved connection name and use the persisted name for conversations
* whose connection was removed. Older plugin conversations may have neither,
* in which case the plugin name is the safest available fallback.
*/
export function pluginComposerConnectionLabel(context: AiPluginContext, boundConnectionName?: string, persistedConnectionName?: string): string {
return boundConnectionName?.trim() || persistedConnectionName?.trim() || context.pluginName;
}
export function buildPluginAiRequest(config: AiConfig, context: AiPluginContext, messages: AiMessage[], instructions?: string[]): AiCompletionRequest {
return {
config,