feat(ai): split Ask/Agent action menus with task-oriented Agent actions
* feat(ai): add task-oriented Agent actions with per-action contract
Introduce three Agent-native actions — query, exploreSchema,
executeAndExplain — so Agent mode surfaces task-oriented operations
instead of reusing Ask's SQL-producing action set.
- ai.ts: extend AiAction with the new actions; add ASK_ACTIONS /
AGENT_ACTIONS and defaultActionForMode / isValidActionForMode
helpers; raise maxTokens for the explanatory task actions.
- aiSkills.ts: add skill definitions (zh/en) for the three actions.
- aiAgentPlan.ts: task actions no longer emit a misleading
"unsupported_action" execute step; they execute via the
execute_query tool events, not the legacy client-side path.
- agent_loop.rs: per-action task-contract rules in both the prompt
augmentation and repair paths (query -> execute & answer from real
data; exploreSchema -> list_tables/get_columns; executeAndExplain
-> run current SQL & explain).
- i18n (en/zh-CN/zh-TW): new action labels, placeholders, a
generateNoExec label for Agent mode, and a task-oriented agent
modeHint.
es/it/ja/pt-BR have no `ai` section and fall back to `en`, matching
existing coverage.
* feat(ai): split Ask/Agent action menus with mode-aware defaults
Wire the new Agent task actions into the assistant UI so each mode
shows a distinct, intent-matching action set.
- actionButtons is now a computed returning Ask or Agent buttons
based on assistantMode. Agent menu: query / exploreSchema /
executeAndExplain / generate (labeled "生成但不执行" via
generateNoExec). Ask menu is unchanged.
- Switching mode lands on that mode's default (Ask -> generate,
Agent -> query); the shared `generate` is not carried across
because its label/semantics differ per mode. Vector DBs stay on
`generate` since their action menu is hidden and they lack SQL
tools (no execute_query contract).
- External Ask-style triggers (Fix with AI, Explain history) switch
to Ask mode when invoked from Agent mode so the action is valid
and the menu reflects what runs.
- Reset the active action to the mode default after each send.
* test(ai): cover Agent task-action contract and mode/action mapping
Lock in the deterministic parts of the Ask/Agent split so only the
LLM-behavior criteria need manual verification.
Backend (agent_loop.rs):
- query contract instructs the LLM to call execute_query and is not
treated as a SQL-producing action.
- exploreSchema contract points to list_tables/get_columns and says
not to execute data queries.
- executeAndExplain contract tells the LLM to run the current SQL.
- task actions do not require a SQL deliverable (a conclusion without
a fenced SQL block still satisfies the contract).
- query repair prompt also targets execute_query.
Frontend (aiActions.spec.ts):
- defaultActionForMode: Ask -> generate, Agent -> query (not generate).
- isValidActionForMode: generate valid in both; Ask-only actions
rejected in Agent mode and vice versa.
- ASK_ACTIONS / AGENT_ACTIONS composition (Agent menu starts with
query and still offers generate).
* fix(ai): correct action menu on mode-switched triggers and i18n gaps
Issues found during review of the Ask/Agent action split:
- [#I01] triggerAction (Fix with AI / Explain history) invoked from
Agent mode switched to Ask and set the action, but the mode-switch
watch then reset activeAction to the Ask default ("generate"),
overwriting the action just set — so the menu showed "Generate SQL"
during a fix. Add a suppressModeActionReset flag so programmatic
mode switches don't clobber the explicitly-set action.
- [#C01] Remove dead `unsupported_action` reason: buildAiAgentPlan no
longer produces it, so drop the type variant and the unreachable
skippedTitleKey case.
- [#I02] es/it/ja/pt-BR were missing the new Agent action keys
(query/exploreSchema/executeAndExplain/generateNoExec) and their
placeholders, causing English fallback in the Agent menu. Add the
translations to match each locale's existing style.
* test(ai): align app-tests with task-action split
- aiSkills: add query/exploreSchema/executeAndExplain to the expected
action set; broaden the id check (new ids are not _sql-suffixed) and
relax the userInstruction assertion (schema inspection need not mention SQL).
- aiAgentPlan: drop the unsupported_action skipped step for non-generate
actions (#C01 removed it from the plan and the reason union); add coverage
for task-oriented Agent actions not driving client-side execution.
* test(ai): pin locale in dialect prompt spec
buildSystemPrompt selects zh/en copy via currentLocale(), which reflects the
host navigator.language. The spec asserts English strings, so it failed on
zh-CN machines (e.g. Windows with a Chinese system locale) while passing on
CI's en-US runners. Pin the locale to en in beforeAll so the assertions are
deterministic regardless of the host OS locale.
This commit is contained in:
1 parent
c819885d2e
commit
8539011f25
17 files changed
+405
-26
No files matched your search
@@ -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");
|
||||
|
||||
|
||||
@@ -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"]);
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -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 };
|
||||
|
||||
@@ -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 };
|
||||
}
|
||||
|
||||
|
||||
@@ -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:
|
||||
|
||||
@@ -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 {
|
||||
|
||||
Reference in new issue
Block a user