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
feat(history): make query history retention configurable
cowking576943c543df
diff --git a/apps/desktop/src/components/editor/EditorSettingsDialog.vue b/apps/desktop/src/components/editor/EditorSettingsDialog.vueindex 4e3ff64dcb..6889c11646 100644--- a/apps/desktop/src/components/editor/EditorSettingsDialog.vue+++ b/apps/desktop/src/components/editor/EditorSettingsDialog.vue@@ -1,4 +1,5 @@<script setup lang="ts">+import { HISTORY_RETENTION_LIMITS, useHistoryRetentionSetting } from "@/composables/useHistoryRetentionSetting";import { ref, watch, shallowRef, computed, onMounted, onUnmounted, nextTick } from "vue";import type { Ref } from "vue";import type { EditorView as EditorViewType } from "@codemirror/view";@@ -293,6 +294,8 @@ import { buildConnectionGroupIdPathMap, connectionGroupDestinationRows, connecticonst { t, locale } = useI18n();const { toast } = useToast();const settingsStore = useSettingsStore();+const historyRetention = useHistoryRetentionSetting();+const { draft: editHistoryRetentionLimit, loaded: historyRetentionLoaded, loading: historyRetentionLoading, saving: historyRetentionSaving, loadError: historyRetentionLoadError } = historyRetention;const connectionStore = useConnectionStore();const hasSqlServerConnection = computed(() => connectionStore.connections.some((connection) => effectiveDatabaseTypeForConnection(connection) === "sqlserver"));const savedSqlStore = useSavedSqlStore();@@ -1839,6 +1842,7 @@ watch((open) => {if (open) {syncEditorSettingsDraftFromStore();+ void historyRetention.load();editShowTrayIcon.value = settingsStore.desktopSettings.show_tray_icon;editQuitOnClose.value = settingsStore.desktopSettings.quit_on_close;editIconTheme.value = settingsStore.desktopSettings.icon_theme;@@ -1847,6 +1851,7 @@ watch(editDuckDbWorkerProcessIsolation.value = settingsStore.desktopSettings.duckdb_worker_process_isolation;editSidebarTablePageSize.value = settingsStore.desktopSettings.sidebar_table_page_size ?? DEFAULT_SIDEBAR_TABLE_PAGE_SIZE;} else {+ historyRetention.discard();clearThemePalettePreview();clearUiFontFamilyPreview();restoreLocaleOptionPreview();@@ -2035,10 +2040,11 @@ const hasBlockingShortcutConflicts = computed(() => {});const hasBlockingFormatterConfig = computed(() => activeSettingsTab.value === "formatter" && !sqlFormatterConfigValid.value);const hasBlockingQueryResultRowLimit = computed(() => editQueryResultMaxRowsEnabled.value && editQueryResultMaxRows.value < editPageSize.value);-const hasApplyBlocker = computed(() => hasBlockingShortcutConflicts.value || hasBlockingFormatterConfig.value || hasBlockingQueryResultRowLimit.value);+const hasApplyBlocker = computed(() => historyRetention.invalid.value || historyRetentionSaving.value || hasBlockingShortcutConflicts.value || hasBlockingFormatterConfig.value || hasBlockingQueryResultRowLimit.value);function hasChanges(): boolean {return (+ historyRetention.changed.value ||hasImportedSettingsPendingApply.value ||hasEditorDraftChanges.value ||editShowTrayIcon.value !== settingsStore.desktopSettings.show_tray_icon ||@@ -2054,6 +2060,7 @@ function hasChanges(): boolean {async function persistSettings() {if (hasApplyBlocker.value) return;+ await historyRetention.save();const editorSettingsPatch = editorSettingsPatchFromDraft(currentEditorSettingsDraft(), editEditorSettingsBase.value);const sidebarObjectDisplayChanged = editorSettingsPatch.sidebarObjectDisplay !== undefined && editorSettingsPatch.sidebarObjectDisplay !== settingsStore.editorSettings.sidebarObjectDisplay;const sidebarTablePageSizeChanged = editSidebarTablePageSize.value !== (settingsStore.desktopSettings.sidebar_table_page_size ?? DEFAULT_SIDEBAR_TABLE_PAGE_SIZE);@@ -2230,6 +2237,7 @@ function resetDefaultsForTab(tab: SettingsCategory) {editSidebarCopyTableNameIncludeSchema.value = DEFAULT_EDITOR_SETTINGS.sidebarCopyTableNameIncludeSchema;editToolbarItems.value = { ...DEFAULT_EDITOR_SETTINGS.toolbarItems };} else if (tab === "data") {+ historyRetention.reset();editShowColumnCommentsInHeader.value = DEFAULT_EDITOR_SETTINGS.showColumnCommentsInHeader;editShowColumnTypesInHeader.value = DEFAULT_EDITOR_SETTINGS.showColumnTypesInHeader;editDataGridShowTransposeFieldMetadata.value = DEFAULT_EDITOR_SETTINGS.dataGridShowTransposeFieldMetadata;@@ -2287,6 +2295,7 @@ function resetDefaultsForTab(tab: SettingsCategory) {}function resetAllDefaults() {+ historyRetention.reset();// Same contract as resetDefaultsForTab: a full reset also exits any// in-progress shortcut capture (#9066).editingShortcutId.value = null;@@ -7424,6 +7433,21 @@ onUnmounted(() => {<!-- Data Tab --><section v-else-if="activeSettingsTab === 'data'" data-settings-search-id="data" :class="['flex flex-col gap-5 py-2', settingsSearchTargetClass('data')]">+ <div data-settings-search-id="history-retention" :class="['space-y-2', settingsSearchTargetClass('history-retention')]">+ <Label for="history-retention-limit">{{ t("settings.historyRetentionLimit") }}</Label>+ <p class="text-xs text-muted-foreground">{{ t("settings.historyRetentionDescription") }}</p>+ <Select :model-value="String(editHistoryRetentionLimit)" :disabled="!historyRetentionLoaded || historyRetentionSaving" @update:model-value="(value) => (editHistoryRetentionLimit = Number(value))">+ <SelectTrigger id="history-retention-limit" class="w-40"><SelectValue /></SelectTrigger>+ <SelectContent>+ <SelectItem v-for="limit in HISTORY_RETENTION_LIMITS" :key="limit" :value="String(limit)">{{ limit === 0 ? t("settings.historyRetentionUnlimited") : String(limit) }}</SelectItem>+ </SelectContent>+ </Select>+ <p v-if="historyRetentionLoading" class="text-xs text-muted-foreground">{{ t("common.loading") }}</p>+ <div v-if="historyRetentionLoadError" class="flex items-center gap-2 text-xs text-destructive" role="alert">+ <span>{{ t("settings.historyRetentionLoadFailed", { error: historyRetentionLoadError }) }}</span>+ <Button type="button" variant="outline" size="sm" @click="historyRetention.load">{{ t("common.retry") }}</Button>+ </div>+ </div><div data-settings-search-id="data-grid-filter-view" :class="['overflow-hidden rounded-md border bg-muted/20', settingsSearchTargetClass('data-grid-filter-view')]"><div class="space-y-3 p-3"><div class="flex items-start justify-between gap-4">diff --git a/apps/desktop/src/components/editor/__tests__/EditorSettingsDialog.historyRetention.integration.spec.ts b/apps/desktop/src/components/editor/__tests__/EditorSettingsDialog.historyRetention.integration.spec.tsnew file mode 100644index 0000000000..68b0332b1c--- /dev/null+++ b/apps/desktop/src/components/editor/__tests__/EditorSettingsDialog.historyRetention.integration.spec.ts@@ -0,0 +1,261 @@+// @vitest-environment happy-dom++import { createApp, defineComponent, h, nextTick, type App } from "vue";+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";+import { createPinia } from "pinia";+import { DEFAULT_EDITOR_SETTINGS } from "@/stores/settingsStore";++const hoisted = vi.hoisted(() => ({ shortcuts: {} as Record<string, string>, limit: 5000, failLoad: false, failSave: false, closes: [] as boolean[], saves: [] as number[] }));++vi.mock("vue-i18n", async () => {+ const { ref } = await import("vue");+ const locale = ref("en");+ const t = (key: string) => key;+ return {+ createI18n: () => ({ global: { t, locale }, install: () => undefined }),+ useI18n: () => ({ t, locale }),+ };+});++vi.mock("@/components/ui/dialog", async () => {+ const { defineComponent, h } = await import("vue");+ const passthrough = defineComponent({+ setup(_props, { slots }) {+ return () => h("div", slots.default?.());+ },+ });+ return {+ Dialog: defineComponent({+ props: { open: { type: Boolean, default: false } },+ setup:+ (props, { slots }) =>+ () =>+ props.open ? h("div", slots.default?.()) : null,+ }),+ DialogContent: passthrough,+ DialogFooter: passthrough,+ DialogHeader: passthrough,+ DialogTitle: passthrough,+ };+});++vi.mock("@/components/ui/button", async () => {+ const { defineComponent, h } = await import("vue");+ return {+ Button: defineComponent({+ inheritAttrs: false,+ setup(props, { attrs, slots }) {+ return () => h("button", { ...attrs, disabled: (props as { disabled?: boolean }).disabled ? true : undefined }, slots.default?.());+ },+ props: { disabled: { type: Boolean, default: false } },+ }),+ };+});++// ChangelogPanel fires a network fetch on mount (About tab); irrelevant here.+vi.mock("@/components/settings/ChangelogPanel.vue", async () => {+ const { defineComponent } = await import("vue");+ return { default: defineComponent({ setup: () => () => null }) };+});++// Back the store composable with a stub so the dialog boots without the Tauri+// backend, but read `shortcuts` through the hoisted object so each test can seed+// the configuration it wants before mounting.+vi.mock("@/stores/settingsStore", async (importOriginal) => {+ const actual = await importOriginal<typeof import("@/stores/settingsStore")>();+ const store = {+ settingsPageActive: false,+ editorSettings: {+ ...actual.DEFAULT_EDITOR_SETTINGS,+ get shortcuts() {+ return hoisted.shortcuts;+ },+ },+ desktopSettings: actual.DEFAULT_DESKTOP_SETTINGS,+ mcpGlobalPolicy: { configured: false, readOnly: false },+ aiConfigs: [],+ aiDefaultTemplatesByDbType: {},+ defaultAiMode: "ask",+ restoreLastConversation: false,+ initMcpGlobalPolicy: vi.fn(async () => undefined),+ updateMcpGlobalPolicy: vi.fn(async () => undefined),+ initAiConfigs: vi.fn(async () => undefined),+ initDesktopSettings: vi.fn(async () => undefined),+ updateEditorSettingsAndPersist: vi.fn(async () => undefined),+ updateEditorSettings: vi.fn(),+ persistEditorSettings: vi.fn(async () => undefined),+ updateDesktopSettings: vi.fn(async () => undefined),+ reloadAiConfigs: vi.fn(async () => undefined),+ removeTemplateFromDefaultAndLastUsed: vi.fn(),+ setDefaultTemplatesForDbType: vi.fn(),+ updateAiConfigItem: vi.fn(),+ createAiConfig: vi.fn(),+ deleteAiConfig: vi.fn(),+ setDefaultAiConfig: vi.fn(),+ setDefaultAiMode: vi.fn(),+ setRestoreLastConversation: vi.fn(),+ };+ return { ...actual, useSettingsStore: () => store };+});++vi.mock("@/lib/backend/api", async (importOriginal) => {+ const actual = await importOriginal<typeof import("@/lib/backend/api")>();+ return {+ ...actual,+ loadHistoryRetentionLimit: async () => {+ if (hoisted.failLoad) throw new Error("load failed");+ return hoisted.limit;+ },+ saveHistoryRetentionLimit: async (limit: number) => {+ if (hoisted.failSave) throw new Error("save failed");+ hoisted.saves.push(limit);+ hoisted.limit = limit;+ },+ };+});++import EditorSettingsDialog from "../EditorSettingsDialog.vue";++if (!("ResizeObserver" in globalThis)) {+ (globalThis as unknown as { ResizeObserver: unknown }).ResizeObserver = class {+ observe() {}+ unobserve() {}+ disconnect() {}+ };+}++const mountedApps: Array<{ app: App; host: HTMLElement }> = [];++afterEach(() => {+ for (const { app, host } of mountedApps.splice(0)) {+ app.unmount();+ host.remove();+ }+});++async function flushAsyncUpdates() {+ for (let i = 0; i < 5; i++) {+ await nextTick();+ await Promise.resolve();+ }+}++function defaults() {+ return { ...DEFAULT_EDITOR_SETTINGS.shortcuts };+}++async function mountDataTab() {+ const host = document.createElement("div");+ document.body.append(host);+ const app = createApp(defineComponent({ setup: () => () => h(EditorSettingsDialog, { variant: "page", initialTab: "data", "onUpdate:open": (open: boolean) => hoisted.closes.push(open) }) }));+ app.use(createPinia());+ app.mount(host);+ mountedApps.push({ app, host });+ await flushAsyncUpdates();+ return host;+}++function button(host: HTMLElement, text: string) {+ return [...host.querySelectorAll<HTMLButtonElement>("button")].find((item) => item.textContent?.trim() === text)!;+}++beforeEach(() => {+ hoisted.shortcuts = defaults();+ hoisted.limit = 5000;+ hoisted.failLoad = false;+ hoisted.failSave = false;+ hoisted.saves = [];+ hoisted.closes = [];+});++// Mounts the complete settings workbench; concurrent Rust/typecheck jobs can+// delay rendering on developer machines without changing the assertions.+describe("query history retention settings", { timeout: 30_000 }, () => {+ it("loads the server limit and applies a selected limit only on Apply", async () => {+ const host = await mountDataTab();+ const control = host.querySelector<HTMLElement>("#history-retention-limit");+ expect(control, "retention setting must be available in Data settings").not.toBeNull();+ expect(control!.textContent).toContain("5000");+ expect(host.textContent).toContain("settings.historyRetentionDescription");+ expect(hoisted.saves).toEqual([]);+ control!.dispatchEvent(new KeyboardEvent("keydown", { key: "ArrowDown", bubbles: true, cancelable: true }));+ await flushAsyncUpdates();+ const options = [...document.querySelectorAll<HTMLElement>('[role="option"]')];+ expect(options.map((option) => option.textContent?.trim())).toEqual(["200", "1000", "5000", "10000", "settings.historyRetentionUnlimited"]);+ const option = options[0];+ option.focus();+ option.dispatchEvent(new KeyboardEvent("keydown", { key: "Enter", bubbles: true, cancelable: true }));+ await flushAsyncUpdates();+ expect(control!.textContent).toContain("200");+ expect(hoisted.saves).toEqual([]);+ const apply = button(host, "settings.apply");+ expect(apply.disabled).toBe(false);+ apply.click();+ await flushAsyncUpdates();+ expect(hoisted.limit).toBe(200);+ expect(apply.disabled).toBe(true);+ });++ it("keeps the draft on save failure and can retry", async () => {+ const host = await mountDataTab();+ button(host, "settings.resetDefaults").click();+ await flushAsyncUpdates();+ expect(host.querySelector("#history-retention-limit")!.textContent).toContain("1000");+ hoisted.failSave = true;+ button(host, "settings.apply").click();+ await flushAsyncUpdates();+ expect(hoisted.limit).toBe(5000);+ expect(button(host, "settings.apply").disabled).toBe(false);+ hoisted.failSave = false;+ button(host, "settings.apply").click();+ await flushAsyncUpdates();+ expect(hoisted.limit).toBe(1000);+ });++ it("Apply and Close waits for persistence and reloads the saved value", async () => {+ const host = await mountDataTab();+ button(host, "settings.resetDefaults").click();+ await flushAsyncUpdates();+ hoisted.failSave = true;+ button(host, "settings.applyAndClose").click();+ await flushAsyncUpdates();+ expect(hoisted.closes).toEqual([]);+ expect(hoisted.limit).toBe(5000);+ hoisted.failSave = false;+ button(host, "settings.applyAndClose").click();+ await flushAsyncUpdates();+ expect(hoisted.closes).toEqual([false]);+ expect(hoisted.limit).toBe(1000);+ const reopened = await mountDataTab();+ expect(reopened.querySelector("#history-retention-limit")!.textContent).toContain("1000");+ });++ it("discarding an unapplied change does not save it", async () => {+ const host = await mountDataTab();+ button(host, "settings.resetDefaults").click();+ await flushAsyncUpdates();+ button(host, "common.close").click();+ await flushAsyncUpdates();+ button(host, "settings.unsavedChangesCloseDiscard").click();+ await flushAsyncUpdates();+ expect(hoisted.closes).toEqual([false]);+ expect(hoisted.saves).toEqual([]);+ const reopened = await mountDataTab();+ expect(reopened.querySelector("#history-retention-limit")!.textContent).toContain("5000");+ });++ it("does not overwrite server history retention when loading fails", async () => {+ hoisted.failLoad = true;+ const host = await mountDataTab();+ expect((host.querySelector("#history-retention-limit") as HTMLButtonElement).disabled).toBe(true);+ expect(host.textContent).toContain("settings.historyRetentionLoadFailed");+ button(host, "settings.resetDefaults").click();+ button(host, "settings.apply").click();+ await flushAsyncUpdates();+ expect(hoisted.saves).toEqual([]);+ hoisted.failLoad = false;+ button(host, "common.retry").click();+ await flushAsyncUpdates();+ expect(host.querySelector("#history-retention-limit")!.textContent).toContain("5000");+ });+});diff --git a/apps/desktop/src/composables/useHistoryRetentionSetting.ts b/apps/desktop/src/composables/useHistoryRetentionSetting.tsnew file mode 100644index 0000000000..d39c9f28b9--- /dev/null+++ b/apps/desktop/src/composables/useHistoryRetentionSetting.ts@@ -0,0 +1,65 @@+import { computed, ref } from "vue";+import { loadHistoryRetentionLimit, saveHistoryRetentionLimit } from "@/lib/backend/api";++export const HISTORY_RETENTION_LIMITS = [200, 1000, 5000, 10000, 0] as const;+export const DEFAULT_HISTORY_RETENTION_LIMIT = 1000;++export function isHistoryRetentionLimit(value: unknown): value is number {+ return typeof value === "number" && HISTORY_RETENTION_LIMITS.some((limit) => limit === value);+}++/** A server-owned setting: browser localStorage cannot configure MCP retention. */+export function useHistoryRetentionSetting() {+ const draft = ref(DEFAULT_HISTORY_RETENTION_LIMIT);+ const persisted = ref(DEFAULT_HISTORY_RETENTION_LIMIT);+ const loaded = ref(false);+ const loading = ref(false);+ const saving = ref(false);+ const loadError = ref("");+ let generation = 0;+ const changed = computed(() => loaded.value && draft.value !== persisted.value);+ const invalid = computed(() => loaded.value && !isHistoryRetentionLimit(draft.value));++ async function load() {+ const request = ++generation;+ loaded.value = false;+ loading.value = true;+ loadError.value = "";+ try {+ const value = await loadHistoryRetentionLimit();+ if (!isHistoryRetentionLimit(value)) throw new Error("Invalid query history retention limit");+ if (request !== generation) return;+ draft.value = persisted.value = value;+ loaded.value = true;+ } catch (error) {+ if (request === generation) loadError.value = error instanceof Error ? error.message : String(error);+ } finally {+ if (request === generation) loading.value = false;+ }+ }++ async function save() {+ if (!changed.value || saving.value) return;+ if (invalid.value) throw new Error("Invalid query history retention limit");+ const value = draft.value;+ saving.value = true;+ try {+ await saveHistoryRetentionLimit(value);+ persisted.value = value;+ } finally {+ saving.value = false;+ }+ }++ function discard() {+ generation += 1;+ loading.value = false;+ draft.value = persisted.value;+ }++ function reset() {+ if (loaded.value) draft.value = DEFAULT_HISTORY_RETENTION_LIMIT;+ }++ return { draft, loaded, loading, saving, loadError, changed, invalid, load, save, discard, reset };+}diff --git a/apps/desktop/src/i18n/locales/az.ts b/apps/desktop/src/i18n/locales/az.tsindex 462c631bb4..987f2b162d 100644--- a/apps/desktop/src/i18n/locales/az.ts+++ b/apps/desktop/src/i18n/locales/az.ts@@ -6844,6 +6844,10 @@ export default withEnglishFallback({syncSuccess: "Verilənlərin sinxronlaşdırılması uğurla icra edildi",},settings: {+ historyRetentionLimit: "Sorğu tarixçəsinin saxlanma həddi",+ historyRetentionDescription: "Hədd azaldıldıqda köhnə qeydlər növbəti sorğu tarixçəsi yazıldıqda silinir. Həddi artırmaq və ya Limitsiz seçmək silinmiş qeydləri bərpa etmir. Bütün bağlantılara və icra mənbələrinə tətbiq olunur.",+ historyRetentionUnlimited: "Limitsiz",+ historyRetentionLoadFailed: "Tarixçənin saxlanma ayarı yüklənmədi: {error}",tableOpenSortMode: "Cədvəli açarkən sıralama",tableDatabaseSortDirection: "Verilənlər bazası sıralama istiqaməti",tableLocalSortDirection: "Cari səhifənin sıralama istiqaməti",diff --git a/apps/desktop/src/i18n/locales/en.ts b/apps/desktop/src/i18n/locales/en.tsindex 34355d32f6..f1964d6ee9 100644--- a/apps/desktop/src/i18n/locales/en.ts+++ b/apps/desktop/src/i18n/locales/en.ts@@ -7321,6 +7321,10 @@ export default {syncSuccess: "Data sync executed successfully",},settings: {+ historyRetentionLimit: "Query history retention",+ historyRetentionDescription: "Lowering the limit removes older records the next time query history is recorded. Increasing the limit or choosing Unlimited does not restore deleted records. The limit applies to all connections and execution sources.",+ historyRetentionUnlimited: "Unlimited",+ historyRetentionLoadFailed: "Could not load history retention: {error}",tableOpenSortMode: "Default table sort",tableDatabaseSortDirection: "Default database sort direction",tableLocalSortDirection: "Default current page sort direction",diff --git a/apps/desktop/src/i18n/locales/es.ts b/apps/desktop/src/i18n/locales/es.tsindex ce782c62bc..6c4ad7ed13 100644--- a/apps/desktop/src/i18n/locales/es.ts+++ b/apps/desktop/src/i18n/locales/es.ts@@ -6725,6 +6725,10 @@ export default withEnglishFallback({syncSuccess: "Sincronización de datos ejecutada exitosamente",},settings: {+ historyRetentionLimit: "Límite del historial de consultas",+ historyRetentionDescription: "Al reducir el límite, los registros antiguos se eliminarán la próxima vez que se guarde una consulta. Aumentarlo o elegir Sin límite no recupera registros eliminados. Se aplica a todas las conexiones y fuentes de ejecución.",+ historyRetentionUnlimited: "Sin límite",+ historyRetentionLoadFailed: "No se pudo cargar el límite del historial: {error}",tableOpenSortMode: "Orden predeterminado de tablas",tableDatabaseSortDirection: "Dirección del orden en la base de datos",tableLocalSortDirection: "Dirección del orden de la página actual",diff --git a/apps/desktop/src/i18n/locales/it.ts b/apps/desktop/src/i18n/locales/it.tsindex 7d5817cccd..7d9b7e5a03 100644--- a/apps/desktop/src/i18n/locales/it.ts+++ b/apps/desktop/src/i18n/locales/it.ts@@ -6724,6 +6724,10 @@ export default withEnglishFallback({syncSuccess: "Sincronizzazione dei dati eseguita con successo",},settings: {+ historyRetentionLimit: "Limite della cronologia query",+ historyRetentionDescription: "Riducendo il limite, i record più vecchi verranno eliminati al prossimo salvataggio nella cronologia. Aumentare il limite o scegliere Illimitato non ripristina i record eliminati. Si applica a tutte le connessioni e origini di esecuzione.",+ historyRetentionUnlimited: "Illimitato",+ historyRetentionLoadFailed: "Impossibile caricare il limite della cronologia: {error}",tableOpenSortMode: "Ordinamento predefinito delle tabelle",tableDatabaseSortDirection: "Direzione nel database",tableLocalSortDirection: "Direzione nella pagina corrente",diff --git a/apps/desktop/src/i18n/locales/ja.ts b/apps/desktop/src/i18n/locales/ja.tsindex acc34682e0..d5a2a86820 100644--- a/apps/desktop/src/i18n/locales/ja.ts+++ b/apps/desktop/src/i18n/locales/ja.ts@@ -6761,6 +6761,10 @@ export default withEnglishFallback({syncSuccess: "データ同期が正常に実行されました",},settings: {+ historyRetentionLimit: "クエリ履歴の保持件数",+ historyRetentionDescription: "上限を減らすと、次回のクエリ履歴の記録時に古い履歴が削除されます。上限の増加や「無制限」の選択で削除済みの履歴は復元されません。すべての接続と実行元に適用されます。",+ historyRetentionUnlimited: "無制限",+ historyRetentionLoadFailed: "履歴の保持設定を読み込めませんでした: {error}",tableOpenSortMode: "テーブルの既定の並び順",tableDatabaseSortDirection: "データベースの既定のソート方向",tableLocalSortDirection: "現在のページの既定のソート方向",diff --git a/apps/desktop/src/i18n/locales/ko.ts b/apps/desktop/src/i18n/locales/ko.tsindex 15b4970a15..904cc6caaa 100644--- a/apps/desktop/src/i18n/locales/ko.ts+++ b/apps/desktop/src/i18n/locales/ko.ts@@ -6484,6 +6484,10 @@ export default withEnglishFallback({syncSuccess: "데이터 동기화를 성공적으로 실행했습니다",},settings: {+ historyRetentionLimit: "쿼리 기록 보관 개수",+ historyRetentionDescription: "한도를 낮추면 다음 쿼리 기록을 저장할 때 오래된 기록이 삭제됩니다. 한도를 높이거나 무제한을 선택해도 삭제된 기록은 복원되지 않습니다. 모든 연결과 실행 경로에 적용됩니다.",+ historyRetentionUnlimited: "무제한",+ historyRetentionLoadFailed: "기록 보관 설정을 불러오지 못했습니다: {error}",tableOpenSortMode: "테이블 기본 정렬",tableDatabaseSortDirection: "데이터베이스 기본 정렬 방향",tableLocalSortDirection: "현재 페이지 기본 정렬 방향",diff --git a/apps/desktop/src/i18n/locales/pt-BR.ts b/apps/desktop/src/i18n/locales/pt-BR.tsindex 0669618049..571f9d99aa 100644--- a/apps/desktop/src/i18n/locales/pt-BR.ts+++ b/apps/desktop/src/i18n/locales/pt-BR.ts@@ -6726,6 +6726,10 @@ export default withEnglishFallback({syncSuccess: "Sincronização de dados executada com sucesso",},settings: {+ historyRetentionLimit: "Limite do histórico de consultas",+ historyRetentionDescription: "Ao reduzir o limite, os registros antigos serão removidos na próxima gravação do histórico. Aumentar o limite ou escolher Sem limite não restaura registros excluídos. Aplica-se a todas as conexões e origens de execução.",+ historyRetentionUnlimited: "Sem limite",+ historyRetentionLoadFailed: "Não foi possível carregar o limite do histórico: {error}",tableOpenSortMode: "Ordenação padrão das tabelas",tableDatabaseSortDirection: "Direção padrão no banco de dados",tableLocalSortDirection: "Direção padrão na página atual",diff --git a/apps/desktop/src/i18n/locales/tr.ts b/apps/desktop/src/i18n/locales/tr.tsindex af44d7deed..60512bf7ef 100644--- a/apps/desktop/src/i18n/locales/tr.ts+++ b/apps/desktop/src/i18n/locales/tr.ts@@ -6726,6 +6726,10 @@ export default withEnglishFallback({syncSuccess: "Veri eşitlemesi başarıyla çalıştırıldı",},settings: {+ historyRetentionLimit: "Sorgu geçmişi saklama sınırı",+ historyRetentionDescription: "Sınır düşürüldüğünde eski kayıtlar bir sonraki sorgu geçmişi kaydında silinir. Sınırı artırmak veya Sınırsız seçmek silinen kayıtları geri getirmez. Tüm bağlantılar ve yürütme kaynakları için geçerlidir.",+ historyRetentionUnlimited: "Sınırsız",+ historyRetentionLoadFailed: "Geçmiş saklama ayarı yüklenemedi: {error}",tableOpenSortMode: "Varsayılan tablo sıralaması",tableDatabaseSortDirection: "Varsayılan veritabanı sıralama yönü",tableLocalSortDirection: "Geçerli sayfanın varsayılan sıralama yönü",diff --git a/apps/desktop/src/i18n/locales/zh-CN.ts b/apps/desktop/src/i18n/locales/zh-CN.tsindex 78d0f0f808..797454684f 100644--- a/apps/desktop/src/i18n/locales/zh-CN.ts+++ b/apps/desktop/src/i18n/locales/zh-CN.ts@@ -7293,6 +7293,10 @@ export default withEnglishFallback({syncSuccess: "数据同步执行成功",},settings: {+ historyRetentionLimit: "查询历史保留条数",+ historyRetentionDescription: "调小上限后,下次记录查询历史时将删除超过上限的旧记录。提高上限或选择“不限”不会恢复已删除记录。此上限适用于所有连接及执行来源。",+ historyRetentionUnlimited: "不限",+ historyRetentionLoadFailed: "无法加载历史保留设置:{error}",tableOpenSortMode: "打开表默认排序",tableDatabaseSortDirection: "全表默认排序方向",tableLocalSortDirection: "当前页默认排序方向",diff --git a/apps/desktop/src/i18n/locales/zh-TW.ts b/apps/desktop/src/i18n/locales/zh-TW.tsindex 657f2192fd..9d5f439b7a 100644--- a/apps/desktop/src/i18n/locales/zh-TW.ts+++ b/apps/desktop/src/i18n/locales/zh-TW.ts@@ -6048,6 +6048,10 @@ export default withEnglishFallback({syncSuccess: "資料同步執行成功",},settings: {+ historyRetentionLimit: "查詢歷史保留筆數",+ historyRetentionDescription: "調小上限後,下次記錄查詢歷史時將刪除超過上限的舊記錄。提高上限或選擇「不限」不會還原已刪除的記錄。此上限適用於所有連線及執行來源。",+ historyRetentionUnlimited: "不限",+ historyRetentionLoadFailed: "無法載入歷史保留設定:{error}",tableOpenSortMode: "開啟表格預設排序",tableDatabaseSortDirection: "全表預設排序方向",tableLocalSortDirection: "目前頁面預設排序方向",diff --git a/apps/desktop/src/lib/backend/api.ts b/apps/desktop/src/lib/backend/api.tsindex e528b5b38f..67735fe28e 100644--- a/apps/desktop/src/lib/backend/api.ts+++ b/apps/desktop/src/lib/backend/api.ts@@ -354,6 +354,8 @@ export const loadMaxAgentTurns = forward("loadMaxAgentTurns");export const loadSqlFileUploadMaxBytes = forward("loadSqlFileUploadMaxBytes");export const saveSqlFileUploadMaxMb = forward("saveSqlFileUploadMaxMb");export const saveMaxAgentTurns = forward("saveMaxAgentTurns");+export const loadHistoryRetentionLimit = forward("loadHistoryRetentionLimit");+export const saveHistoryRetentionLimit = forward("saveHistoryRetentionLimit");export const loadMaxRetries = forward("loadMaxRetries");export const saveMaxRetries = forward("saveMaxRetries");export const completeAppClose = forward("completeAppClose");diff --git a/apps/desktop/src/lib/backend/http.ts b/apps/desktop/src/lib/backend/http.tsindex 3c3196a839..0d53da1aa5 100644--- a/apps/desktop/src/lib/backend/http.ts+++ b/apps/desktop/src/lib/backend/http.ts@@ -2109,6 +2109,19 @@ export async function saveMaxAgentTurns(maxAgentTurns: number): Promise<void> {if (!res.ok) throw await backendResponseError(res);}+export async function loadHistoryRetentionLimit(): Promise<number> {+ return get("/api/app-settings/history-retention-limit");+}++export async function saveHistoryRetentionLimit(limit: number): Promise<void> {+ const res = await fetch(apiUrl("/api/app-settings/history-retention-limit"), {+ method: "PUT",+ headers: { "Content-Type": "application/json" },+ body: JSON.stringify({ limit }),+ });+ if (!res.ok) throw await backendResponseError(res);+}+export async function loadMaxRetries(): Promise<number> {return get("/api/app-settings/max-retries");}diff --git a/apps/desktop/src/lib/backend/tauri.ts b/apps/desktop/src/lib/backend/tauri.tsindex 0606ebf22c..62b9e0c9ce 100644--- a/apps/desktop/src/lib/backend/tauri.ts+++ b/apps/desktop/src/lib/backend/tauri.ts@@ -786,6 +786,14 @@ export async function saveMaxAgentTurns(maxAgentTurns: number): Promise<void> {return invoke("save_max_agent_turns", { maxAgentTurns });}+export async function loadHistoryRetentionLimit(): Promise<number> {+ return invoke("load_history_retention_limit");+}++export async function saveHistoryRetentionLimit(limit: number): Promise<void> {+ return invoke("save_history_retention_limit", { limit });+}+export async function loadMaxRetries(): Promise<number> {return invoke("load_max_retries");}diff --git a/apps/desktop/src/lib/settings/settingsSearch.ts b/apps/desktop/src/lib/settings/settingsSearch.tsindex b38dd657bb..af72e5ff5d 100644--- a/apps/desktop/src/lib/settings/settingsSearch.ts+++ b/apps/desktop/src/lib/settings/settingsSearch.ts@@ -196,6 +196,7 @@ export const SETTINGS_SEARCH_DEFINITIONS: readonly SettingsSearchDefinition[] ={ id: "navigation-sidebar-indent", category: "navigation", titleKey: "settings.sidebarIndent", descriptionKey: "settings.sidebarIndentDescription", targetId: "navigation" },{ id: "navigation-sidebar-font-size", category: "navigation", titleKey: "settings.sidebarFontSize", descriptionKey: "settings.sidebarFontSizeDescription", targetId: "navigation" },{ id: "navigation-hidden-tables", category: "navigation", titleKey: "settings.sidebarHiddenTablePrefixes", descriptionKey: "settings.sidebarHiddenTablePrefixesDescription", targetId: "navigation" },+ { id: "history-retention", category: "data", titleKey: "settings.historyRetentionLimit", descriptionKey: "settings.historyRetentionDescription", targetId: "history-retention" },{ id: "navigation-table-page-size", category: "navigation", titleKey: "settings.sidebarTablePageSize", descriptionKey: "settings.sidebarTablePageSizeDescription", targetId: "navigation" },{ id: "navigation-disconnect-tabs", category: "navigation", titleKey: "settings.disconnectTabHandlingMode", descriptionKey: "settings.disconnectTabHandlingModeDescription", targetId: "navigation" },{ id: "navigation-delete-connection-tabs", category: "navigation", titleKey: "settings.deleteConnectionTabHandlingMode", descriptionKey: "settings.deleteConnectionTabHandlingModeDescription", targetId: "navigation" },diff --git a/crates/dbx-core/src/persistence/history.rs b/crates/dbx-core/src/persistence/history.rsindex 083e827414..671b15837e 100644--- a/crates/dbx-core/src/persistence/history.rs+++ b/crates/dbx-core/src/persistence/history.rs@@ -87,6 +87,13 @@ pub struct HistoryConnectionOption {pub const MAX_HISTORY: usize = 1000;+pub fn validate_history_retention_limit(limit: u32) -> Result<(), String> {+ match limit {+ 0 | 200 | 1000 | 5000 | 10000 => Ok(()),+ _ => Err("History retention limit must be 200, 1000, 5000, 10000, or 0 (unlimited)".to_string()),+ }+}+fn default_activity_kind() -> String {"query".to_string()}diff --git a/crates/dbx-core/src/persistence/storage.rs b/crates/dbx-core/src/persistence/storage.rsindex 8888b50d14..73f33ed915 100644--- a/crates/dbx-core/src/persistence/storage.rs+++ b/crates/dbx-core/src/persistence/storage.rs@@ -45,6 +45,7 @@ const APP_STATE_TRANSFER_TASK_LIBRARY_KEY: &str = "transfer_task_library";const MCP_GLOBAL_POLICY_KEY: &str = "mcp_global_policy";const MCP_HTTP_SERVER_SETTINGS_KEY: &str = "mcp_http_server_settings";const MAX_RETRIES_KEY: &str = "max_retries";+const HISTORY_RETENTION_LIMIT_KEY: &str = "history_retention_limit";const SQL_FILE_UPLOAD_MAX_MB_KEY: &str = "sql_file_upload_max_mb";const APP_STATE_AI_GLOBAL_INSTRUCTIONS_KEY: &str = "ai_global_custom_instructions";const APP_STATE_AI_CHAT_SELECTION_KEY: &str = "ai_chat_selection_v1";@@ -1516,11 +1517,36 @@ fn map_history_row(row: &rusqlite::Row<'_>) -> rusqlite::Result<HistoryEntry> {})}+fn history_retention_limit_from_settings(settings: &serde_json::Map<String, serde_json::Value>) -> u32 {+ settings+ .get(HISTORY_RETENTION_LIMIT_KEY)+ .and_then(serde_json::Value::as_u64)+ .and_then(|value| u32::try_from(value).ok())+ .filter(|value| crate::history::validate_history_retention_limit(*value).is_ok())+ .unwrap_or(MAX_HISTORY as u32)+}++fn load_history_retention_limit_from_conn(conn: &Connection) -> Result<u32, String> {+ let current: Option<String> = conn+ .query_row("SELECT settings_json FROM app_settings WHERE id = 1", [], |row| row.get(0))+ .optional()+ .map_err(|e| e.to_string())?;+ let settings = match current {+ Some(json) => serde_json::from_str::<serde_json::Map<String, serde_json::Value>>(&json)+ .map_err(|e| format!("invalid app settings JSON: {e}"))?,+ None => serde_json::Map::new(),+ };+ Ok(history_retention_limit_from_settings(&settings))+}+impl Storage {pub async fn save_history_entry(&self, entry: &HistoryEntry) -> Result<(), String> {let entry = entry.clone();self.with_conn(move |conn| {- conn.execute(+ let tx =+ conn.transaction_with_behavior(rusqlite::TransactionBehavior::Immediate).map_err(|e| e.to_string())?;+ let limit = load_history_retention_limit_from_conn(&tx)?;+ tx.execute("INSERT OR REPLACE INTO history \(id, connection_name, database, sql_text, executed_at, execution_time_ms, success, error, \activity_kind, connection_id, operation, target, affected_rows, rollback_sql, details_json) \@@ -1545,13 +1571,15 @@ impl Storage {).map_err(|e| e.to_string())?;- conn.execute(- "DELETE FROM history WHERE id NOT IN \- (SELECT id FROM history ORDER BY executed_at DESC LIMIT ?1)",- [MAX_HISTORY as i64],- )- .map_err(|e| e.to_string())?;- Ok(())+ if limit != 0 {+ tx.execute(+ "DELETE FROM history WHERE id NOT IN \+ (SELECT id FROM history ORDER BY executed_at DESC, id DESC LIMIT ?1)",+ [i64::from(limit)],+ )+ .map_err(|e| e.to_string())?;+ }+ tx.commit().map_err(|e| e.to_string())}).await}@@ -2071,7 +2099,8 @@ impl Storage {.query_row("SELECT settings_json FROM app_settings WHERE id = 1", [], |row| row.get(0)).optional().map_err(|e| e.to_string())?;- let dedicated_keys = [MCP_GLOBAL_POLICY_KEY, MAX_RETRIES_KEY, SQL_FILE_UPLOAD_MAX_MB_KEY];+ let dedicated_keys =+ [MCP_GLOBAL_POLICY_KEY, MAX_RETRIES_KEY, SQL_FILE_UPLOAD_MAX_MB_KEY, HISTORY_RETENTION_LIMIT_KEY];for key in dedicated_keys {settings.remove(key);}@@ -2654,6 +2683,33 @@ impl Storage {.unwrap_or(crate::agent_loop::DEFAULT_MAX_AGENT_TURNS))}+ pub async fn load_history_retention_limit(&self) -> Result<u32, String> {+ self.with_conn(|conn| load_history_retention_limit_from_conn(conn)).await+ }++ pub async fn save_history_retention_limit(&self, limit: u32) -> Result<(), String> {+ crate::history::validate_history_retention_limit(limit)?;+ self.with_conn(move |conn| {+ let current: Option<String> = conn+ .query_row("SELECT settings_json FROM app_settings WHERE id = 1", [], |row| row.get(0))+ .optional()+ .map_err(|e| e.to_string())?;+ let mut settings = match current {+ Some(json) => serde_json::from_str::<serde_json::Map<String, serde_json::Value>>(&json)+ .map_err(|e| format!("invalid app settings JSON: {e}"))?,+ None => serde_json::Map::new(),+ };+ settings.insert(HISTORY_RETENTION_LIMIT_KEY.to_string(), serde_json::Value::from(limit));+ conn.execute(+ "INSERT OR REPLACE INTO app_settings (id, settings_json) VALUES (1, ?1)",+ [serde_json::Value::Object(settings).to_string()],+ )+ .map(|_| ())+ .map_err(|e| e.to_string())+ })+ .await+ }+pub async fn save_max_retries(&self, max_retries: u32) -> Result<(), String> {let max_retries = crate::ai::clamp_max_retries(max_retries);self.with_conn(move |conn| {@@ -5873,6 +5929,147 @@ mod tests {let _ = std::fs::remove_file(path);}+ // Seed a backlog efficiently, then exercise the production write path that+ // applies retention. Settings must affect every caller of that path.+ async fn seed_history_backlog(storage: &Storage, count: usize) {+ storage.with_conn(move |conn| {+ let tx = conn.transaction().map_err(|error| error.to_string())?;+ for index in 0..count {+ tx.execute(+ "INSERT INTO history (id, connection_name, database, sql_text, executed_at, execution_time_ms, success) VALUES (?1, 'Main', 'app', 'select 1', '2026-07-18T12:00:00Z', 1, 1)",+ [format!("{index:05}")],+ ).map_err(|error| error.to_string())?;+ }+ tx.commit().map_err(|error| error.to_string())+ }).await.unwrap();+ }++ #[tokio::test]+ async fn history_retention_uses_persisted_limit_on_the_next_write() {+ for (limit, expected) in [(200, 200), (5000, 1002), (10000, 1002), (0, 1002)] {+ let dir = tempfile::tempdir().unwrap();+ let storage = Storage::open(&dir.path().join("dbx.db")).await.unwrap();+ seed_history_backlog(&storage, 1001).await;+ storage+ .with_conn(move |conn| {+ conn.execute(+ "INSERT OR REPLACE INTO app_settings (id, settings_json) VALUES (1, ?1)",+ [serde_json::json!({"history_retention_limit": limit}).to_string()],+ )+ .map(|_| ())+ .map_err(|error| error.to_string())+ })+ .await+ .unwrap();+ // Changing the setting alone must not evict existing history.+ assert_eq!(storage.search_history_entries(HistorySearchRequest::default()).await.unwrap().total, 1001);+ storage+ .save_history_entry(&history_entry(+ "newest",+ "conn",+ "Main",+ "app",+ "select 2",+ "2026-07-19T00:00:00Z",+ true,+ ))+ .await+ .unwrap();+ let result = storage.search_history_entries(HistorySearchRequest::default()).await.unwrap();+ assert_eq!(result.total, expected, "retention limit {limit}");+ assert_eq!(result.entries[0].id, "newest");+ if limit == 200 {+ let remaining = storage.load_history_entries(500, 0, None).await.unwrap();+ assert!(remaining.iter().all(|entry| entry.id == "newest" || entry.id.as_str() >= "00802"));+ }+ }+ }++ #[tokio::test]+ async fn history_retention_defaults_validates_and_survives_stale_settings() {+ let dir = tempfile::tempdir().unwrap();+ let path = dir.path().join("dbx.db");+ let storage = Storage::open(&path).await.unwrap();+ assert_eq!(storage.load_history_retention_limit().await.unwrap(), 1000);+ let stale = storage.load_app_settings_json().await.unwrap();+ for limit in [200, 1000, 5000, 10000, 0] {+ storage.save_history_retention_limit(limit).await.unwrap();+ assert_eq!(storage.load_history_retention_limit().await.unwrap(), limit);+ }+ for invalid in [1, 199, 201, 10001, u32::MAX] {+ assert!(storage.save_history_retention_limit(invalid).await.is_err());+ assert_eq!(storage.load_history_retention_limit().await.unwrap(), 0);+ }+ storage.save_app_settings_json(&stale).await.unwrap();+ assert_eq!(storage.load_history_retention_limit().await.unwrap(), 0);+ drop(storage);+ let reopened = Storage::open(&path).await.unwrap();+ assert_eq!(reopened.load_history_retention_limit().await.unwrap(), 0);+ }++ #[tokio::test]+ async fn history_retention_invalid_persisted_values_use_default() {+ let dir = tempfile::tempdir().unwrap();+ let storage = Storage::open(&dir.path().join("dbx.db")).await.unwrap();+ for value in [+ serde_json::json!(-1),+ serde_json::json!(1),+ serde_json::json!("200"),+ serde_json::json!(u64::MAX),+ serde_json::Value::Null,+ ] {+ storage+ .with_conn(move |conn| {+ conn.execute(+ "INSERT OR REPLACE INTO app_settings (id, settings_json) VALUES (1, ?1)",+ [serde_json::json!({"history_retention_limit": value}).to_string()],+ )+ .map(|_| ())+ .map_err(|error| error.to_string())+ })+ .await+ .unwrap();+ assert_eq!(storage.load_history_retention_limit().await.unwrap(), 1000);+ }+ seed_history_backlog(&storage, 1001).await;+ storage+ .save_history_entry(&history_entry(+ "newest",+ "conn",+ "Main",+ "app",+ "select 2",+ "2026-07-19T00:00:00Z",+ true,+ ))+ .await+ .unwrap();+ assert_eq!(storage.search_history_entries(HistorySearchRequest::default()).await.unwrap().total, 1000);+ }++ #[tokio::test]+ async fn history_retention_setting_changes_do_not_prune_until_next_write() {+ let dir = tempfile::tempdir().unwrap();+ let storage = Storage::open(&dir.path().join("dbx.db")).await.unwrap();+ storage.save_history_retention_limit(0).await.unwrap();+ seed_history_backlog(&storage, 1001).await;+ storage.save_history_retention_limit(200).await.unwrap();+ assert_eq!(storage.search_history_entries(HistorySearchRequest::default()).await.unwrap().total, 1001);+ storage+ .save_history_entry(&history_entry(+ "newest",+ "conn",+ "Main",+ "app",+ "select 2",+ "2026-07-19T00:00:00Z",+ true,+ ))+ .await+ .unwrap();+ assert_eq!(storage.search_history_entries(HistorySearchRequest::default()).await.unwrap().total, 200);+ }+#[tokio::test]async fn history_search_filters_connection_database_and_legacy_entries() {let path = temp_db_path("history-search-scope");diff --git a/crates/dbx-web/src/main.rs b/crates/dbx-web/src/main.rsindex 358a87af3a..548e8226c2 100644--- a/crates/dbx-web/src/main.rs+++ b/crates/dbx-web/src/main.rs@@ -1140,6 +1140,11 @@ async fn main() {"/app-settings/max-agent-turns",get(routes::app_settings::load_max_agent_turns).put(routes::app_settings::save_max_agent_turns),)+ .route(+ "/app-settings/history-retention-limit",+ get(routes::app_settings::load_history_retention_limit)+ .put(routes::app_settings::save_history_retention_limit),+ ).route("/app-settings/max-retries",get(routes::app_settings::load_max_retries).put(routes::app_settings::save_max_retries),diff --git a/crates/dbx-web/src/routes/app_settings.rs b/crates/dbx-web/src/routes/app_settings.rsindex 87f70db26b..d05651395b 100644--- a/crates/dbx-web/src/routes/app_settings.rs+++ b/crates/dbx-web/src/routes/app_settings.rs@@ -120,6 +120,24 @@ pub async fn save_max_agent_turns(Ok(Json(()))}+#[derive(Deserialize)]+pub struct SaveHistoryRetentionLimitRequest {+ pub limit: u32,+}++pub async fn load_history_retention_limit(State(state): State<Arc<WebState>>) -> Result<Json<u32>, AppError> {+ state.app.storage.load_history_retention_limit().await.map(Json).map_err(AppError::from)+}++pub async fn save_history_retention_limit(+ State(state): State<Arc<WebState>>,+ Json(body): Json<SaveHistoryRetentionLimitRequest>,+) -> Result<Json<()>, AppError> {+ dbx_core::history::validate_history_retention_limit(body.limit).map_err(AppError::bad_request)?;+ state.app.storage.save_history_retention_limit(body.limit).await.map_err(AppError::from)?;+ Ok(Json(()))+}+#[derive(Deserialize)]#[serde(rename_all = "camelCase")]pub struct SaveMaxRetriesRequest {diff --git a/docs/content/docs/query-editor.cn.mdx b/docs/content/docs/query-editor.cn.mdxindex 69ed219be3..5fedef6961 100644--- a/docs/content/docs/query-editor.cn.mdx+++ b/docs/content/docs/query-editor.cn.mdx@@ -141,6 +141,8 @@ description: 使用 DBX 编写、理解、参数化、执行、分析和复用 S## 查询历史+在 **设置 → 数据 → 查询历史保留条数** 中,可选择 **200**、**1000**(默认)、**5000**、**10000** 或 **不限**。上限由所有连接及执行来源(包括 MCP)共用。调小后,下次记录历史时才会删除超出上限的旧记录;提高上限不会恢复已删除的记录。历史分页大小保持不变。+查询历史按连接保存已执行 SQL,并记录时间和相关上下文。可以:- 按日期范围过滤diff --git a/docs/content/docs/query-editor.mdx b/docs/content/docs/query-editor.mdxindex 31493cfa5b..430e5f395b 100644--- a/docs/content/docs/query-editor.mdx+++ b/docs/content/docs/query-editor.mdx@@ -141,6 +141,8 @@ Explain Plan accepts query-like SQL that is safe to analyze, such as `SELECT`, `## Query History+In **Settings → Data → Query history retention**, choose **200**, **1000** (default), **5000**, **10000**, or **Unlimited**. The limit is shared by all connections and execution sources, including MCP. A lower limit takes effect the next time a history entry is recorded: older entries beyond the limit are deleted. Raising the limit does not recover deleted entries. History page sizes remain unchanged.+Query history stores executed SQL per connection with time and context. You can:- Filter by date rangediff --git a/src-tauri/src/commands/app_settings.rs b/src-tauri/src/commands/app_settings.rsindex 3f30ee9b71..7a7d302f1d 100644--- a/src-tauri/src/commands/app_settings.rs+++ b/src-tauri/src/commands/app_settings.rs@@ -94,6 +94,16 @@ pub async fn save_max_agent_turns(state: State<'_, Arc<AppState>>, max_agent_turstate.storage.save_max_agent_turns(max_agent_turns).await}+#[tauri::command]+pub async fn load_history_retention_limit(state: State<'_, Arc<AppState>>) -> Result<u32, String> {+ state.storage.load_history_retention_limit().await+}++#[tauri::command]+pub async fn save_history_retention_limit(state: State<'_, Arc<AppState>>, limit: u32) -> Result<(), String> {+ state.storage.save_history_retention_limit(limit).await+}+#[tauri::command]pub async fn load_max_retries(state: State<'_, Arc<AppState>>) -> Result<u32, String> {state.storage.load_max_retries().awaitdiff --git a/src-tauri/src/lib.rs b/src-tauri/src/lib.rsindex ad97ebf1bb..107aa09f38 100644--- a/src-tauri/src/lib.rs+++ b/src-tauri/src/lib.rs@@ -1794,6 +1794,8 @@ pub fn run() {commands::app_settings::save_desktop_settings,commands::app_settings::load_max_agent_turns,commands::app_settings::save_max_agent_turns,+ commands::app_settings::load_history_retention_limit,+ commands::app_settings::save_history_retention_limit,commands::app_settings::load_max_retries,commands::app_settings::save_max_retries,commands::app_settings::set_app_locale,