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): keep the picked database as the chat execution target
Abeautifulsnow07c808e03ccd
diff --git a/apps/desktop/src/components/editor/AiAssistant.vue b/apps/desktop/src/components/editor/AiAssistant.vueindex 07d7c0d4fa..fb0c3d5e8c 100644--- a/apps/desktop/src/components/editor/AiAssistant.vue+++ b/apps/desktop/src/components/editor/AiAssistant.vue@@ -81,6 +81,7 @@ import {Server,ShieldCheck,Table2,+ Target,Play,Square,Sparkles,@@ -146,6 +147,7 @@ import {type CustomPromptContext,} from "@/lib/ai/ai";import { activeAiRunBinding, aiContextTargetFor, bindingForSnapshot, resolveConversationBinding, resolveExternalSendTarget, sameConversationBinding, type AiConversationBinding } from "@/lib/ai/aiConversationBinding";+import { resolveComposerDatabaseReset, toggleSelectedDatabase, withDatabaseSelected, type AiComposerScope } from "@/lib/ai/aiComposerDatabases";import type { AiExternalContextRequest } from "@/lib/ai/aiExternalContext";import {AI_IMAGE_ATTACHMENT_MAX_BYTES,@@ -2470,44 +2472,92 @@ function syncSelectedDatabases() {const active = selectedNamespace.value;const available = dbSelectOptions.value.map((option) => option.database);const retained = selectedDatabases.value.filter((database) => available.includes(database));- const next = retained.length ? retained : active ? [active] : [];+ // The target is always part of the scope: the run executes on it even when the+ // options list has not loaded yet, and @ mentions resolve against the selection+ // (#12972).+ const next = withDatabaseSelected(retained.length ? retained : active ? [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];+ // Extra selected databases are read-only context. The target is set through+ // `setDatabaseTarget` instead, so unchecking cannot silently move SQL elsewhere.+ const next = toggleSelectedDatabase(selectedDatabases.value, database, selectedNamespace.value);+ if (!next) return;+ removeMentionsOfDatabases(selectedDatabases.value.filter((database) => !next.includes(database)));+ selectedDatabases.value = next;+}++/** Drop the extra context databases. The target itself is never deselectable (#12972). */+function clearDatabaseSelection() {+ const next = selectedNamespace.value ? [selectedNamespace.value] : [];+ removeMentionsOfDatabases(selectedDatabases.value.filter((database) => !next.includes(database)));+ selectedDatabases.value = next;+}++/** Whether `database` is the namespace this chat executes on. */+function isTargetNamespace(database: string): boolean {+ return !!database && database === selectedNamespace.value;+}++/**+ * Make `database` the database this chat executes on (#12972).+ *+ * The conversation binding is the single execution target (SQL actions, agent+ * handoff, write confirmations), so retargeting writes it — it must not touch the+ * visible editor tab (#9902). Dameng's top-level namespace is a schema, so there+ * the target is the conversation schema, not its configured database.+ */+function setDatabaseTarget(database: string) {+ const connection = boundConnection.value;+ if (!connection || !database || isTargetNamespace(database)) return;+ clearContextReferences();+ selectedDatabases.value = withDatabaseSelected(selectedDatabases.value, database);+ if (resolveAiNamespaceSelection({ database: boundDatabase.value, schema: boundSchema.value }, connection).kind === "schema") {+ void rebindConversation(connection, boundDatabase.value, database);+ return;}+ // A schema belongs to one database: the previous one may not exist (or may+ // name a different namespace) in the database being retargeted, and it is used+ // for metadata reads and SQL execution alike (#12972). Re-pick it instead.+ void rebindConversation(connection, database, undefined);}const selectedNamespace = computed(() => (boundConnection.value ? resolveAiNamespaceSelection({ database: boundDatabase.value, schema: boundSchema.value }, boundConnection.value).value : ""));-// Reset the composer's database multi-select whenever the *namespace* changes.+/** Scope a selection belongs to; see `resolveComposerDatabaseReset`. */+const composerDatabaseScope = computed<AiComposerScope>(() => ({+ conversationId: conversationId.value,+ connectionId: boundConnectionId.value,+ namespace: selectedNamespace.value,+}));++// Reset the composer's database multi-select when the *scope* moves: another+// conversation, another connection, or (on schema-scoped engines such as Dameng)+// another namespace.//// `selectedDatabases` is a single ref for the whole panel, and the key used to be// `connection:tab` — so switching to another conversation kept the previous one's// selection, i.e. the "bound database" leaked between chats (#9902). The// conversation id belongs in the key; the namespace keeps a fresh, unsaved chat-// following the visible tab. A bound conversation's namespace no longer depends-// on the visible tab, so switching tabs inside it no longer resets the selection.-watch(- () => `${boundConnectionId.value}\u0000${boundDatabase.value}\u0000${boundSchema.value ?? ""}\u0000${conversationId.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;- },-);+// following the visible tab.+//+// A schema change on a database-scoped engine is deliberately NOT a scope change:+// the schema belongs to the target database, and resetting here used to move the+// chat back to the connection's default database (`postgres` on PostgreSQL) while+// the picker still showed the user's choice (#12972).+watch(composerDatabaseScope, (next, previous) => {+ const reset = resolveComposerDatabaseReset(previous, next, selectedDatabases.value);+ if (!reset) return;+ // A chip naming a database this scope 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 (reset.length) removeMentionsOfDatabases(selectedDatabases.value.filter((database) => !reset.includes(database)));+ selectedDatabases.value = reset;+});watch([dbSelectOptions, selectedNamespace], syncSelectedDatabases, { immediate: true });const showAiDatabaseSelector = computed(() => !!boundConnection.value && supportsAiAssistantContext(boundConnection.value.db_type));@@ -4690,13 +4740,14 @@ async function send() {// paying for buildAiContext() too; it can do real backend/schema work that// would be entirely wasted on an already-abandoned request.if (!generationCanContinue()) return;- const requestDatabase = runDatabases[0] ?? tab.database;+ // The run's primary database is the chat's execution target (the picker's+ // "target"), not the first database in the context selection: the model+ // must answer for the database its SQL will actually run on (#12972).+ const requestDatabase = tab.database;const context = await buildAiContext(- {- ...tab,- database: requestDatabase,- schema: runDatabases.length > 1 || requestDatabase !== tab.database ? undefined : tab.schema,- },+ // The schema belongs to the target database; extra context databases must+ // not drop it — they are only readable alongside the target.+ { ...tab, database: requestDatabase },connection,{databases: runDatabases,@@ -7269,6 +7320,11 @@ async function openExternalUrl(url: string) {<PopoverTrigger as-child><Button variant="ghost" :title="selectedDatabaseLabel" :aria-label="selectedDatabaseLabel" :class="['ai-database-selector-trigger h-5 min-w-0 max-w-64 justify-start gap-1 border-0 p-0 px-1 text-xs font-normal text-foreground/80 shadow-none', showAiSchemaSelector && 'flex-1']"><Database class="ai-database-selector-icon h-3 w-3 shrink-0 text-foreground/40" />+ <!-- Non-target databases are read-only context; the target is+ where AI SQL actions run, so it is marked in the trigger (#12972). -->+ <span v-if="selectedNamespace" class="flex shrink-0 items-center" :title="t('ai.databaseTarget')" data-ai-database-target-icon>+ <Target class="h-3 w-3 text-primary/70" />+ </span><span class="truncate">{{ selectedDatabaseLabel }}</span></Button></PopoverTrigger>@@ -7277,12 +7333,16 @@ async function openExternalUrl(url: string) {<Search class="pointer-events-none absolute left-3 h-3 w-3 text-muted-foreground" /><input v-model="databaseSearchQuery" type="search" class="h-6 w-full bg-transparent pl-5 text-xs outline-none placeholder:text-muted-foreground" :placeholder="t('ai.searchDatabases')" /></div>- <button v-if="selectedDatabases.length > 1" type="button" class="mb-1 flex w-full items-center justify-end gap-1 border-b px-2 py-1 text-xs" @click.stop="selectedDatabases = []"><X class="h-3 w-3" />{{ t("ai.clearDatabaseSelection") }}</button>+ <button v-if="selectedDatabases.length > 1" type="button" class="mb-1 flex w-full items-center justify-end gap-1 border-b px-2 py-1 text-xs" @click.stop="clearDatabaseSelection()"><X class="h-3 w-3" />{{ t("ai.clearDatabaseSelection") }}</button><div class="max-h-64 overflow-y-auto overscroll-contain">- <button v-for="option in filteredDbSelectOptions" :key="option.value" type="button" :title="option.label" class="flex w-full min-w-0 items-center gap-2 rounded-sm px-2 py-1.5 text-left text-sm hover:bg-muted" @click="toggleDatabase(option.database)">- <Check :class="['h-4 w-4 shrink-0', selectedDatabaseValues.has(option.database) ? 'opacity-100' : 'opacity-0']" />- <span class="min-w-0 flex-1 truncate">{{ option.label }}</span>- </button>+ <div v-for="option in filteredDbSelectOptions" :key="option.value" class="flex w-full min-w-0 items-center gap-1 rounded-sm pr-1 text-sm hover:bg-muted">+ <button type="button" :title="option.label" class="flex min-w-0 flex-1 items-center gap-2 px-2 py-1.5 text-left" @click="toggleDatabase(option.database)">+ <Check :class="['h-4 w-4 shrink-0', selectedDatabaseValues.has(option.database) ? 'opacity-100' : 'opacity-0']" />+ <span class="min-w-0 flex-1 truncate">{{ option.label }}</span>+ </button>+ <span v-if="isTargetNamespace(option.database)" class="shrink-0 rounded-sm bg-primary/10 px-1.5 py-0.5 text-[10px] font-medium text-primary" data-ai-database-target>{{ t("ai.databaseTarget") }}</span>+ <button v-else type="button" class="shrink-0 rounded-sm px-1.5 py-0.5 text-[10px] text-muted-foreground hover:bg-foreground/5 hover:text-foreground" data-ai-database-target-action @click.stop="setDatabaseTarget(option.database)">{{ t("ai.setDatabaseTarget") }}</button>+ </div><div v-if="!filteredDbSelectOptions.length" class="px-2 py-1.5 text-sm text-muted-foreground">{{ t("ai.noDatabasesFound") }}</div></div></PopoverContent>diff --git a/apps/desktop/src/components/editor/__tests__/AiAssistant.mount.spec.ts b/apps/desktop/src/components/editor/__tests__/AiAssistant.mount.spec.tsindex 72102776d2..1e3f517a82 100644--- a/apps/desktop/src/components/editor/__tests__/AiAssistant.mount.spec.ts+++ b/apps/desktop/src/components/editor/__tests__/AiAssistant.mount.spec.ts@@ -36,6 +36,10 @@ const aiAssistantMountApi = vi.hoisted(() => ({// Fifth argument: the custom prompt context (globals, templates, skill listing).runAgentStreamCustoms: [] as unknown[],savedConversations: [] as Array<Record<string, unknown>>,+ // Namespace listings the composer asks for when its pickers open (#12972).+ // Empty by default, so no existing test's behavior changes.+ databaseNames: [] as string[],+ schemaNames: [] as string[],codeHighlighterDelayMs: 0,// Skill catalog + body a test wants the backend to answer with.skillCatalog: {@@ -191,7 +195,12 @@ vi.mock("@/lib/backend/api", async (importOriginal) => {// Metadata reads a real send performs before `runAgentStream`. Without these// the panel would hit the HTTP backend inside happy-dom and the request// would never leave, which is exactly the moment under test.- listSchemas: empty,+ listSchemas: () => Promise.resolve(aiAssistantMountApi.schemaNames),+ listDatabases: () => Promise.resolve(aiAssistantMountApi.databaseNames.map((name) => ({ name }))),+ // `loadDatabaseOptions`/`loadSchemaOptions` call `ensureConnected`, which+ // probes health for an already-flagged connection; without this stub the+ // probe would reach the HTTP backend.+ checkConnectionHealth: () => Promise.resolve({ ok: true }),listTables: empty,getColumns: empty,listIndexes: empty,@@ -211,6 +220,8 @@ afterEach(() => {aiAssistantMountApi.runAgentStreamHistories = [];aiAssistantMountApi.runAgentStreamCustoms = [];aiAssistantMountApi.savedConversations = [];+ aiAssistantMountApi.databaseNames = [];+ aiAssistantMountApi.schemaNames = [];aiAssistantMountApi.codeHighlighterDelayMs = 0;aiAssistantMountApi.skillCatalog = { defaultRoot: { status: "ok", skills: [] }, customRoot: null };aiAssistantMountApi.skillReadResult = undefined;@@ -1043,6 +1054,65 @@ describe("AiAssistant mount", () => {expect(errors.map(String)).toEqual([]);});+ // #12972: the database picked in the composer is the chat's execution target,+ // not just AI context, and it must survive the schema pick that follows. The+ // old schema belongs to the old database, so retargeting drops it instead of+ // carrying a namespace the new database may not even have.+ it("retargets the chat to the database picked in the composer and re-picks its schema (#12972)", async () => {+ aiAssistantMountApi.databaseNames = ["postgres", "appdb"];+ aiAssistantMountApi.schemaNames = ["old_schema", "public"];+ aiAssistantMountApi.conversations = [storedConversation({ id: "conv-pg", connectionId: "postgres", connectionName: "PostgreSQL", database: "postgres", schema: "old_schema" })];+ const { container, errors, pinia } = await mountPanel(true, POSTGRES, (settings) => {+ configureAiPanel(settings);+ settings.restoreLastConversation = true;+ });+ // Loads the composer's database options without a real backend connect.+ useConnectionStore(pinia).connectedIds.add(POSTGRES.id);+ await settle();+ expect(container.textContent).toContain("previous question");++ // Open the database picker: the bound database is the marked target, appdb is context.+ container.querySelector<HTMLButtonElement>(".ai-database-selector-trigger")!.click();+ await vi.waitFor(() => expect(container.querySelector("[data-ai-database-target]")).not.toBeNull());+ expect(container.querySelector("[data-ai-database-target]")?.textContent).toContain(i18n.global.t("ai.databaseTarget"));++ // Promote appdb to the target through the UI.+ await vi.waitFor(() => expect(container.querySelector("[data-ai-database-target-action]")).not.toBeNull());+ container.querySelector<HTMLButtonElement>("[data-ai-database-target-action]")!.click();++ // The old database's schema is dropped, and the new target is persisted.+ await vi.waitFor(() => {+ const saved = aiAssistantMountApi.savedConversations.at(-1) as { database?: string; schema?: string } | undefined;+ expect(saved?.database).toBe("appdb");+ expect(saved?.schema).toBeUndefined();+ });++ // Pick a schema in the retargeted database via the schema selector (SearchableSelect).+ const schemaTrigger = [...container.querySelectorAll<HTMLButtonElement>("button")].find((button) => button.title === i18n.global.t("editor.selectSchema"));+ expect(schemaTrigger).toBeDefined();+ schemaTrigger!.click();+ await vi.waitFor(() => {+ const option = [...container.querySelectorAll<HTMLButtonElement>('[data-slot="popover-content"] button')].find((button) => button.textContent?.trim() === "public");+ expect(option).toBeDefined();+ });+ [...container.querySelectorAll<HTMLButtonElement>('[data-slot="popover-content"] button')].find((button) => button.textContent?.trim() === "public")!.click();++ await vi.waitFor(() => {+ const saved = aiAssistantMountApi.savedConversations.at(-1) as { database?: string; schema?: string } | undefined;+ expect(saved?.database).toBe("appdb");+ expect(saved?.schema).toBe("public");+ });++ // The request that leaves for the backend targets appdb, not the previously bound postgres.+ await sendPrompt(container, "count orders");+ const input = aiAssistantMountApi.runAgentStreamInputs.at(-1) as AiRequestInput | undefined;+ expect(input).toBeTruthy();+ const context = input!.context as AiContext;+ expect(context.database).toBe("appdb");+ expect(context.schema).toBe("public");+ expect(errors.map(String)).toEqual([]);+ });+it("carries the selection into the outgoing request and marks an over-budget one visibly", async () => {const { errors, container, panelRef } = await mountPanel(true, POSTGRES, configureAiPanel);const oversized = "x".repeat(AI_SELECTION_CONTEXT_MAX_CHARS + 25);diff --git a/apps/desktop/src/i18n/locales/az.ts b/apps/desktop/src/i18n/locales/az.tsindex 78e21b96fb..d341a7170c 100644--- a/apps/desktop/src/i18n/locales/az.ts+++ b/apps/desktop/src/i18n/locales/az.ts@@ -3598,6 +3598,8 @@ export default withEnglishFallback({renameConversation: "Rename conversation",conversationRenameFailed: "Failed to rename conversation",clearDatabaseSelection: "Clear selection",+ databaseTarget: "Hədəf",+ setDatabaseTarget: "Hədəf kimi təyin et",searchDatabases: "Verilənlər bazalarında axtarış…",noDatabasesFound: "Verilənlər bazası tapılmadı",},diff --git a/apps/desktop/src/i18n/locales/en.ts b/apps/desktop/src/i18n/locales/en.tsindex a7b7de4382..00dc657810 100644--- a/apps/desktop/src/i18n/locales/en.ts+++ b/apps/desktop/src/i18n/locales/en.ts@@ -4570,6 +4570,8 @@ export default {renameConversation: "Rename conversation",conversationRenameFailed: "Failed to rename conversation",clearDatabaseSelection: "Clear selection",+ databaseTarget: "Target",+ setDatabaseTarget: "Set as target",searchDatabases: "Search databases…",noDatabasesFound: "No databases found",},diff --git a/apps/desktop/src/i18n/locales/es.ts b/apps/desktop/src/i18n/locales/es.tsindex a966b13ef4..02e0c9ef2d 100644--- a/apps/desktop/src/i18n/locales/es.ts+++ b/apps/desktop/src/i18n/locales/es.ts@@ -4199,6 +4199,8 @@ export default withEnglishFallback({renameConversation: "Rename conversation",conversationRenameFailed: "Failed to rename conversation",clearDatabaseSelection: "Clear selection",+ databaseTarget: "Destino",+ setDatabaseTarget: "Establecer como destino",searchDatabases: "Buscar bases de datos…",noDatabasesFound: "No se encontraron bases de datos",toolApproval: {diff --git a/apps/desktop/src/i18n/locales/id.ts b/apps/desktop/src/i18n/locales/id.tsindex c46b775369..9ac1ef80b2 100644--- a/apps/desktop/src/i18n/locales/id.ts+++ b/apps/desktop/src/i18n/locales/id.ts@@ -3918,6 +3918,8 @@ export default withEnglishFallback({renameConversation: "Ganti nama percakapan",conversationRenameFailed: "Gagal mengganti nama percakapan",clearDatabaseSelection: "Bersihkan pilihan",+ databaseTarget: "Target",+ setDatabaseTarget: "Jadikan target",searchDatabases: "Cari database…",noDatabasesFound: "Tidak ada database yang ditemukan",},diff --git a/apps/desktop/src/i18n/locales/it.ts b/apps/desktop/src/i18n/locales/it.tsindex 7177c3a690..ec991d4119 100644--- a/apps/desktop/src/i18n/locales/it.ts+++ b/apps/desktop/src/i18n/locales/it.ts@@ -3957,6 +3957,8 @@ export default withEnglishFallback({renameConversation: "Rename conversation",conversationRenameFailed: "Failed to rename conversation",clearDatabaseSelection: "Clear selection",+ databaseTarget: "Destinazione",+ setDatabaseTarget: "Imposta come destinazione",searchDatabases: "Cerca database…",noDatabasesFound: "Nessun database trovato",toolApproval: {diff --git a/apps/desktop/src/i18n/locales/ja.ts b/apps/desktop/src/i18n/locales/ja.tsindex 06eba19dba..cdfe427e4e 100644--- a/apps/desktop/src/i18n/locales/ja.ts+++ b/apps/desktop/src/i18n/locales/ja.ts@@ -4078,6 +4078,8 @@ export default withEnglishFallback({renameConversation: "Rename conversation",conversationRenameFailed: "Failed to rename conversation",clearDatabaseSelection: "Clear selection",+ databaseTarget: "ターゲット",+ setDatabaseTarget: "ターゲットに設定",searchDatabases: "データベースを検索…",noDatabasesFound: "データベースが見つかりません",toolApproval: {diff --git a/apps/desktop/src/i18n/locales/ko.ts b/apps/desktop/src/i18n/locales/ko.tsindex a389b00e44..4e3f326507 100644--- a/apps/desktop/src/i18n/locales/ko.ts+++ b/apps/desktop/src/i18n/locales/ko.ts@@ -4122,6 +4122,8 @@ export default withEnglishFallback({renameConversation: "Rename conversation",conversationRenameFailed: "Failed to rename conversation",clearDatabaseSelection: "Clear selection",+ databaseTarget: "대상",+ setDatabaseTarget: "대상으로 설정",searchDatabases: "데이터베이스 검색…",noDatabasesFound: "데이터베이스를 찾을 수 없습니다",},diff --git a/apps/desktop/src/i18n/locales/pl.ts b/apps/desktop/src/i18n/locales/pl.tsindex f8b733e492..72ae9c219f 100644--- a/apps/desktop/src/i18n/locales/pl.ts+++ b/apps/desktop/src/i18n/locales/pl.ts@@ -3988,6 +3988,8 @@ export default withEnglishFallback({renameConversation: "Zmień nazwę rozmowy",conversationRenameFailed: "Nie udało się zmienić nazwy rozmowy",clearDatabaseSelection: "Wyczyść zaznaczenie",+ databaseTarget: "Docelowa",+ setDatabaseTarget: "Ustaw jako docelową",searchDatabases: "Szukaj baz danych…",noDatabasesFound: "Nie znaleziono baz danych",},diff --git a/apps/desktop/src/i18n/locales/pt-BR.ts b/apps/desktop/src/i18n/locales/pt-BR.tsindex 7d336ec409..41ca99fcce 100644--- a/apps/desktop/src/i18n/locales/pt-BR.ts+++ b/apps/desktop/src/i18n/locales/pt-BR.ts@@ -4045,6 +4045,8 @@ export default withEnglishFallback({renameConversation: "Rename conversation",conversationRenameFailed: "Failed to rename conversation",clearDatabaseSelection: "Clear selection",+ databaseTarget: "Destino",+ setDatabaseTarget: "Definir como destino",searchDatabases: "Pesquisar bancos de dados…",noDatabasesFound: "Nenhum banco de dados encontrado",toolApproval: {diff --git a/apps/desktop/src/i18n/locales/ru.ts b/apps/desktop/src/i18n/locales/ru.tsindex fdcc159694..8f556124b0 100644--- a/apps/desktop/src/i18n/locales/ru.ts+++ b/apps/desktop/src/i18n/locales/ru.ts@@ -4282,6 +4282,8 @@ export default withEnglishFallback({renameConversation: "Переименовать диалог",conversationRenameFailed: "Не удалось переименовать диалог",clearDatabaseSelection: "Очистить выбор",+ databaseTarget: "Целевая",+ setDatabaseTarget: "Сделать целевой",searchDatabases: "Поиск баз данных…",noDatabasesFound: "Базы данных не найдены",},diff --git a/apps/desktop/src/i18n/locales/th.ts b/apps/desktop/src/i18n/locales/th.tsindex 3f9e114c49..e53f8da58e 100644--- a/apps/desktop/src/i18n/locales/th.ts+++ b/apps/desktop/src/i18n/locales/th.ts@@ -4481,6 +4481,8 @@ export default withEnglishFallback({renameConversation: "เปลี่ยนชื่อการสนทนา",conversationRenameFailed: "เปลี่ยนชื่อการสนทนาไม่สำเร็จ",clearDatabaseSelection: "ล้างการเลือก",+ databaseTarget: "เป้าหมาย",+ setDatabaseTarget: "ตั้งเป็นเป้าหมาย",searchDatabases: "ค้นหาฐานข้อมูล…",noDatabasesFound: "ไม่พบฐานข้อมูล",magpieImport: "นำเข้าจาก Magpie",diff --git a/apps/desktop/src/i18n/locales/tr.ts b/apps/desktop/src/i18n/locales/tr.tsindex 0be8e2de8e..1c972dbf03 100644--- a/apps/desktop/src/i18n/locales/tr.ts+++ b/apps/desktop/src/i18n/locales/tr.ts@@ -3568,6 +3568,8 @@ export default withEnglishFallback({renameConversation: "Rename conversation",conversationRenameFailed: "Failed to rename conversation",clearDatabaseSelection: "Clear selection",+ databaseTarget: "Hedef",+ setDatabaseTarget: "Hedef olarak ayarla",searchDatabases: "Veritabanlarında ara…",noDatabasesFound: "Veritabanı bulunamadı",},diff --git a/apps/desktop/src/i18n/locales/zh-CN.ts b/apps/desktop/src/i18n/locales/zh-CN.tsindex 48f45973a8..8e60ab5f31 100644--- a/apps/desktop/src/i18n/locales/zh-CN.ts+++ b/apps/desktop/src/i18n/locales/zh-CN.ts@@ -4498,6 +4498,8 @@ export default withEnglishFallback({renameConversation: "重命名会话",conversationRenameFailed: "会话重命名失败",clearDatabaseSelection: "清空选择",+ databaseTarget: "目标库",+ setDatabaseTarget: "设为目标库",searchDatabases: "搜索数据库…",noDatabasesFound: "未找到数据库",},diff --git a/apps/desktop/src/i18n/locales/zh-TW.ts b/apps/desktop/src/i18n/locales/zh-TW.tsindex 9e51225a18..52fcd59a20 100644--- a/apps/desktop/src/i18n/locales/zh-TW.ts+++ b/apps/desktop/src/i18n/locales/zh-TW.ts@@ -4174,6 +4174,8 @@ export default withEnglishFallback({renameConversation: "Rename conversation",conversationRenameFailed: "Failed to rename conversation",clearDatabaseSelection: "Clear selection",+ databaseTarget: "目標庫",+ setDatabaseTarget: "設為目標庫",searchDatabases: "搜尋資料庫…",noDatabasesFound: "未找到資料庫",},diff --git a/apps/desktop/src/lib/ai/__tests__/aiComposerDatabases.spec.ts b/apps/desktop/src/lib/ai/__tests__/aiComposerDatabases.spec.tsnew file mode 100644index 0000000000..0f26262204--- /dev/null+++ b/apps/desktop/src/lib/ai/__tests__/aiComposerDatabases.spec.ts@@ -0,0 +1,86 @@+import { describe, expect, it } from "vitest";+import { resolveComposerDatabaseReset, toggleSelectedDatabase, withDatabaseSelected, type AiComposerScope } from "@/lib/ai/aiComposerDatabases";++function scope(overrides: Partial<AiComposerScope> = {}): AiComposerScope {+ return { conversationId: "conv-1", connectionId: "conn-b", namespace: "appdb", ...overrides };+}++describe("resolveComposerDatabaseReset (#12972)", () => {+ it("keeps the selection when only the schema changed", () => {+ // The namespace is the database for database-scoped engines, so a schema+ // change (PostgreSQL `public`) is not a target change.+ const reset = resolveComposerDatabaseReset(scope(), scope(), ["appdb", "other"]);+ expect(reset).toBeNull();+ });++ it("keeps the selection when the new namespace is already selected (set-as-target)", () => {+ const reset = resolveComposerDatabaseReset(scope(), scope({ namespace: "other" }), ["appdb", "other"]);+ expect(reset).toBeNull();+ });++ it("resets to the new namespace when something else moved the target", () => {+ expect(resolveComposerDatabaseReset(scope(), scope({ namespace: "other" }), ["appdb"])).toEqual(["other"]);+ });++ it("resets on a connection switch", () => {+ expect(resolveComposerDatabaseReset(scope(), scope({ connectionId: "conn-c", namespace: "postgres" }), ["appdb", "other"])).toEqual(["postgres"]);+ });++ it("resets on a conversation switch", () => {+ expect(resolveComposerDatabaseReset(scope(), scope({ conversationId: "conv-2", namespace: "other" }), ["appdb"])).toEqual(["other"]);+ });++ it("resets when a new chat is swapped for a persisted chat on the same namespace", () => {+ // The selection belongs to the chat on screen; a different conversation must+ // never inherit context databases (#9902).+ expect(resolveComposerDatabaseReset(scope({ conversationId: "" }), scope({ conversationId: "conv-1" }), ["appdb", "other"])).toEqual(["appdb"]);+ });++ it("returns an empty selection for an engine without a namespace", () => {+ expect(resolveComposerDatabaseReset(scope(), scope({ namespace: "" }), ["appdb"])).toEqual([]);+ });++ it("keeps the chosen target through a schema change (#12972)", () => {+ // Connection B is bound to the default `postgres`; the user then sets `appdb`+ // as the target and picks the `public` schema — the target must stay appdb.+ const afterTarget = withDatabaseSelected(["postgres"], "appdb");+ const beforeSchema = scope({ namespace: "postgres" });+ const targetMoved = scope({ namespace: "appdb" });+ expect(resolveComposerDatabaseReset(beforeSchema, targetMoved, afterTarget)).toBeNull();+ expect(resolveComposerDatabaseReset(targetMoved, targetMoved, afterTarget)).toBeNull();+ expect(toggleSelectedDatabase(afterTarget, "appdb", "appdb")).toBeNull();+ expect(toggleSelectedDatabase(afterTarget, "postgres", "appdb")).toEqual(["appdb"]);+ });+});++describe("toggleSelectedDatabase", () => {+ it("adds a database to the context selection", () => {+ expect(toggleSelectedDatabase(["appdb"], "other", "appdb")).toEqual(["appdb", "other"]);+ });++ it("removes a non-target database", () => {+ expect(toggleSelectedDatabase(["appdb", "other"], "other", "appdb")).toEqual(["appdb"]);+ });++ it("refuses to remove the target database", () => {+ expect(toggleSelectedDatabase(["appdb", "other"], "appdb", "appdb")).toBeNull();+ });++ it("refuses to remove the last selected database", () => {+ expect(toggleSelectedDatabase(["appdb"], "appdb", "")).toBeNull();+ });++ it("ignores an empty database", () => {+ expect(toggleSelectedDatabase(["appdb"], "", "appdb")).toBeNull();+ });+});++describe("withDatabaseSelected", () => {+ it("appends the target when it is missing", () => {+ expect(withDatabaseSelected(["other"], "appdb")).toEqual(["other", "appdb"]);+ });++ it("keeps the selection when the target is already selected", () => {+ expect(withDatabaseSelected(["appdb", "other"], "appdb")).toEqual(["appdb", "other"]);+ });+});diff --git a/apps/desktop/src/lib/ai/aiComposerDatabases.ts b/apps/desktop/src/lib/ai/aiComposerDatabases.tsnew file mode 100644index 0000000000..1622eb8f64--- /dev/null+++ b/apps/desktop/src/lib/ai/aiComposerDatabases.ts@@ -0,0 +1,60 @@+/**+ * Composer database-selection rules for the AI panel (#12972).+ *+ * The composer's database multi-select is *context*: every selected database can+ * be inspected by the model (#11660). The database the chat executes SQL on is+ * the conversation binding, shown in the picker as the target. These helpers keep+ * the selection from silently following changes that are not a target change —+ * notably a schema change, which used to reset the selection (and therefore the+ * execution target) to the connection's default database (`postgres` for+ * PostgreSQL).+ */++export interface AiComposerScope {+ /** Persisted conversation on screen; `""` while the chat has no record yet. */+ conversationId: string;+ connectionId: string;+ /**+ * Namespace the run targets: the database, or the schema for engines whose+ * top-level namespace is a schema (Dameng — see `resolveAiNamespaceSelection`).+ */+ namespace: string;+}++/**+ * Selection to apply after the chat's scope moved, or `null` to keep it.+ *+ * Reset to the new namespace only for a real scope switch: another conversation,+ * another connection, or (on schema-scoped engines) another namespace. A schema+ * change on a database-scoped engine leaves `namespace` untouched, so the+ * selection survives it. A namespace change that the panel itself initiated+ * ("set as target") already contains the new target in `selection`, so it is+ * kept as-is — the remaining context databases must not be dropped.+ */+export function resolveComposerDatabaseReset(previous: AiComposerScope, next: AiComposerScope, selection: readonly string[]): string[] | null {+ if (previous.connectionId !== next.connectionId || previous.conversationId !== next.conversationId) {+ return next.namespace ? [next.namespace] : [];+ }+ if (next.namespace === previous.namespace) return null;+ if (next.namespace && selection.includes(next.namespace)) return null;+ return next.namespace ? [next.namespace] : [];+}++/**+ * Selection and the new target after a toggle. `null` means the toggle is a+ * no-op: the target is always part of the scope (removing it would leave SQL+ * executing on a database the context no longer lists), and the picker never+ * becomes empty.+ */+export function toggleSelectedDatabase(selection: readonly string[], database: string, target: string): string[] | null {+ if (!database) return null;+ if (!selection.includes(database)) return [...selection, database];+ if (database === target || selection.length === 1) return null;+ return selection.filter((item) => item !== database);+}++/** `selection` with `database` appended when it is not already selected. */+export function withDatabaseSelected(selection: readonly string[], database: string): string[] {+ if (!database || selection.includes(database)) return [...selection];+ return [...selection, database];+}