Skip to content

armgit / dbx

Public Imported from GitHub
0

25 MB lightweight cross-platform database client for 100+ databases, including MySQL, PostgreSQL, SQLite, Redis, MongoDB, DuckDB, SQL Server, and Dameng. Built-in AI, MCP Server, CLI, desktop and Docker. | 轻量级跨平台数据库管理工具,支持 MySQL、PostgreSQL、SQLite、Redis、MongoDB、达梦等 100+ 数据库,提供桌面端、Docker、CLI、内置 AI 助手和 MCP。

49.1 KB
Raw Blame
<script setup lang="ts">
import { ref, computed, nextTick, onBeforeUnmount, onMounted, watch } from "vue";
import type { McpCallHistoryRequest, McpCallHistoryResource } from "@/lib/mcp/mcpCallHistory";
import { useI18n } from "vue-i18n";
import { useSqlHighlighter } from "@/composables/useSqlHighlighter";
import { CalendarClock, Check, Copy, Database, ListFilter, LoaderCircle, Maximize2, Minimize2, Minus, RefreshCw, RotateCcw, Search, Sparkles, Trash2, X } from "@lucide/vue";
import { RecycleScroller } from "vue-virtual-scroller";
import { Button } from "@/components/ui/button";
import { Dialog, DialogContent, DialogHeader, DialogTitle, DialogFooter } from "@/components/ui/dialog";
import { Popover, PopoverContent, PopoverTrigger } from "@/components/ui/popover";
import CustomContextMenu, { type ContextMenuItem } from "@/components/ui/CustomContextMenu.vue";
import { useHistoryStore } from "@/stores/historyStore";
import { useConnectionStore } from "@/stores/connectionStore";
import { useToast } from "@/composables/useToast";
import { resolveHistoryActivityKind } from "@/lib/history/historyActivityKind";
import { canRollbackHistoryEntry } from "@/lib/history/historyAiAnalysis";
import { hasHistoryDateRange, historyDateRangeIsValid, type HistoryDateRange } from "@/lib/history/historyTimeRange";
import { HISTORY_ROW_HEIGHT, HISTORY_SCROLL_BUFFER, shouldVirtualizeHistory } from "@/lib/history/historyVirtualList";
import { historyConnectionHasSelectedDatabase } from "@/lib/history/historySearch";
import { historyEntrySource } from "@/lib/history/historyEntrySource";
import { formatQueryDuration } from "@/lib/format/duration";
import type { HistoryConnectionFilter, HistoryDatabaseFilter, HistoryEntry, HistorySearchRequest } from "@/lib/backend/api";
import { copyToClipboard } from "@/lib/common/clipboard";
import { executeWithProductionSqlGuard } from "@/lib/database/productionExecutionGuard";
import { supportsTransaction } from "@/lib/database/databaseFeatureSupport";
import { formatError, isManualTransactionSessionExpired } from "@/lib/backend/errorUtils";
import * as api from "@/lib/backend/api";

const { t } = useI18n();
const { toast } = useToast();
const { highlight } = useSqlHighlighter();
const store = useHistoryStore();
const connectionStore = useConnectionStore();

const props = defineProps<{
  currentConnectionId?: string;
  currentDatabase?: string;
  maximized?: boolean;
  mcpRequest?: McpCallHistoryRequest | null;
}>();

const emit = defineEmits<{
  restore: [sql: string, entry: HistoryEntry];
  analyzeAi: [entry: HistoryEntry];
  close: [];
  toggleMaximize: [];
  mcpRequestHandled: [];
}>();

type HistoryFilter = "all" | "query" | "data_change" | "schema_change" | "failed" | "mcp_success";
type HistorySource = "sql" | "mcp";

const searchText = ref("");
const mcpToolName = ref("");
const mcpToolOptions = ref<string[]>([]);
const activeFilter = ref<HistoryFilter>("all");
const activeSource = ref<HistorySource>("sql");
const dateRange = ref<HistoryDateRange>({ startDate: "", endDate: "" });
const dateRangeDraft = ref<HistoryDateRange>({ startDate: "", endDate: "" });
const dateRangeOpen = ref(false);
const scopeFilterOpen = ref(false);
const scopeSearchText = ref("");
const selectedConnections = ref<HistoryConnectionFilter[]>([]);
const selectedDatabases = ref<HistoryDatabaseFilter[]>([]);
const startDateInputRef = ref<HTMLInputElement | null>(null);
const endDateInputRef = ref<HTMLInputElement | null>(null);
const selectedEntry = ref<HistoryEntry | null>(null);
const isRollingBack = ref(false);
const manualRollback = ref(false);
const resolvingTransaction = ref(false);
const pendingRollback = ref<{ sessionId: string; entry: HistoryEntry; affectedRows: number; executionTime: number; ready: boolean; commitUncertain?: boolean }>();
const rollbackLocked = computed(() => isRollingBack.value || !!pendingRollback.value || resolvingTransaction.value);
let disposed = false;
const canUseManualRollback = computed(() => supportsTransaction(connectionStore.getConfig(selectedEntry.value?.connection_id ?? "")?.db_type));
const showDeleteConfirm = ref(false);
const showClearConfirm = ref(false);
const deleteTargetId = ref<string | null>(null);
const filterScrollRef = ref<HTMLElement | null>(null);
const filtersScrollable = ref(false);
let filterScrollResizeObserver: ResizeObserver | null = null;
let searchDebounceTimer: ReturnType<typeof setTimeout> | null = null;

const filters = computed<HistoryFilter[]>(() => (activeSource.value === "mcp" ? ["all", "failed", "mcp_success"] : ["all", "query", "data_change", "schema_change", "failed"]));
const mcpQuickTools = computed(() => mcpToolOptions.value);
const canClearHistory = computed(() => store.total > 0);
const hasDateFilter = computed(() => hasHistoryDateRange(dateRange.value));
const dateRangeDraftValid = computed(() => historyDateRangeIsValid(dateRangeDraft.value));
const dateRangeSummary = computed(() => {
  if (!hasDateFilter.value) return "";
  const start = dateRange.value.startDate || t("history.dateRange.unboundedStart");
  const end = dateRange.value.endDate || t("history.dateRange.unboundedEnd");
  return `${start} -> ${end}`;
});

