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。

fix(ai): include the failed SQL in error repair context

Zzza400eb338df1
diff --git a/apps/desktop/src/App.vue b/apps/desktop/src/App.vue
index 717878109e..190559f16e 100644
--- a/apps/desktop/src/App.vue
+++ b/apps/desktop/src/App.vue
@@ -210,7 +210,7 @@ import { dismissOpenModalSurface } from "@/lib/ui/modalSurface";
import { hasTreeNodeDatabaseContext } from "@/lib/sidebar/treeNodeContext";
import { objectBrowserTablesToAiTreeNodes } from "@/lib/ai/objectBrowserToAiTargets";
import { aiTargetFromTab, type AiConversationBinding } from "@/lib/ai/aiConversationBinding";
-import type { AiExternalContextRequest } from "@/lib/ai/aiExternalContext";
+import { queryErrorSelection, type AiExternalContextRequest } from "@/lib/ai/aiExternalContext";
import { isSchemaAware, isSingleDatabase, supportsConnectionQueryActions, usesTreeSchemaMode } from "@/lib/database/databaseFeatureSupport";
import { codeMirrorSqlDialect, connectionObjectTreeNodeSchema, connectionUsesDatabaseObjectTreeMode, effectiveDatabaseTypeForConnection } from "@/lib/database/jdbcDialect";
import { canFormatSqlForDatabaseType, formatSqlForEditing, sqlFormatDialectForDbType } from "@/lib/sql/sqlFormatter";
@@ -2103,10 +2103,14 @@ function editorAiTarget(tabId?: string): AiConversationBinding | null {
}
function fixWithAi(tabId: string, errorMessage: string) {
+ const tab = queryStore.tabs.find((candidate) => candidate.id === tabId);
+ const selection = queryErrorSelection(tab);
+ const target = aiTargetFromTab(queryStore.activeResultExecutionTarget(tabId) ?? tab, (connectionId) => !!connectionStore.getConfig(connectionId));
openRightSidebarPanel("ai");
invokeWhenAiReady((handle) =>
handle.openExternalContext({
- target: editorAiTarget(tabId),
+ target,
+ selections: selection ? [selection] : [],
action: "fix",
instruction: errorMessage,
unresolvedKey: "ai.externalTargetUnavailable",
diff --git a/apps/desktop/src/components/editor/AiAssistant.vue b/apps/desktop/src/components/editor/AiAssistant.vue
index fb0c3d5e8c..e4c828bc68 100644
--- a/apps/desktop/src/components/editor/AiAssistant.vue
+++ b/apps/desktop/src/components/editor/AiAssistant.vue
@@ -4121,6 +4121,11 @@ async function send() {
// A background auto-send has no composer of its own, so it runs on the
// conversation's own database.
const runDatabases = connection && tab && resolveAiNamespaceSelection(tab, connection).kind === "database" ? (auto || confirmationRetargets ? [runBinding.database] : [...selectedDatabases.value]) : [];
+ // Keep the submitted SQL paired with `text` even if another external fix
+ // replaces the composer while skills or prompt templates are loading.
+ // Like other composer context, selections cannot cross a confirmation target.
+ const selectionContexts = auto || confirmationRetargets ? [] : [...selectedEditorSelections.value];
+ const composerSelectionIds = new Set(selectedEditorSelections.value.map((selection) => selection.id));
const activeConfig = activeFullConfig.value;
if (!activeConfig) {
clearPendingWriteGrant();
@@ -4357,9 +4362,6 @@ async function send() {
const selectedSqlFiles = auto || confirmationRetargets || runPluginContext ? [] : [...selectedSqlFileMentions.value];
const csvAttachments = auto || confirmationRetargets ? [] : [...selectedCsvAttachments.value];
const imageAttachments = auto || confirmationRetargets ? [] : [...selectedImageAttachments.value];
- // A selection describes the namespace the user picked it in, so it is dropped
- // exactly like the other composer context when the run targets another one.
- const selectionContexts = auto || confirmationRetargets ? [] : [...selectedEditorSelections.value];
const mentionedTables = [...selectedTableMentions, ...parseAiTableMentions(text, runDatabases)];
const modelInstruction = buildAiModelInstruction({
tableMentionRaws: selectedTableMentions.map((mention) => mention.raw),
@@ -4385,12 +4387,15 @@ async function send() {
}
historyIndex.value = -1;
draftBeforeHistory.value = "";
- prompt.value = "";
+ // Consume only this send's selections. A later fix stays staged with its
+ // error, including when both failures have the same error text.
+ const pendingSelections = selectedEditorSelections.value.filter((selection) => !composerSelectionIds.has(selection.id));
+ if (prompt.value.trim() === text && pendingSelections.length === 0) prompt.value = "";
selectedMentions.value = [];
selectedSqlFileMentions.value = [];
selectedCsvAttachments.value = [];
selectedImageAttachments.value = [];
- selectedEditorSelections.value = [];
+ selectedEditorSelections.value = pendingSelections;
}
if (autoSendVisible) scrollToBottom({ force: true });
@@ -6582,6 +6587,9 @@ function openExternalContext(request: AiExternalContextRequest) {
}
applyDraftBinding(plan.binding);
if (!plan.binding.connectionId && request.unresolvedKey) toast(t(request.unresolvedKey), 5000);
+ // An explicit failed result replaces staged SQL selections, including a
+ // previous failed query. It must not be dropped by a full selection budget.
+ if (request.action === "fix" && request.selections?.some((selection) => selection.source === "query-error")) selectedEditorSelections.value = [];
for (const selection of request.selections ?? []) {
const budgetError = selectionContextBudgetError(selectedEditorSelections.value);
if (budgetError) {
diff --git a/apps/desktop/src/components/editor/__tests__/AiAssistant.externalContext.spec.ts b/apps/desktop/src/components/editor/__tests__/AiAssistant.externalContext.spec.ts
index dad1044d18..8ec02247be 100644
--- a/apps/desktop/src/components/editor/__tests__/AiAssistant.externalContext.spec.ts
+++ b/apps/desktop/src/components/editor/__tests__/AiAssistant.externalContext.spec.ts
@@ -72,8 +72,7 @@ describe("editor selections reach the AI panel as context (#10058)", () => {
const body = bodyOf("function clearContextReferences()");
expect(body).toContain("selectedEditorSelections.value = [];");
- // send() clears it alongside the attachments, or the next turn would resend it.
- expect(bodyOf("async function send()")).toContain("selectedEditorSelections.value = [];");
+ // Mounted tests cover consuming sent selections without discarding a newer draft.
// Queuing carries text/mode/action only, so — like every other composer
// context — the selection must not stay behind looking like it was sent.
expect(bodyOf("function queueInput()")).toContain("selectedEditorSelections.value = [];");
diff --git a/apps/desktop/src/components/editor/__tests__/AiAssistant.mount.spec.ts b/apps/desktop/src/components/editor/__tests__/AiAssistant.mount.spec.ts
index 1e3f517a82..f60d064aec 100644
--- a/apps/desktop/src/components/editor/__tests__/AiAssistant.mount.spec.ts
+++ b/apps/desktop/src/components/editor/__tests__/AiAssistant.mount.spec.ts
@@ -15,9 +15,9 @@ import { beginPanelResize, endPanelResize } from "@/lib/app/panelResizeState";
import { useSettingsStore } from "@/stores/settingsStore";
import { useConnectionStore } from "@/stores/connectionStore";
import { useToast } from "@/composables/useToast";
-import type { ConnectionConfig } from "@/types/database";
+import type { ConnectionConfig, QueryTab } from "@/types/database";
import type { PluginAiRecommendationHostUpdate } from "@/lib/plugins/pluginHostBridge";
-import type { AiExternalContextRequest } from "@/lib/ai/aiExternalContext";
+import { queryErrorSelection, type AiExternalContextRequest } from "@/lib/ai/aiExternalContext";
import type { AiContext, AiRequestInput } from "@/lib/ai/ai";
import { buildAgentRequest } from "@/lib/ai/ai";
import { AI_SELECTION_CONTEXT_MAX_CHARS } from "@/lib/ai/aiAttachments";
@@ -260,11 +260,11 @@ function stubResizeObserver(): Array<{ callback: ResizeObserverCallback; targets
return observers;
}
-async function mountPanel(aiConfigLoaded: boolean, connection?: ConnectionConfig, configureSettings?: (settings: ReturnType<typeof useSettingsStore>) => void, pluginRecommendations?: PluginAiRecommendationHostUpdate, extraConnections: ConnectionConfig[] = []) {
+async function mountPanel(aiConfigLoaded: boolean, connection?: ConnectionConfig, configureSettings?: (settings: ReturnType<typeof useSettingsStore>) => void, pluginRecommendations?: PluginAiRecommendationHostUpdate, extraConnections: ConnectionConfig[] = [], tab?: QueryTab) {
const pinia = createPinia();
const errors: unknown[] = [];
const panelRef = ref<{ openExternalContext: (request: AiExternalContextRequest) => void; selectConversationById: (convId: string) => void } | null>(null);
- const app = createApp({ render: () => h(TooltipProvider, () => h(AiAssistant, { ref: panelRef, connection, pluginRecommendations })) });
+ const app = createApp({ render: () => h(TooltipProvider, () => h(AiAssistant, { ref: panelRef, connection, pluginRecommendations, tab })) });
app.use(pinia);
app.use(i18n);
app.config.errorHandler = (error) => errors.push(error);
@@ -1209,6 +1209,122 @@ describe("AiAssistant mount", () => {
expect(errors.map(String)).toEqual([]);
});
+ it("sends the failed statement with its error instead of the edited SQL or older conversation context", async () => {
+ aiAssistantMountApi.conversations = [storedConversation({ messages: [{ role: "user", content: "Explain SELECT 42 AS earlier_query" }] })];
+ const tab = {
+ id: "query-13288",
+ title: "Query 13288",
+ connectionId: "conn-a",
+ database: "db_a",
+ sql: "SELECT 99 AS edited_after_execution;",
+ resultBaseSql: "SELECT 42 AS earlier_query; SHOW INDEX;",
+ lastExecutedSql: "SELECT 100 AS another_execution;",
+ result: { columns: ["Error"], rows: [["MySQL ERROR 1064"]], execution_error: true, sourceStatement: "SHOW INDEX" },
+ } as QueryTab;
+ const { errors, panelRef } = await mountPanel(true, CONN_A, configureAiPanel, undefined, [], tab);
+ panelRef.value!.selectConversationById("conv-a");
+ await settle();
+
+ // Staged editor selections must not consume the failed statement's budget.
+ for (let index = 0; index < 8; index++) {
+ panelRef.value!.openExternalContext({ target: { connectionId: "conn-a", database: "db_a" }, selections: [{ source: "editor", content: `SELECT ${index}` }] });
+ }
+ const selection = queryErrorSelection(tab)!;
+ // A lazy panel mount or another execution can replace the result meanwhile.
+ tab.result!.sourceStatement = "SELECT 101 AS next_execution";
+ panelRef.value!.openExternalContext({
+ target: { connectionId: "conn-a", database: "db_a" },
+ action: "fix",
+ instruction: "MySQL ERROR 1064",
+ selections: [selection],
+ });
+ await vi.waitFor(() => expect(aiAssistantMountApi.runAgentStreamInputs).toHaveLength(1));
+
+ const input = aiAssistantMountApi.runAgentStreamInputs[0] as AiRequestInput;
+ expect(input.action).toBe("fix");
+ expect(input.instruction).toBe("MySQL ERROR 1064");
+ expect(input.context.currentSql).toBe("SHOW INDEX");
+ expect(input.context.selections).toEqual([{ id: expect.any(String), source: "query-error", label: "Query 13288", content: "SHOW INDEX" }]);
+ const request = buildAgentRequest(input, aiAssistantMountApi.runAgentStreamHistories[0] as never);
+ expect(request.systemPrompt).toContain("Current SQL:\nSHOW INDEX");
+ expect(request.systemPrompt).not.toContain("edited_after_execution");
+ expect(request.messages.at(-1)?.content).toContain("MySQL ERROR 1064");
+ expect(request.messages.at(-1)?.content).toContain("Source: query-error");
+ expect(request.messages.at(-1)?.content).toContain("SHOW INDEX");
+ expect(request.messages.some((message) => message.content.includes("Explain SELECT 42 AS earlier_query"))).toBe(true);
+ await settle();
+ const savedUserMessage = aiAssistantMountApi.savedConversations.at(-1)?.messages as Array<{ role: string; selectionsOmitted?: boolean; selections?: unknown[] }>;
+ expect(savedUserMessage.findLast((message) => message.role === "user")?.selectionsOmitted).toBe(true);
+ expect(savedUserMessage.findLast((message) => message.role === "user")?.selections).toBeUndefined();
+ panelRef.value!.openExternalContext({ target: { connectionId: "conn-a", database: "db_a" }, action: "explain", instruction: "Explain current SQL" });
+ await vi.waitFor(() => expect(aiAssistantMountApi.runAgentStreamInputs).toHaveLength(2));
+ const nextInput = aiAssistantMountApi.runAgentStreamInputs[1] as AiRequestInput;
+ expect(nextInput.context.currentSql).toBe("SELECT 99 AS edited_after_execution;");
+ expect(nextInput.context.selections).toBeUndefined();
+ expect(errors.map(String)).toEqual([]);
+ });
+
+ it.each(["ERROR B", "ERROR A"])("keeps concurrent fix requests paired while skills load (next error: %s)", async (nextError) => {
+ const { errors, container, panelRef } = await mountPanel(true, CONN_A, (settings) => {
+ configureAiPanel(settings);
+ settings.desktopSettings = { ...settings.desktopSettings, custom_ai_skill_auto_enabled: true };
+ });
+ let resolveCatalog!: (catalog: UserSkillsListResult) => void;
+ aiAssistantMountApi.listUserSkills.mockImplementationOnce(
+ () =>
+ new Promise((resolve) => {
+ resolveCatalog = resolve;
+ }),
+ );
+ panelRef.value!.openExternalContext({
+ target: { connectionId: "conn-a", database: "db_a" },
+ action: "fix",
+ instruction: "ERROR A",
+ selections: [{ source: "query-error", label: "Failed A", content: "SHOW INDEX" }],
+ });
+ await vi.waitFor(() => expect(resolveCatalog).toBeTypeOf("function"));
+ expect(aiAssistantMountApi.runAgentStreamInputs).toHaveLength(0);
+ panelRef.value!.openExternalContext({
+ target: { connectionId: "conn-a", database: "db_a" },
+ action: "fix",
+ instruction: nextError,
+ selections: [{ source: "query-error", label: "Failed B", content: "SELECT * FROM missing_b" }],
+ });
+ resolveCatalog({ defaultRoot: { status: "ok", skills: [] }, customRoot: null });
+ await vi.waitFor(() => expect(aiAssistantMountApi.runAgentStreamInputs).toHaveLength(1));
+ const firstInput = aiAssistantMountApi.runAgentStreamInputs[0] as AiRequestInput;
+ expect(firstInput.instruction).toBe("ERROR A");
+ expect(firstInput.context.currentSql).toBe("SHOW INDEX");
+ expect(firstInput.context.selections?.map((selection) => selection.content)).toEqual(["SHOW INDEX"]);
+ await vi.waitFor(() => expect(sendControl(container).title).not.toBe(i18n.global.t("ai.stopGenerating")));
+
+ // The busy send guard leaves the next request in the composer. Finishing
+ // the first send must not consume that newer SQL or its error text.
+ expect(container.querySelector<HTMLTextAreaElement>("textarea.ai-conversation-text")?.value).toBe(nextError);
+ expect(container.querySelector("[data-ai-selection-chips]")?.textContent).toContain("Failed B");
+ sendControl(container).click();
+ await vi.waitFor(() => expect(aiAssistantMountApi.runAgentStreamInputs).toHaveLength(2));
+ const secondInput = aiAssistantMountApi.runAgentStreamInputs[1] as AiRequestInput;
+ expect(secondInput.instruction).toBe(nextError);
+ expect(secondInput.context.currentSql).toBe("SELECT * FROM missing_b");
+ expect(secondInput.context.selections?.map((selection) => selection.content)).toEqual(["SELECT * FROM missing_b"]);
+ await settle();
+ expect(container.querySelector("[data-ai-selection-chips]")).toBeNull();
+ expect(errors.map(String)).toEqual([]);
+ });
+
+ it.each([
+ { result: { sourceStatement: "SHOW INDEX" }, resultBaseSql: "SELECT 1; SHOW INDEX;", lastExecutedSql: "SELECT 2", expected: "SHOW INDEX" },
+ { result: { sourceStatement: "SELECT * FROM missing" }, resultSortedSql: "SELECT * FROM missing ORDER BY id", resultBaseSql: "SELECT * FROM missing", lastExecutedSql: "SELECT 2", expected: "SELECT * FROM missing ORDER BY id" },
+ { resultBaseSql: "SHOW INDEX", lastExecutedSql: "SELECT 2", expected: "SHOW INDEX" },
+ { lastExecutedSql: "SHOW INDEX", expected: "SHOW INDEX" },
+ { expected: undefined },
+ ])("resolves the failed result SQL from recorded execution: $expected", ({ expected, ...recorded }) => {
+ const selection = queryErrorSelection({ title: "Query", sql: "SELECT 99 AS unsaved_edit", ...recorded } as QueryTab);
+ expect(selection?.content).toBe(expected);
+ expect(queryErrorSelection(undefined)).toBeUndefined();
+ });
+
it("opens a new chat bound to the tree node's namespace and keeps its table mention", async () => {
aiAssistantMountApi.conversations = [storedConversation()];
const { errors, container, panelRef } = await mountPanel(
diff --git a/apps/desktop/src/lib/ai/ai.ts b/apps/desktop/src/lib/ai/ai.ts
index 43cf78becd..513e63b2df 100644
--- a/apps/desktop/src/lib/ai/ai.ts
+++ b/apps/desktop/src/lib/ai/ai.ts
@@ -130,7 +130,7 @@ export interface AiInlineImageContext {
* model-facing data block name the origin without inventing a second channel —
* adding a member here must not require touching the request pipeline.
*/
-export type AiSelectionSource = "editor" | "terminal";
+export type AiSelectionSource = "editor" | "terminal" | "query-error";
/**
* A user selection attached as *context*, never as an instruction (#10058 R8).
@@ -1073,7 +1073,7 @@ export async function buildAiContext(
databaseType,
database,
schema,
- currentSql: currentCollectionName ?? tab.sql ?? "",
+ currentSql: currentCollectionName ?? options.selections?.find((selection) => selection.source === "query-error")?.content ?? tab.sql ?? "",
lastError: extractLastError(tab.result),
lastResultPreview: (options.includeQueryResult !== undefined ? options.includeQueryResult : options.excludeQueryResult !== undefined ? !options.excludeQueryResult : false) ? formatResultPreview(tab.result) : undefined,
tables,
diff --git a/apps/desktop/src/lib/ai/aiExternalContext.ts b/apps/desktop/src/lib/ai/aiExternalContext.ts
index 30face8119..3a14446e30 100644
--- a/apps/desktop/src/lib/ai/aiExternalContext.ts
+++ b/apps/desktop/src/lib/ai/aiExternalContext.ts
@@ -1,6 +1,14 @@
import type { AiAction } from "@/lib/ai/ai";
import type { AiSelectionContextInput } from "@/lib/ai/aiAttachments";
import type { AiConversationBinding } from "@/lib/ai/aiConversationBinding";
+import type { QueryTab } from "@/types/database";
+import { queryResultExecutionSql } from "@/lib/tabs/tabPresentation";
+
+/** Capture the displayed result's SQL before the panel loads or the editor changes. */
+export function queryErrorSelection(tab: Pick<QueryTab, "title" | "result" | "resultSortedSql" | "resultBaseSql" | "lastExecutedSql"> | undefined): AiSelectionContextInput | undefined {
+ const sql = tab ? queryResultExecutionSql({ ...tab, sql: "" }) : "";
+ return sql?.trim() ? { source: "query-error", label: tab?.title, content: sql } : undefined;
+}
/**
* Request shape shared by every AI entry point that lives *outside* the panel