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。
TypeScript aicliclickhousedatabasedatabase-clientdatabase-managementdockerguimcpmongodbmysqlpostgresqlredisrustsql-serversqlitetaurivue
fix(ai): list @ table mentions from every selected database
Abeautifulsnowf43a99b4fef1
diff --git a/apps/desktop/src/components/editor/AiAssistant.vue b/apps/desktop/src/components/editor/AiAssistant.vueindex 2497579f0b..1120e73c88 100644--- a/apps/desktop/src/components/editor/AiAssistant.vue+++ b/apps/desktop/src/components/editor/AiAssistant.vue@@ -121,7 +121,7 @@ import { useNavigationTargets } from "@/composables/useNavigationTargets";import {buildAiContext,resolveAiDatabaseTarget,- resolveAiMentionDatabase,+ resolveAiMentionDatabases,resolveAiNamespaceSelection,resolveDefaultAiSchema,aiDatabaseTypeForConnection,@@ -223,7 +223,20 @@ import { isSchemaAware, isSingleDatabase } from "@/lib/database/databaseCapabiliimport ExplainPlanViewer from "@/components/explain/ExplainPlanViewer.vue";import { parseExplainResult, parseOracleExplainText, parseDb2ExplainText, type ParsedExplainPlan } from "@/lib/diagram/explainPlan";import { copyToClipboard } from "@/lib/common/clipboard";-import { AI_TABLE_MENTION_CANDIDATE_LIMIT, AI_TABLE_MENTION_SCHEMA_LIMIT, filterAiTableMentionCandidates, formatAiTableMention, parseAiTableMentions, type AiTableMention } from "@/lib/ai/aiTableMentions";+import {+ AI_TABLE_MENTION_CANDIDATE_LIMIT,+ AI_TABLE_MENTION_SCHEMA_LIMIT,+ aiTableMentionDatabasePlan,+ aiTableMentionKey,+ aiTableMentionQualifier,+ filterAiTableMentionCandidates,+ formatAiTableMention,+ formatAiTableMentionLabel,+ normalizeAiTableMentionQuery,+ parseAiTableMentions,+ withoutAiTableMentionsOfDatabases,+ type AiTableMention,+} from "@/lib/ai/aiTableMentions";import { handleAiTableReferenceDropEvent } from "@/lib/ai/aiTableReferenceDrop";import { DBX_TABLE_REFERENCE_DROP_EVENT, clearActiveTableReferencePayload } from "@/lib/editor/queryEditorTableDrop";import { canSubmitAiPrompt, isAiPromptImeCompositionEvent, shouldSubmitAiPromptOnKeydown } from "@/lib/ai/aiPromptKeyboard";@@ -1641,6 +1654,12 @@ let responsiveControlDragEpoch = 0;interface AiTableMentionCandidate {kind: "table";+ /**+ * Owning database (#11660): every listed candidate records the database it+ * came from. Whether it is also displayed is decided by+ * `aiTableMentionQualifier`, so a single-database list reads as before.+ */+ database?: string;schema?: string;name: string;tableType: string;@@ -2223,13 +2242,16 @@ function syncSelectedDatabases() {const active = selectedNamespace.value;const available = dbSelectOptions.value.map((option) => option.database);const retained = selectedDatabases.value.filter((database) => available.includes(database));- selectedDatabases.value = retained.length ? retained : active ? [active] : [];+ const next = retained.length ? retained : active ? [active] : [];+ removeMentionsOfDatabases(selectedDatabases.value.filter((database) => !next.includes(database)));+ selectedDatabases.value = next;}function toggleDatabase(database: string) {if (selectedDatabaseValues.value.has(database)) {if (selectedDatabases.value.length === 1) return;selectedDatabases.value = selectedDatabases.value.filter((item) => item !== database);+ removeMentionsOfDatabases([database]);} else {selectedDatabases.value = [...selectedDatabases.value, database];}@@ -2248,7 +2270,14 @@ const selectedNamespace = computed(() => (boundConnection.value ? resolveAiNameswatch(() => `${boundConnectionId.value}\u0000${boundDatabase.value}\u0000${boundSchema.value ?? ""}\u0000${conversationId.value}`,() => {- selectedDatabases.value = selectedNamespace.value ? [selectedNamespace.value] : [];+ const next = selectedNamespace.value ? [selectedNamespace.value] : [];+ // A chip naming a database this namespace change just dropped out of the+ // selection would be quoted in the message while the run refuses to read it+ // (#11660) — the same rule the deselect handler applies, at the other place+ // the selection changes. An unresolved namespace prunes nothing: the chip is+ // inert and the request-time scope guard still refuses it.+ if (next.length) removeMentionsOfDatabases(selectedDatabases.value.filter((database) => !next.includes(database)));+ selectedDatabases.value = next;},);watch([dbSelectOptions, selectedNamespace], syncSelectedDatabases, { immediate: true });@@ -2799,8 +2828,11 @@ watch({ flush: "post" },);-function mentionCacheKey(connectionId: string, database: string, query: string) {- return `${connectionId}:${database}:${savedSqlStore.version}:${query.toLowerCase()}`;+function mentionCacheKey(connectionId: string, databases: readonly string[], query: string) {+ // The whole database set is part of the key: adding, removing or reordering a+ // selected database must reload the candidates instead of serving a list that+ // describes another selection (#11660).+ return `${connectionId}:${databases.join("|")}:${savedSqlStore.version}:${query.toLowerCase()}`;}function mentionSchemaOrder(schemas: string[]): string[] {@@ -2823,26 +2855,87 @@ function activeMentionAtCursor(): { start: number; query: string } | null {return { start: beforeCursor.length - match[2].length - 1, query: match[2] };}-function normalizeMentionQuery(query: string): { schemaPrefix: string; tableFilter: string } {- const clean = query.replace(/^["`]+|["`]+$/g, "");- const dot = clean.lastIndexOf(".");- if (dot < 0) return { schemaPrefix: "", tableFilter: clean };- return {- schemaPrefix: clean.slice(0, dot).replace(/^["`]+|["`]+$/g, ""),- tableFilter: clean.slice(dot + 1).replace(/^["`]+|["`]+$/g, ""),- };+function mentionTargetDatabases(): string[] {+ return boundConnection.value ? resolveAiMentionDatabases({ database: boundDatabase.value, schema: boundSchema.value }, boundConnection.value, selectedDatabases.value) : [];}-function mentionTargetDatabase(): string {- return boundConnection.value ? resolveAiMentionDatabase({ database: boundDatabase.value, schema: boundSchema.value }, boundConnection.value, selectedDatabases.value) : "";+/** Database an unqualified mention resolves against (the head of the list). */+function mentionPrimaryDatabase(): string {+ return mentionTargetDatabases()[0] ?? "";+}++/**+ * Candidate tables of one database.+ *+ * Every candidate records the database it came from (#11660): that is what the+ * chip is later resolved against and cleaned up by. Whether the database is also+ * *displayed* is a separate rule (`aiTableMentionQualifier`), so a single+ * database list still looks exactly as it did before. Whether a candidate is+ * written as `db.table` or `db.schema.table` follows from the same+ * `isSchemaAware` gate the rest of the loading path uses.+ */+async function loadTableMentionCandidates(connectionId: string, connection: ConnectionConfig, database: string, options: { schemaPrefix: string; tableFilter: string; limit: number }): Promise<AiTableMentionCandidate[]> {+ const { schemaPrefix, tableFilter, limit } = options;+ if (isSchemaAware(connection.db_type)) {+ const schemas = mentionSchemaOrder(await listSchemas(connectionId, database));+ const filteredSchemas = schemaPrefix ? schemas.filter((schema) => schema.toLowerCase().includes(schemaPrefix.toLowerCase())) : schemas;+ const results = await Promise.all(+ filteredSchemas.slice(0, AI_TABLE_MENTION_SCHEMA_LIMIT).map(async (schema) => {+ const tables = await listTables(connectionId, database, schema, tableFilter || undefined, limit);+ return filterAiTableMentionCandidates(+ tables.map((table) => mentionCandidateFromTable(table, schema, database)),+ tableFilter,+ limit,+ );+ }),+ );+ return filterAiTableMentionCandidates(results.flat(), "", limit);+ }+ const namespace = connection.db_type === "sqlite" ? normalizeSqliteNamespace(database || connection.database, connection) : database;+ const schema = namespace || connection.database || "main";+ const tables = await listTables(connectionId, namespace, schema, tableFilter || undefined, limit);+ return filterAiTableMentionCandidates(+ tables.map((table) => mentionCandidateFromTable(table, undefined, database)),+ tableFilter,+ limit,+ );+}++/**+ * Candidate tables of several databases, loaded in parallel.+ *+ * One unreachable database (permission, timeout, dropped connection) must not+ * empty the others' candidates, so each database reports its own failure and the+ * list only fails when every database failed — the pre-existing single-database+ * outcome.+ */+async function loadMentionCandidatesForDatabases(connectionId: string, connection: ConnectionConfig, databases: readonly string[], options: { schemaPrefix: string; tableFilter: string; limit: number }): Promise<AiTableMentionCandidate[]> {+ let firstError: unknown;+ const loaded = await Promise.all(+ databases.map(async (database) => {+ try {+ return await loadTableMentionCandidates(connectionId, connection, database, options);+ } catch (error: unknown) {+ if (firstError === undefined) firstError = error;+ return null;+ }+ }),+ );+ if (loaded.every((candidates) => candidates === null)) throw firstError ?? new Error("mention candidates unavailable");+ return filterAiTableMentionCandidates(+ loaded.flatMap((candidates) => candidates ?? []),+ "",+ AI_TABLE_MENTION_CANDIDATE_LIMIT,+ );}async function loadMentionCandidates(query: string) {const connection = boundConnection.value;- const mentionDatabase = mentionTargetDatabase();- if (pluginContext.value || !connection || !supportsAiAssistantContext(connection.db_type) || !boundConnectionId.value || !mentionDatabase) return;+ const connectionId = boundConnectionId.value;+ const mentionDatabases = mentionTargetDatabases();+ if (pluginContext.value || !connection || !supportsAiAssistantContext(connection.db_type) || !connectionId || !mentionDatabases.length) return;- const key = mentionCacheKey(boundConnectionId.value, mentionDatabase, query);+ const key = mentionCacheKey(connectionId, mentionDatabases, query);if (mentionCache.value[key]) {mentionCandidates.value = mentionCache.value[key];return;@@ -2851,37 +2944,18 @@ async function loadMentionCandidates(query: string) {const requestId = ++mentionRequestId;mentionLoading.value = true;mentionError.value = "";- const { schemaPrefix, tableFilter } = normalizeMentionQuery(query);+ const { databasePrefix, schemaPrefix, tableFilter } = normalizeAiTableMentionQuery(query, mentionDatabases);+ const { databases: scopedDatabases, perDatabaseLimit } = aiTableMentionDatabasePlan(mentionDatabases, databasePrefix);let sqlFileCandidates: AiSqlFileMentionCandidate[] = [];try {sqlFileCandidates = await loadSqlFileMentionCandidates(query);- await connectionStore.ensureConnected(boundConnectionId.value);- let tableCandidates: AiMentionCandidate[] = [];- if (isSchemaAware(connection.db_type)) {- const schemas = mentionSchemaOrder(await listSchemas(boundConnectionId.value, mentionDatabase));- const filteredSchemas = schemaPrefix ? schemas.filter((schema) => schema.toLowerCase().includes(schemaPrefix.toLowerCase())) : schemas;- const results = await Promise.all(- filteredSchemas.slice(0, AI_TABLE_MENTION_SCHEMA_LIMIT).map(async (schema) => {- const tables = await listTables(boundConnectionId.value, mentionDatabase, schema, tableFilter || undefined, AI_TABLE_MENTION_CANDIDATE_LIMIT);- return filterAiTableMentionCandidates(- tables.map((table) => mentionCandidateFromTable(table, schema)),- tableFilter,- AI_TABLE_MENTION_CANDIDATE_LIMIT,- );- }),- );- tableCandidates = filterAiTableMentionCandidates(results.flat(), "", AI_TABLE_MENTION_CANDIDATE_LIMIT);- } else {- const database = connection.db_type === "sqlite" ? normalizeSqliteNamespace(mentionDatabase || connection.database, connection) : mentionDatabase;- const schema = database || connection.database || "main";- const tables = await listTables(boundConnectionId.value, database, schema, tableFilter || undefined, AI_TABLE_MENTION_CANDIDATE_LIMIT);- tableCandidates = filterAiTableMentionCandidates(- tables.map((table) => mentionCandidateFromTable(table)),- tableFilter,- AI_TABLE_MENTION_CANDIDATE_LIMIT,- );- }+ await connectionStore.ensureConnected(connectionId);+ const tableCandidates = await loadMentionCandidatesForDatabases(connectionId, connection, scopedDatabases, {+ schemaPrefix,+ tableFilter,+ limit: perDatabaseLimit,+ });if (requestId !== mentionRequestId) return;mentionCache.value[key] = [...tableCandidates, ...sqlFileCandidates];@@ -2943,25 +3017,30 @@ function savedSqlFolderPath(file: SavedSqlFile): string | undefined {return names.length ? names.join(" / ") : undefined;}-function mentionCandidateFromTable(table: TableInfo, schema?: string): AiTableMentionCandidate {- return { kind: "table", schema, name: table.name, tableType: table.table_type };+function mentionCandidateFromTable(table: TableInfo, schema: string | undefined, database: string): AiTableMentionCandidate {+ return { kind: "table", database, schema, name: table.name, tableType: table.table_type };}function mentionCandidateName(candidate: AiMentionCandidate) {if (candidate.kind === "sqlFile") return candidate.name;- return [candidate.schema, candidate.name].filter(Boolean).join(".");+ return formatAiTableMentionLabel(candidate.schema, candidate.name, mentionQualifier(candidate.database));}function mentionDisplayName(mention: AiPromptMentionChip) {if (mention.kind === "sqlFile") return mention.name;- return [mention.schema, mention.table].filter(Boolean).join(".");+ return formatAiTableMentionLabel(mention.schema, mention.table, mentionQualifier(mention.database));+}++/** Whether a mention names its database in the label/raw text, not just owns it. */+function mentionQualifier(database: string | undefined): string | undefined {+ return aiTableMentionQualifier(database, mentionPrimaryDatabase(), mentionTargetDatabases().length > 1);}function promptMentionChipsFromMessage(message: ChatMessage): AiPromptMentionChip[] {const chips: AiPromptMentionChip[] = [];for (const mention of message.mentions || []) {if (mention.kind === "sqlFile") chips.push({ kind: "sqlFile", raw: mention.raw, id: mention.id, name: mention.name });- if (mention.kind === "table") chips.push({ kind: "table", raw: mention.raw, schema: mention.schema, table: mention.table });+ if (mention.kind === "table") chips.push({ kind: "table", raw: mention.raw, database: mention.database, schema: mention.schema, table: mention.table });}return chips;}@@ -3063,10 +3142,28 @@ function addSelectedMention(candidate: AiMentionCandidate) {selectedSqlFileMentions.value.push({ kind: "sqlFile", raw, id: candidate.id, name: candidate.name });return;}- const raw = formatAiTableMention(candidate.schema, candidate.name);- const key = `${candidate.schema || ""}.${candidate.name}`.toLowerCase();- if (selectedMentions.value.some((mention) => `${mention.schema || ""}.${mention.table}`.toLowerCase() === key)) return;- selectedMentions.value.push({ raw, schema: candidate.schema, table: candidate.name });+ // The owning database is recorded only from the caller (#11660) — a candidate+ // carries the database it was listed from, and the external entrypoints pass+ // the namespace their table came from. Guessing it from the binding here would+ // capture whatever the binding was mid-retarget, so a caller that names none+ // leaves the mention unqualified and resolved at request time, as before.+ const ownDatabase = candidate.database;+ const raw = formatAiTableMention(candidate.schema, candidate.name, mentionQualifier(ownDatabase));+ // Both sides key an unqualified mention by the primary database, so a caller+ // that names no database cannot add a second chip for a table already listed.+ const primaryDatabase = mentionPrimaryDatabase();+ const key = aiTableMentionKey(candidate.schema, candidate.name, ownDatabase ?? primaryDatabase);+ if (selectedMentions.value.some((mention) => aiTableMentionKey(mention.schema, mention.table, mention.database ?? primaryDatabase) === key)) return;+ selectedMentions.value.push(ownDatabase ? { raw, database: ownDatabase, schema: candidate.schema, table: candidate.name } : { raw, schema: candidate.schema, table: candidate.name });+}++/**+ * Drops the mentions of databases the composer no longer selects (#11660).+ * Keeping the chip would send a reference the run has to discard, so the user+ * would see the table quoted in their message and missing from the request.+ */+function removeMentionsOfDatabases(databases: Iterable<string>) {+ selectedMentions.value = withoutAiTableMentionsOfDatabases(selectedMentions.value, databases);}function formatMentionCandidateType(candidate: AiMentionCandidate) {@@ -3109,13 +3206,15 @@ function selectedMessageMentions(tableMentions: AiTableMention[], sqlFileMention// Only ever reached for the visible conversation: every caller passes empty// arrays for a background/auto send (see the `auto ? [] : …` locals in send()).const connectionId = boundConnectionId.value;- const database = mentionTargetDatabase() || boundConnection.value?.database || "";+ const database = mentionPrimaryDatabase() || boundConnection.value?.database || "";return [...tableMentions.map((mention) => ({kind: "table" as const,raw: mention.raw,connectionId,- database,+ // A mention of another selected database keeps its own database, so the+ // chip reopens the table it actually names (#11660).+ database: mention.database || database,schema: mention.schema,table: mention.table,})),@@ -3210,7 +3309,7 @@ function refreshMentionState() {commandOpen.value = false;const mention = activeMentionAtCursor();- if (!mention || !boundConnection.value || !mentionTargetDatabase()) {+ if (!mention || !boundConnection.value || !mentionTargetDatabases().length) {mentionOpen.value = false;return;}@@ -3668,7 +3767,10 @@ function onTableReferenceDropEvent(event: Event) {// contract, which existed only because the panel's connection was whatever// tab was active and there was nothing to retarget — #9902.)void bindConversation({ connectionId: payload.connectionId, database: payload.database, schema: payload.schema });- addSelectedMention({ kind: "table", schema: mention.schema, name: mention.table, tableType: "table" });+ // The dropped table's own database rides along (#11660): the drop retargets+ // the conversation, but with several databases selected the chip still has+ // to name the database the table came from.+ addSelectedMention({ kind: "table", database: payload.database, schema: mention.schema, name: mention.table, tableType: "table" });clearActiveTableReferencePayload(payload);nextTick(() => promptTextareaRef.value?.focus());},@@ -3967,7 +4069,7 @@ async function send() {// 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)];+ const mentionedTables = [...selectedTableMentions, ...parseAiTableMentions(text, runDatabases)];const modelInstruction = buildAiModelInstruction({tableMentionRaws: selectedTableMentions.map((mention) => mention.raw),sqlFileMentionRaws: selectedSqlFiles.map((mention) => mention.raw),@@ -4356,6 +4458,7 @@ async function send() {},connection,{+ databases: runDatabases,mentionedTables,sqlFiles,csvFiles: csvAttachments,@@ -6064,7 +6167,10 @@ function openExternalContext(request: AiExternalContextRequest) {selectedEditorSelections.value.push(createSelectionContext(selection, uuid()));}for (const mention of request.tableMentions ?? []) {- addSelectedMention({ kind: "table", schema: mention.schema, name: mention.table, tableType: "TABLE" });+ // The table's own namespace is the one the request targets: the binding has+ // this very moment been retargeted to it, while a mention recorded without it+ // would be resolved against whatever database the run ends up with (#11660).+ addSelectedMention({ kind: "table", database: mention.database ?? plan.binding.database, schema: mention.schema, name: mention.table, tableType: "TABLE" });}nextTick(() => promptTextareaRef.value?.focus());if (request.action) triggerAction(request.action, request.instruction);@@ -6953,7 +7059,7 @@ async function openExternalUrl(url: string) {<div v-else ref="mentionListRef" class="max-h-56 overflow-auto p-1"><buttonv-for="(candidate, index) in mentionCandidates"- :key="candidate.kind === 'sqlFile' ? `sql-file:${candidate.id}` : `table:${candidate.schema || ''}.${candidate.name}`"+ :key="candidate.kind === 'sqlFile' ? `sql-file:${candidate.id}` : `table:${candidate.database || ''}.${candidate.schema || ''}.${candidate.name}`"type="button":data-mention-index="index"class="flex w-full min-w-0 items-center gap-2 rounded px-2 py-1.5 text-left text-xs hover:bg-muted"diff --git a/apps/desktop/src/components/editor/__tests__/AiAssistant.externalContext.spec.ts b/apps/desktop/src/components/editor/__tests__/AiAssistant.externalContext.spec.tsindex 67592b786a..dad1044d18 100644--- a/apps/desktop/src/components/editor/__tests__/AiAssistant.externalContext.spec.ts+++ b/apps/desktop/src/components/editor/__tests__/AiAssistant.externalContext.spec.ts@@ -109,6 +109,16 @@ describe("external AI entries share one target rule (#10058)", () => {expect(source).toContain("openExternalContext,");});+ // #11660: a table mention recorded without its namespace resolves against+ // whatever database the run ends up with — and mid-retarget the binding still+ // reads the previous one, so the target the gesture named is the only owner the+ // panel may record.+ it("keeps a table mention bound to the namespace the gesture named", () => {+ const body = bodyOf("function openExternalContext(request: AiExternalContextRequest)");++ expect(body).toContain("mention.database ?? plan.binding.database");+ });+it("routes every external entry in App.vue through the panel's single method", () => {expect(appBodyOf("function sendSelectionToAi(tabId: string, sql: string)")).toContain("handle.openExternalContext({");expect(appBodyOf("function fixWithAi(tabId: string, errorMessage: string)")).toContain("handle.openExternalContext({");diff --git a/apps/desktop/src/lib/__tests__/ai/aiContext.spec.ts b/apps/desktop/src/lib/__tests__/ai/aiContext.spec.tsindex 0c74264314..9db74d734a 100644--- a/apps/desktop/src/lib/__tests__/ai/aiContext.spec.ts+++ b/apps/desktop/src/lib/__tests__/ai/aiContext.spec.ts@@ -1,10 +1,11 @@import { beforeEach, describe, expect, it, vi } from "vitest";-import { aiSchemaSelectionSupported, buildAiContext, resolveAiDatabaseTarget, resolveAiMentionDatabase, resolveAiNamespaceSelection, resolveDefaultAiSchema, runAgentStream } from "@/lib/ai/ai";+import { aiSchemaSelectionSupported, buildAiContext, resolveAiDatabaseTarget, resolveAiMentionDatabases, resolveAiNamespaceSelection, resolveDefaultAiSchema, runAgentStream } from "@/lib/ai/ai";import type { AiConfig } from "@/types/ai";import type { ConnectionConfig, QueryTab } from "@/types/database";const apiMock = vi.hoisted(() => ({listTables: vi.fn(),+ listSchemas: vi.fn(),getColumns: vi.fn(),listIndexes: vi.fn(),listForeignKeys: vi.fn(),@@ -100,6 +101,18 @@ describe("SQLite AI context routing", () => {expect(context.database).toBe("analytics");expect(apiMock.listTables).toHaveBeenCalledWith("sqlite-1", "analytics", "analytics");});++ // A mention records the database it was listed from verbatim; it has to be+ // read through the same namespace resolution as the run (#11660).+ it("reads a mention recorded with a path-shaped SQLite database from main", async () => {+ const context = await buildAiContext(queryTab("/tmp/real.sqlite"), sqliteConnection(), {+ mentionedTables: [{ raw: "@users", database: "/tmp/real.sqlite", table: "users" }],+ });++ expect(apiMock.getColumns).toHaveBeenCalledWith("sqlite-1", "main", "main", "users");+ expect(context.tables).toEqual([expect.objectContaining({ name: "users" })]);+ expect(context.tables[0]?.database).toBeUndefined();+ });});describe("Dameng AI context routing", () => {@@ -145,12 +158,12 @@ describe("Dameng AI context routing", () => {expect(resolveDefaultAiSchema(connection, ["REPORTING", "ARCHIVE"])).toBe("REPORTING");});- it("lists @ mention tables from the database picked in the composer", () => {+ it("lists @ mention tables from the databases picked in the composer", () => {const connection = postgresConnection();- expect(resolveAiMentionDatabase(queryTab("db_first"), connection, ["db_second"])).toBe("db_second");- expect(resolveAiMentionDatabase(queryTab("db_first"), connection, ["db_second", "db_first"])).toBe("db_second");- expect(resolveAiMentionDatabase(queryTab("db_first"), connection, [])).toBe("db_first");- expect(resolveAiMentionDatabase(queryTab("db_first"), damengConnection(), ["ignored"])).toBe("db_first");+ expect(resolveAiMentionDatabases(queryTab("db_first"), connection, ["db_second"])).toEqual(["db_second"]);+ expect(resolveAiMentionDatabases(queryTab("db_first"), connection, ["db_second", "db_first"])).toEqual(["db_second", "db_first"]);+ expect(resolveAiMentionDatabases(queryTab("db_first"), connection, [])).toEqual(["db_first"]);+ expect(resolveAiMentionDatabases(queryTab("db_first"), damengConnection(), ["ignored"])).toEqual(["db_first"]);});it("does not change non-Dameng namespace behavior", () => {@@ -158,6 +171,113 @@ describe("Dameng AI context routing", () => {});});+// #11660: several databases can be selected at once, so `@` has to list and+// resolve against every one of them instead of only the first.+describe("AI multi-database table mentions", () => {+ const tab = { ...queryTab("db_first"), connectionId: "postgres-1" };++ beforeEach(() => {+ vi.clearAllMocks();+ apiMock.listSchemas.mockResolvedValue(["public"]);+ apiMock.listTables.mockResolvedValue([]);+ apiMock.getColumns.mockResolvedValue([{ name: "id", data_type: "integer", is_nullable: false, is_primary_key: true }]);+ apiMock.listIndexes.mockResolvedValue([]);+ apiMock.listForeignKeys.mockResolvedValue([]);+ apiMock.aiAgentStream.mockResolvedValue("done");+ });++ it("lists every selected database and falls back to the tab's own one", () => {+ const connection = postgresConnection();+ expect(resolveAiMentionDatabases(queryTab("db_first"), connection, ["db_first", "db_second"])).toEqual(["db_first", "db_second"]);+ expect(resolveAiMentionDatabases(queryTab("db_first"), connection, [])).toEqual(["db_first"]);+ // Dameng's top-level selector is a schema, so the database stays the tab's.+ expect(resolveAiMentionDatabases(queryTab("db_first"), damengConnection(), ["ignored"])).toEqual(["db_first"]);+ expect(resolveAiMentionDatabases(queryTab(""), postgresConnection(""), [])).toEqual([]);+ });++ it("loads a qualified mention from its own database and qualifies it in the prompt", async () => {+ const context = await buildAiContext(tab, postgresConnection(), {+ databases: ["db_first", "db_second"],+ mentionedTables: [{ raw: "@db_second.public.logs", database: "db_second", schema: "public", table: "logs" }],+ });++ expect(apiMock.getColumns).toHaveBeenCalledWith("postgres-1", "db_second", "public", "logs");+ expect(context.tables).toEqual([expect.objectContaining({ database: "db_second", schema: "public", name: "logs" })]);++ await runAgentStream({ config: aiConfig(), action: "general", mode: "ask", instruction: "inspect logs", context }, [], vi.fn(), "session-multi");+ // The schema block has to name the database, or the model cannot tell two+ // same-named tables of different databases apart.+ expect(apiMock.aiAgentStream.mock.calls[0]?.[1]?.systemPrompt).toContain("db_second.public.logs");+ });++ it("keeps same-named tables of two databases as two entries", async () => {+ const context = await buildAiContext(tab, postgresConnection(), {+ databases: ["db_first", "db_second"],+ mentionedTables: [+ { raw: "@db_first.public.logs", database: "db_first", schema: "public", table: "logs" },+ { raw: "@db_second.public.logs", database: "db_second", schema: "public", table: "logs" },+ ],+ });++ expect(context.tables.map((table) => table.database)).toEqual(["db_first", "db_second"]);+ });++ it("does not list a mention of the tab's own table twice", async () => {+ const focused = { ...tab, tableMeta: { schema: "public", tableName: "logs", columns: [] } };+ const context = await buildAiContext(focused, postgresConnection(), {+ databases: ["db_first", "db_second"],+ mentionedTables: [{ raw: "@db_first.public.logs", database: "db_first", schema: "public", table: "logs" }],+ });++ expect(context.tables.filter((table) => table.name === "logs")).toHaveLength(1);+ });++ it("inherits the focused table's schema for a differently-cased database name", async () => {+ const focused = { ...tab, tableMeta: { schema: "public", tableName: "logs", columns: [] } };+ await buildAiContext(focused, postgresConnection(), {+ databases: ["db_first"],+ mentionedTables: [{ raw: "@DB_FIRST.logs", database: "DB_FIRST", table: "logs" }],+ });++ expect(apiMock.getColumns).toHaveBeenCalledWith("postgres-1", "DB_FIRST", "public", "logs");+ });++ it("drops a mention of a database outside the run scope", async () => {+ const context = await buildAiContext(tab, postgresConnection(), {+ databases: ["db_first"],+ mentionedTables: [{ raw: "@db_third.public.logs", database: "db_third", schema: "public", table: "logs" }],+ });++ expect(apiMock.getColumns).not.toHaveBeenCalled();+ expect(context.tables).toEqual([]);+ });++ // A mention typed without a database belongs to the run's own database, so it+ // has to deduplicate against that database's schema dump (#11660).+ it("does not repeat an unqualified mention already loaded with the schema", async () => {+ apiMock.listTables.mockResolvedValue([{ name: "users", table_type: "TABLE" }]);+ const context = await buildAiContext(tab, postgresConnection(), {+ databases: ["db_first", "db_second"],+ mentionedTables: [{ raw: "@public.users", schema: "public", table: "users" }],+ });++ expect(context.tables.filter((table) => table.name === "users")).toHaveLength(1);+ });++ it("loads a MySQL-style db.table mention from its own database", async () => {+ const connection: ConnectionConfig = { ...postgresConnection(), id: "mysql-1", name: "MySQL", db_type: "mysql", database: "app-db" };+ const context = await buildAiContext({ ...queryTab("app-db"), connectionId: "mysql-1" }, connection, {+ databases: ["app-db", "analytics"],+ mentionedTables: [{ raw: "@analytics.users", database: "analytics", table: "users" }],+ });++ // MySQL has no separate schema level, so the database doubles as the schema.+ expect(apiMock.getColumns).toHaveBeenCalledWith("mysql-1", "analytics", "analytics", "users");+ expect(context.tables).toEqual([expect.objectContaining({ database: "analytics", name: "users" })]);+ expect(context.tables[0]?.schema).toBeUndefined();+ });+});+describe("PostgreSQL AI schema routing", () => {beforeEach(() => {vi.clearAllMocks();diff --git a/apps/desktop/src/lib/__tests__/ai/aiTableMentions.spec.ts b/apps/desktop/src/lib/__tests__/ai/aiTableMentions.spec.tsindex 51da0a8f5b..66218c9afa 100644--- a/apps/desktop/src/lib/__tests__/ai/aiTableMentions.spec.ts+++ b/apps/desktop/src/lib/__tests__/ai/aiTableMentions.spec.ts@@ -1,5 +1,5 @@import { describe, expect, it } from "vitest";-import { AI_TABLE_MENTION_CANDIDATE_LIMIT, filterAiTableMentionCandidates, formatAiTableMention, parseAiTableMentions } from "@/lib/ai/aiTableMentions";+import { AI_TABLE_MENTION_CANDIDATE_LIMIT, aiTableMentionDatabasePlan, aiTableMentionQualifier, filterAiTableMentionCandidates, formatAiTableMention, formatAiTableMentionLabel, normalizeAiTableMentionQuery, parseAiTableMentions, withoutAiTableMentionsOfDatabases } from "@/lib/ai/aiTableMentions";describe("AI table mention parsing", () => {it("parses plain and schema-qualified table mentions", () => {@@ -12,6 +12,99 @@ describe("AI table mention parsing", () => {it("formats quoted table mentions when identifiers need escaping", () => {expect(formatAiTableMention("public", "order items")).toBe('@public."order items"');});++ // #11660+ it("keeps same-named tables of different selected databases apart", () => {+ expect(parseAiTableMentions("@db_first.public.logs @db_second.public.logs", ["db_first", "db_second"])).toEqual([+ { raw: "@db_first.public.logs", database: "db_first", schema: "public", table: "logs" },+ { raw: "@db_second.public.logs", database: "db_second", schema: "public", table: "logs" },+ ]);+ });++ it("reads the leading segment as a database only when it is selected", () => {+ expect(parseAiTableMentions("@db_second.logs", ["db_second"])).toEqual([{ raw: "@db_second.logs", database: "db_second", schema: undefined, table: "logs" }]);+ expect(parseAiTableMentions("@public.logs", ["db_second"])).toEqual([{ raw: "@public.logs", schema: "public", table: "logs" }]);+ });++ it("formats and labels database-qualified mentions", () => {+ expect(formatAiTableMention("public", "logs", "db_second")).toBe("@db_second.public.logs");+ expect(formatAiTableMention(undefined, "logs", "db_second")).toBe("@db_second.logs");+ expect(formatAiTableMentionLabel("public", "logs", "db_second")).toBe("db_second.public.logs");+ expect(formatAiTableMentionLabel("public", "logs")).toBe("public.logs");+ });+});++describe("AI table mention query", () => {+ it("scopes to a selected database the query names", () => {+ expect(normalizeAiTableMentionQuery("db_second.public.ord", ["db_first", "db_second"])).toEqual({ databasePrefix: "db_second", schemaPrefix: "public", tableFilter: "ord" });+ expect(normalizeAiTableMentionQuery("db_second.ord", ["db_first", "db_second"])).toEqual({ databasePrefix: "db_second", schemaPrefix: "", tableFilter: "ord" });+ });++ it("keeps the schema reading for anything else", () => {+ expect(normalizeAiTableMentionQuery("public.ord", ["db_first"])).toEqual({ schemaPrefix: "public", tableFilter: "ord" });+ expect(normalizeAiTableMentionQuery("ord", ["db_first"])).toEqual({ schemaPrefix: "", tableFilter: "ord" });+ });+});++// #11660: the candidate load has to cover every selected database, and split the+// budget so one large database cannot starve the others.+describe("AI table mention database plan", () => {+ it("searches every selected database", () => {+ expect(aiTableMentionDatabasePlan(["db_first", "db_second"], undefined)).toEqual({ databases: ["db_first", "db_second"], perDatabaseLimit: AI_TABLE_MENTION_CANDIDATE_LIMIT / 2 });+ expect(aiTableMentionDatabasePlan(["only"], undefined)).toEqual({ databases: ["only"], perDatabaseLimit: AI_TABLE_MENTION_CANDIDATE_LIMIT });+ });++ it("scopes to the database the query names, case-insensitively", () => {+ expect(aiTableMentionDatabasePlan(["db_first", "db_second"], "DB_SECOND")).toEqual({ databases: ["db_second"], perDatabaseLimit: AI_TABLE_MENTION_CANDIDATE_LIMIT });+ });++ it("gives every database an equal share of the budget", () => {+ // 200 / 3 rounds up, so the merged list may exceed the cap by two entries and+ // the caller's final filter trims it — a database is never cut to zero.+ expect(aiTableMentionDatabasePlan(["a", "b", "c"], undefined).perDatabaseLimit).toBe(67);+ expect(+ aiTableMentionDatabasePlan(+ Array.from({ length: 300 }, (_, index) => `db_${index}`),+ undefined,+ ).perDatabaseLimit,+ ).toBe(1);+ });+});++describe("AI table mention chip pruning", () => {+ it("drops only the mentions of a deselected database", () => {+ const mentions = [+ { raw: "@db_first.public.logs", database: "db_first", schema: "public", table: "logs" },+ { raw: "@db_second.public.logs", database: "db_second", schema: "public", table: "logs" },+ { raw: "@public.users", schema: "public", table: "users" },+ ];++ expect(withoutAiTableMentionsOfDatabases(mentions, ["db_second"])).toEqual([mentions[0], mentions[2]]);+ expect(withoutAiTableMentionsOfDatabases(mentions, [])).toEqual(mentions);+ // Nothing to drop hands the caller's own array back, so assigning it to the+ // composer ref cannot re-trigger the watchers behind it.+ expect(withoutAiTableMentionsOfDatabases(mentions, [])).toBe(mentions);+ });++ // A chip picked while a single database was selected has a bare label, but it+ // still records which database it came from: deselecting that database has to+ // drop the chip instead of letting it resolve against the database left over.+ it("drops a bare chip as soon as its recorded database leaves the selection", () => {+ const bareChip = { raw: "@public.users", database: "db_first", schema: "public", table: "users" };++ expect(withoutAiTableMentionsOfDatabases([bareChip], ["db_first"])).toEqual([]);+ expect(withoutAiTableMentionsOfDatabases([bareChip], ["db_second"])).toEqual([bareChip]);+ });+});++describe("AI table mention qualifier", () => {+ it("names the database only while several are in play or it is not the primary", () => {+ expect(aiTableMentionQualifier("db_first", "db_first", false)).toBeUndefined();+ expect(aiTableMentionQualifier("DB_FIRST", "db_first", false)).toBeUndefined();+ expect(aiTableMentionQualifier("db_second", "db_first", false)).toBe("db_second");+ expect(aiTableMentionQualifier("db_first", "db_first", true)).toBe("db_first");+ expect(aiTableMentionQualifier(undefined, "db_first", true)).toBeUndefined();+ });});describe("AI table mention candidates", () => {diff --git a/apps/desktop/src/lib/ai/ai.ts b/apps/desktop/src/lib/ai/ai.tsindex 00b061317e..4563c19f4f 100644--- a/apps/desktop/src/lib/ai/ai.ts+++ b/apps/desktop/src/lib/ai/ai.ts@@ -5,7 +5,7 @@ import type { ColumnInfo, ConnectionConfig, DatabaseType, ForeignKeyInfo, IndexIimport type { PromptTemplate } from "@/types/promptTemplate";import * as api from "@/lib/backend/api";import { currentLocale, type Locale } from "@/i18n";-import { aiTableMentionKey, type AiTableMention } from "@/lib/ai/aiTableMentions";+import { aiTableMentionKey, aiTableMentionQualifier, type AiTableMention } from "@/lib/ai/aiTableMentions";import { isCliProvider } from "@/lib/ai/aiConfigCandidates";import { aiSkillForAction } from "@/lib/ai/aiSkills";import { isSchemaAware } from "@/lib/database/databaseCapabilities";@@ -79,6 +79,13 @@ function isChineseLocale(locale: Locale): boolean {}export interface AiSchemaTable {+ /**+ * Owning database, set only for tables loaded through a mention that carries+ * an explicit database (#11660). Tables of the run's own database leave it+ * undefined, so the formatted schema block of a single-database run is+ * unchanged.+ */+ database?: string;schema?: string;name: string;tableType: string;@@ -549,7 +556,9 @@ function buildBasePromptLines(isZh: boolean): string[] {isZh ? "表注释和列注释是语义别名;当用户用中文业务名描述表或字段时,优先根据注释匹配真实表名和字段名。" : "Table and column comments are semantic aliases; when the user describes tables or fields by business names, prefer matching those comments to the real table and column names.",isZh ? "当用户要求分析或查看某个表时,生成 SELECT 查询获取数据,而不是查询元数据。" : "When the user asks to 'analyze' or 'look at' a table, generate a SELECT query to retrieve data, not a metadata query.",isZh ? "不要编造 Schema 中不存在的表或列。" : "Never invent tables or columns that are not in the schema context.",- isZh ? "用户输入中的 @schema.table 或 @table 表示用户明确提到的表;这些表已优先放入 Schema 上下文。" : "User input may contain @schema.table or @table mentions. Treat them as explicit table references; mentioned tables are prioritized in the schema context.",+ isZh+ ? "用户输入中的 @table、@schema.table 或 @database.schema.table 表示用户明确提到的表;在本次可选数据库范围内的这些表已优先放入 Schema 上下文。"+ : "User input may contain @table, @schema.table or @database.schema.table mentions. Treat them as explicit table references; those within the databases available to this request are prioritized in the schema context.",isZh ? "用户引用的 SQL 库文件是额外上下文;可参考其中的查询意图、业务过滤条件和 SQL 写法,但不要把它当作当前编辑器内容。" : "Referenced SQL library files are additional context. Use them for query intent, business filters, and SQL style, but do not treat them as the current editor content.",isZh ? "不要生成多语句 SQL,除非用户明确要求。不要在同一个回答里混合 SELECT 和写操作。" : "Do not generate multi-statement SQL unless the user explicitly asks for it. Do not mix SELECT statements and write operations in the same answer.",isZh ? "对于 DROP、DELETE、TRUNCATE、ALTER 或没有 WHERE 的 UPDATE,简要警告并优先提供安全的 SELECT 预览。" : "For destructive statements (DROP, DELETE, TRUNCATE, ALTER, UPDATE without WHERE), warn briefly and prefer a safer SELECT preview.",@@ -775,7 +784,7 @@ function formatSchema(context: AiContext): string {return context.tables.map((table) => {- const name = table.schema ? `${table.schema}.${table.name}` : table.name;+ const name = [table.database, table.schema, table.name].filter(Boolean).join(".");const lines: string[] = [`${name} (${table.tableType})`];const tableComment = table.comment?.trim();if (tableComment) lines.push(` Comment: ${tableComment}`);@@ -879,7 +888,7 @@ export interface AiContextTarget extends AiNamespaceSource {export async function buildAiContext(tab: AiContextTarget,connection: ConnectionConfig,- options: { maxTables?: number; maxColumnsPerTable?: number; maxIndexesPerTable?: number; maxFksPerTable?: number; mentionedTables?: AiTableMention[]; sqlFiles?: AiSqlFileContext[]; csvFiles?: AiCsvFileContext[]; selections?: AiSelectionContext[] } = {},+ options: { maxTables?: number; maxColumnsPerTable?: number; maxIndexesPerTable?: number; maxFksPerTable?: number; databases?: string[]; mentionedTables?: AiTableMention[]; sqlFiles?: AiSqlFileContext[]; csvFiles?: AiCsvFileContext[]; selections?: AiSelectionContext[] } = {},): Promise<AiContext> {const maxTables = options.maxTables ?? 50;const maxColumnsPerTable = options.maxColumnsPerTable ?? 40;@@ -888,6 +897,11 @@ export async function buildAiContext(const databaseType = aiDatabaseTypeForConnection(connection);const { database, schema } = resolveAiDatabaseTarget(tab, connection);const supportsMetadata = connection.db_type !== "plugin";+ // Databases this run may read from: the conversation's own database plus the+ // composer's selection (#11660). A mention outside that scope is dropped below+ // rather than resolved against the primary database, which would attach the+ // wrong table silently.+ const allowedDatabases = new Set([tab.database, ...(options.databases ?? [])].filter((database): database is string => !!database).map((database) => database.toLowerCase()));const tables: AiSchemaTable[] = [];const tableKeys = new Set<string>();let truncated = false;@@ -909,16 +923,26 @@ export async function buildAiContext(indexes: indexes.slice(0, maxIndexesPerTable),foreignKeys: foreignKeys.slice(0, maxFksPerTable),});- tableKeys.add(aiTableMentionKey(tab.tableMeta.schema, tName));+ // Keyed by the resolved database so a mention of this same table (#11660)+ // deduplicates against it instead of adding a second, identical entry.+ tableKeys.add(aiTableMentionKey(tab.tableMeta.schema, tName, database));truncated = tab.tableMeta.columns.length > maxColumnsPerTable;}for (const mention of supportsMetadata ? (options.mentionedTables ?? []) : []) {- const key = aiTableMentionKey(mention.schema, mention.table);+ if (mention.database && !allowedDatabases.has(mention.database.toLowerCase())) continue;+ // An unqualified mention belongs to the run's own database, so it is keyed+ // with that database — otherwise it could not deduplicate against the same+ // table loaded below under its database (#11660).+ const mentionDatabase = aiMentionDatabaseNamespace(mention, connection, database);+ const key = aiTableMentionKey(mention.schema, mention.table, mentionDatabase);if (tableKeys.has(key)) continue;- const entry = await loadMentionedTableContext(tab, connection, mention, maxColumnsPerTable, maxIndexesPerTable, maxFksPerTable).catch(() => undefined);+ const entry = await loadMentionedTableContext(tab, connection, mention, maxColumnsPerTable, maxIndexesPerTable, maxFksPerTable, allowedDatabases.size > 1).catch(() => undefined);if (!entry) continue;- tableKeys.add(aiTableMentionKey(entry.schema, entry.name));+ // The entry itself only carries a database while it has to be displayed with+ // one, but the deduplication key always uses the database it was read from,+ // so the same table cannot be added twice (#11660).+ tableKeys.add(aiTableMentionKey(entry.schema, entry.name, mentionDatabase));tables.push(entry);}@@ -938,11 +962,11 @@ export async function buildAiContext(comment: currentCollection.dimension ? `${currentCollection.dimension}d vector` : undefined,columns: [],});- tableKeys.add(aiTableMentionKey(undefined, currentCollection.name));+ tableKeys.add(aiTableMentionKey(undefined, currentCollection.name, database));}for (const col of collections.slice(0, maxTables)) {- const key = aiTableMentionKey(undefined, col.name);+ const key = aiTableMentionKey(undefined, col.name, database);if (tableKeys.has(key)) continue;tables.push({name: col.name,@@ -986,7 +1010,7 @@ export async function buildAiContext(for (const meta of metaResults) {if (meta._truncatedCols) truncated = true;const { _truncatedCols, ...entry } = meta;- const key = aiTableMentionKey(entry.schema, entry.name);+ const key = aiTableMentionKey(entry.schema, entry.name, database);if (tableKeys.has(key)) continue;tableKeys.add(key);tables.push(entry);@@ -1018,17 +1042,24 @@ export async function buildAiContext(};}-async function loadMentionedTableContext(tab: AiContextTarget, connection: ConnectionConfig, mention: AiTableMention, maxColumnsPerTable: number, maxIndexesPerTable: number, maxFksPerTable: number): Promise<AiSchemaTable | undefined> {+async function loadMentionedTableContext(tab: AiContextTarget, connection: ConnectionConfig, mention: AiTableMention, maxColumnsPerTable: number, maxIndexesPerTable: number, maxFksPerTable: number, multipleDatabases: boolean): Promise<AiSchemaTable | undefined> {const databaseType = aiDatabaseTypeForConnection(connection);- const database = aiDatabaseNamespace(tab, connection);- const schema = await resolveMentionedTableSchema(tab, connection, mention);+ const runDatabase = aiDatabaseNamespace(tab, connection);+ // A qualified mention resolves against its own database so a table of another+ // selected database is read from where it actually lives (#11660).+ const database = aiMentionDatabaseNamespace(mention, connection, runDatabase);+ const schema = await resolveMentionedTableSchema(tab, connection, mention, database);const [columns, indexes, foreignKeys, tableComment] = await Promise.all([api.getColumns(tab.connectionId, database, schema, mention.table),api.listIndexes(tab.connectionId, database, schema, mention.table).catch(() => [] as IndexInfo[]),api.listForeignKeys(tab.connectionId, database, schema, mention.table).catch(() => [] as ForeignKeyInfo[]),loadTableComment(tab.connectionId, database, schema, mention.table).catch(() => undefined),]);+ // Only named while several databases are in play, so the schema block of a+ // single-database run reads exactly as it did before (#11660).+ const qualifier = aiTableMentionQualifier(mention.database ? database : undefined, runDatabase, multipleDatabases);return {+ ...(qualifier ? { database: qualifier } : {}),schema: schema === database && !isSchemaAware(databaseType) ? undefined : schema,name: mention.table,tableType: "TABLE",@@ -1044,30 +1075,36 @@ async function loadTableComment(connectionId: string, database: string, schema:return tables.find((table) => table.name.toLowerCase() === tableName.toLowerCase())?.comment?.trim() || undefined;}-async function resolveMentionedTableSchema(tab: AiContextTarget, connection: ConnectionConfig, mention: AiTableMention): Promise<string> {+async function resolveMentionedTableSchema(tab: AiContextTarget, connection: ConnectionConfig, mention: AiTableMention, database: string): Promise<string> {if (mention.schema) return mention.schema;- if (tab.tableMeta?.tableName.toLowerCase() === mention.table.toLowerCase() && tab.tableMeta.schema) {+ // The focused-table shortcut describes the tab's own database only; a mention+ // of another database must not inherit the tab's schema (#11660). Database+ // names are compared case-insensitively, like the run scope is.+ const isTabDatabase = database.toLowerCase() === aiDatabaseNamespace(tab, connection).toLowerCase();+ if (isTabDatabase && tab.tableMeta?.tableName.toLowerCase() === mention.table.toLowerCase() && tab.tableMeta.schema) {return tab.tableMeta.schema;}if (isSchemaAware(aiDatabaseTypeForConnection(connection))) {- const database = aiDatabaseNamespace(tab, connection);- const schemas = await loadCandidateSchemas(tab, connection);+ const schemas = await loadCandidateSchemas(tab, connection, database);for (const schema of schemas) {const tables = await api.listTables(tab.connectionId, database, schema, mention.table, 10).catch(() => []);if (tables.some((table) => table.name.toLowerCase() === mention.table.toLowerCase())) return schema;}}- return aiDatabaseNamespace(tab, connection);+ return database;}-async function loadCandidateSchemas(tab: AiContextTarget, connection: ConnectionConfig): Promise<string[]> {+async function loadCandidateSchemas(tab: AiContextTarget, connection: ConnectionConfig, databaseOverride?: string): Promise<string[]> {const { database, schema } = resolveAiDatabaseTarget(tab, connection);- if (schema) return [schema];+ const scope = databaseOverride || database;+ // An explicit database override drops the tab's schema selection: it describes+ // a namespace the tab's schema does not belong to (#11660).+ if (!databaseOverride && schema) return [schema];if (isSchemaAware(aiDatabaseTypeForConnection(connection))) {- const schemas = await api.listSchemas(tab.connectionId, database);+ const schemas = await api.listSchemas(tab.connectionId, scope);return prioritizeSchemas(schemas);}- return [database];+ return [scope];}export function aiDatabaseTypeForConnection(connection: ConnectionConfig): DatabaseType {@@ -1089,6 +1126,15 @@ function aiDatabaseNamespace(tab: AiNamespaceSource, connection: ConnectionConfireturn resolveAiDatabaseTarget(tab, connection).database;}+/**+ * Database a table mention is read from: its own database when it names one,+ * otherwise the run's. The mention's own value goes through the same namespace+ * resolution as the run's, so a SQLite file-path value still reads from `main`.+ */+function aiMentionDatabaseNamespace(mention: AiTableMention, connection: ConnectionConfig, runDatabase: string): string {+ return mention.database ? aiDatabaseNamespace({ database: mention.database }, connection) : runDatabase;+}+export function resolveAiNamespaceSelection(tab: AiNamespaceSource, connection: ConnectionConfig): AiNamespaceSelection {if (connection.db_type === "dameng") {return { kind: "schema", value: tab.schema?.trim() || "" };@@ -1097,14 +1143,16 @@ export function resolveAiNamespaceSelection(tab: AiNamespaceSource, connection:}/**- * Database that `@` table mentions are listed from and resolved against. It has- * to match the request database (`selectedDatabases[0] ?? tab.database`), so a- * database picked in the composer wins over the query tab's own database.+ * Databases that `@` table mentions are listed from and resolved against: every+ * database the composer has selected, or the tab's own one when nothing is+ * selected. #9617 collapsed this to the request database; with several databases+ * selected that hid every database but the first (#11660).*/-export function resolveAiMentionDatabase(tab: AiNamespaceSource, connection: ConnectionConfig, selectedDatabases: string[]): string {- const namespace = resolveAiNamespaceSelection(tab, connection);- if (namespace.kind !== "database") return tab.database || "";- return selectedDatabases[0] ?? tab.database ?? "";+export function resolveAiMentionDatabases(tab: AiNamespaceSource, connection: ConnectionConfig, selectedDatabases: readonly string[]): string[] {+ if (resolveAiNamespaceSelection(tab, connection).kind !== "database") return tab.database ? [tab.database] : [];+ const selected = selectedDatabases.filter(Boolean);+ if (selected.length) return [...selected];+ return tab.database ? [tab.database] : [];}export function resolveDefaultAiSchema(connection: ConnectionConfig, schemaOptions: string[]): string | undefined {diff --git a/apps/desktop/src/lib/ai/aiExternalContext.ts b/apps/desktop/src/lib/ai/aiExternalContext.tsindex d6cf676444..30face8119 100644--- a/apps/desktop/src/lib/ai/aiExternalContext.ts+++ b/apps/desktop/src/lib/ai/aiExternalContext.ts@@ -24,7 +24,7 @@ export interface AiExternalContextRequest {/** Selections taken from that surface, attached as context data (R4/R8). */selections?: readonly AiSelectionContextInput[];/** Tables the gesture referred to — the object tree's "Add to AI". */- tableMentions?: readonly { schema?: string; table: string }[];+ tableMentions?: readonly { database?: string; schema?: string; table: string }[];/** Action to run immediately (query-result "Fix with AI"); omitted = fill the composer only. */action?: AiAction;/** Instruction text handed to `action`. */diff --git a/apps/desktop/src/lib/ai/aiTableMentions.ts b/apps/desktop/src/lib/ai/aiTableMentions.tsindex a487be3c0f..0fe7c68b5a 100644--- a/apps/desktop/src/lib/ai/aiTableMentions.ts+++ b/apps/desktop/src/lib/ai/aiTableMentions.ts@@ -1,5 +1,12 @@export interface AiTableMention {raw: string;+ /**+ * Owning database (#11660). Chips picked from the candidate list always record+ * it; a hand-typed mention carries it only when its leading segment names a+ * selected database. Whether it is also written into the raw text is decided+ * by `aiTableMentionQualifier`, so a single-database mention reads as before.+ */+ database?: string;schema?: string;table: string;}@@ -69,7 +76,34 @@ function readMentionToken(source: string, start: number): { raw: string; parts:return { raw, parts: usableParts, end: i };}-export function parseAiTableMentions(text: string): AiTableMention[] {+function matchesSelectedDatabase(value: string, selectedDatabases: readonly string[]): boolean {+ return selectedDatabases.some((database) => database.toLowerCase() === value.toLowerCase());+}++/**+ * Reads the database/schema/table parts of a mention token.+ *+ * A segment is read as the database only when it names one of+ * `selectedDatabases` (#11660): two parts are then `database.table` (the+ * MySQL-style name, which has no schema level), three or more are+ * `database.schema.table`. Anything else keeps the legacy reading, where the+ * last two segments are schema and table — a hand-typed name with an extra+ * leading segment stays resolvable instead of turning into a database this run+ * cannot read and being dropped.+ */+function splitMentionParts(parts: string[], selectedDatabases: readonly string[]): { database?: string; schema?: string; table: string } {+ const table = parts[parts.length - 1];+ if (parts.length === 1) return { table };+ if (parts.length === 2) {+ const leading = parts[0];+ return matchesSelectedDatabase(leading, selectedDatabases) ? { database: leading, table } : { schema: leading, table };+ }+ const schema = parts[parts.length - 2];+ const database = parts[parts.length - 3];+ return matchesSelectedDatabase(database, selectedDatabases) ? { database, schema, table } : { schema, table };+}++export function parseAiTableMentions(text: string, selectedDatabases: readonly string[] = []): AiTableMention[] {const mentions: AiTableMention[] = [];const seen = new Set<string>();@@ -78,12 +112,11 @@ export function parseAiTableMentions(text: string): AiTableMention[] {const token = readMentionToken(text, i + 1);if (!token) continue;- const table = token.parts[token.parts.length - 1];- const schema = token.parts.length > 1 ? token.parts[token.parts.length - 2] : undefined;- const key = `${schema || ""}.${table}`.toLowerCase();+ const { database, schema, table } = splitMentionParts(token.parts, selectedDatabases);+ const key = aiTableMentionKey(schema, table, database);if (!seen.has(key)) {seen.add(key);- mentions.push({ raw: `@${token.raw}`, schema, table });+ mentions.push(database ? { raw: `@${token.raw}`, database, schema, table } : { raw: `@${token.raw}`, schema, table });}i = token.end - 1;}@@ -91,8 +124,8 @@ export function parseAiTableMentions(text: string): AiTableMention[] {return mentions;}-export function formatAiTableMention(schema: string | undefined, table: string): string {- const parts = [schema, table].filter((part): part is string => !!part);+export function formatAiTableMention(schema: string | undefined, table: string, database?: string): string {+ const parts = [database, schema, table].filter((part): part is string => !!part);return `@${parts.map(formatMentionPart).join(".")}`;}@@ -101,8 +134,77 @@ function formatMentionPart(part: string): string {return `"${part.replace(/"/g, '""')}"`;}-export function aiTableMentionKey(schema: string | undefined, table: string): string {- return `${schema || ""}.${table}`.toLowerCase();+/**+ * Label shown for a mention chip or candidate row (no `@` sigil). Same argument+ * order as `formatAiTableMention` so the two cannot be mixed up.+ */+export function formatAiTableMentionLabel(schema: string | undefined, table: string, database?: string): string {+ return [database, schema, table].filter(Boolean).join(".");+}++/**+ * Database to write into a fully qualified mention, label or schema entry: one+ * is named while several databases are in play, or when it differs from the+ * run's primary database (#11660). A single-database reference to the primary+ * database stays bare, exactly as it was before multi-database mentions.+ */+export function aiTableMentionQualifier(database: string | undefined, primaryDatabase: string, multipleDatabases: boolean): string | undefined {+ if (!database) return undefined;+ if (multipleDatabases) return database;+ return database.toLowerCase() === primaryDatabase.toLowerCase() ? undefined : database;+}++export function aiTableMentionKey(schema: string | undefined, table: string, database?: string): string {+ return `${database || ""}.${schema || ""}.${table}`.toLowerCase();+}++/**+ * Splits what the user typed after `@` into an optional database prefix, an+ * optional schema prefix and the table filter.+ *+ * A leading segment is read as a database only when it names one of+ * `selectedDatabases` (#11660) — candidate labels are written in that same+ * order. Anything else keeps the legacy reading, where the part before the last+ * dot is a schema, so single-database filtering is unchanged.+ */+export function normalizeAiTableMentionQuery(query: string, selectedDatabases: readonly string[] = []): { databasePrefix?: string; schemaPrefix: string; tableFilter: string } {+ const clean = query.replace(/^["`]+|["`]+$/g, "");+ const segments = clean.split(".").map((segment) => segment.replace(/^["`]+|["`]+$/g, ""));+ const databasePrefix = segments.length > 1 && selectedDatabases.some((database) => database.toLowerCase() === segments[0].toLowerCase()) ? segments[0] : undefined;+ const scoped = (databasePrefix ? segments.slice(1) : segments).join(".");+ const dot = scoped.lastIndexOf(".");+ const parsed = dot < 0 ? { schemaPrefix: "", tableFilter: scoped } : { schemaPrefix: scoped.slice(0, dot), tableFilter: scoped.slice(dot + 1) };+ return databasePrefix ? { databasePrefix, ...parsed } : parsed;+}++/**+ * Which databases a `@` candidate load covers, and how much of the candidate+ * budget each of them gets (#11660).+ *+ * A query naming a selected database scopes the load to it; otherwise every+ * selected database is searched. The budget is split evenly so one large+ * database cannot consume all of it and push the other databases' candidates+ * out of the list.+ */+export function aiTableMentionDatabasePlan(databases: readonly string[], databasePrefix: string | undefined, totalLimit = AI_TABLE_MENTION_CANDIDATE_LIMIT): { databases: string[]; perDatabaseLimit: number } {+ const scoped = databasePrefix ? databases.filter((database) => database.toLowerCase() === databasePrefix.toLowerCase()) : [...databases];+ return { databases: scoped, perDatabaseLimit: Math.max(1, Math.ceil(totalLimit / Math.max(scoped.length, 1))) };+}++/**+ * Drops the mentions that belong to a database the composer no longer selects+ * (#11660): the reference could not be resolved any more, so the chip would+ * quote a table that never reaches the request. Unqualified mentions+ * (single-database mode) are always kept.+ */+export function withoutAiTableMentionsOfDatabases<T extends AiTableMention>(mentions: T[], removedDatabases: Iterable<string>): T[] {+ const removed = new Set<string>();+ for (const database of removedDatabases) removed.add(database.toLowerCase());+ // Handing back the caller's own array when nothing is dropped keeps the+ // composer's ref identity stable, so a caller that runs on every option change+ // does not re-trigger the watchers behind it.+ if (!removed.size) return mentions;+ return mentions.filter((mention) => !mention.database || !removed.has(mention.database.toLowerCase()));}export function filterAiTableMentionCandidates<T extends { name: string }>(candidates: T[], tableFilter: string, limit = AI_TABLE_MENTION_CANDIDATE_LIMIT): T[] {diff --git a/packages/app-tests/aiPrompt.test.ts b/packages/app-tests/aiPrompt.test.tsindex d44399a5d7..f12f94367b 100644--- a/packages/app-tests/aiPrompt.test.ts+++ b/packages/app-tests/aiPrompt.test.ts@@ -95,6 +95,16 @@ test("focused table context is not presented as a complete table list", () => {assert.doesNotMatch(prompt, /Schema context is complete\./);});+// #11660: with several databases selected a mention names its own database, so+// the prompt has to document that form and scope the "prioritized" claim to the+// databases this request may actually read.+test("prompt documents database-qualified table mentions within the run scope", () => {+ const prompt = buildSystemPrompt("generate", context(), "ask");++ assert.match(prompt, /@table、@schema\.table 或 @database\.schema\.table/);+ assert.match(prompt, /在本次可选数据库范围内的这些表已优先放入 Schema 上下文/);+});+test("prompt enforces database dialect and single executable statement safety", () => {const prompt = buildSystemPrompt("generate", context({ databaseType: "sqlserver" }), "agent");diff --git a/packages/app-tests/aiTableMentions.test.ts b/packages/app-tests/aiTableMentions.test.tsindex 09d5a6fb41..813eebe9d7 100644--- a/packages/app-tests/aiTableMentions.test.ts+++ b/packages/app-tests/aiTableMentions.test.ts@@ -1,6 +1,6 @@import { strict as assert } from "node:assert";import { test } from "vitest";-import { formatAiTableMention, parseAiTableMentions } from "../../apps/desktop/src/lib/ai/aiTableMentions.ts";+import { formatAiTableMention, normalizeAiTableMentionQuery, parseAiTableMentions, withoutAiTableMentionsOfDatabases } from "../../apps/desktop/src/lib/ai/aiTableMentions.ts";test("parses simple and schema-qualified AI table mentions", () => {assert.deepEqual(parseAiTableMentions("show @users and join @public.orders"), [@@ -24,3 +24,54 @@ test("formats AI table mentions with quotes only when needed", () => {assert.equal(formatAiTableMention("public", "users"), "@public.users");assert.equal(formatAiTableMention("sales schema", "order items"), '@"sales schema"."order items"');});++// #11660: with several databases selected a mention has to name its own+// database, and the same table name in two databases must stay two mentions.+test("parses database-qualified AI table mentions", () => {+ assert.deepEqual(parseAiTableMentions("compare @db_first.public.logs with @db_second.public.logs", ["db_first", "db_second"]), [+ { raw: "@db_first.public.logs", database: "db_first", schema: "public", table: "logs" },+ { raw: "@db_second.public.logs", database: "db_second", schema: "public", table: "logs" },+ ]);+});++test("reads the leading segment as a database only when it is selected", () => {+ // MySQL-style names carry no schema: the selected database is the qualifier.+ assert.deepEqual(parseAiTableMentions("@analytics.users", ["analytics"]), [{ raw: "@analytics.users", database: "analytics", schema: undefined, table: "users" }]);+ // A schema that happens not to be a selected database keeps the legacy reading.+ assert.deepEqual(parseAiTableMentions("@public.users", ["analytics"]), [{ raw: "@public.users", schema: "public", table: "users" }]);+ assert.deepEqual(parseAiTableMentions("@public.users"), [{ raw: "@public.users", schema: "public", table: "users" }]);+});++// A three-part name typed by hand used to mean `schema.table` with the leading+// segment ignored; turning every one of them into a database reference (#11660)+// would drop names whose first segment is not a database this run can read.+test("keeps the legacy reading for a three-part name that is not a selected database", () => {+ assert.deepEqual(parseAiTableMentions("@catalog.public.users", ["analytics"]), [{ raw: "@catalog.public.users", schema: "public", table: "users" }]);+ assert.deepEqual(parseAiTableMentions("@catalog.public.users"), [{ raw: "@catalog.public.users", schema: "public", table: "users" }]);+ assert.deepEqual(parseAiTableMentions("@catalog.public.users", ["catalog"]), [{ raw: "@catalog.public.users", database: "catalog", schema: "public", table: "users" }]);+});++test("formats AI table mentions with the owning database", () => {+ assert.equal(formatAiTableMention("public", "users", "db_second"), "@db_second.public.users");+ assert.equal(formatAiTableMention(undefined, "users", "db_second"), "@db_second.users");+});++test("normalizes a mention query against the selected databases", () => {+ assert.deepEqual(normalizeAiTableMentionQuery("db_second.public.ord", ["db_first", "db_second"]), { databasePrefix: "db_second", schemaPrefix: "public", tableFilter: "ord" });+ assert.deepEqual(normalizeAiTableMentionQuery("public.ord", ["db_first"]), { schemaPrefix: "public", tableFilter: "ord" });+ assert.deepEqual(normalizeAiTableMentionQuery("orders", []), { schemaPrefix: "", tableFilter: "orders" });+});++test("drops the mentions of databases that are no longer selected", () => {+ const mentions = [+ { raw: "@db_first.public.logs", database: "db_first", schema: "public", table: "logs" },+ { raw: "@db_second.public.logs", database: "db_second", schema: "public", table: "logs" },+ { raw: "@public.users", schema: "public", table: "users" },+ ];+ assert.deepEqual(withoutAiTableMentionsOfDatabases(mentions, ["db_first"]), [mentions[1], mentions[2]]);+ // An unqualified (single-database) mention is never dropped.+ assert.deepEqual(withoutAiTableMentionsOfDatabases(mentions, []), mentions);+ // Nothing to drop also means nothing to allocate: the ref identity the caller+ // assigns back stays the same.+ assert.equal(withoutAiTableMentionsOfDatabases(mentions, []), mentions);+});