const hasScopeFilter = computed(() => selectedConnections.value.length > 0 || selectedDatabases.value.length > 0);
const wholeConnectionCount = computed(() => selectedConnections.value.filter((connection) => !isConnectionNarrowed(connection)).length);
const scopeSummary = computed(() => {
  const parts: string[] = [];
  if (wholeConnectionCount.value > 0) parts.push(t("history.scope.connectionCount", { count: wholeConnectionCount.value }));
  if (selectedDatabases.value.length > 0) parts.push(t("history.scope.databaseCount", { count: selectedDatabases.value.length }));
  return parts.join(" / ");
});
const emptyMessage = computed(() => (hasScopeFilter.value || hasDateFilter.value || activeFilter.value !== "all" || searchText.value ? t("history.emptyFiltered") : t("history.empty")));

function activityKind(entry: HistoryEntry) {
  return resolveHistoryActivityKind(entry);
}

function isMcpEntry(entry: HistoryEntry) {
  return entry.source === "mcp" || historyEntrySource(entry) === "MCP";
}

function restore(entry: HistoryEntry) {
  emit("restore", entry.sql, entry);
  selectedEntry.value = null;
}

async function copyText(text: string) {
  try {
    await copyToClipboard(text);
    toast(t("grid.copied"));
  } catch (e: any) {
    toast(t("grid.copyFailed", { message: e?.message || String(e) }), 5000);
  }
}

function confirmDeleteEntry(id: string) {
  deleteTargetId.value = id;
  showDeleteConfirm.value = true;
}

function executeDelete() {
  if (deleteTargetId.value) {
    store.remove(deleteTargetId.value);
    deleteTargetId.value = null;
  }
  showDeleteConfirm.value = false;
}

function confirmClearHistory() {
  if (canClearHistory.value) {
    showClearConfirm.value = true;
  }
}

function executeClear() {
  void store.clear(activeSource.value);
  showClearConfirm.value = false;
}

function formatTime(iso: string): string {
  const d = new Date(iso);
  const pad = (n: number) => String(n).padStart(2, "0");
  return `${pad(d.getMonth() + 1)}-${pad(d.getDate())} ${pad(d.getHours())}:${pad(d.getMinutes())}`;
}

function formatFullTime(iso: string): string {
  const d = new Date(iso);
  return Number.isNaN(d.getTime()) ? iso : d.toLocaleString();
}

function truncateSql(sql: string): string {
  const line = sql.replace(/\s+/g, " ").trim();
  return line.length > 120 ? line.slice(0, 120) + "..." : line;
}

function formatHistoryJson(value?: string | null): string {
  if (!value) return "-";
  try {
    return JSON.stringify(JSON.parse(value), null, 2);
  } catch {
    return value;
  }
}

function isLegacyResponse(value?: string | null): boolean {
  try {
    const parsed = JSON.parse(value || "null");
    return !!parsed && typeof parsed.content_blocks === "number" && !("content" in parsed);
  } catch {
    return false;
  }
}

function entryTitle(entry: HistoryEntry) {
  if (isMcpEntry(entry)) return entry.mcp_tool_name || entry.operation || "MCP call";
  return entry.target || entry.operation || truncateSql(entry.sql);
}

function entrySubtitle(entry: HistoryEntry) {
  if (isMcpEntry(entry)) return truncateSql(entry.mcp_request_json || entry.target || entry.operation || "-");
  if (activityKind(entry) === "query") return truncateSql(entry.sql);
  return truncateSql(entry.sql || entry.target || entry.operation || "");
}

function filterLabel(filter: HistoryFilter) {
  return t(`history.filters.${filter}`);
}

function connectionKey(connection: HistoryConnectionFilter) {
  return connection.connection_id ? `id:${connection.connection_id}` : `legacy:${connection.connection_name}`;
}

function databaseKey(database: HistoryDatabaseFilter) {
  return `${connectionKey(database)}\0${database.database}`;
}

function isConnectionSelected(connection: HistoryConnectionFilter) {
  const key = connectionKey(connection);
  return selectedConnections.value.some((candidate) => connectionKey(candidate) === key);
}

function isConnectionNarrowed(connection: HistoryConnectionFilter) {
  return historyConnectionHasSelectedDatabase(connection, selectedDatabases.value);
}

function toggleConnection(connection: HistoryConnectionFilter) {
  const key = connectionKey(connection);
  if (isConnectionNarrowed(connection)) {
    selectedDatabases.value = selectedDatabases.value.filter((database) => connectionKey(database) !== key);
    return;
  }
  if (isConnectionSelected(connection)) {
    selectedConnections.value = selectedConnections.value.filter((candidate) => connectionKey(candidate) !== key);
    selectedDatabases.value = selectedDatabases.value.filter((database) => connectionKey(database) !== key);
  } else {
    selectedConnections.value = [...selectedConnections.value, { ...connection }];
  }
}

function isDatabaseSelected(database: HistoryDatabaseFilter) {
  const key = databaseKey(database);
  return selectedDatabases.value.some((candidate) => databaseKey(candidate) === key);
}

function toggleDatabase(database: HistoryDatabaseFilter) {
  const key = databaseKey(database);
  if (isDatabaseSelected(database)) {
    selectedDatabases.value = selectedDatabases.value.filter((candidate) => databaseKey(candidate) !== key);
    if (!historyConnectionHasSelectedDatabase(database, selectedDatabases.value)) {
      const parentKey = connectionKey(database);
      selectedConnections.value = selectedConnections.value.filter((connection) => connectionKey(connection) !== parentKey);
    }
    return;
  }
  if (!isConnectionSelected(database)) {
    selectedConnections.value = [...selectedConnections.value, { connection_id: database.connection_id, connection_name: database.connection_name }];
  }
  selectedDatabases.value = [...selectedDatabases.value, { ...database }];
}

const visibleConnectionOptions = computed(() => {
  const query = scopeSearchText.value.trim().toLowerCase();
  return store.connectionOptions.filter((option) => {
    if (!query) return true;
    return option.connection_name.toLowerCase().includes(query) || option.databases.some((database) => database.toLowerCase().includes(query));
  });
});

const visibleDatabaseOptions = computed<HistoryDatabaseFilter[]>(() => {
  const selectedKeys = new Set(selectedConnections.value.map(connectionKey));
  const query = scopeSearchText.value.trim().toLowerCase();
  return store.connectionOptions
    .filter((connection) => selectedKeys.size === 0 || selectedKeys.has(connectionKey(connection)))
    .flatMap((connection) =>
      connection.databases
        .filter((database) => !query || database.toLowerCase().includes(query) || connection.connection_name.toLowerCase().includes(query))
        .map((database) => ({
          connection_id: connection.connection_id,
          connection_name: connection.connection_name,
          database,
        })),
    );
});

const currentConnectionOption = computed(() => store.connectionOptions.find((option) => option.connection_id === props.currentConnectionId));

