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:
Abeautifulsnow authored and GitHub committed 2026-07-06 14:41:39 +08:00
1 parent c819885d2e
commit 8539011f25
17 files changed
+405 -26

No files matched your search

@@ -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();