Skip to content

armgit / dbx

Public Imported from GitHub
0

25 MB lightweight cross-platform database client for 100+ databases, including MySQL, PostgreSQL, SQLite, Redis, MongoDB, DuckDB, SQL Server, and Dameng. Built-in AI, MCP Server, CLI, desktop and Docker. | 轻量级跨平台数据库管理工具,支持 MySQL、PostgreSQL、SQLite、Redis、MongoDB、达梦等 100+ 数据库,提供桌面端、Docker、CLI、内置 AI 助手和 MCP。

feat(ai): split Ask/Agent action menus with task-oriented Agent actions

Abeautifulsnow8539011f2582
diff --git a/apps/desktop/src/components/editor/AiAssistant.vue b/apps/desktop/src/components/editor/AiAssistant.vue
index 87cc95c0cb..d34bfb33cf 100644
--- a/apps/desktop/src/components/editor/AiAssistant.vue
+++ b/apps/desktop/src/components/editor/AiAssistant.vue
@@ -1,9 +1,39 @@
<script setup lang="ts">
-import { computed, nextTick, onMounted, onUnmounted, ref, type Component } from "vue";
+import { computed, nextTick, onMounted, onUnmounted, ref, watch, type Component } from "vue";
import { uuid } from "@/lib/common/utils";
import { useI18n } from "vue-i18n";
import { translateBackendError } from "@/i18n/backend-errors";
-import { ArrowUp, ArrowRightLeft, AlertTriangle, Bot, Check, ChevronRight, CircleSlash, Copy, Database, GitBranch, HelpCircle, History, Loader2, MessageSquarePlus, Pencil, Replace, Server, ShieldCheck, Table2, Play, Square, Trash2, Terminal, Wand2, Wrench, X, Zap, TestTube } from "@lucide/vue";
+import {
+ ArrowUp,
+ ArrowRightLeft,
+ AlertTriangle,
+ Bot,
+ Check,
+ ChevronRight,
+ CircleSlash,
+ Copy,
+ Database,
+ GitBranch,
+ HelpCircle,
+ History,
+ Loader2,
+ MessageSquarePlus,
+ Pencil,
+ Replace,
+ Server,
+ ShieldCheck,
+ Table2,
+ Play,
+ Square,
+ Trash2,
+ Terminal,
+ Wand2,
+ Wrench,
+ X,
+ Zap,
+ TestTube,
+ Search,
+} from "@lucide/vue";
import { Button } from "@/components/ui/button";
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";
import { Popover, PopoverContent, PopoverTrigger } from "@/components/ui/popover";
@@ -18,7 +48,7 @@ import { connectionIconType } from "@/lib/connection/connectionPresentation";
import DatabaseIcon from "@/components/icons/DatabaseIcon.vue";
import { useQueryStore } from "@/stores/queryStore";
import { useToast } from "@/composables/useToast";
-import { buildAiContext, runAgentStream, isVectorDbType, type AiAction } from "@/lib/ai/ai";
+import { buildAiContext, runAgentStream, isVectorDbType, defaultActionForMode, isValidActionForMode, type AiAction, type AiAssistantMode } from "@/lib/ai/ai";
import { formatAiModelOption } from "@/lib/ai/aiModelPresentation";
import type { AgentEvent } from "@/lib/backend/tauri";
import { buildAiAgentPlan } from "@/lib/ai/aiAgentPlan";
@@ -242,7 +272,15 @@ const selectedMentions = ref<AiTableMention[]>([]);
let mentionTimer: ReturnType<typeof setTimeout> | undefined;
let mentionRequestId = 0;
-const actionButtons: { action: AiAction; icon: Component; key: string }[] = [
+interface AiActionButton {
+ action: AiAction;
+ icon: Component;
+ /** i18n key for the menu label. */
+ key: string;
+}
+
+/** Ask-mode actions: SQL-producing, never auto-run. */
+const askActionButtons: AiActionButton[] = [
{ action: "generate", icon: Wand2, key: "ai.actions.generate" },
{ action: "explain", icon: HelpCircle, key: "ai.actions.explain" },
{ action: "optimize", icon: Zap, key: "ai.actions.optimize" },
@@ -251,6 +289,42 @@ const actionButtons: { action: AiAction; icon: Component; key: string }[] = [
{ action: "sampleData", icon: TestTube, key: "ai.actions.sampleData" },
];
+/** Agent-mode actions: task-oriented, drive tool use and real results. */
+const agentActionButtons: AiActionButton[] = [
+ { action: "query", icon: Search, key: "ai.actions.query" },
+ { action: "exploreSchema", icon: Table2, key: "ai.actions.exploreSchema" },
+ { action: "executeAndExplain", icon: Play, key: "ai.actions.executeAndExplain" },
+ // `generate` is shared with Ask so users can still request SQL-only output without execution.
+ { action: "generate", icon: Wand2, key: "ai.actions.generateNoExec" },
+];
+
+const actionButtons = computed<AiActionButton[]>(() => (assistantMode.value === "agent" ? agentActionButtons : askActionButtons));
+
+// Vector DBs hide the action menu and only expose collection tools (list_collections /
+// browse_collection), never SQL tools. Keep their action at `generate` so the task contract
+// doesn't tell the LLM to call execute_query / produce SQL — neither applies to vector stores.
+function resolveDefaultAction(mode: AiAssistantMode): AiAction {
+ if (props.connection && isVectorDbType(props.connection.db_type)) return "generate";
+ return defaultActionForMode(mode);
+}
+
+// Switching mode is a deliberate context change: land on that mode's default action so the
+// menu and behavior match the new intent (Ask → generate, Agent → query). The shared
+// `generate` action is not carried across because its label/semantics differ per mode
+// ("生成 SQL" vs "生成但不执行").
+//
+// `triggerAction` may set the action itself after programmatically switching mode (e.g. "Fix
+// with AI" invoked from Agent mode); `suppressModeActionReset` tells this watch to skip the
+// default reset so the menu keeps reflecting the action actually being run.
+let suppressModeActionReset = false;
+watch(assistantMode, (mode) => {
+ if (suppressModeActionReset) {
+ suppressModeActionReset = false;
+ return;
+ }
+ activeAction.value = resolveDefaultAction(mode);
+});
+
function selectAction(action: AiAction) {
activeAction.value = action;
if (action === "fix" && props.tab?.result) {
@@ -344,7 +418,7 @@ const assistantModeItems = computed(() => [
},
]);
const actionMenuItems = computed(() =>
- actionButtons.map((button) => ({
+ actionButtons.value.map((button) => ({
value: button.action,
label: t(button.key),
icon: button.icon,
@@ -932,7 +1006,7 @@ async function send() {
if (msg && requestedMode === "agent") msg.agentSteps = buildAiAgentStepItems(agentPlan);
if (agentPlan.handoffSql) emit("requestAutoExecuteSql", agentPlan.handoffSql);
}
- activeAction.value = "generate";
+ activeAction.value = resolveDefaultAction(assistantMode.value);
currentSessionId.value = "";
// Apply deferred context compaction after streaming so assistantIdx stays stable.
// Visible chat history is kept for the user; future LLM history starts from this hidden summary.
@@ -1128,6 +1202,15 @@ onUnmounted(() => {
});
function triggerAction(action: AiAction, instruction?: string) {
+ // External Ask-style entry points (Fix with AI, Explain history) produce/analyze SQL text.
+ // If the assistant is currently in Agent mode where those actions aren't offered, switch to
+ // Ask mode so the action is valid and the menu reflects what actually runs.
+ if (!isValidActionForMode(action, assistantMode.value)) {
+ // Suppress the mode-switch watch so it doesn't overwrite `action` (set below) with the
+ // Ask default — the menu must reflect the action actually being run.
+ suppressModeActionReset = true;
+ assistantMode.value = "ask";
+ }
activeAction.value = action;
if (instruction) prompt.value = instruction;
send();
diff --git a/apps/desktop/src/i18n/locales/en.ts b/apps/desktop/src/i18n/locales/en.ts
index 6931f91534..6edf7a505b 100644
--- a/apps/desktop/src/i18n/locales/en.ts
+++ b/apps/desktop/src/i18n/locales/en.ts
@@ -1210,7 +1210,7 @@ export default {
},
modeHints: {
ask: "Generate SQL and explanations without auto-running them",
- agent: "Auto-run safe queries when possible",
+ agent: "Use tools to query data and answer from real results",
},
fixWithAi: "Fix with AI",
truncated: "Context truncated",
@@ -1282,6 +1282,10 @@ export default {
fix: "Fix Error",
convert: "Convert Dialect",
sampleData: "Sample Data",
+ query: "Query Data",
+ exploreSchema: "Inspect Schema",
+ executeAndExplain: "Run & Explain",
+ generateNoExec: "Generate (no run)",
},
placeholders: {
generate: "Describe what you want to query, e.g. orders per user in the last 7 days",
@@ -1290,6 +1294,9 @@ export default {
fix: "Paste the error or describe the expected result",
convert: "e.g. convert to PostgreSQL / MySQL / SQL Server",
sampleData: "Describe the sample data or test statements to generate",
+ query: "Describe what to query or count, e.g. order totals by region this month",
+ exploreSchema: "Describe the table or structure to inspect, e.g. columns and indexes of orders",
+ executeAndExplain: "Optional: add what to focus on in the explanation",
},
editMessage: "Edit message",
editResend: "Resend",
diff --git a/apps/desktop/src/i18n/locales/es.ts b/apps/desktop/src/i18n/locales/es.ts
index 1a0bff4615..92e3c66e08 100644
--- a/apps/desktop/src/i18n/locales/es.ts
+++ b/apps/desktop/src/i18n/locales/es.ts
@@ -1240,6 +1240,10 @@ export default withEnglishFallback({
fix: "Corregir error",
convert: "Convertir dialecto",
sampleData: "Datos de ejemplo",
+ query: "Consultar datos",
+ exploreSchema: "Inspeccionar esquema",
+ executeAndExplain: "Ejecutar y explicar",
+ generateNoExec: "Generar (sin ejecutar)",
},
placeholders: {
generate: "Describe lo que quieres consultar, p. ej. pedidos por usuario en los últimos 7 días",
@@ -1248,6 +1252,9 @@ export default withEnglishFallback({
fix: "Pega el error o describe el resultado esperado",
convert: "P. ej. convertir a PostgreSQL / MySQL / SQL Server",
sampleData: "Describe los datos de ejemplo o sentencias de prueba a generar",
+ query: "Describe qué consultar o contar, p. ej. totales de pedidos por región este mes",
+ exploreSchema: "Describe la tabla o estructura a inspeccionar, p. ej. columnas e índices de orders",
+ executeAndExplain: "Opcional: indica en qué centrar la explicación",
},
editMessage: "Editar mensaje",
editResend: "Reenviar",
diff --git a/apps/desktop/src/i18n/locales/it.ts b/apps/desktop/src/i18n/locales/it.ts
index 309ba7b7cb..af77be1ca9 100644
--- a/apps/desktop/src/i18n/locales/it.ts
+++ b/apps/desktop/src/i18n/locales/it.ts
@@ -1238,6 +1238,10 @@ export default withEnglishFallback({
fix: "Correggi Errore",
convert: "Converti Dialetto",
sampleData: "Dati di Esempio",
+ query: "Interroga dati",
+ exploreSchema: "Ispeziona schema",
+ executeAndExplain: "Esegui e spiega",
+ generateNoExec: "Genera (senza eseguire)",
},
placeholders: {
generate: "Descrivi cosa desideri interrogare, es. ordini per utente negli ultimi 7 giorni",
@@ -1246,6 +1250,9 @@ export default withEnglishFallback({
fix: "Incolla l'errore o descrivi il risultato atteso",
convert: "es. converti in PostgreSQL / MySQL / SQL Server",
sampleData: "Descrivi i dati di esempio o le istruzioni di test da generare",
+ query: "Descrivi cosa interrogare o conteggiare, es. totali ordini per regione questo mese",
+ exploreSchema: "Descrivi la tabella o struttura da ispezionare, es. colonne e indici di orders",
+ executeAndExplain: "Opzionale: aggiungi su cosa concentrare la spiegazione",
},
editMessage: "Modifica messaggio",
editResend: "Invia di nuovo",
diff --git a/apps/desktop/src/i18n/locales/ja.ts b/apps/desktop/src/i18n/locales/ja.ts
index b09a0b29c9..b1b289f502 100644
--- a/apps/desktop/src/i18n/locales/ja.ts
+++ b/apps/desktop/src/i18n/locales/ja.ts
@@ -1238,6 +1238,10 @@ export default withEnglishFallback({
fix: "エラーを修正",
convert: "方言を変換",
sampleData: "サンプルデータ",
+ query: "データを照会",
+ exploreSchema: "スキーマを確認",
+ executeAndExplain: "実行して解説",
+ generateNoExec: "生成のみ(実行しない)",
},
placeholders: {
generate: "クエリしたい内容を説明してください(例: 過去7日間のユーザーごとの注文数)",
@@ -1246,6 +1250,9 @@ export default withEnglishFallback({
fix: "エラーを貼り付けるか、期待する結果を説明してください",
convert: "例: PostgreSQL / MySQL / SQL Serverに変換",
sampleData: "生成するサンプルデータやテスト文を説明してください",
+ query: "照会や集計するデータを入力(例: 今月の地域別注文合計)",
+ exploreSchema: "確認したいテーブルや構造を入力(例: orders テーブルのカラムとインデックス)",
+ executeAndExplain: "任意: 解説の重点を追加",
},
editMessage: "メッセージを編集",
editResend: "再送信",
diff --git a/apps/desktop/src/i18n/locales/pt-BR.ts b/apps/desktop/src/i18n/locales/pt-BR.ts
index 4e5c280ac1..69c73a1ff8 100644
--- a/apps/desktop/src/i18n/locales/pt-BR.ts
+++ b/apps/desktop/src/i18n/locales/pt-BR.ts
@@ -1239,6 +1239,10 @@ export default withEnglishFallback({
fix: "Corrigir Erro",
convert: "Converter Dialeto",
sampleData: "Dados de Exemplo",
+ query: "Consultar dados",
+ exploreSchema: "Inspecionar esquema",
+ executeAndExplain: "Executar e explicar",
+ generateNoExec: "Gerar (sem executar)",
},
placeholders: {
generate: "Descreva o que você quer consultar, por exemplo, pedidos por usuário nos últimos 7 dias",
@@ -1247,6 +1251,9 @@ export default withEnglishFallback({
fix: "Cole o erro ou descreva o resultado esperado",
convert: "por exemplo, converter para PostgreSQL / MySQL / SQL Server",
sampleData: "Descreva os dados de exemplo ou instruções de teste a gerar",
+ query: "Descreva o que consultar ou contar, por exemplo, totais de pedidos por região este mês",
+ exploreSchema: "Descreva a tabela ou estrutura a inspecionar, por exemplo, colunas e índices de orders",
+ executeAndExplain: "Opcional: adicione o foco da explicação",
},
editMessage: "Editar mensagem",
editResend: "Reenviar",
diff --git a/apps/desktop/src/i18n/locales/zh-CN.ts b/apps/desktop/src/i18n/locales/zh-CN.ts
index 3a363733f4..5b8273c9a7 100644
--- a/apps/desktop/src/i18n/locales/zh-CN.ts
+++ b/apps/desktop/src/i18n/locales/zh-CN.ts
@@ -1212,7 +1212,7 @@ export default withEnglishFallback({
},
modeHints: {
ask: "只生成 SQL 和说明,不自动执行",
- agent: "可自动执行安全查询",
+ agent: "使用工具查询数据并基于真实结果回答",
},
fixWithAi: "用 AI 修复",
truncated: "上下文已截断",
@@ -1284,6 +1284,10 @@ export default withEnglishFallback({
fix: "修复错误",
convert: "转换方言",
sampleData: "生成样例",
+ query: "查询数据",
+ exploreSchema: "查看表结构",
+ executeAndExplain: "执行并解释",
+ generateNoExec: "生成但不执行",
},
placeholders: {
generate: "描述你想查询什么,例如:统计最近 7 天每个用户的订单数",
@@ -1292,6 +1296,9 @@ export default withEnglishFallback({
fix: "粘贴报错或说明期望结果",
convert: "例如:转换成 PostgreSQL / MySQL / SQL Server",
sampleData: "描述要生成的样例数据或测试语句",
+ query: "描述要查询或统计的数据,例如:本月各区域订单总额",
+ exploreSchema: "描述想了解的表或结构,例如:orders 表的字段和索引",
+ executeAndExplain: "可留空,或补充想重点解释的部分",
},
editMessage: "编辑消息",
editResend: "重新发送",
diff --git a/apps/desktop/src/i18n/locales/zh-TW.ts b/apps/desktop/src/i18n/locales/zh-TW.ts
index 6338942921..39452edb2f 100644
--- a/apps/desktop/src/i18n/locales/zh-TW.ts
+++ b/apps/desktop/src/i18n/locales/zh-TW.ts
@@ -1167,7 +1167,7 @@ export default withEnglishFallback({
},
modeHints: {
ask: "只產生 SQL 和說明,不自動執行",
- agent: "可自動執行安全查詢",
+ agent: "使用工具查詢資料並基於真實結果回答",
},
fixWithAi: "用 AI 修復",
truncated: "上下文已截斷",
@@ -1239,6 +1239,10 @@ export default withEnglishFallback({
fix: "修復錯誤",
convert: "轉換",
sampleData: "範例資料",
+ query: "查詢資料",
+ exploreSchema: "查看資料表結構",
+ executeAndExplain: "執行並解釋",
+ generateNoExec: "產生但不執行",
},
placeholders: {
generate: "描述你想查詢什麼,例如:統計最近 7 天每個使用者的訂單數",
@@ -1247,6 +1251,9 @@ export default withEnglishFallback({
fix: "貼上錯誤或說明預期結果",
convert: "例如:轉換成 PostgreSQL / MySQL / SQL Server",
sampleData: "描述要產生的範例資料或測試語句",
+ query: "描述要查詢或統計的資料,例如:本月各區域訂單總額",
+ exploreSchema: "描述想了解的資料表或結構,例如:orders 表的欄位和索引",
+ executeAndExplain: "可留空,或補充想重點解釋的部分",
},
editMessage: "編輯訊息",
editResend: "重新傳送",
diff --git a/apps/desktop/src/lib/__tests__/ai/ai.spec.ts b/apps/desktop/src/lib/__tests__/ai/ai.spec.ts
index 2335522165..8ad7ef8bc9 100644
--- a/apps/desktop/src/lib/__tests__/ai/ai.spec.ts
+++ b/apps/desktop/src/lib/__tests__/ai/ai.spec.ts
@@ -1,5 +1,6 @@
-import { describe, expect, it } from "vitest";
+import { beforeAll, describe, expect, it } from "vitest";
import { buildSystemPrompt, type AiContext } from "@/lib/ai/ai";
+import { setLocale } from "@/i18n";
function context(overrides: Partial<AiContext> = {}): AiContext {
return {
@@ -15,6 +16,12 @@ function context(overrides: Partial<AiContext> = {}): AiContext {
}
describe("AI SQL dialect prompt", () => {
+ // buildSystemPrompt picks zh/en copy via currentLocale(); pin to en so the
+ // English-string assertions are deterministic regardless of the host OS locale.
+ beforeAll(async () => {
+ await setLocale("en");
+ });
+
it("pins identifier quoting to the active database type", () => {
const prompt = buildSystemPrompt("generate", context(), "ask");
diff --git a/apps/desktop/src/lib/ai/__tests__/aiActions.spec.ts b/apps/desktop/src/lib/ai/__tests__/aiActions.spec.ts
new file mode 100644
index 0000000000..f6b8f7f1ca
--- /dev/null
+++ b/apps/desktop/src/lib/ai/__tests__/aiActions.spec.ts
@@ -0,0 +1,61 @@
+import { describe, expect, it } from "vitest";
+import { ASK_ACTIONS, AGENT_ACTIONS, defaultActionForMode, isValidActionForMode } from "@/lib/ai/ai";
+
+describe("AI action mode mapping", () => {
+ describe("defaultActionForMode", () => {
+ it("defaults Ask to generate", () => {
+ expect(defaultActionForMode("ask")).toBe("generate");
+ });
+
+ it("defaults Agent to query (not generate)", () => {
+ // The whole point of the feature: Agent mode must not default to SQL generation.
+ expect(defaultActionForMode("agent")).toBe("query");
+ });
+ });
+
+ describe("isValidActionForMode", () => {
+ it("accepts generate in both modes (shared SQL-only action)", () => {
+ expect(isValidActionForMode("generate", "ask")).toBe(true);
+ expect(isValidActionForMode("generate", "agent")).toBe(true);
+ });
+
+ it("accepts every Ask action in Ask mode", () => {
+ for (const action of ASK_ACTIONS) {
+ expect(isValidActionForMode(action, "ask")).toBe(true);
+ }
+ });
+
+ it("accepts every Agent action in Agent mode", () => {
+ for (const action of AGENT_ACTIONS) {
+ expect(isValidActionForMode(action, "agent")).toBe(true);
+ }
+ });
+
+ it("rejects Ask-only actions in Agent mode", () => {
+ // explain/optimize/fix/convert/sampleData are SQL-text operations and must not
+ // appear in the Agent (task-oriented) menu.
+ for (const action of ["explain", "optimize", "fix", "convert", "sampleData"] as const) {
+ expect(isValidActionForMode(action, "agent")).toBe(false);
+ }
+ });
+
+ it("rejects Agent-only actions in Ask mode", () => {
+ for (const action of ["query", "exploreSchema", "executeAndExplain"] as const) {
+ expect(isValidActionForMode(action, "ask")).toBe(false);
+ }
+ });
+ });
+
+ describe("action sets", () => {
+ it("Ask menu keeps the SQL-producing actions", () => {
+ expect(ASK_ACTIONS).toEqual(["generate", "explain", "optimize", "fix", "convert", "sampleData"]);
+ });
+
+ it("Agent menu is task-oriented, starts with query, and still offers generate", () => {
+ expect(AGENT_ACTIONS[0]).toBe("query");
+ // generate is shared so users can still request SQL-only output ("生成但不执行").
+ expect(AGENT_ACTIONS).toContain("generate");
+ expect(AGENT_ACTIONS).toEqual(["query", "exploreSchema", "executeAndExplain", "generate"]);
+ });
+ });
+});
diff --git a/apps/desktop/src/lib/ai/ai.ts b/apps/desktop/src/lib/ai/ai.ts
index dbf6def28b..b61c85c717 100644
--- a/apps/desktop/src/lib/ai/ai.ts
+++ b/apps/desktop/src/lib/ai/ai.ts
@@ -32,9 +32,26 @@ function dbLabel(dbType: DatabaseType): string {
return labels[dbType] || dbType;
}
-export type AiAction = "generate" | "explain" | "optimize" | "fix" | "convert" | "sampleData";
+export type AiAction = "generate" | "explain" | "optimize" | "fix" | "convert" | "sampleData" | "query" | "exploreSchema" | "executeAndExplain";
export type AiAssistantMode = "ask" | "agent";
+/** Actions shown in the Ask mode menu: SQL-producing, never auto-run. */
+export const ASK_ACTIONS: AiAction[] = ["generate", "explain", "optimize", "fix", "convert", "sampleData"];
+
+/**
+ * Actions shown in the Agent mode menu: task-oriented, drive tool use.
+ * `generate` is shared with Ask so users can still request SQL-only output without execution.
+ */
+export const AGENT_ACTIONS: AiAction[] = ["query", "exploreSchema", "executeAndExplain", "generate"];
+
+export function defaultActionForMode(mode: AiAssistantMode): AiAction {
+ return mode === "agent" ? "query" : "generate";
+}
+
+export function isValidActionForMode(action: AiAction, mode: AiAssistantMode): boolean {
+ return (mode === "agent" ? AGENT_ACTIONS : ASK_ACTIONS).includes(action);
+}
+
function isChineseLocale(locale: Locale): boolean {
return locale === "zh-CN" || locale === "zh-TW";
}
@@ -155,6 +172,9 @@ export function buildUserPrompt(action: AiAction, context: AiContext, instructio
function actionParams(action: AiAction): { maxTokens: number } {
switch (action) {
case "explain":
+ case "query":
+ case "exploreSchema":
+ case "executeAndExplain":
return { maxTokens: 3200 };
case "sampleData":
return { maxTokens: 2400 };
diff --git a/apps/desktop/src/lib/ai/aiAgentPlan.ts b/apps/desktop/src/lib/ai/aiAgentPlan.ts
index 97198aa77e..7958462ca9 100644
--- a/apps/desktop/src/lib/ai/aiAgentPlan.ts
+++ b/apps/desktop/src/lib/ai/aiAgentPlan.ts
@@ -13,7 +13,7 @@ export type AiAgentStep =
| {
kind: "execute_sql";
status: "skipped";
- reason: "ask_mode" | "no_sql" | "no_execution_intent" | "unsupported_action" | "blocked_by_policy" | "requires_confirmation";
+ reason: "ask_mode" | "no_sql" | "no_execution_intent" | "blocked_by_policy" | "requires_confirmation";
};
export interface AiAgentPlanInput {
@@ -48,8 +48,11 @@ export function buildAiAgentPlan(input: AiAgentPlanInput): AiAgentPlan {
return { steps };
}
+ // Task-oriented Agent actions (query / exploreSchema / executeAndExplain) execute via the
+ // execute_query tool, surfaced through real-time tool-call events — not via this legacy
+ // client-side auto-execute path. Only render the generated SQL; do not drive client-side
+ // execution for these actions.
if (input.action !== "generate") {
- steps.push({ kind: "execute_sql", status: "skipped", reason: "unsupported_action" });
return { steps };
}
diff --git a/apps/desktop/src/lib/ai/aiAgentStepPresentation.ts b/apps/desktop/src/lib/ai/aiAgentStepPresentation.ts
index d4408b6931..dc0c59b18d 100644
--- a/apps/desktop/src/lib/ai/aiAgentStepPresentation.ts
+++ b/apps/desktop/src/lib/ai/aiAgentStepPresentation.ts
@@ -109,8 +109,6 @@ function skippedTitleKey(reason: string): string {
return "ai.agentStepTitles.requiresConfirmation";
case "ask_mode":
return "ai.agentStepTitles.askMode";
- case "unsupported_action":
- return "ai.agentStepTitles.unsupportedAction";
case "no_sql":
return "ai.agentStepTitles.noSql";
default:
diff --git a/apps/desktop/src/lib/ai/aiSkills.ts b/apps/desktop/src/lib/ai/aiSkills.ts
index b91e75bf9e..475f620a04 100644
--- a/apps/desktop/src/lib/ai/aiSkills.ts
+++ b/apps/desktop/src/lib/ai/aiSkills.ts
@@ -157,6 +157,72 @@ export const AI_SKILL_DEFINITIONS: AiSkillDefinition[] = [
zh: ["输出格式:先给安全的示例 SQL,再说明哪些值是模拟数据。"],
},
},
+ {
+ id: "query_data",
+ action: "query",
+ title: {
+ en: "Query Data",
+ zh: "查询数据",
+ },
+ riskPolicy: "readonly",
+ contextNeeds: ["schema", "indexes", "foreignKeys", "databaseDialect"],
+ userInstruction: {
+ en: "Query or aggregate data per the user's request. Confirm structure via the schema or list_tables/get_columns, then call execute_query to run a read-only query and obtain real results, then answer based on the actual data. Do not stop after merely outputting SQL text.",
+ zh: "根据用户请求查询或统计数据。先用 Schema 或 list_tables/get_columns 确认结构,然后调用 execute_query 执行只读查询获取真实结果,最后基于真实结果回答用户。不要只输出 SQL 文本就停止。",
+ },
+ systemRules: {
+ en: ["You MUST obtain real data via the execute_query tool before answering; do not stop at SQL text only.", "If safe execution requirements are not met, explain why first, then provide a read-only preview or a clarifying question."],
+ zh: ["必须通过 execute_query 工具获取真实数据后再回答,不要只生成 SQL 文本。", "如果安全执行条件不满足,先说明原因,再给只读预览或澄清问题。"],
+ },
+ outputContract: {
+ en: ["Output format: lead with a one-sentence conclusion based on real data, then include the SQL used in a ```sql code block. When safe execution is not possible, state the reason and ask one clarifying question."],
+ zh: ["输出格式:先给一句基于真实数据的结论,再附上所用的 SQL(放在 ```sql 代码块中)。无法安全执行时,说明原因并提出一个澄清问题。"],
+ },
+ },
+ {
+ id: "explore_schema",
+ action: "exploreSchema",
+ title: {
+ en: "Inspect Schema",
+ zh: "查看表结构",
+ },
+ riskPolicy: "readonly",
+ contextNeeds: ["schema", "databaseDialect"],
+ userInstruction: {
+ en: "Help the user understand the database or table structure. Prefer the loaded schema context; call list_tables / get_columns for more complete or authoritative definitions, then clearly summarize the structure.",
+ zh: "帮助用户了解数据库或表的结构。优先使用已加载的 Schema 上下文;需要更完整或权威的定义时调用 list_tables / get_columns,然后清晰总结结构。",
+ },
+ systemRules: {
+ en: ["Never invent tables or columns not present in the schema context.", "Use get_columns for authoritative column definitions; do not guess."],
+ zh: ["不要编造 Schema 中不存在的表或列。", "需要权威列定义时使用 get_columns,不要猜测。"],
+ },
+ outputContract: {
+ en: ["Output format: summarize the key structural points first, then list relevant tables/columns and their purpose. If further exploration helps, include a read-only metadata query."],
+ zh: ["输出格式:先概括结构要点,再列出相关表/列及其用途。如需进一步探索,附一个只读元数据查询。"],
+ },
+ },
+ {
+ id: "execute_and_explain",
+ action: "executeAndExplain",
+ title: {
+ en: "Run & Explain",
+ zh: "执行并解释",
+ },
+ riskPolicy: "readonly",
+ contextNeeds: ["currentSql", "schema", "indexes", "foreignKeys", "lastResultPreview", "databaseDialect"],
+ userInstruction: {
+ en: "Execute the current SQL and explain the results. First call execute_query to run the current SQL, then explain the query meaning, data characteristics, and notable points based on the real results.",
+ zh: "执行当前的 SQL 并解释结果。先调用 execute_query 运行当前 SQL,再基于真实结果解释查询含义、数据特征和值得注意的点。",
+ },
+ systemRules: {
+ en: ["Only SELECT/WITH/SHOW/DESCRIBE/EXPLAIN can be executed. If the current SQL is a write operation, do not execute; explain its impact instead.", "Base explanations on real execution results; do not speculate about data."],
+ zh: ["只有 SELECT/WITH/SHOW/DESCRIBE/EXPLAIN 可执行。如果当前 SQL 是写操作,不要执行,改为解释其影响。", "解释要基于真实执行结果,不要凭空推测数据。"],
+ },
+ outputContract: {
+ en: ["Output format: lead with an execution-result summary, then step through the key data and its meaning."],
+ zh: ["输出格式:先给执行结果概要,再逐步解释关键数据和含义。"],
+ },
+ },
];
export function aiSkillForAction(action: AiAction): AiSkillDefinition {
diff --git a/crates/dbx-core/src/agent_loop.rs b/crates/dbx-core/src/agent_loop.rs
index 183fb3660e..5f3d1d7d65 100644
--- a/crates/dbx-core/src/agent_loop.rs
+++ b/crates/dbx-core/src/agent_loop.rs
@@ -470,10 +470,14 @@ fn augment_system_prompt_with_task_contract(
let user_request = contract.user_request.as_deref().unwrap_or("(not provided)");
let mode_rule = if action_requires_sql_deliverable(action) {
"This is a SQL-producing action: produce the final SQL in a fenced ```sql code block. Use tools only as intermediate evidence for schema/dialect; do not stop at a tool-result summary. In Agent mode, execute a query only when the original request explicitly asks for real data/results, not when it merely asks to generate SQL."
- } else if is_agent_mode {
- "For data-query intents, obtain real results with execute_query when safe; otherwise state the blocker."
} else {
- "In Ask mode, produce SQL/explanation only and do not claim execution."
+ match action.to_ascii_lowercase().as_str() {
+ "query" => "This is a data-query task: call execute_query to obtain real results, then answer based on the actual data. Do not stop after merely outputting SQL text.",
+ "exploreschema" => "This is a schema-inspection task: use list_tables/get_columns to obtain authoritative structure, then summarize. Do not execute data queries unless the user explicitly asks for data.",
+ "executeandexplain" => "This is an execute-and-explain task: call execute_query to run the current SQL, then explain the real results.",
+ _ if is_agent_mode => "For data-query intents, obtain real results with execute_query when safe; otherwise state the blocker.",
+ _ => "In Ask mode, produce SQL/explanation only and do not claim execution.",
+ }
};
format!(
@@ -517,10 +521,14 @@ fn build_contract_repair_prompt(task_contract: Option<&AiTaskContract>, is_agent
let user_request = task_contract.and_then(|c| c.user_request.as_deref()).unwrap_or("(not provided)");
let mode_rule = if action_requires_sql_deliverable(action) {
"For this SQL-producing action, produce SQL in a fenced ```sql code block. Tool results are evidence only; do not answer by summarizing schema/tool output. Execute a query only when the original request explicitly asks for real data/results."
- } else if is_agent_mode {
- "If the original request asks for real data and it can be answered safely, call execute_query before the final answer."
} else {
- "In Ask mode, generate SQL and concise explanation only; do not claim the SQL was executed."
+ match action.to_ascii_lowercase().as_str() {
+ "query" => "For this data-query task, call execute_query and answer based on real data; do not stop at SQL text or a schema summary.",
+ "exploreschema" => "For this schema-inspection task, summarize real structure from list_tables/get_columns; do not invent columns.",
+ "executeandexplain" => "For this execute-and-explain task, run the current SQL via execute_query and explain the real results.",
+ _ if is_agent_mode => "If the original request asks for real data and it can be answered safely, call execute_query before the final answer.",
+ _ => "In Ask mode, generate SQL and concise explanation only; do not claim the SQL was executed.",
+ }
};
format!(
@@ -1284,4 +1292,67 @@ mod tests {
assert_eq!(events.len(), 1);
assert!(matches!(&events[0], AgentEvent::TextDelta { .. }));
}
+
+ // --- Agent task-action contract tests (query / exploreSchema / executeAndExplain) ---
+
+ fn contract_for(action: &str, user_request: &str, mode: &str) -> AiTaskContract {
+ AiTaskContract {
+ action: Some(action.to_string()),
+ mode: Some(mode.to_string()),
+ user_request: Some(user_request.to_string()),
+ }
+ }
+
+ #[test]
+ fn query_action_contract_requires_execute_query() {
+ let contract = contract_for("query", "统计今天订单数", "agent");
+ let prompt = augment_system_prompt_with_task_contract("base", Some(&contract), true);
+
+ assert!(prompt.contains("data-query task"), "prompt should mark this as a data-query task");
+ assert!(prompt.contains("call execute_query"), "prompt should instruct the LLM to call execute_query");
+ assert!(!prompt.contains("SQL-producing action"), "query must not be treated as a SQL-producing action");
+ }
+
+ #[test]
+ fn explore_schema_contract_uses_metadata_tools_not_execute_query() {
+ let contract = contract_for("exploreSchema", "看一下 orders 表的结构", "agent");
+ let prompt = augment_system_prompt_with_task_contract("base", Some(&contract), true);
+
+ assert!(prompt.contains("schema-inspection task"));
+ assert!(prompt.contains("list_tables/get_columns"));
+ assert!(prompt.contains("Do not execute data queries"));
+ }
+
+ #[test]
+ fn execute_and_explain_contract_runs_current_sql() {
+ let contract = contract_for("executeAndExplain", "执行并解释当前 SQL", "agent");
+ let prompt = augment_system_prompt_with_task_contract("base", Some(&contract), true);
+
+ assert!(prompt.contains("execute-and-explain task"));
+ assert!(prompt.contains("run the current SQL"));
+ }
+
+ #[test]
+ fn task_actions_do_not_require_sql_deliverable() {
+ // query / exploreSchema / executeAndExplain are task-oriented, not SQL-producing:
+ // a final answer without a fenced SQL block must still satisfy the contract.
+ let answer_without_sql = "今天共有 42 笔订单。";
+ for action in ["query", "exploreSchema", "executeAndExplain"] {
+ let contract = contract_for(action, "统计今天订单数", "agent");
+ assert_eq!(
+ validate_final_answer(Some(&contract), answer_without_sql),
+ FinalAnswerCheck::Satisfied,
+ "action {action} should not require a SQL deliverable",
+ );
+ }
+ }
+
+ #[test]
+ fn query_action_repair_prompt_targets_execute_query() {
+ let contract = contract_for("query", "统计今天订单数", "agent");
+ let repair = build_contract_repair_prompt(Some(&contract), true, "previous answer did not execute");
+
+ assert!(repair.contains("data-query task"));
+ assert!(repair.contains("call execute_query"));
+ }
}
diff --git a/packages/app-tests/aiAgentPlan.test.ts b/packages/app-tests/aiAgentPlan.test.ts
index a6382ca774..64dd046244 100644
--- a/packages/app-tests/aiAgentPlan.test.ts
+++ b/packages/app-tests/aiAgentPlan.test.ts
@@ -105,12 +105,23 @@ test("non-generate actions do not execute even in agent mode", () => {
assert.deepEqual(plan.steps, [
{ kind: "generate_sql", status: "done", sql: "SELECT count(*) FROM users" },
- { kind: "execute_sql", status: "skipped", reason: "unsupported_action" },
]);
assert.equal(plan.executableSql, undefined);
assert.equal(plan.handoffSql, undefined);
});
+test("task-oriented Agent actions do not drive client-side execution", () => {
+ for (const action of ["query", "exploreSchema", "executeAndExplain"] as AiAction[]) {
+ const plan = buildAiAgentPlan(planInput({ action, instruction: "查一下用户数量" }));
+
+ assert.deepEqual(plan.steps, [
+ { kind: "generate_sql", status: "done", sql: "SELECT count(*) FROM users" },
+ ]);
+ assert.equal(plan.executableSql, undefined);
+ assert.equal(plan.handoffSql, undefined);
+ }
+});
+
test("agent plan blocks dangerous SQL", () => {
const plan = buildAiAgentPlan(
planInput({
diff --git a/packages/app-tests/aiSkills.test.ts b/packages/app-tests/aiSkills.test.ts
index e44fddd33a..a81cc1f869 100644
--- a/packages/app-tests/aiSkills.test.ts
+++ b/packages/app-tests/aiSkills.test.ts
@@ -3,7 +3,17 @@ import { test } from "vitest";
import type { AiAction } from "../../apps/desktop/src/lib/ai/ai.ts";
import { AI_SKILL_DEFINITIONS, aiSkillForAction } from "../../apps/desktop/src/lib/ai/aiSkills.ts";
-const actions: AiAction[] = ["generate", "explain", "optimize", "fix", "convert", "sampleData"];
+const actions: AiAction[] = [
+ "generate",
+ "explain",
+ "optimize",
+ "fix",
+ "convert",
+ "sampleData",
+ "query",
+ "exploreSchema",
+ "executeAndExplain",
+];
test("defines one internal AI skill per assistant action", () => {
assert.deepEqual(AI_SKILL_DEFINITIONS.map((skill) => skill.action).sort(), [...actions].sort());
@@ -12,14 +22,14 @@ test("defines one internal AI skill per assistant action", () => {
const skill = aiSkillForAction(action);
assert.equal(skill.action, action);
- assert.ok(skill.id.endsWith("_sql") || skill.id === "sample_data");
+ assert.match(skill.id, /^[a-z][a-z0-9_]*$/);
assert.ok(skill.title.zh);
assert.ok(skill.title.en);
assert.ok(skill.contextNeeds.length > 0);
assert.ok(skill.systemRules.zh.length > 0);
assert.ok(skill.systemRules.en.length > 0);
- assert.ok(skill.userInstruction.zh.includes("SQL"));
- assert.ok(skill.userInstruction.en.includes("SQL"));
+ assert.ok(skill.userInstruction.zh.length > 0);
+ assert.ok(skill.userInstruction.en.length > 0);
}
});