function selectCurrentScope() {
  const connection = currentConnectionOption.value;
  if (!connection) return;
  selectedConnections.value = [{ connection_id: connection.connection_id, connection_name: connection.connection_name }];
  selectedDatabases.value = props.currentDatabase && connection.databases.includes(props.currentDatabase) ? [{ connection_id: connection.connection_id, connection_name: connection.connection_name, database: props.currentDatabase }] : [];
  scopeFilterOpen.value = false;
}

function resetScopeFilter() {
  selectedConnections.value = [];
  selectedDatabases.value = [];
}

// Preserve local-day boundaries before converting date-only input to UTC ISO timestamps.
function localDateBoundary(value: string, endOfDay: boolean): string | undefined {
  if (!value) return undefined;
  const [year, month, day] = value.split("-").map(Number);
  if (!year || !month || !day) return undefined;
  return new Date(year, month - 1, day, endOfDay ? 23 : 0, endOfDay ? 59 : 0, endOfDay ? 59 : 0, endOfDay ? 999 : 0).toISOString();
}

function buildHistorySearchRequest(): HistorySearchRequest {
  return {
    search_text: searchText.value,
    connections: selectedConnections.value.map((connection) => ({ ...connection })),
    databases: selectedDatabases.value.map((database) => ({ ...database })),
    activity_kind: activeFilter.value !== "all" && activeFilter.value !== "failed" && activeFilter.value !== "mcp_success" ? activeFilter.value : undefined,
    success: activeFilter.value === "failed" ? false : activeFilter.value === "mcp_success" ? true : undefined,
    started_at: localDateBoundary(dateRange.value.startDate, false),
    ended_at: localDateBoundary(dateRange.value.endDate, true),
    limit: 100,
    source: activeSource.value,
    mcp_tool_name: activeSource.value === "mcp" ? mcpToolName.value.trim() || undefined : undefined,
  };
}

async function runHistorySearch() {
  try {
    await store.search(buildHistorySearchRequest());
  } catch {
    // The panel already renders the backend error; avoid a duplicate toast.
  }
}

function refreshHistory() {
  void runHistorySearch();
}

// Debounce all filter changes through one timer to avoid redundant history scans.
function scheduleHistorySearch() {
  if (searchDebounceTimer) clearTimeout(searchDebounceTimer);
  searchDebounceTimer = setTimeout(() => {
    searchDebounceTimer = null;
    void runHistorySearch();
  }, 250);
}

function updateFilterScrollability() {
  const el = filterScrollRef.value;
  if (!el) return;
  const scrollable = el.scrollWidth > el.clientWidth + 3;
  filtersScrollable.value = scrollable;
  if (!scrollable && el.scrollLeft !== 0) {
    el.scrollLeft = 0;
  }
}

function openDateRangeFilter() {
  dateRangeDraft.value = { ...dateRange.value };
}

function setDateRangeOpen(value: boolean) {
  if (value) openDateRangeFilter();
  dateRangeOpen.value = value;
}

function applyDateRangeFilter() {
  if (!dateRangeDraftValid.value) return;
  dateRange.value = { ...dateRangeDraft.value };
  dateRangeOpen.value = false;
}

function clearDateRangeFilter() {
  dateRange.value = { startDate: "", endDate: "" };
  dateRangeDraft.value = { startDate: "", endDate: "" };
}

function cancelDateRangeFilter() {
  dateRangeDraft.value = { ...dateRange.value };
  dateRangeOpen.value = false;
}

function dateFieldLabel(value: string) {
  return value ? value.replaceAll("-", "/") : "yyyy/mm/dd";
}

function openDatePicker(input: HTMLInputElement | null) {
  if (!input) return;
  input.focus();
  const pickerInput = input as HTMLInputElement & { showPicker?: () => void };
  if (pickerInput.showPicker) {
    pickerInput.showPicker();
  } else {
    input.click();
  }
}

function kindLabel(entry: HistoryEntry) {
  return t(`history.kinds.${activityKind(entry)}`);
}

function kindShortLabel(entry: HistoryEntry) {
  return t(`history.kindShort.${activityKind(entry)}`);
}

function detailsRows(entry: HistoryEntry) {
  const rows = [
    [t("history.detail.kind"), kindLabel(entry)],
    [t("history.detail.operation"), entry.operation || "-"],
    [t("history.detail.connection"), entry.connection_name || "-"],
    [t("history.detail.database"), entry.database || "-"],
    [t("history.detail.target"), entry.target || "-"],
    [t("history.detail.time"), formatFullTime(entry.executed_at)],
    [t("history.detail.duration"), formatQueryDuration(entry.execution_time_ms)],
    [t("history.detail.affectedRows"), entry.affected_rows ?? "-"],
    [t("history.detail.rollback"), canRollbackHistoryEntry(entry) ? t("history.rollbackAvailable") : t("history.rollbackUnavailable")],
    [t("history.detail.status"), entry.success ? t("history.success") : t("history.failed")],
  ];
  if (entry.source === "mcp" || historyEntrySource(entry) === "MCP") {
    rows.splice(1, 0, [t("history.detail.mcpTool"), entry.mcp_tool_name || entry.operation || "-"]);
    const client = mcpClientLabel(entry);
    if (client) rows.splice(2, 0, [t("history.detail.mcpClient"), client]);
    const audit = mcpAuditDetails(entry);
    if (audit.transport) rows.splice(3, 0, [t("history.detail.mcpTransport"), audit.transport]);
    if (audit.accessLevel) rows.splice(4, 0, [t("history.detail.mcpAccess"), audit.accessLevel]);
    if (audit.confirmation) rows.splice(5, 0, [t("history.detail.mcpConfirmation"), audit.confirmation]);
  }
  if (entry.error) rows.push([t("history.detail.error"), entry.error]);
  return rows;
}

/** The MCP client recorded in `details_json` (`{ client: { name, version } }`), if any. */
function mcpClientLabel(entry: HistoryEntry): string {
  try {
    const client = JSON.parse(entry.details_json || "{}")?.client;
    if (!client?.name) return "";
    return client.version ? `${client.name} ${client.version}` : String(client.name);
  } catch {
    return "";
  }
}

function mcpAuditDetails(entry: HistoryEntry): { transport?: string; accessLevel?: string; confirmation?: string } {
  try {
    const details = JSON.parse(entry.details_json || "{}");
    return {
      transport: typeof details?.transport === "string" ? details.transport : undefined,
      accessLevel: typeof details?.accessLevel === "string" ? details.accessLevel : undefined,
      confirmation: typeof details?.confirmation === "string" ? details.confirmation : undefined,
    };
  } catch {
    return {};
  }
}

async function recordRollback(entry: HistoryEntry, affectedRows: number, executionTime: number) {
  await store.add({
    connection_id: entry.connection_id,
    connection_name: entry.connection_name,
    database: entry.database,
    sql: entry.rollback_sql!,
    execution_time_ms: executionTime,
    success: true,
    activity_kind: "data_change",
    operation: "ROLLBACK",
    target: entry.target,
    affected_rows: affectedRows,
    details_json: JSON.stringify({ rollback_of: entry.id }),
  });
}

async function rollback(entry: HistoryEntry, manual = false) {
  if (!canRollbackHistoryEntry(entry) || rollbackLocked.value) return;
  if (!window.confirm(t("history.rollbackConfirm"))) return;

  entry = { ...entry };
  const connectionId = entry.connection_id!;
  const rollbackSql = entry.rollback_sql!;
  const useTransaction = manual && supportsTransaction(connectionStore.getConfig(connectionId)?.db_type);
  isRollingBack.value = true;
  const start = Date.now();
  try {
    const result = await executeWithProductionSqlGuard({
      connection: connectionStore.getConfig(connectionId),
      database: entry.database,
      sql: rollbackSql,
      source: t("production.sourceQueryHistory"),
      execute: async () => {
        if (!useTransaction) return api.executeScript(connectionId, entry.database, rollbackSql);
        if (disposed) return undefined;
        const sessionId = await api.beginManualTransaction(connectionId, entry.database);
        pendingRollback.value = { sessionId, entry, affectedRows: 0, executionTime: 0, ready: false };
        if (disposed) return undefined;
        const results = await api.executeInManualTransaction(sessionId, rollbackSql, entry.database);
        return { affected_rows: results.reduce((total, result) => total + result.affected_rows, 0) };
      },
    });
    if (!result) return;
    if (pendingRollback.value) {
      pendingRollback.value.affectedRows = result.affected_rows;
      pendingRollback.value.executionTime = Date.now() - start;
      pendingRollback.value.ready = true;
    } else {
      await recordRollback(entry, result.affected_rows, Date.now() - start);
      toast(t("history.rollbackSuccess"));
    }
    selectedEntry.value = null;
  } catch (e: any) {
    toast(t("history.rollbackFailed", { message: e?.message || String(e) }), 5000);
  } finally {
    if (pendingRollback.value && (!pendingRollback.value.ready || disposed)) await finishRollbackTransaction(false);
    isRollingBack.value = false;
  }
}

async function finishRollbackTransaction(commit: boolean): Promise<boolean> {
  const pending = pendingRollback.value;
  if (!pending || resolvingTransaction.value || (commit && (!pending.ready || isRollingBack.value))) return false;
  resolvingTransaction.value = true;
  try {
    let committed = false;
    try {
      if (commit) {
        await api.commitManualTransaction(pending.sessionId);
        committed = true;
      } else await api.rollbackManualTransaction(pending.sessionId);
    } catch (error) {
      if (!isManualTransactionSessionExpired(error) && formatError(error) !== "Transaction session not found") {
        if (commit) {
          pending.commitUncertain = true;
          pending.ready = false;
        }
        throw error;
      }
      if (pending.commitUncertain) toast(t("toolbar.commitOutcomeUnknown"), 5000);
      else if (commit) toast(t("history.transactionEnded"), 5000);
    }
    pendingRollback.value = undefined;
    if (committed) {
      toast(t("history.rollbackSuccess"));
      // A history-storage error cannot undo a database commit or leave a
      // transaction control that invites committing the same work again.
      try {
        await recordRollback(pending.entry, pending.affectedRows, pending.executionTime);
      } catch (error) {
        toast(formatError(error), 5000);
      }
    }
    return true;
  } catch (error) {
    toast(formatError(error), 5000);
    return false;
  } finally {
    resolvingTransaction.value = false;
  }
}

async function closeHistory() {
  if (resolvingTransaction.value || (isRollingBack.value && pendingRollback.value)) return;
  if (pendingRollback.value) {
    if (!window.confirm(t("history.rollbackBeforeClose")) || !(await finishRollbackTransaction(false))) return;
  }
  emit("close");
}

function getHistoryMenuItems(entry: HistoryEntry): ContextMenuItem[] {
  const isMcp = isMcpEntry(entry);
  return [
    {
      label: t("history.viewDetails"),
      action: () => {
        selectedEntry.value = entry;
      },
    },
    ...(isMcp
      ? []
      : [
          { label: t("history.restore"), action: () => restore(entry) },
          { label: t("history.analyzeWithAi"), action: () => emit("analyzeAi", entry), icon: Sparkles },
          { label: t("history.copy"), action: () => copyText(entry.sql) },
          ...(canRollbackHistoryEntry(entry) ? [{ label: t("history.rollback"), action: () => rollback(entry) }] : []),
        ]),
    { label: t("history.delete"), action: () => confirmDeleteEntry(entry.id), variant: "destructive" as const },
  ];
}

watch(activeSource, () => {
  void nextTick(updateFilterScrollability);
});

watch(
  () => store.entries,
  (entries) => {
    const known = new Set(mcpToolOptions.value);
    for (const entry of entries) {
      if (isMcpEntry(entry) && entry.mcp_tool_name) known.add(entry.mcp_tool_name);
    }
    mcpToolOptions.value = [...known].sort().slice(0, 50);
  },
  { deep: true },
);

watch([searchText, mcpToolName, activeSource, activeFilter, () => dateRange.value.startDate, () => dateRange.value.endDate, () => selectedConnections.value.map(connectionKey).join("\0"), () => selectedDatabases.value.map(databaseKey).join("\0")], scheduleHistorySearch);

function applyMcpResource(resource?: McpCallHistoryResource) {
  activeSource.value = "mcp";
  activeFilter.value = "all";
  resetScopeFilter();
  scopeFilterOpen.value = false;
  if (!resource?.connectionId) return;
  // Scope by the requested IDs immediately. History options contain only resources
  // with existing records and must not widen the scope or replay navigation later.
  const connection = store.connectionOptions.find((option) => option.connection_id === resource.connectionId);
  const target = { connection_id: resource.connectionId, connection_name: connection?.connection_name ?? connectionStore.getConfig(resource.connectionId)?.name ?? "" };
  selectedConnections.value = [target];
  selectedDatabases.value = resource.database ? [{ ...target, database: resource.database }] : [];
}

watch(
  () => props.mcpRequest,
  (request) => {
    if (!request) return;
    applyMcpResource(request.resource);
    emit("mcpRequestHandled");
  },
  { immediate: true },
);

onMounted(() => {
  store.setHistoryPanelActive(true);
  void store.loadConnectionOptions().catch(() => {});
  void runHistorySearch();
  void nextTick(updateFilterScrollability);

  if (filterScrollRef.value) {
    filterScrollResizeObserver = new ResizeObserver(updateFilterScrollability);
    filterScrollResizeObserver.observe(filterScrollRef.value);
  }
});

onBeforeUnmount(() => {
  disposed = true;
  if (pendingRollback.value && !isRollingBack.value) void finishRollbackTransaction(false);
  store.setHistoryPanelActive(false);
  if (searchDebounceTimer) clearTimeout(searchDebounceTimer);
  searchDebounceTimer = null;
  filterScrollResizeObserver?.disconnect();
  filterScrollResizeObserver = null;
});
</script>

<template>
  <div class="h-full flex flex-col overflow-hidden border-l">
    <div class="h-9 flex items-center gap-1 px-2 border-b shrink-0 bg-muted/20">
      <span class="text-xs font-medium">{{ t("history.title") }}</span>
      <span v-if="store.total > 0" class="text-[10px] text-muted-foreground">{{ store.total }}</span>
      <span class="flex-1" />
      <Button v-if="canClearHistory" variant="ghost" size="icon" class="h-5 w-5" @click="confirmClearHistory">
        <Trash2 class="h-3 w-3" />
      </Button>
      <Button variant="ghost" size="icon" class="h-5 w-5" :disabled="store.loading" :title="t('history.refresh')" :aria-label="t('history.refresh')" @click="refreshHistory">
        <RefreshCw class="h-3 w-3" :class="{ 'animate-spin': store.loading }" />
      </Button>
      <Button variant="ghost" size="icon" class="h-5 w-5" :title="t(maximized ? 'diff.restore' : 'diff.maximize')" :aria-label="t(maximized ? 'diff.restore' : 'diff.maximize')" :aria-pressed="!!maximized" @click="emit('toggleMaximize')">
        <Minimize2 v-if="maximized" class="h-3 w-3" />
        <Maximize2 v-else class="h-3 w-3" />
      </Button>
      <Button variant="ghost" size="icon" class="h-5 w-5" :aria-label="t('common.close')" :disabled="resolvingTransaction || (isRollingBack && !!pendingRollback)" @click="closeHistory">
        <X class="h-3 w-3" />
      </Button>
    </div>

    <div v-if="pendingRollback" class="flex flex-wrap items-center gap-2 border-b p-2 text-xs" role="status">
      <span class="w-full">{{ pendingRollback.entry.connection_name }} / {{ pendingRollback.entry.database }}: {{ t("history.pendingRollback") }}</span>
      <Button size="sm" variant="outline" :disabled="isRollingBack || resolvingTransaction" @click="finishRollbackTransaction(false)">{{ t("history.discardRollback") }}</Button>
      <Button size="sm" :disabled="isRollingBack || resolvingTransaction || !pendingRollback.ready" @click="finishRollbackTransaction(true)">{{ t("toolbar.commit") }}</Button>
    </div>

    <div class="border-b shrink-0">
      <div class="flex gap-1 px-2 pt-2">
        <button
          v-for="source in ['sql', 'mcp'] as HistorySource[]"
          :key="source"
          type="button"
          class="h-7 rounded border px-3 text-xs"
          :class="activeSource === source ? 'border-primary bg-primary text-primary-foreground' : 'bg-background'"
          @click="
            activeSource = source;
            activeFilter = 'all';
          "
        >
          {{ t(`history.sources.${source}`) }}
        </button>
      </div>
      <div ref="filterScrollRef" class="history-filter-scroll flex gap-1 px-2 pt-2" :class="{ 'history-filter-scroll--scrollable': filtersScrollable }">
        <button v-for="filter in filters" :key="filter" type="button" class="h-6 shrink-0 rounded border px-2 text-xs" :class="activeFilter === filter ? 'border-primary bg-primary text-primary-foreground' : 'bg-background'" @click="activeFilter = filter">
          {{ filterLabel(filter) }}
        </button>
      </div>
      <div class="relative flex items-center px-2 py-1">
        <select v-if="activeSource === 'mcp'" data-mcp-tool-search v-model="mcpToolName" class="mr-1 h-5 max-w-52 rounded border bg-background px-1 text-xs outline-none" :title="t('history.mcp.toolSearch')">
          <option value="">{{ t("history.mcp.allTools") }}</option>
          <option v-for="tool in mcpQuickTools" :key="tool" :value="tool">{{ tool }}</option>
        </select>
        <Search v-if="activeSource !== 'mcp'" class="absolute left-3 w-3 h-3 text-muted-foreground pointer-events-none" />
        <input
          data-history-search
          v-model="searchText"
          autocapitalize="off"
          autocorrect="off"
          spellcheck="false"
          class="flex-1 h-5 text-xs bg-transparent border rounded pr-1 outline-none placeholder:text-muted-foreground"
          :class="activeSource === 'mcp' ? 'pl-1' : 'pl-5'"
          :placeholder="t('history.search')"
        />
        <Popover :open="dateRangeOpen" @update:open="setDateRangeOpen">
          <PopoverTrigger as-child>
            <button
              type="button"
              class="ml-1 flex h-5 w-5 shrink-0 items-center justify-center rounded border transition-colors"
              :class="hasDateFilter ? 'border-primary/40 bg-primary/10 text-primary hover:bg-primary/15' : 'border-border/70 text-muted-foreground hover:bg-accent hover:text-foreground'"
              :title="t('history.dateRange.title')"
            >
              <CalendarClock class="h-3 w-3" />
            </button>
          </PopoverTrigger>
          <PopoverContent align="end" class="w-auto max-w-[calc(100vw-24px)] gap-3 p-3" @click.stop @keydown.stop>
            <div class="flex items-center justify-between gap-3">
              <div class="text-xs font-medium text-foreground">{{ t("history.dateRange.title") }}</div>
            </div>
            <div class="flex flex-wrap items-end gap-2">
              <label class="grid min-w-0 gap-1 text-[11px] text-muted-foreground">
                <span>{{ t("history.dateRange.start") }}</span>
                <input ref="startDateInputRef" v-model="dateRangeDraft.startDate" type="date" class="sr-only" tabindex="-1" aria-hidden="true" />
                <button type="button" class="flex h-8 w-28 min-w-0 items-center gap-1.5 rounded-md border border-input bg-background px-2 text-left text-xs text-foreground outline-none hover:bg-muted/50 focus:border-ring focus:ring-2 focus:ring-ring/30" @click="openDatePicker(startDateInputRef)">
                  <span class="min-w-0 flex-1 truncate tabular-nums" :class="{ 'text-muted-foreground': !dateRangeDraft.startDate }">
                    {{ dateFieldLabel(dateRangeDraft.startDate) }}
                  </span>
                  <CalendarClock class="h-3 w-3 shrink-0 text-muted-foreground" />
                </button>
              </label>
              <span class="pb-2 text-xs text-muted-foreground">-></span>
              <label class="grid min-w-0 gap-1 text-[11px] text-muted-foreground">
                <span>{{ t("history.dateRange.end") }}</span>
                <input ref="endDateInputRef" v-model="dateRangeDraft.endDate" type="date" class="sr-only" tabindex="-1" aria-hidden="true" />
                <button type="button" class="flex h-8 w-28 min-w-0 items-center gap-1.5 rounded-md border border-input bg-background px-2 text-left text-xs text-foreground outline-none hover:bg-muted/50 focus:border-ring focus:ring-2 focus:ring-ring/30" @click="openDatePicker(endDateInputRef)">
                  <span class="min-w-0 flex-1 truncate tabular-nums" :class="{ 'text-muted-foreground': !dateRangeDraft.endDate }">
                    {{ dateFieldLabel(dateRangeDraft.endDate) }}
                  </span>
                  <CalendarClock class="h-3 w-3 shrink-0 text-muted-foreground" />
                </button>
              </label>
            </div>
            <div v-if="!dateRangeDraftValid" class="rounded-md border border-destructive/30 bg-destructive/10 px-2 py-1.5 text-xs text-destructive">
              {{ t("history.dateRange.invalid") }}
            </div>
            <div class="flex items-center justify-between gap-2 pt-1">
              <Button variant="ghost" size="sm" class="h-8 px-2 text-xs" @click="clearDateRangeFilter">
                {{ t("history.dateRange.clear") }}
              </Button>
              <div class="flex items-center gap-2">
                <Button variant="outline" size="sm" class="h-8 px-2 text-xs" @click="cancelDateRangeFilter">
                  {{ t("dangerDialog.cancel") }}
                </Button>
                <Button size="sm" class="h-8 px-3 text-xs" :disabled="!dateRangeDraftValid" @click="applyDateRangeFilter">
                  {{ t("history.dateRange.apply") }}
                </Button>
              </div>
            </div>
          </PopoverContent>
        </Popover>
        <Popover :open="scopeFilterOpen" @update:open="scopeFilterOpen = $event">
          <PopoverTrigger as-child>
            <button
              type="button"
              class="ml-1 flex h-5 w-5 shrink-0 items-center justify-center rounded border transition-colors"
              :class="hasScopeFilter ? 'border-primary/40 bg-primary/10 text-primary hover:bg-primary/15' : 'border-border/70 text-muted-foreground hover:bg-accent hover:text-foreground'"
              :title="t('history.scope.title')"
            >
              <ListFilter class="h-3 w-3" />
            </button>
          </PopoverTrigger>
          <PopoverContent align="end" class="w-72 max-w-[calc(100vw-24px)] p-3" @click.stop @keydown.stop>
            <div class="mb-2 flex items-center justify-between gap-2">
              <div class="text-xs font-medium">{{ t("history.scope.title") }}</div>
              <Button variant="ghost" size="sm" class="h-6 px-2 text-[11px]" :disabled="!hasScopeFilter" @click="resetScopeFilter">
                {{ t("history.scope.reset") }}
              </Button>
            </div>
            <div class="relative mb-2">
              <Search class="pointer-events-none absolute left-2 top-2 h-3 w-3 text-muted-foreground" />
              <input v-model="scopeSearchText" class="h-7 w-full rounded border bg-background pl-7 pr-2 text-xs outline-none focus:border-ring" :placeholder="t('history.scope.search')" />
            </div>
            <div class="mb-2 flex gap-1">
              <Button variant="outline" size="sm" class="h-7 flex-1 px-2 text-[11px]" @click="resetScopeFilter">
                {{ t("history.scope.allConnections") }}
              </Button>
              <Button v-if="currentConnectionOption" variant="outline" size="sm" class="h-7 flex-1 px-2 text-[11px]" @click="selectCurrentScope">
                {{ t("history.scope.current") }}
              </Button>
            </div>
            <div class="mb-1 text-[11px] font-medium text-muted-foreground">{{ t("history.scope.connections") }}</div>
            <div class="max-h-32 overflow-y-auto rounded border">
              <button v-for="connection in visibleConnectionOptions" :key="connectionKey(connection)" type="button" class="flex w-full items-center gap-2 border-b px-2 py-1.5 text-left text-xs last:border-b-0 hover:bg-accent" @click="toggleConnection(connection)">
                <span class="flex h-4 w-4 shrink-0 items-center justify-center rounded border" :class="{ 'border-primary bg-primary text-primary-foreground': isConnectionSelected(connection) }">
                  <Minus v-if="isConnectionNarrowed(connection)" class="h-3 w-3" />
                  <Check v-else-if="isConnectionSelected(connection)" class="h-3 w-3" />
                </span>
                <span class="min-w-0 flex-1 truncate">{{ connection.connection_name || t("history.scope.unknownConnection") }}</span>
                <span class="shrink-0 text-[10px] text-muted-foreground">{{ connection.databases.length }}</span>
              </button>
              <div v-if="visibleConnectionOptions.length === 0" class="px-2 py-3 text-center text-[11px] text-muted-foreground">{{ t("history.scope.noOptions") }}</div>
            </div>
            <div class="mb-1 mt-3 text-[11px] font-medium text-muted-foreground">{{ t("history.scope.databases") }}</div>
            <div class="max-h-32 overflow-y-auto rounded border">
              <button v-for="database in visibleDatabaseOptions" :key="databaseKey(database)" type="button" class="flex w-full items-center gap-2 border-b px-2 py-1.5 text-left text-xs last:border-b-0 hover:bg-accent" @click="toggleDatabase(database)">
                <span class="flex h-4 w-4 shrink-0 items-center justify-center rounded border" :class="{ 'border-primary bg-primary text-primary-foreground': isDatabaseSelected(database) }">
                  <Check v-if="isDatabaseSelected(database)" class="h-3 w-3" />
                </span>
                <span class="min-w-0 flex-1 truncate">{{ database.database }}</span>
                <span class="max-w-24 shrink-0 truncate text-[10px] text-muted-foreground">{{ database.connection_name }}</span>
              </button>
              <div v-if="visibleDatabaseOptions.length === 0" class="px-2 py-3 text-center text-[11px] text-muted-foreground">{{ t("history.scope.noOptions") }}</div>
            </div>
          </PopoverContent>
        </Popover>
      </div>
      <div v-if="hasDateFilter || hasScopeFilter" class="flex flex-wrap items-center gap-1 px-2 pb-2">
        <button v-if="hasDateFilter" type="button" class="flex min-w-0 items-center gap-1 rounded border border-primary/30 bg-primary/10 px-1.5 py-0.5 text-[11px] font-medium text-primary hover:bg-primary/15" :title="t('history.dateRange.title')" @click="setDateRangeOpen(true)">
          <CalendarClock class="h-3 w-3 shrink-0" />
          <span class="shrink-0">{{ t("history.dateRange.label") }}</span>
          <span class="min-w-0 truncate tabular-nums">{{ dateRangeSummary }}</span>
        </button>
        <button v-if="hasDateFilter" type="button" class="flex h-5 w-5 shrink-0 items-center justify-center rounded text-muted-foreground hover:bg-muted hover:text-foreground" :title="t('history.dateRange.clear')" @click="clearDateRangeFilter">
          <X class="h-3 w-3" />
        </button>
        <button v-if="hasScopeFilter" type="button" class="flex min-w-0 items-center gap-1 rounded border border-primary/30 bg-primary/10 px-1.5 py-0.5 text-[11px] font-medium text-primary hover:bg-primary/15" :title="t('history.scope.title')" @click="scopeFilterOpen = true">
          <ListFilter class="h-3 w-3 shrink-0" />
          <span class="min-w-0 truncate">{{ scopeSummary }}</span>
        </button>
        <button v-if="hasScopeFilter" type="button" class="flex h-5 w-5 shrink-0 items-center justify-center rounded text-muted-foreground hover:bg-muted hover:text-foreground" :title="t('history.scope.reset')" @click="resetScopeFilter">
          <X class="h-3 w-3" />
        </button>
      </div>
    </div>

    <div class="flex min-h-0 flex-1 flex-col">
      <RecycleScroller v-if="shouldVirtualizeHistory(store.entries.length)" class="min-h-0 flex-1" :items="store.entries" :item-size="HISTORY_ROW_HEIGHT" :buffer="HISTORY_SCROLL_BUFFER" :skip-hover="true" key-field="id">
        <template #default="{ item: entry }">
          <CustomContextMenu :items="getHistoryMenuItems(entry)" v-slot="{ onContextMenu, isOpen }">
            <div class="h-[80px] cursor-pointer select-none border-b border-border/50 px-2 py-1.5 text-xs" :class="isOpen || selectedEntry?.id === entry.id ? 'bg-accent text-accent-foreground' : ''" @click="selectedEntry = entry" @contextmenu="onContextMenu">
              <div class="h-full rounded-md border bg-card px-2 py-1.5 shadow-sm transition-colors hover:border-primary/30 hover:bg-accent/40">
                <div class="mb-0.5 flex items-center gap-1">
                  <span class="inline-flex h-5 w-9 shrink-0 items-center justify-center overflow-hidden rounded border px-1 text-[10px] leading-none text-muted-foreground">
                    {{ isMcpEntry(entry) ? "MCP" : kindShortLabel(entry) }}
                  </span>
                  <span class="truncate font-medium">{{ entryTitle(entry) }}</span>
                  <span v-if="historyEntrySource(entry) && !isMcpEntry(entry)" class="inline-flex h-5 shrink-0 items-center rounded border border-primary/30 bg-primary/5 px-1 text-[10px] font-medium text-primary">
                    {{ historyEntrySource(entry) }}
                  </span>
                  <span class="ml-auto shrink-0 text-muted-foreground">{{ formatTime(entry.executed_at) }}</span>
                </div>
                <div class="truncate font-mono text-muted-foreground">{{ entrySubtitle(entry) }}</div>
                <div class="mt-0.5 flex items-center gap-2">
                  <span class="inline-flex min-w-0 items-center gap-1 text-muted-foreground">
                    <Database class="h-3 w-3 shrink-0" />
                    <span class="truncate">
                      {{ entry.connection_name || entry.target || t("history.scope.unknownConnection") }}<template v-if="entry.database"> / {{ entry.database }}</template>
                    </span>
                  </span>
                  <span class="ml-auto shrink-0" :class="entry.success ? 'text-green-500' : 'text-red-500'">
                    {{ entry.success ? formatQueryDuration(entry.execution_time_ms) : t("history.failed") }}
                  </span>
                </div>
              </div>
            </div>
          </CustomContextMenu>
        </template>
      </RecycleScroller>

      <div v-if="store.loading && store.entries.length === 0" class="flex items-center justify-center gap-2 px-3 py-8 text-xs text-muted-foreground">
        <LoaderCircle class="h-3.5 w-3.5 animate-spin" />
        {{ t("common.loading") }}
      </div>
      <div v-else-if="store.error && store.entries.length === 0" class="px-3 py-8 text-center text-xs text-destructive">
        {{ store.error }}
      </div>
      <div v-else-if="store.entries.length === 0" class="px-3 py-8 text-center text-muted-foreground text-xs">
        {{ emptyMessage }}
      </div>
      <button v-if="store.nextCursor" type="button" class="flex h-8 shrink-0 items-center justify-center gap-1 border-t text-xs text-muted-foreground hover:bg-accent hover:text-foreground disabled:opacity-60" :disabled="store.loadingMore" @click="store.loadMore">
        <LoaderCircle v-if="store.loadingMore" class="h-3.5 w-3.5 animate-spin" />
        {{ store.loadingMore ? t("common.loading") : t("history.loadMore") }}
      </button>
    </div>

    <Dialog :open="!!selectedEntry" @update:open="(value) => !value && (selectedEntry = null)">
      <DialogContent class="sm:max-w-2xl duration-75" @interact-outside="selectedEntry = null">
        <DialogHeader>
          <DialogTitle>{{ selectedEntry ? entryTitle(selectedEntry) : t("history.viewDetails") }}</DialogTitle>
        </DialogHeader>
        <div v-if="selectedEntry" class="space-y-4 overflow-y-auto max-h-[60vh]">
          <div class="grid grid-cols-[120px_1fr] gap-x-3 gap-y-2 text-sm">
            <template v-for="[label, value] in detailsRows(selectedEntry)" :key="label">
              <div class="text-muted-foreground">{{ label }}</div>
              <div class="min-w-0 break-words">{{ value }}</div>
            </template>
          </div>
          <div v-if="selectedEntry.source === 'mcp' || historyEntrySource(selectedEntry) === 'MCP'" class="space-y-2">
            <div class="mb-1 flex items-center justify-between">
              <div class="text-sm font-medium">{{ t("history.mcp.request") }}</div>
              <Button variant="ghost" size="icon" class="h-7 w-7" :title="t('history.copy')" :aria-label="t('history.copy')" @click="copyText(selectedEntry.mcp_request_json || selectedEntry.sql || selectedEntry.details_json || '-')">
                <Copy class="h-3.5 w-3.5" />
              </Button>
            </div>
            <pre class="max-h-64 overflow-auto rounded border bg-muted/30 p-3 text-xs">{{ formatHistoryJson(selectedEntry.mcp_request_json || selectedEntry.sql || selectedEntry.details_json) }}</pre>
            <div class="mb-1 flex items-center justify-between">
              <div class="text-sm font-medium">{{ t("history.mcp.response") }}</div>
              <Button variant="ghost" size="icon" class="h-7 w-7" :title="t('history.copy')" :aria-label="t('history.copy')" @click="copyText(selectedEntry.mcp_response_json || '-')">
                <Copy class="h-3.5 w-3.5" />
              </Button>
            </div>
            <p v-if="isLegacyResponse(selectedEntry.mcp_response_json)" class="text-xs text-muted-foreground">{{ t("history.mcp.legacyResponse") }}</p>
            <pre class="max-h-[min(50vh,32rem)] overflow-auto rounded border bg-muted/30 p-3 text-xs">{{ formatHistoryJson(selectedEntry.mcp_response_json) }}</pre>
          </div>
          <div v-else>
            <div class="mb-1 flex items-center justify-between">
              <div class="text-sm font-medium">SQL</div>
              <Button variant="ghost" size="sm" class="h-7" @click="copyText(selectedEntry.sql)">
                <Copy class="h-3.5 w-3.5" />
                {{ t("history.copy") }}
              </Button>
            </div>
            <pre class="max-h-48 overflow-auto rounded border bg-muted/30 p-3 text-xs" v-html="highlight(selectedEntry.sql)"></pre>
          </div>
          <div v-if="selectedEntry.rollback_sql">
            <div class="mb-1 flex items-center justify-between">
              <div class="text-sm font-medium">{{ t("history.rollbackSql") }}</div>
              <Button variant="ghost" size="sm" class="h-7" @click="copyText(selectedEntry.rollback_sql || '')">
                <Copy class="h-3.5 w-3.5" />
                {{ t("history.copy") }}
              </Button>
            </div>
            <pre class="max-h-40 overflow-auto rounded border bg-muted/30 p-3 text-xs" v-html="highlight(selectedEntry.rollback_sql || '')"></pre>
          </div>
        </div>
        <DialogFooter>
          <Button v-if="selectedEntry && selectedEntry.source !== 'mcp' && historyEntrySource(selectedEntry) !== 'MCP'" variant="outline" @click="selectedEntry && emit('analyzeAi', selectedEntry)">
            <Sparkles class="h-4 w-4" />
            {{ t("history.analyzeWithAi") }}
          </Button>
          <Button v-if="selectedEntry && selectedEntry.source !== 'mcp' && historyEntrySource(selectedEntry) !== 'MCP'" variant="outline" @click="selectedEntry && restore(selectedEntry)">{{ t("history.restore") }}</Button>
          <label v-if="selectedEntry && canRollbackHistoryEntry(selectedEntry) && canUseManualRollback" class="flex items-center gap-2 text-xs" :title="t('history.manualRollbackHint')">
            <input v-model="manualRollback" type="checkbox" :disabled="rollbackLocked" />
            {{ t("toolbar.manualTransaction") }}
          </label>
          <Button v-if="selectedEntry && canRollbackHistoryEntry(selectedEntry)" :disabled="rollbackLocked" @click="rollback(selectedEntry, manualRollback)">
            <RotateCcw class="h-4 w-4" />
            {{ isRollingBack ? t("common.loading") : t("history.rollback") }}
          </Button>
        </DialogFooter>
      </DialogContent>
    </Dialog>

    <Dialog v-model:open="showDeleteConfirm">
      <DialogContent class="sm:max-w-[400px]">
        <DialogHeader>
          <DialogTitle>{{ t("history.delete") }}</DialogTitle>
        </DialogHeader>
        <p class="text-sm text-muted-foreground">{{ t("history.confirmDelete") }}</p>
        <DialogFooter>
          <Button variant="outline" @click="showDeleteConfirm = false">{{ t("dangerDialog.cancel") }}</Button>
          <Button variant="destructive" @click="executeDelete">{{ t("dangerDialog.confirm") }}</Button>
        </DialogFooter>
      </DialogContent>
    </Dialog>

    <Dialog v-model:open="showClearConfirm">
      <DialogContent class="sm:max-w-[400px]">
        <DialogHeader>
          <DialogTitle>{{ t("history.clear") }}</DialogTitle>
        </DialogHeader>
        <p class="text-sm text-muted-foreground">{{ t("history.confirmClearSource", { source: t(`history.sources.${activeSource}`) }) }}</p>
        <DialogFooter>
          <Button variant="outline" @click="showClearConfirm = false">{{ t("dangerDialog.cancel") }}</Button>
          <Button variant="destructive" @click="executeClear">{{ t("dangerDialog.confirm") }}</Button>
        </DialogFooter>
      </DialogContent>
    </Dialog>
  </div>
</template>

<style scoped>
.history-filter-scroll {
  overflow-x: hidden;
  overscroll-behavior-x: none;
}

.history-filter-scroll--scrollable {
  overflow-x: auto;
  /* Keep the search row in place when scrollbar space changes. */
  min-height: calc(2rem + 12px);
  padding-bottom: 2px;
  scrollbar-color: color-mix(in oklab, var(--muted-foreground) 45%, transparent) transparent;
  scrollbar-width: thin;
}

.history-filter-scroll--scrollable::-webkit-scrollbar {
  height: 4px;
}

.history-filter-scroll--scrollable::-webkit-scrollbar-track {
  background: transparent;
}

.history-filter-scroll--scrollable::-webkit-scrollbar-thumb {
  border-radius: 999px;
  background: color-mix(in oklab, var(--muted-foreground) 45%, transparent);
}
</style>