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。

feat(dolt): add database-aware version control workspace

hanxuanyucf1476a6dc72
diff --git a/apps/desktop/src/components/dolt/DoltCellDiffDialog.vue b/apps/desktop/src/components/dolt/DoltCellDiffDialog.vue
new file mode 100644
index 0000000000..795c9ea7af
--- /dev/null
+++ b/apps/desktop/src/components/dolt/DoltCellDiffDialog.vue
@@ -0,0 +1,270 @@
+<script setup lang="ts">
+import { computed, nextTick, onUnmounted, ref, watch, type CSSProperties } from "vue";
+import { AlertCircle, Copy, FileDiff } from "@lucide/vue";
+import { useI18n } from "vue-i18n";
+import { Button } from "@/components/ui/button";
+import { Dialog, DialogContent, DialogHeader, DialogTitle } from "@/components/ui/dialog";
+import DoltScrollArea from "@/components/dolt/DoltScrollArea.vue";
+import { useToast } from "@/composables/useToast";
+import { copyToClipboard } from "@/lib/common/clipboard";
+import { buildDoltTextDiff, detectDoltCellFormat, doltCellCopyText, doltCellDisplayValue, formatDoltCellText, type DoltCellFormat, type DoltCellFormatMode, type DoltCellSide, type DoltDiffCellTarget, type DoltTextDiffKind } from "@/lib/dolt/doltCellDiff";
+
+const props = defineProps<{
+ target: DoltDiffCellTarget | null;
+ tableName: string;
+ fromRevision: string;
+ toRevision: string;
+}>();
+
+const open = defineModel<boolean>("open", { default: false });
+const { t } = useI18n();
+const { toast } = useToast();
+const formatMode = ref<DoltCellFormatMode>("auto");
+const beforeScrollArea = ref<InstanceType<typeof DoltScrollArea> | null>(null);
+const afterScrollArea = ref<InstanceType<typeof DoltScrollArea> | null>(null);
+const scrollTop = ref(0);
+const viewportHeight = ref(0);
+let scrollSyncing = false;
+let scrollSyncFrame = 0;
+
+const ROW_HEIGHT = 22;
+const ROW_BUFFER = 12;
+
+const displayLabels = computed(() => ({
+ nullValue: t("doltVersionControl.cellNullValue"),
+ rowMissing: t("doltVersionControl.cellRowMissing"),
+ columnMissing: t("doltVersionControl.cellColumnMissing"),
+}));
+const beforeDisplay = computed(() => (props.target ? doltCellDisplayValue(props.target, "before", displayLabels.value) : null));
+const afterDisplay = computed(() => (props.target ? doltCellDisplayValue(props.target, "after", displayLabels.value) : null));
+const detectedFormat = computed<DoltCellFormat>(() => detectDoltCellFormat([beforeDisplay.value, afterDisplay.value].filter((value): value is NonNullable<typeof value> => !!value)));
+const effectiveFormat = computed<DoltCellFormat>(() => (formatMode.value === "auto" ? detectedFormat.value : formatMode.value));
+const beforeFormatted = computed(() => (beforeDisplay.value ? formatDoltCellText(beforeDisplay.value, effectiveFormat.value) : { text: "", error: null }));
+const afterFormatted = computed(() => (afterDisplay.value ? formatDoltCellText(afterDisplay.value, effectiveFormat.value) : { text: "", error: null }));
+const diffRows = computed(() => {
+ const rows = buildDoltTextDiff(beforeFormatted.value.text, afterFormatted.value.text);
+ if (beforeDisplay.value?.state !== "value" && afterDisplay.value?.state === "value") return rows.map((row) => ({ ...row, kind: "added" as const }));
+ if (afterDisplay.value?.state !== "value" && beforeDisplay.value?.state === "value") return rows.map((row) => ({ ...row, kind: "removed" as const }));
+ return rows;
+});
+const visibleStart = computed(() => Math.max(0, Math.floor(scrollTop.value / ROW_HEIGHT) - ROW_BUFFER));
+const visibleEnd = computed(() => Math.min(diffRows.value.length, Math.ceil((scrollTop.value + viewportHeight.value) / ROW_HEIGHT) + ROW_BUFFER));
+const visibleRows = computed(() => diffRows.value.slice(visibleStart.value, visibleEnd.value).map((row, offset) => ({ row, index: visibleStart.value + offset })));
+const longestLineLength = computed(() => {
+ let maximum = 0;
+ for (const row of diffRows.value) maximum = Math.max(maximum, row.beforeText.length, row.afterText.length);
+ return Math.min(20_000, maximum);
+});
+const textContentStyle = computed<CSSProperties>(() => ({
+ height: `${Math.max(1, diffRows.value.length * ROW_HEIGHT)}px`,
+ width: `max(100%, ${Math.max(40, longestLineLength.value + 8)}ch)`,
+}));
+const formatOptions = computed<Array<{ value: DoltCellFormatMode; label: string }>>(() => [
+ { value: "auto", label: t("doltVersionControl.cellDiffFormatAuto") },
+ { value: "raw", label: t("doltVersionControl.cellDiffFormatRaw") },
+ { value: "json", label: "JSON" },
+ { value: "xml", label: "XML" },
+]);
+
+function rowClass(kind: DoltTextDiffKind, side: DoltCellSide): string {
+ if (kind === "modified") return "dolt-cell-text-row-modified";
+ if (kind === "added" && side === "after") return "dolt-cell-text-row-added";
+ if (kind === "removed" && side === "before") return "dolt-cell-text-row-removed";
+ return "";
+}
+
+function updateViewport(element: HTMLElement) {
+ scrollTop.value = element.scrollTop;
+ viewportHeight.value = element.clientHeight;
+}
+
+function syncScroll(side: DoltCellSide, source: HTMLElement) {
+ updateViewport(source);
+ if (scrollSyncing) return;
+ const target = side === "before" ? afterScrollArea.value?.scrollerElement() : beforeScrollArea.value?.scrollerElement();
+ if (!target) return;
+ scrollSyncing = true;
+ target.scrollTop = source.scrollTop;
+ target.scrollLeft = source.scrollLeft;
+ if (scrollSyncFrame) cancelAnimationFrame(scrollSyncFrame);
+ scrollSyncFrame = requestAnimationFrame(() => {
+ scrollSyncFrame = 0;
+ scrollSyncing = false;
+ });
+}
+
+function onResize(element: HTMLElement) {
+ viewportHeight.value = Math.max(viewportHeight.value, element.clientHeight);
+}
+
+async function copyValue(side: DoltCellSide) {
+ if (!props.target) return;
+ const value = doltCellCopyText(props.target, side);
+ if (value === null) return;
+ try {
+ await copyToClipboard(value);
+ toast(t("doltVersionControl.cellValueCopied"), 2000);
+ } catch (error) {
+ toast(error instanceof Error ? error.message : String(error), 5000);
+ }
+}
+
+watch(
+ () => [open.value, props.target?.rowIndex, props.target?.columnIndex, props.target?.side],
+ async ([isOpen]) => {
+ if (!isOpen) return;
+ formatMode.value = "auto";
+ scrollTop.value = 0;
+ await nextTick();
+ const before = beforeScrollArea.value?.scrollerElement();
+ const after = afterScrollArea.value?.scrollerElement();
+ if (before) before.scrollTo({ top: 0, left: 0 });
+ if (after) after.scrollTo({ top: 0, left: 0 });
+ },
+);
+
+watch(effectiveFormat, async () => {
+ scrollTop.value = 0;
+ await nextTick();
+ beforeScrollArea.value?.scrollerElement()?.scrollTo({ top: 0, left: 0 });
+ afterScrollArea.value?.scrollerElement()?.scrollTo({ top: 0, left: 0 });
+});
+
+onUnmounted(() => {
+ if (scrollSyncFrame) cancelAnimationFrame(scrollSyncFrame);
+});
+</script>
+
+<template>
+ <Dialog v-model:open="open">
+ <DialogContent v-if="target" class="flex h-[min(82vh,760px)] min-w-0 max-w-[min(1180px,calc(100vw-32px))] flex-col gap-0 overflow-hidden p-0 sm:max-w-[min(1180px,calc(100vw-32px))]">
+ <DialogHeader class="shrink-0 border-b px-4 py-3 pr-11">
+ <DialogTitle class="flex min-w-0 items-center gap-2 text-sm">
+ <FileDiff class="h-4 w-4 shrink-0 text-blue-600 dark:text-blue-400" />
+ <span class="min-w-0 truncate">{{ t("doltVersionControl.cellDiffTitle", { table: tableName, column: target.columnName }) }}</span>
+ </DialogTitle>
+ </DialogHeader>
+
+ <div class="flex h-9 shrink-0 items-center gap-3 border-b px-3">
+ <div class="inline-flex h-7 items-center rounded border bg-muted/20 p-0.5" role="group" :aria-label="t('doltVersionControl.cellDiffFormat')">
+ <Button v-for="option in formatOptions" :key="option.value" type="button" size="sm" :variant="formatMode === option.value ? 'secondary' : 'ghost'" class="h-6 rounded-sm px-2 text-[11px] shadow-none" @click="formatMode = option.value">
+ {{ option.label }}
+ </Button>
+ </div>
+ <span v-if="formatMode === 'auto'" class="truncate text-[11px] text-muted-foreground">{{ t("doltVersionControl.cellDiffDetectedFormat", { format: effectiveFormat.toUpperCase() }) }}</span>
+ </div>
+
+ <div v-if="beforeFormatted.error || afterFormatted.error" class="grid shrink-0 grid-cols-2 border-b bg-amber-500/10 text-[11px] text-amber-700 dark:text-amber-300">
+ <div class="flex min-w-0 items-start gap-1.5 border-r px-2 py-1">
+ <template v-if="beforeFormatted.error"
+ ><AlertCircle class="mt-0.5 h-3 w-3 shrink-0" /><span class="min-w-0 break-words">{{ t("doltVersionControl.cellDiffFormatFailed", { message: beforeFormatted.error }) }}</span></template
+ >
+ </div>
+ <div class="flex min-w-0 items-start gap-1.5 px-2 py-1">
+ <template v-if="afterFormatted.error"
+ ><AlertCircle class="mt-0.5 h-3 w-3 shrink-0" /><span class="min-w-0 break-words">{{ t("doltVersionControl.cellDiffFormatFailed", { message: afterFormatted.error }) }}</span></template
+ >
+ </div>
+ </div>
+
+ <div class="grid min-h-0 flex-1 grid-cols-2 overflow-hidden">
+ <section class="flex min-w-0 min-h-0 flex-col border-r">
+ <div class="flex h-8 shrink-0 items-center gap-2 border-b bg-muted/20 px-2 text-[11px]">
+ <span class="min-w-0 flex-1 truncate font-mono text-muted-foreground" :title="fromRevision">{{ fromRevision }}</span>
+ <Button variant="ghost" size="icon" class="h-6 w-6" :disabled="doltCellCopyText(target, 'before') === null" :title="t('doltVersionControl.copyBeforeValue')" @click="copyValue('before')"><Copy class="h-3 w-3" /></Button>
+ </div>
+ <DoltScrollArea ref="beforeScrollArea" class="min-h-0 flex-1" scroller-class="dolt-cell-diff-before-scroller" @scroll="syncScroll('before', $event)" @resize="onResize">
+ <div class="dolt-cell-text-content" :style="textContentStyle">
+ <div v-for="visible in visibleRows" :key="`before-${visible.index}`" class="dolt-cell-text-row" :class="rowClass(visible.row.kind, 'before')" :style="{ top: `${visible.index * ROW_HEIGHT}px`, height: `${ROW_HEIGHT}px` }">
+ <span class="dolt-cell-text-line-number">{{ visible.row.beforeLineNumber ?? "" }}</span>
+ <code class="dolt-cell-text-code"
+ ><template v-for="(segment, index) in visible.row.beforeSegments" :key="index"
+ ><span :class="{ 'dolt-cell-text-segment-changed': segment.changed }">{{ segment.text }}</span></template
+ >&nbsp;</code
+ >
+ </div>
+ </div>
+ </DoltScrollArea>
+ </section>
+
+ <section class="flex min-w-0 min-h-0 flex-col">
+ <div class="flex h-8 shrink-0 items-center gap-2 border-b bg-muted/20 px-2 text-[11px]">
+ <span class="min-w-0 flex-1 truncate font-mono text-muted-foreground" :title="toRevision">{{ toRevision }}</span>
+ <Button variant="ghost" size="icon" class="h-6 w-6" :disabled="doltCellCopyText(target, 'after') === null" :title="t('doltVersionControl.copyAfterValue')" @click="copyValue('after')"><Copy class="h-3 w-3" /></Button>
+ </div>
+ <DoltScrollArea ref="afterScrollArea" class="min-h-0 flex-1" scroller-class="dolt-cell-diff-after-scroller" @scroll="syncScroll('after', $event)" @resize="onResize">
+ <div class="dolt-cell-text-content" :style="textContentStyle">
+ <div v-for="visible in visibleRows" :key="`after-${visible.index}`" class="dolt-cell-text-row" :class="rowClass(visible.row.kind, 'after')" :style="{ top: `${visible.index * ROW_HEIGHT}px`, height: `${ROW_HEIGHT}px` }">
+ <span class="dolt-cell-text-line-number">{{ visible.row.afterLineNumber ?? "" }}</span>
+ <code class="dolt-cell-text-code"
+ ><template v-for="(segment, index) in visible.row.afterSegments" :key="index"
+ ><span :class="{ 'dolt-cell-text-segment-changed': segment.changed }">{{ segment.text }}</span></template
+ >&nbsp;</code
+ >
+ </div>
+ </div>
+ </DoltScrollArea>
+ </section>
+ </div>
+ </DialogContent>
+ </Dialog>
+</template>
+
+<style scoped>
+.dolt-cell-text-content {
+ position: relative;
+ min-width: 100%;
+ font-family: var(--font-mono);
+ font-size: 12px;
+}
+
+.dolt-cell-text-row {
+ position: absolute;
+ left: 0;
+ display: flex;
+ width: 100%;
+ min-width: 100%;
+ align-items: center;
+ border-bottom: 1px solid color-mix(in srgb, var(--border) 45%, transparent);
+ line-height: 21px;
+}
+
+.dolt-cell-text-line-number {
+ position: sticky;
+ left: 0;
+ z-index: 1;
+ width: 48px;
+ height: 100%;
+ flex: 0 0 48px;
+ border-right: 1px solid var(--border);
+ background: var(--background);
+ padding-right: 8px;
+ text-align: right;
+ color: var(--muted-foreground);
+ user-select: none;
+}
+
+.dolt-cell-text-code {
+ display: block;
+ min-width: 0;
+ padding: 0 8px;
+ white-space: pre;
+ font-family: inherit;
+}
+
+.dolt-cell-text-row-modified {
+ background: rgb(217 119 6 / 0.11);
+}
+
+.dolt-cell-text-row-added {
+ background: rgb(22 163 74 / 0.11);
+}
+
+.dolt-cell-text-row-removed {
+ background: rgb(220 38 38 / 0.1);
+}
+
+.dolt-cell-text-row-modified .dolt-cell-text-segment-changed {
+ background: rgb(217 119 6 / 0.32);
+}
+</style>
diff --git a/apps/desktop/src/components/dolt/DoltDiffPagination.vue b/apps/desktop/src/components/dolt/DoltDiffPagination.vue
new file mode 100644
index 0000000000..ab36e7cb6a
--- /dev/null
+++ b/apps/desktop/src/components/dolt/DoltDiffPagination.vue
@@ -0,0 +1,86 @@
+<script setup lang="ts">
+import { computed, ref, watch } from "vue";
+import { ChevronLeft, ChevronRight, ChevronsLeft, ChevronsRight, Loader2 } from "@lucide/vue";
+import { useI18n } from "vue-i18n";
+import { Button } from "@/components/ui/button";
+import { Input } from "@/components/ui/input";
+import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";
+
+const DOLT_DIFF_PAGE_SIZE_OPTIONS = [20, 50, 100, 500, 1000];
+
+const props = defineProps<{
+ currentPage: number;
+ pageSize: number;
+ totalRows: number;
+ loading: boolean;
+}>();
+
+const emit = defineEmits<{
+ pageChange: [page: number];
+ pageSizeChange: [pageSize: number];
+}>();
+
+const { t } = useI18n();
+const pageInput = ref(String(props.currentPage));
+const maximumPage = computed(() => Math.max(1, Math.ceil(props.totalRows / props.pageSize)));
+const pageSizeOptions = computed(() => [...new Set([...DOLT_DIFF_PAGE_SIZE_OPTIONS, props.pageSize])].sort((left, right) => left - right));
+
+watch(
+ () => props.currentPage,
+ (page) => (pageInput.value = String(page)),
+);
+
+function requestPage(page: number) {
+ const normalized = Math.min(maximumPage.value, Math.max(1, Math.floor(page)));
+ pageInput.value = String(normalized);
+ if (normalized !== props.currentPage) emit("pageChange", normalized);
+}
+
+function applyPageInput() {
+ const page = Number(pageInput.value);
+ if (!Number.isSafeInteger(page) || page < 1) {
+ pageInput.value = String(props.currentPage);
+ return;
+ }
+ requestPage(page);
+}
+
+function selectPageSize(value: unknown) {
+ const pageSize = Number(value);
+ if (Number.isSafeInteger(pageSize) && pageSize > 0 && pageSize !== props.pageSize) emit("pageSizeChange", pageSize);
+}
+</script>
+
+<template>
+ <div class="flex min-h-[30px] shrink-0 items-center gap-2 border-t bg-muted/30 px-1.5 py-0.5 pl-2">
+ <span class="text-[11px] text-muted-foreground">{{ t("grid.totalRows", { count: totalRows }) }}</span>
+ <div class="ml-auto flex min-w-max items-center gap-1">
+ <Loader2 v-if="loading" class="h-3 w-3 animate-spin text-muted-foreground" />
+ <Select :model-value="String(pageSize)" :disabled="loading" @update:model-value="selectPageSize">
+ <SelectTrigger class="h-6 w-[82px] border-0 bg-transparent px-1.5 text-[11px] shadow-none focus:ring-0">
+ <SelectValue />
+ </SelectTrigger>
+ <SelectContent>
+ <SelectItem v-for="size in pageSizeOptions" :key="size" :value="String(size)">{{ size }}{{ t("grid.rowsPerPageShort") }}</SelectItem>
+ </SelectContent>
+ </Select>
+ <Button variant="ghost" size="icon" class="h-6 w-6" :disabled="loading || currentPage <= 1" :title="t('grid.page', { page: 1 })" @click="requestPage(1)"><ChevronsLeft class="h-3.5 w-3.5" /></Button>
+ <Button variant="ghost" size="icon" class="h-6 w-6" :disabled="loading || currentPage <= 1" :title="t('grid.page', { page: Math.max(1, currentPage - 1) })" @click="requestPage(currentPage - 1)"><ChevronLeft class="h-3.5 w-3.5" /></Button>
+ <Input
+ v-model="pageInput"
+ type="number"
+ inputmode="numeric"
+ min="1"
+ :max="maximumPage"
+ :disabled="loading"
+ :aria-label="t('grid.jumpToPage')"
+ class="h-6 w-14 px-1 text-center text-[11px] tabular-nums [appearance:textfield] [&::-webkit-inner-spin-button]:appearance-none [&::-webkit-outer-spin-button]:appearance-none"
+ @keydown.enter.prevent.stop="applyPageInput"
+ @blur="applyPageInput"
+ />
+ <span class="px-0.5 text-[11px] text-muted-foreground">/ {{ maximumPage }}</span>
+ <Button variant="ghost" size="icon" class="h-6 w-6" :disabled="loading || currentPage >= maximumPage" :title="t('grid.page', { page: Math.min(maximumPage, currentPage + 1) })" @click="requestPage(currentPage + 1)"><ChevronRight class="h-3.5 w-3.5" /></Button>
+ <Button variant="ghost" size="icon" class="h-6 w-6" :disabled="loading || currentPage >= maximumPage" :title="t('grid.page', { page: maximumPage })" @click="requestPage(maximumPage)"><ChevronsRight class="h-3.5 w-3.5" /></Button>
+ </div>
+ </div>
+</template>
diff --git a/apps/desktop/src/components/dolt/DoltDiffTable.vue b/apps/desktop/src/components/dolt/DoltDiffTable.vue
new file mode 100644
index 0000000000..2c4205d3f4
--- /dev/null
+++ b/apps/desktop/src/components/dolt/DoltDiffTable.vue
@@ -0,0 +1,336 @@
+<script setup lang="ts">
+import { computed, nextTick, onMounted, onUnmounted, ref, watch, type CSSProperties } from "vue";
+import DoltScrollArea from "@/components/dolt/DoltScrollArea.vue";
+import type { QueryResult } from "@/types/database";
+import type { DoltDiffColumnKind, DoltDiffRow } from "@/lib/dolt/doltVersionControl";
+import type { DoltDiffCellTarget } from "@/lib/dolt/doltCellDiff";
+
+type CellValue = QueryResult["rows"][number][number];
+
+const props = defineProps<{
+ columns: string[];
+ columnKinds: DoltDiffColumnKind[];
+ rows: DoltDiffRow[];
+ side: "before" | "after";
+ selectedCell?: DoltDiffCellTarget | null;
+ columnWidths?: readonly number[];
+ cellClass?: (rowIndex: number, columnIndex: number, row: CellValue[]) => string | undefined;
+ headerClass?: (columnIndex: number, columnName: string) => string | undefined;
+}>();
+
+const emit = defineEmits<{
+ "column-widths-change": [widths: number[]];
+ "cell-select": [target: DoltDiffCellTarget];
+ "cell-context-menu": [target: DoltDiffCellTarget, event: MouseEvent];
+ "cell-open-details": [target: DoltDiffCellTarget];
+}>();
+
+const HEADER_HEIGHT = 28;
+const ROW_HEIGHT = 26;
+const ROW_BUFFER = 8;
+const COLUMN_BUFFER = 240;
+const minimumColumnWidth = 72;
+const maximumColumnWidth = 360;
+
+const scrollArea = ref<InstanceType<typeof DoltScrollArea> | null>(null);
+const measuredWidths = ref<number[]>([]);
+const scrollTop = ref(0);
+const scrollLeft = ref(0);
+const viewportWidth = ref(0);
+const viewportHeight = ref(0);
+let activeResizeStop: (() => void) | undefined;
+let scrollFrame = 0;
+
+function sameWidths(left: readonly number[], right: readonly number[]): boolean {
+ return left.length === right.length && left.every((width, index) => Math.abs(width - (right[index] ?? 0)) < 0.5);
+}
+
+function textWidth(value: unknown): number {
+ const text = value === null || value === undefined ? "" : String(value);
+ return Math.min(maximumColumnWidth, Math.max(minimumColumnWidth, text.length * 7 + 24));
+}
+
+function measureWidths(): number[] {
+ const widths = props.columns.map(textWidth);
+ for (const diffRow of props.rows) {
+ const row = diffRow[props.side];
+ for (let index = 0; index < widths.length; index += 1) widths[index] = Math.max(widths[index] ?? minimumColumnWidth, textWidth(row[index]));
+ }
+ return widths;
+}
+
+const effectiveWidths = computed(() => {
+ if (props.columnWidths?.length === props.columns.length) return [...props.columnWidths];
+ return measuredWidths.value.length === props.columns.length ? measuredWidths.value : measureWidths();
+});
+const columnOffsets = computed(() => {
+ const offsets: number[] = [];
+ let offset = 0;
+ for (const width of effectiveWidths.value) {
+ offsets.push(offset);
+ offset += width;
+ }
+ return offsets;
+});
+const totalWidth = computed(() => effectiveWidths.value.reduce((sum, width) => sum + width, 0));
+const totalHeight = computed(() => HEADER_HEIGHT + props.rows.length * ROW_HEIGHT);
+const contentStyle = computed<CSSProperties>(() => ({ width: `${Math.max(totalWidth.value, 1)}px`, height: `${Math.max(totalHeight.value, HEADER_HEIGHT)}px` }));
+const visibleRowStart = computed(() => Math.max(0, Math.floor(Math.max(0, scrollTop.value - HEADER_HEIGHT) / ROW_HEIGHT) - ROW_BUFFER));
+const visibleRowEnd = computed(() => Math.min(props.rows.length, Math.ceil(Math.max(0, scrollTop.value - HEADER_HEIGHT + viewportHeight.value) / ROW_HEIGHT) + ROW_BUFFER));
+function findVisibleColumnRange(): { start: number; end: number } {
+ const left = Math.max(0, scrollLeft.value - COLUMN_BUFFER);
+ const right = scrollLeft.value + viewportWidth.value + COLUMN_BUFFER;
+ const widths = effectiveWidths.value;
+ const offsets = columnOffsets.value;
+ let start = 0;
+ while (start < widths.length && (offsets[start] ?? 0) + (widths[start] ?? 0) < left) start += 1;
+ let end = start;
+ while (end < widths.length && (offsets[end] ?? 0) <= right) end += 1;
+ return { start, end };
+}
+const visibleColumnRange = computed(findVisibleColumnRange);
+const visibleColumns = computed(() => {
+ const { start, end } = visibleColumnRange.value;
+ return props.columns.slice(start, end).map((column, offset) => {
+ const index = start + offset;
+ return { column, index, kind: props.columnKinds[index], left: columnOffsets.value[index] ?? 0, width: effectiveWidths.value[index] ?? minimumColumnWidth };
+ });
+});
+const visibleRows = computed(() =>
+ props.rows.slice(visibleRowStart.value, visibleRowEnd.value).map((diffRow, offset) => {
+ const rowIndex = visibleRowStart.value + offset;
+ const row = diffRow[props.side];
+ return { diffRow, row, rowIndex, values: visibleColumns.value.map(({ index }) => valueText(row[index])) };
+ }),
+);
+
+function valueText(value: unknown): string {
+ if (value === null || value === undefined) return "";
+ if (typeof value === "object") {
+ try {
+ return JSON.stringify(value);
+ } catch {
+ return String(value);
+ }
+ }
+ return String(value);
+}
+
+function cellTarget(rowIndex: number, columnIndex: number, diffRow: DoltDiffRow): DoltDiffCellTarget {
+ return {
+ rowIndex,
+ columnIndex,
+ side: props.side,
+ columnName: props.columns[columnIndex] ?? "",
+ columnKind: props.columnKinds[columnIndex] ?? "unchanged",
+ rowKind: diffRow.kind,
+ beforeValue: diffRow.before[columnIndex] ?? null,
+ afterValue: diffRow.after[columnIndex] ?? null,
+ };
+}
+
+function isSelected(rowIndex: number, columnIndex: number): boolean {
+ const selected = props.selectedCell;
+ return !!selected && selected.side === props.side && selected.rowIndex === rowIndex && selected.columnIndex === columnIndex;
+}
+
+function selectCell(rowIndex: number, columnIndex: number, diffRow: DoltDiffRow) {
+ emit("cell-select", cellTarget(rowIndex, columnIndex, diffRow));
+}
+
+function openCellContextMenu(rowIndex: number, columnIndex: number, diffRow: DoltDiffRow, event: MouseEvent) {
+ emit("cell-context-menu", cellTarget(rowIndex, columnIndex, diffRow), event);
+}
+
+function openCellDetails(rowIndex: number, columnIndex: number, diffRow: DoltDiffRow) {
+ emit("cell-open-details", cellTarget(rowIndex, columnIndex, diffRow));
+}
+
+function initializeWidths() {
+ const measured = measureWidths();
+ if (!sameWidths(measuredWidths.value, measured)) measuredWidths.value = measured;
+ if (!props.columnWidths?.length && measured.length) emit("column-widths-change", [...measured]);
+}
+
+function updateViewport(element = scrollArea.value?.scrollerElement()) {
+ if (!element) return;
+ viewportWidth.value = element.clientWidth;
+ viewportHeight.value = element.clientHeight;
+ scrollTop.value = element.scrollTop;
+ scrollLeft.value = element.scrollLeft;
+}
+
+function onScroll(element: HTMLElement) {
+ if (scrollFrame) return;
+ scrollFrame = requestAnimationFrame(() => {
+ scrollFrame = 0;
+ updateViewport(element);
+ });
+}
+
+function startResize(columnIndex: number, event: PointerEvent) {
+ event.preventDefault();
+ event.stopPropagation();
+ activeResizeStop?.();
+ const startX = event.clientX;
+ const startWidths = effectiveWidths.value.slice();
+ const startWidth = startWidths[columnIndex] ?? minimumColumnWidth;
+ let pendingClientX = startX;
+ let resizeFrame = 0;
+ const applyResize = () => {
+ resizeFrame = 0;
+ const next = startWidths.slice();
+ next[columnIndex] = Math.min(maximumColumnWidth, Math.max(minimumColumnWidth, startWidth + pendingClientX - startX));
+ measuredWidths.value = next;
+ emit("column-widths-change", next);
+ };
+ const onMove = (moveEvent: PointerEvent) => {
+ pendingClientX = moveEvent.clientX;
+ if (!resizeFrame) resizeFrame = requestAnimationFrame(applyResize);
+ };
+ const stop = (stopEvent?: PointerEvent) => {
+ if (stopEvent) pendingClientX = stopEvent.clientX;
+ if (resizeFrame) cancelAnimationFrame(resizeFrame);
+ applyResize();
+ window.removeEventListener("pointermove", onMove);
+ window.removeEventListener("pointerup", stop);
+ window.removeEventListener("pointercancel", stop);
+ if (activeResizeStop === stop) activeResizeStop = undefined;
+ };
+ activeResizeStop = stop;
+ window.addEventListener("pointermove", onMove);
+ window.addEventListener("pointerup", stop);
+ window.addEventListener("pointercancel", stop);
+}
+
+watch(
+ () => props.columnWidths,
+ (widths) => {
+ if (widths?.length === props.columns.length && !sameWidths(widths, measuredWidths.value)) measuredWidths.value = [...widths];
+ },
+ { deep: true },
+);
+watch(
+ () => props.columns.join("\0"),
+ () => nextTick(initializeWidths),
+ { immediate: true },
+);
+
+onMounted(() => {
+ initializeWidths();
+ nextTick(updateViewport);
+});
+onUnmounted(() => {
+ activeResizeStop?.();
+ if (scrollFrame) cancelAnimationFrame(scrollFrame);
+});
+</script>
+
+<template>
+ <DoltScrollArea ref="scrollArea" class="min-h-0 flex-1" scroller-class="dolt-diff-table-scroller" @scroll="onScroll" @resize="updateViewport">
+ <div class="dolt-diff-table-content" :style="contentStyle">
+ <div class="dolt-diff-table-header" :style="{ width: `${Math.max(totalWidth, 1)}px`, height: '28px' }">
+ <div v-for="column in visibleColumns" :key="`header-${column.index}-${column.column}`" class="dolt-diff-table-header-cell" :class="headerClass?.(column.index, column.column)" :data-column-kind="column.kind" :style="{ left: `${column.left}px`, width: `${column.width}px` }">
+ <span class="min-w-0 flex-1 truncate" :title="column.column">{{ column.column }}</span>
+ <span class="dolt-diff-table-resize-handle" @pointerdown="startResize(column.index, $event)" />
+ </div>
+ </div>
+ <div
+ v-for="visibleRow in visibleRows"
+ :key="`${visibleRow.rowIndex}-${visibleRow.diffRow.kind}`"
+ class="dolt-diff-table-row"
+ :class="{ 'dolt-diff-table-row-even': visibleRow.rowIndex % 2 === 1 }"
+ :style="{ top: `${HEADER_HEIGHT + visibleRow.rowIndex * ROW_HEIGHT}px`, width: `${Math.max(totalWidth, 1)}px`, height: `${ROW_HEIGHT}px` }"
+ >
+ <div
+ v-for="(column, visibleColumnIndex) in visibleColumns"
+ :key="`${visibleRow.rowIndex}-${column.index}`"
+ class="dolt-diff-table-cell"
+ :class="[cellClass?.(visibleRow.rowIndex, column.index, visibleRow.row), { 'dolt-diff-table-cell-selected': isSelected(visibleRow.rowIndex, column.index) }]"
+ :style="{ left: `${column.left}px`, width: `${column.width}px` }"
+ :title="visibleRow.values[visibleColumnIndex]"
+ @click="selectCell(visibleRow.rowIndex, column.index, visibleRow.diffRow)"
+ @contextmenu="openCellContextMenu(visibleRow.rowIndex, column.index, visibleRow.diffRow, $event)"
+ @dblclick="openCellDetails(visibleRow.rowIndex, column.index, visibleRow.diffRow)"
+ >
+ {{ visibleRow.values[visibleColumnIndex] }}
+ </div>
+ </div>
+ <div v-if="rows.length === 0" class="dolt-diff-table-empty">{{ $t("doltVersionControl.noRowChanges") }}</div>
+ </div>
+ </DoltScrollArea>
+</template>
+
+<style scoped>
+.dolt-diff-table-content {
+ position: relative;
+ min-width: 100%;
+}
+.dolt-diff-table-header {
+ position: sticky;
+ top: 0;
+ z-index: 2;
+ min-width: 100%;
+ border-bottom: 1px solid var(--border);
+ background: var(--background);
+ font-size: 11px;
+ font-weight: 600;
+}
+.dolt-diff-table-row {
+ position: absolute;
+ left: 0;
+ min-width: 100%;
+}
+.dolt-diff-table-header-cell,
+.dolt-diff-table-cell {
+ position: absolute;
+ top: 0;
+ bottom: 0;
+ box-sizing: border-box;
+ min-width: 0;
+ overflow: hidden;
+ border-right: 1px solid var(--border);
+ border-bottom: 1px solid color-mix(in srgb, var(--border) 65%, transparent);
+ padding: 5px 8px;
+ white-space: nowrap;
+ text-overflow: ellipsis;
+}
+.dolt-diff-table-header-cell {
+ display: flex;
+ align-items: center;
+}
+.dolt-diff-table-cell {
+ font-size: 12px;
+ line-height: 16px;
+ cursor: default;
+ user-select: none;
+}
+.dolt-diff-table-cell-selected {
+ z-index: 1;
+ outline: 2px solid color-mix(in srgb, var(--primary) 78%, transparent);
+ outline-offset: -2px;
+}
+.dolt-diff-table-row-even .dolt-diff-table-cell {
+ background: color-mix(in srgb, var(--muted) 18%, transparent);
+}
+.dolt-diff-table-resize-handle {
+ position: absolute;
+ top: 0;
+ right: 0;
+ bottom: 0;
+ width: 6px;
+ cursor: col-resize;
+}
+.dolt-diff-table-resize-handle:hover {
+ background: color-mix(in srgb, var(--primary) 35%, transparent);
+}
+.dolt-diff-table-empty {
+ position: sticky;
+ left: 0;
+ width: min(100%, 480px);
+ padding: 24px 12px;
+ text-align: center;
+ font-size: 12px;
+ color: var(--muted-foreground);
+}
+</style>
diff --git a/apps/desktop/src/components/dolt/DoltRevisionSelector.vue b/apps/desktop/src/components/dolt/DoltRevisionSelector.vue
new file mode 100644
index 0000000000..f8148bf086
--- /dev/null
+++ b/apps/desktop/src/components/dolt/DoltRevisionSelector.vue
@@ -0,0 +1,286 @@
+<script setup lang="ts">
+import { computed, nextTick, onMounted, onUnmounted, ref, watch } from "vue";
+import { Check, ChevronDown, GitBranch, Tag } from "@lucide/vue";
+import DoltScrollArea from "@/components/dolt/DoltScrollArea.vue";
+import type { DoltRef } from "@/lib/dolt/doltVersionControl";
+
+const props = defineProps<{
+ modelValue: string;
+ options: readonly DoltRef[];
+ disabled?: boolean;
+ placeholder: string;
+ inputLabel: string;
+}>();
+
+const emit = defineEmits<{
+ commit: [value: string];
+}>();
+
+const root = ref<HTMLElement | null>(null);
+const input = ref<HTMLInputElement | null>(null);
+const draft = ref(props.modelValue);
+const open = ref(false);
+const highlightedIndex = ref(0);
+const keyboardNavigation = ref(false);
+
+const filteredOptions = computed(() => {
+ const query = draft.value.trim().toLowerCase();
+ if (!query || query === props.modelValue.toLowerCase()) return props.options;
+ return props.options.filter((option) => option.name.toLowerCase().includes(query));
+});
+
+watch(
+ () => props.modelValue,
+ (value) => {
+ draft.value = value;
+ },
+);
+
+watch(filteredOptions, (options) => {
+ highlightedIndex.value = Math.min(highlightedIndex.value, Math.max(0, options.length - 1));
+});
+
+function showOptions() {
+ if (props.disabled) return;
+ open.value = true;
+ const selectedIndex = filteredOptions.value.findIndex((option) => option.name === props.modelValue);
+ highlightedIndex.value = Math.max(0, selectedIndex);
+ keyboardNavigation.value = false;
+}
+
+function toggleOptions() {
+ if (open.value) {
+ open.value = false;
+ return;
+ }
+ showOptions();
+ void nextTick(() => input.value?.focus());
+}
+
+function commitDraft() {
+ const revision = draft.value.trim();
+ if (!revision) {
+ draft.value = props.modelValue;
+ open.value = false;
+ return;
+ }
+ draft.value = revision;
+ open.value = false;
+ if (revision !== props.modelValue) emit("commit", revision);
+}
+
+function selectOption(option: DoltRef) {
+ draft.value = option.name;
+ open.value = false;
+ if (option.name !== props.modelValue) emit("commit", option.name);
+ void nextTick(() => input.value?.focus());
+}
+
+function onInput(event: Event) {
+ draft.value = (event.currentTarget as HTMLInputElement).value;
+ showOptions();
+}
+
+function onKeydown(event: KeyboardEvent) {
+ if (event.key === "Enter") {
+ event.preventDefault();
+ const highlighted = keyboardNavigation.value ? filteredOptions.value[highlightedIndex.value] : undefined;
+ if (highlighted) {
+ selectOption(highlighted);
+ return;
+ }
+ commitDraft();
+ return;
+ }
+ if (event.key === "Escape") {
+ event.preventDefault();
+ draft.value = props.modelValue;
+ open.value = false;
+ return;
+ }
+ if (event.key !== "ArrowDown" && event.key !== "ArrowUp") return;
+ event.preventDefault();
+ if (!open.value) showOptions();
+ const count = filteredOptions.value.length;
+ if (!count) return;
+ keyboardNavigation.value = true;
+ highlightedIndex.value = (highlightedIndex.value + (event.key === "ArrowDown" ? 1 : -1) + count) % count;
+}
+
+function onBlur() {
+ window.setTimeout(() => {
+ if (root.value?.contains(document.activeElement)) return;
+ commitDraft();
+ }, 0);
+}
+
+function onDocumentPointerDown(event: PointerEvent) {
+ if (root.value?.contains(event.target as Node)) return;
+ if (open.value) commitDraft();
+}
+
+onMounted(() => document.addEventListener("pointerdown", onDocumentPointerDown));
+onUnmounted(() => document.removeEventListener("pointerdown", onDocumentPointerDown));
+</script>
+
+<template>
+ <div ref="root" class="dolt-revision-selector">
+ <span class="dolt-revision-selector-sizer" aria-hidden="true">{{ draft || placeholder }}</span>
+ <div class="dolt-revision-selector-field" :class="{ 'dolt-revision-selector-field-open': open, 'dolt-revision-selector-field-disabled': disabled }">
+ <input
+ ref="input"
+ :value="draft"
+ type="text"
+ autocomplete="off"
+ autocapitalize="off"
+ spellcheck="false"
+ class="dolt-revision-selector-input"
+ role="combobox"
+ aria-autocomplete="list"
+ :aria-expanded="open"
+ :aria-label="inputLabel"
+ :title="draft || placeholder"
+ :placeholder="placeholder"
+ :disabled="disabled"
+ @focus="showOptions"
+ @input="onInput"
+ @keydown="onKeydown"
+ @blur="onBlur"
+ />
+ <button type="button" class="dolt-revision-selector-toggle" :disabled="disabled" tabindex="-1" :aria-label="inputLabel" @mousedown.prevent @click="toggleOptions">
+ <ChevronDown class="h-3.5 w-3.5" />
+ </button>
+ </div>
+
+ <div v-if="open && filteredOptions.length" class="dolt-revision-selector-options" role="listbox">
+ <DoltScrollArea class="max-h-[240px]" scroller-class="p-[3px]">
+ <button
+ v-for="(option, index) in filteredOptions"
+ :key="`${option.kind}:${option.name}`"
+ type="button"
+ role="option"
+ :aria-selected="option.name === modelValue"
+ class="dolt-revision-selector-option"
+ :class="{ 'dolt-revision-selector-option-highlighted': index === highlightedIndex }"
+ @mousedown.prevent="selectOption(option)"
+ @mouseenter="highlightedIndex = index"
+ >
+ <GitBranch v-if="option.kind === 'branch'" class="h-3.5 w-3.5 text-blue-600 dark:text-blue-400" />
+ <Tag v-else class="h-3.5 w-3.5 text-amber-600 dark:text-amber-400" />
+ <span class="min-w-0 flex-1 truncate font-mono text-[11px]">{{ option.name }}</span>
+ <Check v-if="option.name === modelValue" class="h-3.5 w-3.5 text-primary" />
+ </button>
+ </DoltScrollArea>
+ </div>
+ </div>
+</template>
+
+<style scoped>
+.dolt-revision-selector {
+ position: relative;
+ display: inline-grid;
+ min-width: 120px;
+ max-width: 220px;
+ flex: 0 1 auto;
+ grid-template-areas: "control";
+}
+
+.dolt-revision-selector-sizer {
+ grid-area: control;
+ min-width: 0;
+ overflow: hidden;
+ padding: 0 30px 0 8px;
+ visibility: hidden;
+ white-space: pre;
+ font-family: var(--font-mono);
+ font-size: 11px;
+}
+
+.dolt-revision-selector-field {
+ grid-area: control;
+ display: flex;
+ width: 100%;
+ height: 28px;
+ min-width: 0;
+ align-items: center;
+ border: 1px solid var(--border);
+ border-radius: 4px;
+ background: color-mix(in srgb, var(--muted) 28%, transparent);
+}
+
+.dolt-revision-selector-field:focus-within,
+.dolt-revision-selector-field-open {
+ border-color: var(--ring);
+ box-shadow: 0 0 0 1px color-mix(in srgb, var(--ring) 35%, transparent);
+}
+
+.dolt-revision-selector-field-disabled {
+ opacity: 0.55;
+}
+
+.dolt-revision-selector-input {
+ width: 100%;
+ min-width: 0;
+ flex: 1;
+ border: 0;
+ background: transparent;
+ padding: 0 2px 0 7px;
+ outline: none;
+ overflow: hidden;
+ text-overflow: ellipsis;
+ font-family: var(--font-mono);
+ font-size: 11px;
+ color: var(--foreground);
+}
+
+.dolt-revision-selector-input::placeholder {
+ color: var(--muted-foreground);
+}
+
+.dolt-revision-selector-toggle {
+ display: inline-flex;
+ width: 25px;
+ height: 100%;
+ flex-shrink: 0;
+ align-items: center;
+ justify-content: center;
+ color: var(--muted-foreground);
+}
+
+.dolt-revision-selector-toggle:hover:not(:disabled) {
+ color: var(--foreground);
+}
+
+.dolt-revision-selector-options {
+ position: absolute;
+ z-index: 60;
+ top: calc(100% + 4px);
+ left: 0;
+ width: max(100%, 180px);
+ max-width: 280px;
+ max-height: 240px;
+ overflow: hidden;
+ border: 1px solid var(--border);
+ border-radius: 4px;
+ background: var(--popover);
+ color: var(--popover-foreground);
+ box-shadow: 0 6px 18px rgb(0 0 0 / 0.14);
+}
+
+.dolt-revision-selector-option {
+ display: flex;
+ width: 100%;
+ height: 26px;
+ align-items: center;
+ gap: 6px;
+ border-radius: 3px;
+ padding: 0 6px;
+ text-align: left;
+}
+
+.dolt-revision-selector-option:hover,
+.dolt-revision-selector-option-highlighted {
+ background: var(--accent);
+ color: var(--accent-foreground);
+}
+</style>
diff --git a/apps/desktop/src/components/dolt/DoltScrollArea.vue b/apps/desktop/src/components/dolt/DoltScrollArea.vue
new file mode 100644
index 0000000000..3ece6ffa5f
--- /dev/null
+++ b/apps/desktop/src/components/dolt/DoltScrollArea.vue
@@ -0,0 +1,272 @@
+<script setup lang="ts">
+import { nextTick, onMounted, onUnmounted, ref } from "vue";
+
+const props = defineProps<{
+ scrollerClass?: string;
+}>();
+
+const emit = defineEmits<{
+ scroll: [element: HTMLElement];
+ resize: [element: HTMLElement];
+}>();
+
+const scroller = ref<HTMLElement | null>(null);
+const horizontalThumb = ref<HTMLElement | null>(null);
+const verticalThumb = ref<HTMLElement | null>(null);
+const hasHorizontalOverflow = ref(false);
+const hasVerticalOverflow = ref(false);
+let horizontalThumbLeft = 0;
+let horizontalThumbWidth = 100;
+let verticalThumbTop = 0;
+let verticalThumbHeight = 100;
+let resizeObserver: ResizeObserver | undefined;
+let mutationObserver: MutationObserver | undefined;
+let refreshFrame = 0;
+let dragFrame = 0;
+let pendingDragPosition = 0;
+let dragState:
+ | {
+ axis: "horizontal" | "vertical";
+ track: HTMLElement;
+ trackRect: DOMRect;
+ thumbOffset: number;
+ maxScroll: number;
+ }
+ | undefined;
+
+function applyThumbStyles() {
+ if (horizontalThumb.value) {
+ horizontalThumb.value.style.left = `${horizontalThumbLeft}%`;
+ horizontalThumb.value.style.width = `${horizontalThumbWidth}%`;
+ }
+ if (verticalThumb.value) {
+ verticalThumb.value.style.top = `${verticalThumbTop}%`;
+ verticalThumb.value.style.height = `${verticalThumbHeight}%`;
+ }
+}
+
+function updateMetrics(emitResize = false) {
+ const element = scroller.value;
+ if (!element) return;
+ const maxScrollLeft = Math.max(0, element.scrollWidth - element.clientWidth);
+ const maxScrollTop = Math.max(0, element.scrollHeight - element.clientHeight);
+ hasHorizontalOverflow.value = maxScrollLeft > 1;
+ hasVerticalOverflow.value = maxScrollTop > 1;
+
+ const rawHorizontalWidth = element.scrollWidth > 0 ? (element.clientWidth / element.scrollWidth) * 100 : 100;
+ horizontalThumbWidth = Math.min(100, Math.max(6, rawHorizontalWidth));
+ horizontalThumbLeft = maxScrollLeft > 0 ? (element.scrollLeft / maxScrollLeft) * Math.max(0, 100 - horizontalThumbWidth) : 0;
+ const rawVerticalHeight = element.scrollHeight > 0 ? (element.clientHeight / element.scrollHeight) * 100 : 100;
+ verticalThumbHeight = Math.min(100, Math.max(6, rawVerticalHeight));
+ verticalThumbTop = maxScrollTop > 0 ? (element.scrollTop / maxScrollTop) * Math.max(0, 100 - verticalThumbHeight) : 0;
+ nextTick(applyThumbStyles);
+ if (emitResize) emit("resize", element);
+}
+
+function scheduleMetricsRefresh(emitResize = false) {
+ if (refreshFrame) cancelAnimationFrame(refreshFrame);
+ refreshFrame = requestAnimationFrame(() => {
+ refreshFrame = 0;
+ updateMetrics(emitResize);
+ });
+}
+
+function onScroll() {
+ const element = scroller.value;
+ if (!element) return;
+ updateMetrics();
+ emit("scroll", element);
+}
+
+function applyDrag() {
+ dragFrame = 0;
+ const state = dragState;
+ const element = scroller.value;
+ if (!state || !element) return;
+ const trackLength = state.axis === "horizontal" ? state.trackRect.width : state.trackRect.height;
+ const thumbPercent = state.axis === "horizontal" ? horizontalThumbWidth : verticalThumbHeight;
+ const thumbLength = trackLength * (thumbPercent / 100);
+ const maximumThumbPosition = Math.max(1, trackLength - thumbLength);
+ const pointerPosition = pendingDragPosition - (state.axis === "horizontal" ? state.trackRect.left : state.trackRect.top);
+ const thumbPosition = Math.min(maximumThumbPosition, Math.max(0, pointerPosition - state.thumbOffset));
+ const scrollPosition = (thumbPosition / maximumThumbPosition) * state.maxScroll;
+ if (state.axis === "horizontal") element.scrollLeft = scrollPosition;
+ else element.scrollTop = scrollPosition;
+ onScroll();
+}
+
+function onDragMove(event: PointerEvent) {
+ if (!dragState) return;
+ event.preventDefault();
+ pendingDragPosition = dragState.axis === "horizontal" ? event.clientX : event.clientY;
+ if (!dragFrame) dragFrame = requestAnimationFrame(applyDrag);
+}
+
+function stopDrag() {
+ if (!dragState) return;
+ if (dragFrame) {
+ cancelAnimationFrame(dragFrame);
+ applyDrag();
+ }
+ dragState.track.classList.remove("dolt-scrollbar-dragging");
+ dragState = undefined;
+ document.body.style.userSelect = "";
+ window.removeEventListener("pointermove", onDragMove, true);
+ window.removeEventListener("pointerup", stopDrag, true);
+ window.removeEventListener("pointercancel", stopDrag, true);
+}
+
+function startDrag(axis: "horizontal" | "vertical", event: PointerEvent) {
+ const element = scroller.value;
+ const track = event.currentTarget as HTMLElement;
+ if (!element) return;
+ const maxScroll = axis === "horizontal" ? element.scrollWidth - element.clientWidth : element.scrollHeight - element.clientHeight;
+ if (maxScroll <= 1) return;
+ const trackRect = track.getBoundingClientRect();
+ const trackLength = axis === "horizontal" ? trackRect.width : trackRect.height;
+ const thumbPercent = axis === "horizontal" ? horizontalThumbWidth : verticalThumbHeight;
+ const thumbStartPercent = axis === "horizontal" ? horizontalThumbLeft : verticalThumbTop;
+ const thumbLength = trackLength * (thumbPercent / 100);
+ const thumbStart = trackLength * (thumbStartPercent / 100);
+ const pointerPosition = axis === "horizontal" ? event.clientX - trackRect.left : event.clientY - trackRect.top;
+ const pointerInsideThumb = pointerPosition >= thumbStart && pointerPosition <= thumbStart + thumbLength;
+ dragState = {
+ axis,
+ track,
+ trackRect,
+ thumbOffset: pointerInsideThumb ? pointerPosition - thumbStart : thumbLength / 2,
+ maxScroll,
+ };
+ pendingDragPosition = axis === "horizontal" ? event.clientX : event.clientY;
+ track.classList.add("dolt-scrollbar-dragging");
+ document.body.style.userSelect = "none";
+ window.addEventListener("pointermove", onDragMove, true);
+ window.addEventListener("pointerup", stopDrag, true);
+ window.addEventListener("pointercancel", stopDrag, true);
+ event.preventDefault();
+ applyDrag();
+}
+
+function scrollerElement(): HTMLElement | null {
+ return scroller.value;
+}
+
+defineExpose({ scrollerElement, refresh: scheduleMetricsRefresh });
+
+onMounted(() => {
+ updateMetrics(true);
+ resizeObserver = new ResizeObserver(() => scheduleMetricsRefresh(true));
+ if (scroller.value) resizeObserver.observe(scroller.value);
+ mutationObserver = new MutationObserver(() => scheduleMetricsRefresh(true));
+ if (scroller.value) mutationObserver.observe(scroller.value, { childList: true, subtree: true, characterData: true, attributes: true, attributeFilter: ["class", "style"] });
+});
+
+onUnmounted(() => {
+ stopDrag();
+ resizeObserver?.disconnect();
+ mutationObserver?.disconnect();
+ if (refreshFrame) cancelAnimationFrame(refreshFrame);
+});
+</script>
+
+<template>
+ <div class="dolt-scroll-area">
+ <div ref="scroller" class="dolt-scroll-area-scroller" :class="props.scrollerClass" @scroll.passive="onScroll">
+ <slot />
+ </div>
+ <div v-if="hasHorizontalOverflow" class="dolt-horizontal-scrollbar" @pointerdown="startDrag('horizontal', $event)">
+ <div ref="horizontalThumb" class="dolt-horizontal-scrollbar-thumb" />
+ </div>
+ <div v-if="hasVerticalOverflow" class="dolt-vertical-scrollbar" :class="{ 'dolt-vertical-scrollbar-with-horizontal': hasHorizontalOverflow }" @pointerdown="startDrag('vertical', $event)">
+ <div ref="verticalThumb" class="dolt-vertical-scrollbar-thumb" />
+ </div>
+ </div>
+</template>
+
+<style scoped>
+.dolt-scroll-area {
+ position: relative;
+ display: flex;
+ min-width: 0;
+ min-height: 0;
+ flex-direction: column;
+ overflow: hidden;
+}
+
+.dolt-scroll-area-scroller {
+ min-width: 0;
+ min-height: 0;
+ flex: 1;
+ overflow: auto;
+ overscroll-behavior: none;
+ scrollbar-width: none;
+}
+
+.dolt-scroll-area-scroller::-webkit-scrollbar {
+ display: none;
+}
+
+.dolt-horizontal-scrollbar {
+ position: relative;
+ height: 10px;
+ flex: 0 0 10px;
+ cursor: pointer;
+ touch-action: none;
+ background: var(--background);
+}
+
+.dolt-horizontal-scrollbar-thumb {
+ position: absolute;
+ top: 3px;
+ height: 4px;
+ min-width: 24px;
+ border-radius: 999px;
+ background: color-mix(in oklab, var(--foreground) 30%, transparent);
+ transition:
+ top 120ms ease,
+ height 120ms ease,
+ background-color 120ms ease;
+}
+
+.dolt-horizontal-scrollbar:hover .dolt-horizontal-scrollbar-thumb,
+.dolt-horizontal-scrollbar.dolt-scrollbar-dragging .dolt-horizontal-scrollbar-thumb {
+ top: 2px;
+ height: 6px;
+ background: color-mix(in oklab, var(--foreground) 48%, transparent);
+}
+
+.dolt-vertical-scrollbar {
+ position: absolute;
+ top: 2px;
+ right: 0;
+ bottom: 2px;
+ z-index: 5;
+ width: 10px;
+ cursor: pointer;
+ touch-action: none;
+}
+
+.dolt-vertical-scrollbar-with-horizontal {
+ bottom: 12px;
+}
+
+.dolt-vertical-scrollbar-thumb {
+ position: absolute;
+ right: 3px;
+ width: 4px;
+ min-height: 24px;
+ border-radius: 999px;
+ background: color-mix(in oklab, var(--foreground) 30%, transparent);
+ transition:
+ right 120ms ease,
+ width 120ms ease,
+ background-color 120ms ease;
+}
+
+.dolt-vertical-scrollbar:hover .dolt-vertical-scrollbar-thumb,
+.dolt-vertical-scrollbar.dolt-scrollbar-dragging .dolt-vertical-scrollbar-thumb {
+ right: 2px;
+ width: 6px;
+ background: color-mix(in oklab, var(--foreground) 48%, transparent);
+}
+</style>
diff --git a/apps/desktop/src/components/dolt/DoltVersionControl.vue b/apps/desktop/src/components/dolt/DoltVersionControl.vue
new file mode 100644
index 0000000000..a22cfa4a16
--- /dev/null
+++ b/apps/desktop/src/components/dolt/DoltVersionControl.vue
@@ -0,0 +1,1983 @@
+<script setup lang="ts">
+import { computed, onMounted, onUnmounted, ref, shallowRef, watch } from "vue";
+import { useI18n } from "vue-i18n";
+import { ArrowRight, Check, ChevronRight, Clipboard, Database, FileDiff, Folder, FolderOpen, GitBranch, GitCommitHorizontal, GitMerge, GitPullRequest, List, Loader2, Plus, RefreshCw, RotateCcw, Search, Table2, Tag, Trash2, TriangleAlert, Undo2 } from "@lucide/vue";
+import { Splitpanes, Pane } from "splitpanes";
+import "splitpanes/dist/splitpanes.css";
+import { Button } from "@/components/ui/button";
+import { Input } from "@/components/ui/input";
+import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";
+import { Dialog, DialogContent, DialogDescription, DialogFooter, DialogHeader, DialogTitle } from "@/components/ui/dialog";
+import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs";
+import CustomContextMenu, { type ContextMenuItem } from "@/components/ui/CustomContextMenu.vue";
+import DoltDiffPagination from "@/components/dolt/DoltDiffPagination.vue";
+import DoltDiffTable from "@/components/dolt/DoltDiffTable.vue";
+import DoltCellDiffDialog from "@/components/dolt/DoltCellDiffDialog.vue";
+import DoltRevisionSelector from "@/components/dolt/DoltRevisionSelector.vue";
+import DoltScrollArea from "@/components/dolt/DoltScrollArea.vue";
+import * as api from "@/lib/backend/api";
+import { filterDatabaseNamesForVisiblePicker } from "@/lib/database/visibleDatabases";
+import type { QueryResult } from "@/types/database";
+import {
+ doltAddAllSql,
+ doltCommitSql,
+ doltCreateBranchSql,
+ doltCreateTagSql,
+ doltCheckoutBranchSql,
+ doltDeleteBranchSql,
+ doltDeleteTagSql,
+ doltDiscardWorkingTreeSql,
+ doltDiffSummarySql,
+ doltClientSessionScope,
+ doltGraphEdgePath,
+ doltGraphEdgeRoute,
+ doltHardResetSql,
+ doltLogSql,
+ doltMergeBranchSql,
+ doltRevertCommitSql,
+ doltRefColorIndexes,
+ doltRefsByCommit,
+ doltStatusSql,
+ doltTableChangeFlags,
+ doltTableChangeKind,
+ doltTableChangeSymbol,
+ doltTableDiffCountSql,
+ doltTableDiffSql,
+ layoutDoltCommitGraph,
+ parseDoltBranches,
+ parseDoltCommits,
+ parseDoltRowDiff,
+ parseDoltStatus,
+ parseDoltTableChanges,
+ parseDoltTags,
+ type DoltCommit,
+ type DoltDiffRow,
+ type DoltGraphEdgeRoute,
+ type DoltRef,
+ type DoltTableChange,
+ type DoltTableChangeFlag,
+ type DoltWorkingChange,
+ type DoltClientSessionScope,
+} from "@/lib/dolt/doltVersionControl";
+import { useConnectionStore } from "@/stores/connectionStore";
+import { useQueryStore } from "@/stores/queryStore";
+import { useToast } from "@/composables/useToast";
+import { copyToClipboard } from "@/lib/common/clipboard";
+import { doltCellCopyText, type DoltCellSide, type DoltDiffCellTarget } from "@/lib/dolt/doltCellDiff";
+
+const props = defineProps<{
+ connectionId: string;
+ database: string;
+ initialBranch?: string;
+}>();
+
+const { t, locale } = useI18n();
+const connectionStore = useConnectionStore();
+const queryStore = useQueryStore();
+const { toast } = useToast();
+function baseDatabaseName(database: string): string {
+ const slash = database.indexOf("/");
+ return slash > 0 ? database.slice(0, slash) : database;
+}
+const loading = ref(false);
+const graphLoading = ref(false);
+const comparisonLoading = ref(false);
+const tableDiffLoading = ref(false);
+const error = ref("");
+const comparisonError = ref("");
+const tableDiffError = ref("");
+const activeBranch = ref("");
+const selectedDatabase = ref(baseDatabaseName(props.database));
+const databaseOptions = ref<string[]>([]);
+const databaseLoading = ref(false);
+const databaseSwitching = ref(false);
+const branchSwitchingTarget = ref("");
+const branches = ref<DoltRef[]>([]);
+const tags = ref<DoltRef[]>([]);
+const commits = ref<DoltCommit[]>([]);
+const workingChanges = ref<DoltWorkingChange[]>([]);
+const selectedRef = ref("");
+const selectedRevisionKeys = ref<string[]>([]);
+const comparedFrom = ref("");
+const comparedTo = ref("");
+const changes = ref<DoltTableChange[]>([]);
+const selectedTableName = ref("");
+const tableDiff = shallowRef<QueryResult | null>(null);
+const selectedDiffCell = ref<DoltDiffCellTarget | null>(null);
+const diffCellContextTarget = ref<DoltDiffCellTarget | null>(null);
+const diffCellDetailTarget = ref<DoltDiffCellTarget | null>(null);
+const diffCellDetailOpen = ref(false);
+const refFilter = ref("");
+const refListTab = ref<"branches" | "tags">("branches");
+const branchTreeView = ref(true);
+const collapsedBranchPaths = ref<Set<string>>(new Set());
+const branchDialog = ref<"create" | "merge" | "delete" | "create-tag" | "delete-tag" | null>(null);
+const branchNameDraft = ref("");
+const branchSourceRevision = ref("HEAD");
+const branchActionTarget = ref("");
+const mutationLoading = ref(false);
+const mutationError = ref("");
+const commitDialogOpen = ref(false);
+const commitMessageDraft = ref("");
+const commitError = ref("");
+const commitHistoryOperation = ref<"revert" | "hard-reset" | null>(null);
+const commitHistoryTarget = ref<DoltCommit | null>(null);
+const commitHistoryError = ref("");
+const discardWorkingTreeDialogOpen = ref(false);
+const discardWorkingTreeError = ref("");
+const activeDatabase = computed(() => selectedDatabase.value || baseDatabaseName(props.database));
+const clientSessionId = computed(() => doltClientSessionScope(props.connectionId, activeDatabase.value).clientSessionId);
+let loadGeneration = 0;
+let comparisonGeneration = 0;
+let tableDiffGeneration = 0;
+let databaseSwitchGeneration = 0;
+const COMMIT_ROW_HEIGHT = 30;
+const DOLT_DIFF_DEFAULT_PAGE_SIZE = 100;
+const DOLT_LEFT_PANE_DEFAULT_SIZE = 20;
+const DOLT_LEFT_PANE_MIN_SIZE = 15;
+const DOLT_LEFT_PANE_MAX_SIZE = 40;
+const GRAPH_COLORS = ["#2f6fdb", "#1f8f55", "#b7791f", "#c2413a", "#7c3aed", "#0f766e", "#b45309", "#0891b2", "#be185d", "#4d7c0f", "#4338ca", "#a16207", "#0e7490", "#9f1239", "#166534", "#6d28d9", "#92400e", "#475569"];
+const doltLeftPaneSize = ref(DOLT_LEFT_PANE_DEFAULT_SIZE);
+
+const allRefs = computed(() => [...branches.value, ...tags.value]);
+const normalizedRefFilter = computed(() => refFilter.value.trim().toLowerCase());
+const visibleBranches = computed(() =>
+ branches.value
+ .filter((item) => item.active || !normalizedRefFilter.value || item.name.toLowerCase().includes(normalizedRefFilter.value))
+ .sort((left, right) => {
+ if (left.active !== right.active) return left.active ? -1 : 1;
+ return left.name.localeCompare(right.name, locale.value, { sensitivity: "base" });
+ }),
+);
+const visibleTags = computed(() => tags.value.filter((item) => !normalizedRefFilter.value || item.name.toLowerCase().includes(normalizedRefFilter.value)));
+
+interface BranchTreeNode {
+ path: string;
+ label: string;
+ branch?: DoltRef;
+ children: Map<string, BranchTreeNode>;
+}
+
+interface BranchTreeRow {
+ key: string;
+ label: string;
+ depth: number;
+ branch?: DoltRef;
+ folder: boolean;
+ expanded: boolean;
+}
+
+const branchTreeRows = computed<BranchTreeRow[]>(() => {
+ const roots = new Map<string, BranchTreeNode>();
+ for (const branch of visibleBranches.value) {
+ const parts = branch.name.split("/").filter(Boolean);
+ if (parts.length === 0) continue;
+ let level = roots;
+ let parentPath = "";
+ parts.forEach((part, index) => {
+ const path = parentPath ? `${parentPath}/${part}` : part;
+ const node = level.get(path) ?? { path, label: part, children: new Map<string, BranchTreeNode>() };
+ if (index === parts.length - 1) node.branch = branch;
+ level.set(path, node);
+ parentPath = path;
+ level = node.children;
+ });
+ }
+
+ const rows: BranchTreeRow[] = [];
+ const activeBranchName = branches.value.find((branch) => branch.active)?.name ?? "";
+ const append = (nodes: Map<string, BranchTreeNode>, depth: number) => {
+ [...nodes.values()]
+ .sort((left, right) => {
+ const leftContainsActive = !!activeBranchName && (left.path === activeBranchName || activeBranchName.startsWith(`${left.path}/`));
+ const rightContainsActive = !!activeBranchName && (right.path === activeBranchName || activeBranchName.startsWith(`${right.path}/`));
+ if (leftContainsActive !== rightContainsActive) return leftContainsActive ? -1 : 1;
+ if (left.branch?.active !== right.branch?.active) return left.branch?.active ? -1 : 1;
+ return left.label.localeCompare(right.label, locale.value, { sensitivity: "base" });
+ })
+ .forEach((node) => {
+ const folder = node.children.size > 0;
+ const expanded = folder && !collapsedBranchPaths.value.has(node.path);
+ rows.push({ key: node.path, label: node.label, depth, branch: node.branch, folder, expanded });
+ if (expanded) append(node.children, depth + 1);
+ });
+ };
+ append(roots, 0);
+ return rows;
+});
+const refsByCommit = computed(() => doltRefsByCommit(commits.value, allRefs.value));
+const graphRefColorIndexes = computed(() =>
+ doltRefColorIndexes(
+ [...refsByCommit.value.values()].flat().map((refItem) => refItem.name),
+ GRAPH_COLORS.length,
+ ),
+);
+const graphLayout = computed(() => layoutDoltCommitGraph(commits.value, allRefs.value, activeBranch.value));
+const workingTreeLane = computed(() => graphLayout.value.rows[0]?.lane ?? 0);
+const workingTreeRef = computed(() => graphLayout.value.rows[0]?.nodeRef ?? activeBranch.value);
+const graphWidth = computed(() => Math.max(72, graphLayout.value.laneCount * 18 + 30));
+const showWorkingTree = computed(() => workingChanges.value.length > 0 && selectedRef.value === activeBranch.value);
+const graphRowOffset = computed(() => (showWorkingTree.value ? 1 : 0));
+const graphHeight = computed(() => (commits.value.length + graphRowOffset.value) * COMMIT_ROW_HEIGHT);
+const stagedWorkingChangeCount = computed(() => workingChanges.value.filter((change) => change.staged).length);
+const unstagedWorkingChangeCount = computed(() => workingChanges.value.length - stagedWorkingChangeCount.value);
+const workingTreeTitle = computed(() => workingChanges.value.map((change) => `${change.tableName}: ${change.status || "modified"}`).join("\n"));
+const selectedChange = computed(() => changes.value.find((change) => change.tableName === selectedTableName.value));
+const parsedTableDiff = computed(() => (tableDiff.value ? parseDoltRowDiff(tableDiff.value, selectedChange.value?.schemaChange) : { columns: [], columnKinds: [], rows: [] as DoltDiffRow[] }));
+const diffGridScopeKey = computed(() => [props.connectionId, activeDatabase.value, comparedFrom.value, comparedTo.value, selectedTableName.value].join(":"));
+const diffColumnWidths = ref<number[]>([]);
+const beforeDiffSide = ref<HTMLElement | null>(null);
+const afterDiffSide = ref<HTMLElement | null>(null);
+let diffColumnWidthReports: Partial<Record<"before" | "after", number[]>> = {};
+const diffColumnWidthsReady = ref(false);
+let detachDiffScrollSync: (() => void) | undefined;
+let diffScrollSyncFrame = 0;
+let diffScrollSyncRetry = 0;
+let diffScrollSyncRetryTimer = 0;
+let diffScrollSyncing = false;
+const tableDiffPage = ref(1);
+const tableDiffPageSize = ref(DOLT_DIFF_DEFAULT_PAGE_SIZE);
+const tableDiffTotalRows = ref(0);
+const tableDiffMaximumPage = computed(() => Math.max(1, Math.ceil(tableDiffTotalRows.value / tableDiffPageSize.value)));
+const selectedRevisionKeySet = computed(() => new Set(selectedRevisionKeys.value));
+const connectionReadOnly = computed(() => connectionStore.getConfig(props.connectionId)?.read_only ?? false);
+const createsNamedRef = computed(() => branchDialog.value === "create" || branchDialog.value === "create-tag");
+const mutationDialogTitle = computed(() => {
+ if (branchDialog.value === "create") return t("doltVersionControl.createBranch");
+ if (branchDialog.value === "create-tag") return t("doltVersionControl.createTag");
+ if (branchDialog.value === "merge") return t("doltVersionControl.mergeBranch");
+ if (branchDialog.value === "delete-tag") return t("doltVersionControl.deleteTag");
+ return t("doltVersionControl.deleteBranch");
+});
+const mutationDialogDescription = computed(() => {
+ if (branchDialog.value === "create") return t("doltVersionControl.createBranchDescription");
+ if (branchDialog.value === "create-tag") return t("doltVersionControl.createTagDescription");
+ if (branchDialog.value === "merge") return t("doltVersionControl.mergeBranchDescription", { name: branchActionTarget.value });
+ if (branchDialog.value === "delete-tag") return t("doltVersionControl.deleteTagDescription", { name: branchActionTarget.value });
+ return t("doltVersionControl.deleteBranchDescription", { name: branchActionTarget.value });
+});
+const commitHistoryOperationTitle = computed(() => t(commitHistoryOperation.value === "hard-reset" ? "doltVersionControl.hardResetTitle" : "doltVersionControl.revertCommitTitle"));
+const commitHistoryOperationDescription = computed(() => {
+ const commit = commitHistoryTarget.value;
+ if (!commit) return "";
+ const params = { hash: shortHash(commit.hash), branch: activeBranch.value };
+ return t(commitHistoryOperation.value === "hard-reset" ? "doltVersionControl.hardResetDescription" : "doltVersionControl.revertCommitDescription", params);
+});
+const commitHistoryOperationSql = computed(() => {
+ const commit = commitHistoryTarget.value;
+ if (!commit || !commitHistoryOperation.value) return "";
+ return commitHistoryOperation.value === "hard-reset" ? doltHardResetSql(commit.hash) : doltRevertCommitSql(commit.hash);
+});
+const discardWorkingTreeSqlPreview = computed(() => doltDiscardWorkingTreeSql());
+
+const graphEdges = computed(() => {
+ const edges: Array<{ key: string; path: string; color: string; diagonal: boolean }> = [];
+ const commitIndexes = new Map(commits.value.map((commit, index) => [commit.hash, index]));
+ const targetIndexForHash = (hash: string) => commitIndexes.get(hash) ?? commits.value.findIndex((commit) => commit.hash.startsWith(hash) || hash.startsWith(commit.hash));
+ graphLayout.value.rows.forEach((row, index) => {
+ const commit = commits.value[index];
+ commit?.parents.forEach((parentHash, parentIndex) => {
+ const targetIndex = targetIndexForHash(parentHash);
+ if (targetIndex <= index) return;
+ const parentRow = graphLayout.value.rows[targetIndex];
+ if (!parentRow) return;
+ const diagonal = row.lane !== parentRow.lane;
+ const route: DoltGraphEdgeRoute = doltGraphEdgeRoute(parentRow.lane, row.lane, targetIndex - index, commit.parents.length);
+ edges.push({
+ key: `${commit.hash}-${parentHash}-${parentIndex}`,
+ path: doltGraphEdgePath(laneX(parentRow.lane), commitRowY(targetIndex), laneX(row.lane), commitRowY(index), route),
+ color: graphColor(parentIndex === 0 ? row.lane : parentRow.lane, parentIndex === 0 ? row.nodeRef : parentRow.nodeRef),
+ diagonal,
+ });
+ });
+ });
+ return edges.sort((left, right) => Number(left.diagonal) - Number(right.diagonal));
+});
+
+type RevisionSelection = {
+ key: string;
+ revision: string;
+ label: string;
+};
+
+function refSelection(refItem: DoltRef): RevisionSelection {
+ return { key: `${refItem.kind}:${refItem.name}`, revision: refItem.name, label: refItem.name };
+}
+
+function commitSelection(commit: DoltCommit): RevisionSelection {
+ return { key: `commit:${commit.hash}`, revision: commit.hash, label: `${shortHash(commit.hash)} ${commit.message || t("doltVersionControl.noMessage")}` };
+}
+
+function workingTreeSelection(): RevisionSelection {
+ return { key: "working", revision: "WORKING", label: t("doltVersionControl.workingTree") };
+}
+
+function selectionForKey(key: string): RevisionSelection | undefined {
+ if (key === "working") return showWorkingTree.value ? workingTreeSelection() : undefined;
+ if (key.startsWith("commit:")) {
+ const hash = key.slice("commit:".length);
+ const commit = commits.value.find((item) => item.hash === hash);
+ return commit ? commitSelection(commit) : undefined;
+ }
+ const separator = key.indexOf(":");
+ const kind = key.slice(0, separator);
+ const name = key.slice(separator + 1);
+ const refItem = allRefs.value.find((item) => item.kind === kind && item.name === name);
+ return refItem ? refSelection(refItem) : undefined;
+}
+
+const selectedRevisions = computed(() => selectedRevisionKeys.value.map(selectionForKey).filter((item): item is RevisionSelection => !!item));
+
+function revisionLabel(revision: string): string {
+ if (!revision) return t("doltVersionControl.noRevision");
+ if (revision === "WORKING") return t("doltVersionControl.workingTree");
+ const refItem = allRefs.value.find((item) => item.name === revision);
+ if (refItem) return refItem.name;
+ const commit = commits.value.find((item) => item.hash === revision || item.hash.startsWith(revision) || revision.startsWith(item.hash));
+ return commit ? `${shortHash(commit.hash)} ${commit.message || t("doltVersionControl.noMessage")}` : shortHash(revision);
+}
+
+async function updateModifiedSelection(selection: RevisionSelection) {
+ const next = [...selectedRevisionKeys.value];
+ const existingIndex = next.indexOf(selection.key);
+ if (existingIndex >= 0) next.splice(existingIndex, 1);
+ else if (next.length >= 2) next.splice(0, 1, selection.key);
+ else next.push(selection.key);
+ selectedRevisionKeys.value = next;
+ const selected = next.map(selectionForKey).filter((item): item is RevisionSelection => !!item);
+ if (selected.length === 2) await loadComparison(selected[0].revision, selected[1].revision);
+}
+
+async function query(sql: string, maxRows = 1000): Promise<QueryResult> {
+ return api.executeQuery(props.connectionId, activeDatabase.value, sql, undefined, undefined, { maxRows, timeoutSecs: 30, clientSessionId: clientSessionId.value });
+}
+
+function workspaceTab() {
+ return queryStore.tabs.find((candidate) => candidate.id === queryStore.activeTabId && candidate.mode === "dolt-version-control" && candidate.connectionId === props.connectionId);
+}
+
+function syncWorkspaceBranch(branch: string) {
+ const tab = workspaceTab();
+ if (tab && tab.workspaceBranch !== branch) tab.workspaceBranch = branch || undefined;
+}
+
+function firstCell(result: QueryResult): string {
+ return String(result.rows[0]?.[0] ?? "");
+}
+
+function errorMessage(value: unknown): string {
+ return value instanceof Error ? value.message : String(value);
+}
+
+async function refresh() {
+ const generation = ++loadGeneration;
+ comparisonGeneration += 1;
+ tableDiffGeneration += 1;
+ comparisonLoading.value = false;
+ tableDiffLoading.value = false;
+ loading.value = true;
+ error.value = "";
+ try {
+ const activeResult = await query("SELECT ACTIVE_BRANCH()", 1);
+ if (generation !== loadGeneration) return;
+ activeBranch.value = firstCell(activeResult);
+ syncWorkspaceBranch(activeBranch.value);
+ const [branchResult, tagResult, statusResult] = await Promise.all([query("SELECT * FROM dolt_branches ORDER BY name", 1000), query("SELECT * FROM dolt_tags ORDER BY tag_name", 1000).catch(() => null), query(doltStatusSql(), 1000).catch(() => null)]);
+ if (generation !== loadGeneration) return;
+ branches.value = parseDoltBranches(branchResult, activeBranch.value);
+ tags.value = tagResult ? parseDoltTags(tagResult) : [];
+ workingChanges.value = statusResult ? parseDoltStatus(statusResult) : [];
+ const availableRefs = new Set(allRefs.value.map((item) => item.name));
+ selectedRef.value = availableRefs.has(selectedRef.value) ? selectedRef.value : activeBranch.value || branches.value[0]?.name || "--all";
+ selectedRevisionKeys.value = [];
+ await loadGraph(selectedRef.value, generation);
+ if (generation === loadGeneration) await loadComparison("HEAD", "WORKING");
+ } catch (value) {
+ if (generation === loadGeneration) error.value = errorMessage(value);
+ } finally {
+ if (generation === loadGeneration) loading.value = false;
+ }
+}
+
+function clearDatabaseContext() {
+ loadGeneration += 1;
+ comparisonGeneration += 1;
+ tableDiffGeneration += 1;
+ activeBranch.value = "";
+ branches.value = [];
+ tags.value = [];
+ commits.value = [];
+ workingChanges.value = [];
+ selectedRef.value = "";
+ selectedRevisionKeys.value = [];
+ comparedFrom.value = "";
+ comparedTo.value = "";
+ changes.value = [];
+ selectedTableName.value = "";
+ tableDiff.value = null;
+ comparisonError.value = "";
+ tableDiffError.value = "";
+ clearDiffCellInteraction();
+}
+
+async function loadDatabaseOptions() {
+ databaseLoading.value = true;
+ try {
+ const names = [...new Set((await api.listDatabases(props.connectionId)).map((item) => baseDatabaseName(item.name)).filter((name) => name && !name.includes("/")))].sort((left, right) => left.localeCompare(right, locale.value, { sensitivity: "base" }));
+ if (selectedDatabase.value && !names.includes(selectedDatabase.value)) names.unshift(selectedDatabase.value);
+ databaseOptions.value = filterDatabaseNamesForVisiblePicker(names, connectionStore.getConfig(props.connectionId));
+ } catch {
+ databaseOptions.value = selectedDatabase.value ? [selectedDatabase.value] : [];
+ } finally {
+ databaseLoading.value = false;
+ }
+}
+
+function refreshDatabaseOptionsOnOpen(open: boolean) {
+ if (open && !databaseLoading.value && !databaseSwitching.value) void loadDatabaseOptions();
+}
+
+function switchDatabase(database: unknown) {
+ if (typeof database !== "string" || !database || database === activeDatabase.value) return;
+ const previousSession = doltClientSessionScope(props.connectionId, activeDatabase.value);
+ databaseSwitching.value = true;
+ clearDatabaseContext();
+ selectedDatabase.value = database;
+ const tab = workspaceTab();
+ if (tab) {
+ tab.workspaceBranch = undefined;
+ queryStore.updateDatabase(tab.id, database);
+ } else void reloadDatabaseContext(database, undefined, previousSession);
+}
+
+async function reloadDatabaseContext(database: string, requestedBranch = props.initialBranch, previousSession?: DoltClientSessionScope) {
+ const generation = ++databaseSwitchGeneration;
+ const targetDatabase = baseDatabaseName(database);
+ const resetCurrentDatabaseSession = !requestedBranch && activeBranch.value && activeDatabase.value === targetDatabase;
+ selectedDatabase.value = targetDatabase;
+ try {
+ if (previousSession) {
+ await api.closeClientConnectionSession(previousSession.connectionId, previousSession.database, previousSession.clientSessionId).catch(() => undefined);
+ } else if (resetCurrentDatabaseSession) {
+ await api.closeClientConnectionSession(props.connectionId, targetDatabase, clientSessionId.value).catch(() => undefined);
+ }
+ await loadDatabaseOptions();
+ const branch = requestedBranch?.trim();
+ if (branch) {
+ const currentBranch = firstCell(await query("SELECT ACTIVE_BRANCH()", 1));
+ if (currentBranch !== branch) await query(doltCheckoutBranchSql(branch), 10);
+ selectedRef.value = branch;
+ }
+ await refresh();
+ } catch (value) {
+ if (generation === databaseSwitchGeneration) {
+ error.value = errorMessage(value);
+ syncWorkspaceBranch(activeBranch.value);
+ }
+ } finally {
+ if (generation === databaseSwitchGeneration) databaseSwitching.value = false;
+ }
+}
+
+async function loadGraph(revision: string, parentGeneration = ++loadGeneration) {
+ graphLoading.value = true;
+ error.value = "";
+ try {
+ let result: QueryResult;
+ try {
+ result = await query(doltLogSql(revision || "--all"), 500);
+ } catch (value) {
+ if (!activeBranch.value || revision === activeBranch.value) throw value;
+ result = await query(doltLogSql(activeBranch.value), 500);
+ }
+ if (parentGeneration !== loadGeneration) return;
+ commits.value = parseDoltCommits(result);
+ } catch (value) {
+ if (parentGeneration === loadGeneration) error.value = errorMessage(value);
+ } finally {
+ if (parentGeneration === loadGeneration) graphLoading.value = false;
+ }
+}
+
+async function selectRef(refItem: DoltRef, event: MouseEvent) {
+ if (event.ctrlKey || event.metaKey) {
+ await updateModifiedSelection(refSelection(refItem));
+ return;
+ }
+ selectedRevisionKeys.value = [refSelection(refItem).key];
+ if (selectedRef.value === refItem.name && commits.value.length) return;
+ selectedRef.value = refItem.name;
+ const generation = ++loadGeneration;
+ await loadGraph(refItem.name, generation);
+}
+
+function toggleBranchTreePath(path: string) {
+ const next = new Set(collapsedBranchPaths.value);
+ if (next.has(path)) next.delete(path);
+ else next.add(path);
+ collapsedBranchPaths.value = next;
+}
+
+function toggleBranchTreeView() {
+ branchTreeView.value = !branchTreeView.value;
+}
+
+function selectBranchTreeRow(row: BranchTreeRow, event: MouseEvent) {
+ if (row.branch) void selectRef(row.branch, event);
+ else if (row.folder) toggleBranchTreePath(row.key);
+}
+
+function branchTreeRowContextMenuItems(row: BranchTreeRow): ContextMenuItem[] {
+ return row.branch ? branchContextMenuItems(row.branch) : [];
+}
+
+function openBranchTreeRowContextMenu(event: MouseEvent, row: BranchTreeRow, openMenu: (event: MouseEvent) => void) {
+ if (row.branch) openRefContextMenu(event, row.branch, openMenu);
+}
+
+async function selectCommit(commit: DoltCommit, event: MouseEvent) {
+ if (event.ctrlKey || event.metaKey) {
+ await updateModifiedSelection(commitSelection(commit));
+ return;
+ }
+ selectedRevisionKeys.value = [commitSelection(commit).key];
+ const parent = commit.parents[0];
+ if (!parent) {
+ comparisonGeneration += 1;
+ tableDiffGeneration += 1;
+ comparisonLoading.value = false;
+ tableDiffLoading.value = false;
+ comparedFrom.value = "";
+ comparedTo.value = commit.hash;
+ changes.value = [];
+ selectedTableName.value = "";
+ tableDiff.value = null;
+ return;
+ }
+ await loadComparison(parent, commit.hash);
+}
+
+async function selectWorkingTree(event: MouseEvent) {
+ const selection = workingTreeSelection();
+ if (event.ctrlKey || event.metaKey) {
+ await updateModifiedSelection(selection);
+ return;
+ }
+ selectedRevisionKeys.value = [selection.key];
+ await loadComparison("HEAD", "WORKING");
+}
+
+function openRefContextMenu(event: MouseEvent, refItem: DoltRef, openMenu: (event: MouseEvent) => void) {
+ selectedRevisionKeys.value = [refSelection(refItem).key];
+ openMenu(event);
+}
+
+function openCommitContextMenu(event: MouseEvent, commit: DoltCommit, openMenu: (event: MouseEvent) => void) {
+ selectedRevisionKeys.value = [commitSelection(commit).key];
+ openMenu(event);
+}
+
+async function loadComparison(fromRevision: string, toRevision: string) {
+ if (!fromRevision || !toRevision || fromRevision === toRevision) return;
+ const generation = ++comparisonGeneration;
+ comparisonLoading.value = true;
+ comparisonError.value = "";
+ tableDiffError.value = "";
+ comparedFrom.value = fromRevision;
+ comparedTo.value = toRevision;
+ changes.value = [];
+ selectedTableName.value = "";
+ tableDiff.value = null;
+ try {
+ const result = await query(doltDiffSummarySql(fromRevision, toRevision), 1000);
+ if (generation !== comparisonGeneration) return;
+ changes.value = parseDoltTableChanges(result);
+ const first = changes.value[0];
+ if (first) await loadTableDiff(first, generation);
+ } catch (value) {
+ if (generation === comparisonGeneration) comparisonError.value = errorMessage(value);
+ } finally {
+ if (generation === comparisonGeneration) comparisonLoading.value = false;
+ }
+}
+
+async function swapComparison() {
+ if (!comparedFrom.value || !comparedTo.value || comparisonLoading.value) return;
+ if (selectedRevisions.value.length === 2 && selectedRevisions.value[0].revision === comparedFrom.value && selectedRevisions.value[1].revision === comparedTo.value) {
+ selectedRevisionKeys.value = [...selectedRevisionKeys.value].reverse();
+ }
+ await loadComparison(comparedTo.value, comparedFrom.value);
+}
+
+async function selectComparisonRevision(side: "from" | "to", revision: string) {
+ const normalized = revision.trim();
+ if (!normalized) return;
+ const fromRevision = side === "from" ? normalized : comparedFrom.value;
+ const toRevision = side === "to" ? normalized : comparedTo.value;
+ if (fromRevision === comparedFrom.value && toRevision === comparedTo.value) return;
+ if (!fromRevision || !toRevision || fromRevision === toRevision) {
+ comparisonGeneration += 1;
+ tableDiffGeneration += 1;
+ comparedFrom.value = fromRevision;
+ comparedTo.value = toRevision;
+ changes.value = [];
+ selectedTableName.value = "";
+ tableDiff.value = null;
+ comparisonError.value = "";
+ return;
+ }
+ selectedRevisionKeys.value = [];
+ await loadComparison(fromRevision, toRevision);
+}
+
+function openCreateBranch(sourceRevision?: string) {
+ if (connectionReadOnly.value) return;
+ mutationError.value = "";
+ branchNameDraft.value = "";
+ branchSourceRevision.value = sourceRevision || selectedRevisions.value[0]?.revision || activeBranch.value || "HEAD";
+ branchActionTarget.value = "";
+ branchDialog.value = "create";
+}
+
+function openCreateTag(sourceRevision?: string) {
+ if (connectionReadOnly.value) return;
+ mutationError.value = "";
+ branchNameDraft.value = "";
+ branchSourceRevision.value = sourceRevision || selectedRevisions.value[0]?.revision || activeBranch.value || "HEAD";
+ branchActionTarget.value = "";
+ branchDialog.value = "create-tag";
+}
+
+function openMergeBranch(branch: DoltRef) {
+ if (connectionReadOnly.value || branch.active) return;
+ mutationError.value = "";
+ branchActionTarget.value = branch.name;
+ branchDialog.value = "merge";
+}
+
+function openDeleteBranch(branch: DoltRef) {
+ if (connectionReadOnly.value || branch.active) return;
+ mutationError.value = "";
+ branchActionTarget.value = branch.name;
+ branchDialog.value = "delete";
+}
+
+function openDeleteTag(tag: DoltRef) {
+ if (connectionReadOnly.value) return;
+ mutationError.value = "";
+ branchActionTarget.value = tag.name;
+ branchDialog.value = "delete-tag";
+}
+
+async function runRefMutation(sql: string, successMessage: string, options: { selectedRefAfter?: string } = {}): Promise<boolean> {
+ if (connectionReadOnly.value || mutationLoading.value) return false;
+ mutationLoading.value = true;
+ mutationError.value = "";
+ try {
+ await query(sql, 10);
+ toast(successMessage, 3000);
+ // Version-control mutations can change both visible metadata and active
+ // branch decorations in the connection tree.
+ await connectionStore.refreshDatabaseTreeNode(props.connectionId, activeDatabase.value).catch(() => undefined);
+ if (options.selectedRefAfter) selectedRef.value = options.selectedRefAfter;
+ await refresh();
+ return true;
+ } catch (value) {
+ mutationError.value = errorMessage(value);
+ toast(mutationError.value, 5000);
+ return false;
+ } finally {
+ mutationLoading.value = false;
+ }
+}
+
+function compareWithCurrent(refItem: DoltRef) {
+ if (!activeBranch.value || refItem.active) return;
+ void loadComparison(activeBranch.value, refItem.name);
+}
+
+async function checkoutBranch(branch: DoltRef) {
+ if (branch.active || branchSwitchingTarget.value) return;
+ branchSwitchingTarget.value = branch.name;
+ try {
+ await runRefMutation(doltCheckoutBranchSql(branch.name), t("doltVersionControl.branchCheckedOut", { name: branch.name }), { selectedRefAfter: branch.name });
+ } finally {
+ branchSwitchingTarget.value = "";
+ }
+}
+
+function switchBranch(branchName: unknown) {
+ if (typeof branchName !== "string" || !branchName || branchName === activeBranch.value) return;
+ const branch = branches.value.find((item) => item.name === branchName);
+ if (branch) void checkoutBranch(branch);
+}
+
+async function copyCommitHash(commit: DoltCommit) {
+ try {
+ await navigator.clipboard.writeText(commit.hash);
+ toast(t("doltVersionControl.hashCopied"), 2000);
+ } catch (value) {
+ toast(errorMessage(value), 5000);
+ }
+}
+
+async function stageWorkingTree() {
+ await runRefMutation(doltAddAllSql(), t("doltVersionControl.changesStaged"));
+}
+
+function openCommitDialog() {
+ if (connectionReadOnly.value || mutationLoading.value || workingChanges.value.length === 0) return;
+ commitMessageDraft.value = "";
+ commitError.value = "";
+ commitDialogOpen.value = true;
+}
+
+function closeCommitDialog() {
+ if (mutationLoading.value) return;
+ commitDialogOpen.value = false;
+ commitMessageDraft.value = "";
+ commitError.value = "";
+}
+
+async function submitWorkingTreeCommit() {
+ const message = commitMessageDraft.value.trim();
+ if (!message) {
+ commitError.value = t("doltVersionControl.commitMessageRequired");
+ return;
+ }
+ if (connectionReadOnly.value || mutationLoading.value) return;
+ mutationLoading.value = true;
+ commitError.value = "";
+ try {
+ await query(doltAddAllSql(), 10);
+ await query(doltCommitSql(message), 10);
+ commitDialogOpen.value = false;
+ commitMessageDraft.value = "";
+ toast(t("doltVersionControl.workingTreeCommitted"), 3000);
+ await connectionStore.refreshDatabaseTreeNode(props.connectionId, activeDatabase.value).catch(() => undefined);
+ await refresh();
+ } catch (value) {
+ commitError.value = errorMessage(value);
+ } finally {
+ mutationLoading.value = false;
+ }
+}
+
+function openDiscardWorkingTreeDialog() {
+ if (connectionReadOnly.value || mutationLoading.value || workingChanges.value.length === 0) return;
+ discardWorkingTreeError.value = "";
+ discardWorkingTreeDialogOpen.value = true;
+}
+
+function closeDiscardWorkingTreeDialog() {
+ if (mutationLoading.value) return;
+ discardWorkingTreeDialogOpen.value = false;
+ discardWorkingTreeError.value = "";
+}
+
+async function submitDiscardWorkingTree() {
+ if (!discardWorkingTreeDialogOpen.value || mutationLoading.value || connectionReadOnly.value) return;
+ const succeeded = await runRefMutation(doltDiscardWorkingTreeSql(), t("doltVersionControl.discardWorkingTreeComplete"), { selectedRefAfter: activeBranch.value });
+ if (succeeded) closeDiscardWorkingTreeDialog();
+ else {
+ discardWorkingTreeError.value = mutationError.value;
+ mutationError.value = "";
+ }
+}
+
+function workingTreeContextMenuItems(): ContextMenuItem[] {
+ return [
+ { label: t("doltVersionControl.stageAllChanges"), icon: Check, disabled: connectionReadOnly.value || mutationLoading.value || unstagedWorkingChangeCount.value === 0, action: () => void stageWorkingTree() },
+ { label: t("doltVersionControl.commitWorkingTree"), icon: GitCommitHorizontal, disabled: connectionReadOnly.value || mutationLoading.value || workingChanges.value.length === 0, action: openCommitDialog },
+ { separator: true, label: "" },
+ { label: t("doltVersionControl.discardWorkingTree"), icon: RotateCcw, variant: "destructive", disabled: connectionReadOnly.value || mutationLoading.value || workingChanges.value.length === 0, action: openDiscardWorkingTreeDialog },
+ ];
+}
+
+function openWorkingTreeContextMenu(event: MouseEvent, openMenu: (event: MouseEvent) => void) {
+ selectedRevisionKeys.value = [workingTreeSelection().key];
+ openMenu(event);
+}
+
+function branchContextMenuItems(branch: DoltRef): ContextMenuItem[] {
+ const items: ContextMenuItem[] = [];
+ if (branch.kind === "branch") {
+ items.push(
+ { label: t("doltVersionControl.compareCurrent"), icon: GitPullRequest, disabled: branch.active, action: () => compareWithCurrent(branch) },
+ { label: t("doltVersionControl.checkoutBranch"), icon: GitBranch, disabled: connectionReadOnly.value || branch.active, action: () => void checkoutBranch(branch) },
+ );
+ }
+ items.push(
+ { separator: true, label: "" },
+ { label: t("doltVersionControl.createBranch"), icon: Plus, disabled: connectionReadOnly.value, action: () => openCreateBranch(branch.name) },
+ { label: t("doltVersionControl.createTag"), icon: Tag, disabled: connectionReadOnly.value, action: () => openCreateTag(branch.name) },
+ );
+ if (branch.kind === "branch") {
+ items.push(
+ { separator: true, label: "" },
+ { label: t("doltVersionControl.mergeBranch"), icon: GitMerge, disabled: connectionReadOnly.value || branch.active, action: () => openMergeBranch(branch) },
+ { label: t("doltVersionControl.deleteBranch"), icon: Trash2, variant: "destructive", disabled: connectionReadOnly.value || branch.active, action: () => openDeleteBranch(branch) },
+ );
+ } else {
+ items.push({ label: t("doltVersionControl.deleteTag"), icon: Trash2, variant: "destructive", disabled: connectionReadOnly.value, action: () => openDeleteTag(branch) });
+ }
+ return items;
+}
+
+function refContextMenuItems(refItem: DoltRef): ContextMenuItem[] {
+ return branchContextMenuItems(refItem);
+}
+
+function commitContextMenuItems(commit: DoltCommit): ContextMenuItem[] {
+ const activeHead = branches.value.find((branch) => branch.active)?.hash;
+ const isCurrentHead = !!activeHead && (activeHead === commit.hash || activeHead.startsWith(commit.hash) || commit.hash.startsWith(activeHead));
+ return [
+ { label: t("doltVersionControl.copyHash"), icon: Clipboard, action: () => void copyCommitHash(commit) },
+ { separator: true, label: "" },
+ { label: t("doltVersionControl.createBranch"), icon: Plus, disabled: connectionReadOnly.value, action: () => openCreateBranch(commit.hash) },
+ { label: t("doltVersionControl.createTag"), icon: Tag, disabled: connectionReadOnly.value, action: () => openCreateTag(commit.hash) },
+ { separator: true, label: "" },
+ { label: t("doltVersionControl.revertCommit"), icon: Undo2, disabled: connectionReadOnly.value || mutationLoading.value, action: () => openCommitHistoryOperation("revert", commit) },
+ { label: t("doltVersionControl.hardResetToCommit"), icon: RotateCcw, variant: "destructive", disabled: connectionReadOnly.value || mutationLoading.value || isCurrentHead, action: () => openCommitHistoryOperation("hard-reset", commit) },
+ ];
+}
+
+function openCommitHistoryOperation(operation: "revert" | "hard-reset", commit: DoltCommit) {
+ if (connectionReadOnly.value || mutationLoading.value) return;
+ commitHistoryOperation.value = operation;
+ commitHistoryTarget.value = commit;
+ commitHistoryError.value = "";
+ mutationError.value = "";
+}
+
+function closeCommitHistoryDialog() {
+ if (mutationLoading.value) return;
+ commitHistoryOperation.value = null;
+ commitHistoryTarget.value = null;
+ commitHistoryError.value = "";
+}
+
+async function submitCommitHistoryOperation() {
+ const operation = commitHistoryOperation.value;
+ const commit = commitHistoryTarget.value;
+ if (!operation || !commit || mutationLoading.value || connectionReadOnly.value) return;
+ const succeeded = await runRefMutation(operation === "hard-reset" ? doltHardResetSql(commit.hash) : doltRevertCommitSql(commit.hash), t(operation === "hard-reset" ? "doltVersionControl.hardResetComplete" : "doltVersionControl.revertCommitComplete", { hash: shortHash(commit.hash) }), {
+ selectedRefAfter: activeBranch.value,
+ });
+ if (succeeded) closeCommitHistoryDialog();
+ else {
+ commitHistoryError.value = mutationError.value;
+ mutationError.value = "";
+ }
+}
+
+function closeBranchDialog() {
+ if (mutationLoading.value) return;
+ branchDialog.value = null;
+ branchActionTarget.value = "";
+ mutationError.value = "";
+}
+
+async function submitBranchOperation() {
+ if (!branchDialog.value || mutationLoading.value || connectionReadOnly.value) return;
+ const operation = branchDialog.value;
+ const branchName = branchNameDraft.value.trim();
+ const sourceBranch = branchActionTarget.value;
+ if (createsNamedRef.value && !branchName) {
+ mutationError.value = t(operation === "create-tag" ? "doltVersionControl.tagNameRequired" : "doltVersionControl.branchNameRequired");
+ return;
+ }
+ if ((operation === "merge" || operation === "delete" || operation === "delete-tag") && !sourceBranch) return;
+ mutationLoading.value = true;
+ mutationError.value = "";
+ try {
+ const sql =
+ operation === "create"
+ ? doltCreateBranchSql(branchName, branchSourceRevision.value)
+ : operation === "create-tag"
+ ? doltCreateTagSql(branchName, branchSourceRevision.value)
+ : operation === "merge"
+ ? doltMergeBranchSql(sourceBranch)
+ : operation === "delete-tag"
+ ? doltDeleteTagSql(sourceBranch)
+ : doltDeleteBranchSql(sourceBranch);
+ await query(sql, 10);
+ const message =
+ operation === "create"
+ ? t("doltVersionControl.branchCreated", { name: branchName })
+ : operation === "create-tag"
+ ? t("doltVersionControl.tagCreated", { name: branchName })
+ : operation === "merge"
+ ? t("doltVersionControl.branchMerged", { name: sourceBranch })
+ : operation === "delete-tag"
+ ? t("doltVersionControl.tagDeleted", { name: sourceBranch })
+ : t("doltVersionControl.branchDeleted", { name: sourceBranch });
+ branchDialog.value = null;
+ branchActionTarget.value = "";
+ toast(message, 3000);
+ await refresh();
+ } catch (value) {
+ mutationError.value = errorMessage(value);
+ } finally {
+ mutationLoading.value = false;
+ }
+}
+
+async function loadTableDiff(change: DoltTableChange, parentGeneration = comparisonGeneration, options: { page?: number; countTotal?: boolean } = {}) {
+ const generation = ++tableDiffGeneration;
+ const tableChanged = selectedTableName.value !== change.tableName || !tableDiff.value;
+ const requestedPage = Math.max(1, Math.floor(options.page ?? 1));
+ const requestedPageSize = tableDiffPageSize.value;
+ const requestedOffset = (requestedPage - 1) * requestedPageSize;
+ const countTotal = options.countTotal ?? tableChanged;
+ selectedTableName.value = change.tableName;
+ tableDiffLoading.value = true;
+ tableDiffError.value = "";
+ if (tableChanged) {
+ tableDiff.value = null;
+ tableDiffPage.value = 1;
+ tableDiffTotalRows.value = 0;
+ diffColumnWidths.value = [];
+ diffColumnWidthReports = {};
+ diffColumnWidthsReady.value = false;
+ }
+ try {
+ const resultRequest = query(doltTableDiffSql(comparedFrom.value, comparedTo.value, change.tableName, requestedPageSize, requestedOffset), requestedPageSize);
+ const [result, countResult] = countTotal ? await Promise.all([resultRequest, query(doltTableDiffCountSql(comparedFrom.value, comparedTo.value, change.tableName), 1)]) : [await resultRequest, null];
+ if (generation !== tableDiffGeneration || parentGeneration !== comparisonGeneration) return;
+ tableDiff.value = result;
+ tableDiffPage.value = requestedPage;
+ if (countResult) {
+ const count = Number(firstCell(countResult));
+ tableDiffTotalRows.value = Number.isSafeInteger(count) && count >= 0 ? count : result.rows.length;
+ }
+ } catch (value) {
+ if (generation === tableDiffGeneration && parentGeneration === comparisonGeneration) tableDiffError.value = errorMessage(value);
+ } finally {
+ if (generation === tableDiffGeneration) tableDiffLoading.value = false;
+ }
+}
+
+function loadTableDiffPage(page: number) {
+ const change = selectedChange.value;
+ if (!change || tableDiffLoading.value) return;
+ const normalizedPage = Math.min(tableDiffMaximumPage.value, Math.max(1, Math.floor(page)));
+ if (normalizedPage === tableDiffPage.value) return;
+ void loadTableDiff(change, comparisonGeneration, { page: normalizedPage, countTotal: false });
+}
+
+function changeTableDiffPageSize(value: unknown) {
+ const parsed = Number(value);
+ const size = Number.isSafeInteger(parsed) && parsed > 0 ? parsed : tableDiffPageSize.value;
+ if (size === tableDiffPageSize.value) return;
+ tableDiffPageSize.value = size;
+ const change = selectedChange.value;
+ if (change) void loadTableDiff(change, comparisonGeneration, { page: 1, countTotal: false });
+}
+
+function shortHash(hash: string): string {
+ return hash.slice(0, 8);
+}
+
+function formatDate(value: string): string {
+ if (!value) return "";
+ const date = new Date(value);
+ return Number.isNaN(date.getTime()) ? value : new Intl.DateTimeFormat(locale.value, { dateStyle: "short", timeStyle: "short" }).format(date);
+}
+
+function laneX(lane: number): number {
+ return 18 + lane * 18;
+}
+
+function rowY(row: number): number {
+ return row * COMMIT_ROW_HEIGHT + COMMIT_ROW_HEIGHT / 2;
+}
+
+function commitRowY(commitIndex: number): number {
+ return rowY(commitIndex + graphRowOffset.value);
+}
+
+function graphColor(lane: number, refName?: string | null): string {
+ const colorIndex = refName ? graphRefColorIndexes.value.get(refName) : undefined;
+ return GRAPH_COLORS[colorIndex ?? ((lane % GRAPH_COLORS.length) + GRAPH_COLORS.length) % GRAPH_COLORS.length];
+}
+
+function refBadgeStyle(refItem: DoltRef): Record<string, string> {
+ return { "--dolt-ref-color": graphColor(0, refItem.name) };
+}
+
+function changeKindClass(change: DoltTableChange): string {
+ return `dolt-change-${doltTableChangeKind(change)}`;
+}
+
+function changeFlags(change: DoltTableChange): DoltTableChangeFlag[] {
+ return doltTableChangeFlags(change);
+}
+
+function changeFlagSymbol(flag: DoltTableChangeFlag): string {
+ if (flag === "data") return "D";
+ if (flag === "schema") return "S";
+ return "M";
+}
+
+function changeFlagTitle(flag: DoltTableChangeFlag, change: DoltTableChange): string {
+ if (flag === "data") return t("history.kindShort.data_change");
+ if (flag === "schema") return t("history.kindShort.schema_change");
+ return change.diffType || t("doltVersionControl.changedTables");
+}
+
+function changeFlagsTitle(change: DoltTableChange): string {
+ return changeFlags(change)
+ .map((flag) => changeFlagTitle(flag, change))
+ .join(" + ");
+}
+
+function clearDiffCellInteraction() {
+ selectedDiffCell.value = null;
+ diffCellContextTarget.value = null;
+ diffCellDetailTarget.value = null;
+ diffCellDetailOpen.value = false;
+}
+
+function selectDiffCell(target: DoltDiffCellTarget) {
+ if (tableDiffLoading.value) return;
+ selectedDiffCell.value = target;
+}
+
+function openDiffCellDetails(target: DoltDiffCellTarget) {
+ if (tableDiffLoading.value) return;
+ selectedDiffCell.value = target;
+ diffCellDetailTarget.value = { ...target };
+ diffCellDetailOpen.value = true;
+}
+
+function openDiffCellContextMenu(target: DoltDiffCellTarget, event: MouseEvent, openMenu: (event: MouseEvent) => void) {
+ event.preventDefault();
+ if (tableDiffLoading.value) return;
+ selectedDiffCell.value = target;
+ diffCellContextTarget.value = { ...target };
+ openMenu(event);
+}
+
+async function copyDiffCellValue(side: DoltCellSide) {
+ const target = diffCellContextTarget.value;
+ if (!target) return;
+ const value = doltCellCopyText(target, side);
+ if (value === null) return;
+ try {
+ await copyToClipboard(value);
+ toast(t("doltVersionControl.cellValueCopied"), 2000);
+ } catch (error) {
+ toast(errorMessage(error), 5000);
+ }
+}
+
+function diffCellContextMenuItems(): ContextMenuItem[] {
+ const target = diffCellContextTarget.value;
+ if (!target) return [];
+ return [
+ { label: t("doltVersionControl.copyCurrentValue"), icon: Clipboard, disabled: doltCellCopyText(target, target.side) === null, action: () => void copyDiffCellValue(target.side) },
+ { label: t("doltVersionControl.copyBeforeValue"), icon: Clipboard, disabled: doltCellCopyText(target, "before") === null, action: () => void copyDiffCellValue("before") },
+ { label: t("doltVersionControl.copyAfterValue"), icon: Clipboard, disabled: doltCellCopyText(target, "after") === null, action: () => void copyDiffCellValue("after") },
+ { label: "", separator: true },
+ { label: t("doltVersionControl.viewCellDiff"), icon: FileDiff, action: () => openDiffCellDetails(target) },
+ ];
+}
+
+function diffCellClass(side: "before" | "after", rowIndex: number, columnIndex: number): string | undefined {
+ const row = parsedTableDiff.value.rows[rowIndex];
+ const column = parsedTableDiff.value.columns[columnIndex];
+ const columnKind = parsedTableDiff.value.columnKinds[columnIndex];
+ if (!row || !column) return undefined;
+ if (columnKind === "added") return side === "after" ? "dolt-grid-cell-added" : "dolt-grid-cell-structural-missing";
+ if (columnKind === "removed") return side === "before" ? "dolt-grid-cell-removed" : "dolt-grid-cell-structural-missing";
+ if (!row.changedColumns.includes(column)) return undefined;
+ if (row.kind === "added") return "dolt-grid-cell-added";
+ if (row.kind === "removed") return "dolt-grid-cell-removed";
+ return "dolt-grid-cell-modified";
+}
+
+function diffHeaderClass(side: "before" | "after", columnIndex: number): string | undefined {
+ const kind = parsedTableDiff.value.columnKinds[columnIndex];
+ if (kind === "added") return side === "after" ? "dolt-grid-header-added" : "dolt-grid-header-added-missing";
+ if (kind === "removed") return side === "before" ? "dolt-grid-header-removed" : "dolt-grid-header-removed-missing";
+ return undefined;
+}
+
+function syncDiffColumnWidths(side: "before" | "after", widths: number[]) {
+ if (widths.length !== parsedTableDiff.value.columns.length) return;
+ if (!diffColumnWidthsReady.value) {
+ diffColumnWidthReports[side] = [...widths];
+ const before = diffColumnWidthReports.before;
+ const after = diffColumnWidthReports.after;
+ if (before && after) {
+ diffColumnWidths.value = widths.map((_, index) => Math.max(before[index] ?? 0, after[index] ?? 0));
+ diffColumnWidthsReady.value = true;
+ return;
+ }
+ }
+ if (diffColumnWidths.value.length === widths.length && widths.every((width, index) => Math.abs(width - (diffColumnWidths.value[index] ?? 0)) < 0.5)) return;
+ diffColumnWidths.value = [...widths];
+}
+
+function bindDiffScrollSync() {
+ detachDiffScrollSync?.();
+ detachDiffScrollSync = undefined;
+ if (!tableDiff.value) {
+ diffScrollSyncRetry = 0;
+ if (diffScrollSyncRetryTimer) window.clearTimeout(diffScrollSyncRetryTimer);
+ diffScrollSyncRetryTimer = 0;
+ return;
+ }
+ const beforeScroller = beforeDiffSide.value?.querySelector<HTMLElement>(".dolt-diff-table-scroller");
+ const afterScroller = afterDiffSide.value?.querySelector<HTMLElement>(".dolt-diff-table-scroller");
+ if (!beforeScroller || !afterScroller) {
+ if (diffScrollSyncRetry < 5) {
+ diffScrollSyncRetry += 1;
+ diffScrollSyncRetryTimer = window.setTimeout(() => {
+ diffScrollSyncRetryTimer = 0;
+ scheduleDiffScrollSync();
+ }, 50);
+ }
+ return;
+ }
+ diffScrollSyncRetry = 0;
+ const sync = (source: HTMLElement, target: HTMLElement) => {
+ if (diffScrollSyncing) return;
+ const syncTop = Math.abs(target.scrollTop - source.scrollTop) >= 0.5;
+ const syncLeft = Math.abs(target.scrollLeft - source.scrollLeft) >= 0.5;
+ if (!syncTop && !syncLeft) return;
+ diffScrollSyncing = true;
+ if (syncTop) target.scrollTop = source.scrollTop;
+ if (syncLeft) target.scrollLeft = source.scrollLeft;
+ requestAnimationFrame(() => {
+ diffScrollSyncing = false;
+ });
+ };
+ const onBeforeScroll = () => sync(beforeScroller, afterScroller);
+ const onAfterScroll = () => sync(afterScroller, beforeScroller);
+ beforeScroller.addEventListener("scroll", onBeforeScroll, { passive: true });
+ afterScroller.addEventListener("scroll", onAfterScroll, { passive: true });
+ afterScroller.scrollTop = beforeScroller.scrollTop;
+ afterScroller.scrollLeft = beforeScroller.scrollLeft;
+ detachDiffScrollSync = () => {
+ beforeScroller.removeEventListener("scroll", onBeforeScroll);
+ afterScroller.removeEventListener("scroll", onAfterScroll);
+ };
+}
+
+function scheduleDiffScrollSync() {
+ if (diffScrollSyncFrame) cancelAnimationFrame(diffScrollSyncFrame);
+ diffScrollSyncFrame = requestAnimationFrame(() => {
+ diffScrollSyncFrame = 0;
+ bindDiffScrollSync();
+ });
+}
+
+watch(
+ () => [props.connectionId, props.database, props.initialBranch] as const,
+ ([connectionId, database, branch], [previousConnectionId, previousDatabase, previousBranch]) => {
+ const databaseChanged = connectionId !== previousConnectionId || database !== previousDatabase;
+ const branchTargetChanged = branch !== previousBranch && branch !== activeBranch.value;
+ const previousSession = databaseChanged ? doltClientSessionScope(previousConnectionId, baseDatabaseName(previousDatabase)) : undefined;
+ if (databaseChanged || branchTargetChanged) void reloadDatabaseContext(database, branch, previousSession);
+ },
+);
+
+watch(
+ () => [tableDiff.value, selectedTableName.value],
+ () => scheduleDiffScrollSync(),
+ { flush: "post" },
+);
+
+watch(
+ () => [diffGridScopeKey.value, tableDiffPage.value],
+ () => clearDiffCellInteraction(),
+);
+
+onMounted(() => {
+ selectedDatabase.value = baseDatabaseName(props.database);
+ const tab = workspaceTab();
+ if (tab && tab.database !== selectedDatabase.value) queryStore.updateDatabase(tab.id, selectedDatabase.value);
+ void reloadDatabaseContext(props.database, props.initialBranch);
+ scheduleDiffScrollSync();
+});
+
+onUnmounted(() => {
+ if (diffScrollSyncFrame) cancelAnimationFrame(diffScrollSyncFrame);
+ if (diffScrollSyncRetryTimer) window.clearTimeout(diffScrollSyncRetryTimer);
+ detachDiffScrollSync?.();
+ void api.closeClientConnectionSession(props.connectionId, activeDatabase.value, clientSessionId.value).catch(() => undefined);
+});
+</script>
+
+<template>
+ <div class="dolt-workspace flex h-full min-h-0 flex-col bg-background text-foreground">
+ <header class="flex h-10 shrink-0 items-center gap-2 border-b px-2">
+ <div class="dolt-scope-selectors">
+ <Select :model-value="activeDatabase" :disabled="databaseLoading || databaseSwitching || mutationLoading || databaseOptions.length < 2" @update:model-value="switchDatabase" @update:open="refreshDatabaseOptionsOnOpen">
+ <SelectTrigger size="sm" class="dolt-scope-trigger dolt-scope-trigger-database" :title="activeDatabase" :aria-label="t('doltVersionControl.switchDatabase')">
+ <Loader2 v-if="databaseLoading || databaseSwitching" class="h-3.5 w-3.5 animate-spin text-muted-foreground" />
+ <Database v-else class="h-3.5 w-3.5 text-emerald-600 dark:text-emerald-400" />
+ <SelectValue :placeholder="activeDatabase" />
+ </SelectTrigger>
+ <SelectContent class="max-h-72">
+ <SelectItem v-for="databaseName in databaseOptions" :key="databaseName" :value="databaseName" class="text-xs">{{ databaseName }}</SelectItem>
+ </SelectContent>
+ </Select>
+ <span class="shrink-0 text-xs text-muted-foreground/60">/</span>
+ <Select :model-value="activeBranch" :disabled="loading || databaseSwitching || mutationLoading || connectionReadOnly || branches.length < 2" @update:model-value="switchBranch">
+ <SelectTrigger size="sm" class="dolt-scope-trigger dolt-scope-trigger-branch" :title="activeBranch || t('doltVersionControl.unknownBranch')" :aria-label="t('doltVersionControl.switchBranch')">
+ <Loader2 v-if="branchSwitchingTarget" class="h-3.5 w-3.5 animate-spin text-muted-foreground" />
+ <GitBranch v-else class="h-3.5 w-3.5 text-blue-600 dark:text-blue-400" />
+ <SelectValue :placeholder="activeBranch || t('doltVersionControl.unknownBranch')" />
+ </SelectTrigger>
+ <SelectContent class="max-h-72">
+ <SelectItem v-for="branch in branches" :key="branch.name" :value="branch.name" class="text-xs">{{ branch.name }}</SelectItem>
+ </SelectContent>
+ </Select>
+ </div>
+ <div class="ml-auto flex min-w-0 max-w-full items-center gap-1.5">
+ <div class="dolt-comparison-controls" :title="t('doltVersionControl.comparison')">
+ <DoltRevisionSelector :model-value="comparedFrom" :options="allRefs" :disabled="comparisonLoading" :placeholder="t('doltVersionControl.noRevision')" :input-label="t('doltVersionControl.comparison')" @commit="selectComparisonRevision('from', $event)" />
+ <Button variant="ghost" size="icon" class="h-7 w-7" :disabled="comparisonLoading || !comparedFrom || !comparedTo" :title="t('doltVersionControl.swapComparison')" :aria-label="t('doltVersionControl.swapComparison')" @click="swapComparison">
+ <ArrowRight class="h-3.5 w-3.5" />
+ </Button>
+ <DoltRevisionSelector :model-value="comparedTo" :options="allRefs" :disabled="comparisonLoading" :placeholder="t('doltVersionControl.noRevision')" :input-label="t('doltVersionControl.comparison')" @commit="selectComparisonRevision('to', $event)" />
+ </div>
+ <Button variant="ghost" size="icon" class="h-7 w-7" :disabled="loading" :title="t('common.refresh')" :aria-label="t('common.refresh')" @click="refresh">
+ <Loader2 v-if="loading" class="h-3.5 w-3.5 animate-spin" />
+ <RefreshCw v-else class="h-3.5 w-3.5" />
+ </Button>
+ </div>
+ </header>
+
+ <div v-if="error" class="shrink-0 border-b border-destructive/30 bg-destructive/10 px-3 py-2 text-xs text-destructive">{{ error }}</div>
+
+ <Splitpanes horizontal class="dolt-main-splitpanes min-h-0 flex-1">
+ <Pane :size="64" :min-size="38">
+ <Splitpanes class="dolt-diff-splitpanes h-full min-h-0">
+ <Pane :size="doltLeftPaneSize" :min-size="DOLT_LEFT_PANE_MIN_SIZE" :max-size="DOLT_LEFT_PANE_MAX_SIZE">
+ <section class="flex h-full min-h-0 flex-col">
+ <div class="flex h-8 shrink-0 items-center gap-1.5 border-b px-2 text-xs font-medium">
+ <FileDiff class="h-3.5 w-3.5 text-blue-600 dark:text-blue-400" />
+ <span class="truncate">{{ t("doltVersionControl.changedTables") }}</span>
+ <span v-if="changes.length" class="ml-auto text-[11px] text-muted-foreground">{{ changes.length }}</span>
+ </div>
+ <DoltScrollArea class="min-h-0 flex-1">
+ <div v-if="comparisonLoading && changes.length === 0" class="flex h-24 items-center justify-center gap-2 text-xs text-muted-foreground"><Loader2 class="h-4 w-4 animate-spin" />{{ t("doltVersionControl.loadingDiff") }}</div>
+ <div v-else-if="comparisonError" class="p-3 text-xs text-destructive">{{ comparisonError }}</div>
+ <div v-else-if="changes.length === 0" class="flex h-24 items-center justify-center px-3 text-center text-xs text-muted-foreground">{{ t("doltVersionControl.noChanges") }}</div>
+ <button v-for="change in changes" :key="`${change.fromTableName}-${change.toTableName}`" type="button" class="dolt-change-row" :class="{ 'dolt-change-row-active': selectedTableName === change.tableName }" :title="changeFlagsTitle(change)" @click="loadTableDiff(change)">
+ <span class="dolt-change-symbol" :class="changeKindClass(change)" aria-hidden="true">{{ doltTableChangeSymbol(change) }}</span>
+ <Table2 class="h-3.5 w-3.5 shrink-0 text-emerald-600 dark:text-emerald-400" />
+ <span class="min-w-0 flex-1 truncate">{{ change.tableName }}</span>
+ <span v-if="changeFlags(change).length" class="dolt-change-flags" :aria-label="changeFlagsTitle(change)">
+ <span v-for="flag in changeFlags(change)" :key="flag" class="dolt-change-flag">{{ changeFlagSymbol(flag) }}</span>
+ </span>
+ </button>
+ </DoltScrollArea>
+ </section>
+ </Pane>
+
+ <Pane :size="100 - doltLeftPaneSize" :min-size="100 - DOLT_LEFT_PANE_MAX_SIZE">
+ <section class="flex h-full min-h-0 flex-col">
+ <div class="flex h-8 shrink-0 items-center gap-1.5 border-b px-2 text-xs font-medium">
+ <Table2 class="h-3.5 w-3.5 text-emerald-600 dark:text-emerald-400" />
+ <span class="truncate">{{ selectedChange?.tableName || t("doltVersionControl.rowDiff") }}</span>
+ <Loader2 v-if="tableDiffLoading && tableDiff" class="ml-auto h-3.5 w-3.5 animate-spin text-muted-foreground" />
+ </div>
+ <div v-if="tableDiffError && tableDiff" class="shrink-0 border-b border-destructive/30 bg-destructive/10 px-2 py-1 text-[11px] text-destructive">{{ tableDiffError }}</div>
+ <div class="min-h-0 flex-1 overflow-hidden">
+ <div v-if="tableDiffLoading && !tableDiff" class="flex h-24 items-center justify-center gap-2 text-xs text-muted-foreground"><Loader2 class="h-4 w-4 animate-spin" />{{ t("doltVersionControl.loadingRows") }}</div>
+ <div v-else-if="tableDiffError && !tableDiff" class="p-3 text-xs text-destructive">{{ tableDiffError }}</div>
+ <div v-else-if="!selectedChange" class="flex h-24 items-center justify-center text-xs text-muted-foreground">{{ t("doltVersionControl.selectTable") }}</div>
+ <div v-else-if="!tableDiff || parsedTableDiff.columns.length === 0" class="flex h-24 items-center justify-center text-xs text-muted-foreground">{{ t("doltVersionControl.noRowChanges") }}</div>
+ <div v-else class="dolt-diff-result">
+ <CustomContextMenu :items="diffCellContextMenuItems" v-slot="{ onContextMenu }">
+ <div class="dolt-diff-pair-grid">
+ <section ref="beforeDiffSide" class="dolt-diff-side">
+ <div class="dolt-diff-side-header">{{ revisionLabel(comparedFrom) }}</div>
+ <DoltDiffTable
+ :key="`before:${diffGridScopeKey}`"
+ :columns="parsedTableDiff.columns"
+ :column-kinds="parsedTableDiff.columnKinds"
+ :rows="parsedTableDiff.rows"
+ side="before"
+ :selected-cell="selectedDiffCell"
+ :column-widths="diffColumnWidthsReady ? diffColumnWidths : undefined"
+ :cell-class="(rowIndex: number, columnIndex: number) => diffCellClass('before', rowIndex, columnIndex)"
+ :header-class="(columnIndex: number) => diffHeaderClass('before', columnIndex)"
+ @column-widths-change="(widths: number[]) => syncDiffColumnWidths('before', widths)"
+ @cell-select="selectDiffCell"
+ @cell-context-menu="(target: DoltDiffCellTarget, event: MouseEvent) => openDiffCellContextMenu(target, event, onContextMenu)"
+ @cell-open-details="openDiffCellDetails"
+ />
+ </section>
+ <section ref="afterDiffSide" class="dolt-diff-side">
+ <div class="dolt-diff-side-header">{{ revisionLabel(comparedTo) }}</div>
+ <DoltDiffTable
+ :key="`after:${diffGridScopeKey}`"
+ :columns="parsedTableDiff.columns"
+ :column-kinds="parsedTableDiff.columnKinds"
+ :rows="parsedTableDiff.rows"
+ side="after"
+ :selected-cell="selectedDiffCell"
+ :column-widths="diffColumnWidthsReady ? diffColumnWidths : undefined"
+ :cell-class="(rowIndex: number, columnIndex: number) => diffCellClass('after', rowIndex, columnIndex)"
+ :header-class="(columnIndex: number) => diffHeaderClass('after', columnIndex)"
+ @column-widths-change="(widths: number[]) => syncDiffColumnWidths('after', widths)"
+ @cell-select="selectDiffCell"
+ @cell-context-menu="(target: DoltDiffCellTarget, event: MouseEvent) => openDiffCellContextMenu(target, event, onContextMenu)"
+ @cell-open-details="openDiffCellDetails"
+ />
+ </section>
+ </div>
+ </CustomContextMenu>
+ <DoltDiffPagination :current-page="tableDiffPage" :page-size="tableDiffPageSize" :total-rows="tableDiffTotalRows" :loading="tableDiffLoading" @page-change="loadTableDiffPage" @page-size-change="changeTableDiffPageSize" />
+ </div>
+ </div>
+ </section>
+ </Pane>
+ </Splitpanes>
+ </Pane>
+
+ <Pane :size="36" :min-size="22">
+ <Splitpanes class="dolt-history-splitpanes h-full min-h-0">
+ <Pane :size="doltLeftPaneSize" :min-size="DOLT_LEFT_PANE_MIN_SIZE" :max-size="DOLT_LEFT_PANE_MAX_SIZE">
+ <aside class="flex h-full min-h-0 flex-col bg-muted/10">
+ <div class="flex items-center gap-1.5 border-b p-2">
+ <div class="relative min-w-0 flex-1">
+ <Search class="pointer-events-none absolute left-2 top-1/2 h-3.5 w-3.5 -translate-y-1/2 text-muted-foreground" />
+ <Input v-model="refFilter" class="h-7 pl-7 text-xs" :placeholder="t('doltVersionControl.filterRefs')" />
+ </div>
+ <Button
+ v-if="refListTab === 'branches'"
+ variant="ghost"
+ size="icon"
+ class="h-7 w-7 shrink-0"
+ :title="t(branchTreeView ? 'doltVersionControl.branchFlatView' : 'doltVersionControl.branchTreeView')"
+ :aria-label="t(branchTreeView ? 'doltVersionControl.branchFlatView' : 'doltVersionControl.branchTreeView')"
+ @click="toggleBranchTreeView"
+ >
+ <FolderOpen v-if="branchTreeView" class="h-3.5 w-3.5" />
+ <List v-else class="h-3.5 w-3.5" />
+ </Button>
+ </div>
+ <Tabs v-model="refListTab" class="min-h-0 flex-1 gap-0">
+ <div class="shrink-0 border-b px-2 pt-1">
+ <TabsList variant="line" class="h-7 w-full justify-start rounded-none bg-transparent p-0">
+ <TabsTrigger value="branches" class="h-7 gap-1 px-2 text-xs"
+ ><GitBranch class="h-3.5 w-3.5" />{{ t("doltVersionControl.branches") }}<span class="text-[10px] text-muted-foreground">{{ visibleBranches.length }}</span></TabsTrigger
+ >
+ <TabsTrigger value="tags" class="h-7 gap-1 px-2 text-xs"
+ ><Tag class="h-3.5 w-3.5" />{{ t("doltVersionControl.tags") }}<span class="text-[10px] text-muted-foreground">{{ visibleTags.length }}</span></TabsTrigger
+ >
+ </TabsList>
+ </div>
+ <TabsContent value="branches" class="m-0 min-h-0 flex-1 overflow-hidden">
+ <DoltScrollArea class="h-full min-h-0" scroller-class="py-1 text-xs">
+ <template v-if="branchTreeView">
+ <CustomContextMenu v-for="row in branchTreeRows" :key="`branch-tree-${row.key}`" :items="() => branchTreeRowContextMenuItems(row)" v-slot="{ onContextMenu, isOpen }">
+ <button
+ type="button"
+ class="dolt-ref-row"
+ :class="{ 'dolt-ref-row-active': isOpen || (!!row.branch && selectedRevisionKeySet.has(`branch:${row.branch.name}`)), 'dolt-ref-row-viewing': !!row.branch && selectedRef === row.branch.name }"
+ :style="{ paddingLeft: `${8 + row.depth * 14}px` }"
+ @click="selectBranchTreeRow(row, $event)"
+ @contextmenu="openBranchTreeRowContextMenu($event, row, onContextMenu)"
+ >
+ <span
+ class="dolt-branch-tree-toggle"
+ :class="{ 'dolt-branch-tree-toggle-empty': !row.folder }"
+ :title="row.folder ? t(row.expanded ? 'doltVersionControl.collapseBranch' : 'doltVersionControl.expandBranch') : undefined"
+ @click.stop="row.folder && toggleBranchTreePath(row.key)"
+ >
+ <ChevronRight v-if="row.folder" class="h-3 w-3 transition-transform" :class="{ 'rotate-90': row.expanded }" />
+ </span>
+ <FolderOpen v-if="row.folder && row.expanded" class="h-3.5 w-3.5 shrink-0 text-blue-600 dark:text-blue-400" />
+ <Folder v-else-if="row.folder" class="h-3.5 w-3.5 shrink-0 text-blue-600 dark:text-blue-400" />
+ <GitBranch v-else class="h-3.5 w-3.5 shrink-0 text-blue-600 dark:text-blue-400" />
+ <span class="truncate">{{ row.label }}</span>
+ <Check v-if="row.branch && row.branch.active" class="ml-auto h-3.5 w-3.5 shrink-0 text-emerald-600" />
+ </button>
+ </CustomContextMenu>
+ </template>
+ <template v-else>
+ <CustomContextMenu v-for="item in visibleBranches" :key="`branch-${item.name}`" :items="() => branchContextMenuItems(item)" v-slot="{ onContextMenu, isOpen }">
+ <button
+ type="button"
+ class="dolt-ref-row"
+ :class="{ 'dolt-ref-row-active': isOpen || selectedRevisionKeySet.has(`branch:${item.name}`), 'dolt-ref-row-viewing': selectedRef === item.name }"
+ @click="selectRef(item, $event)"
+ @contextmenu="openRefContextMenu($event, item, onContextMenu)"
+ >
+ <GitBranch class="h-3.5 w-3.5 shrink-0 text-blue-600 dark:text-blue-400" />
+ <span class="truncate">{{ item.name }}</span>
+ <Check v-if="item.active" class="ml-auto h-3.5 w-3.5 shrink-0 text-emerald-600" />
+ </button>
+ </CustomContextMenu>
+ </template>
+ <div v-if="visibleBranches.length === 0" class="px-7 py-2 text-muted-foreground">{{ t("doltVersionControl.noBranches") }}</div>
+ </DoltScrollArea>
+ </TabsContent>
+ <TabsContent value="tags" class="m-0 min-h-0 flex-1 overflow-hidden">
+ <DoltScrollArea class="h-full min-h-0" scroller-class="py-1 text-xs">
+ <CustomContextMenu v-for="item in visibleTags" :key="`tag-${item.name}`" :items="() => refContextMenuItems(item)" v-slot="{ onContextMenu, isOpen }">
+ <button
+ type="button"
+ class="dolt-ref-row"
+ :class="{ 'dolt-ref-row-active': isOpen || selectedRevisionKeySet.has(`tag:${item.name}`), 'dolt-ref-row-viewing': selectedRef === item.name }"
+ @click="selectRef(item, $event)"
+ @contextmenu="openRefContextMenu($event, item, onContextMenu)"
+ >
+ <Tag class="h-3.5 w-3.5 shrink-0 text-amber-600 dark:text-amber-400" />
+ <span class="truncate">{{ item.name }}</span>
+ </button>
+ </CustomContextMenu>
+ <div v-if="visibleTags.length === 0" class="px-7 py-2 text-muted-foreground">{{ t("doltVersionControl.noTags") }}</div>
+ </DoltScrollArea>
+ </TabsContent>
+ </Tabs>
+ </aside>
+ </Pane>
+
+ <Pane :size="100 - doltLeftPaneSize" :min-size="100 - DOLT_LEFT_PANE_MAX_SIZE">
+ <DoltScrollArea class="relative h-full min-h-0">
+ <div class="dolt-commit-header sticky top-0 z-20 grid h-7 items-center border-b bg-muted/80 text-[11px] font-medium text-muted-foreground backdrop-blur" :style="{ gridTemplateColumns: `${graphWidth}px minmax(240px, 1fr) 150px 155px` }">
+ <span class="px-2">{{ t("doltVersionControl.graph") }}</span>
+ <span class="px-2">{{ t("doltVersionControl.commit") }}</span>
+ <span class="px-2">{{ t("doltVersionControl.author") }}</span>
+ <span class="px-2">{{ t("doltVersionControl.date") }}</span>
+ </div>
+ <div v-if="graphLoading" class="flex h-32 items-center justify-center gap-2 text-xs text-muted-foreground"><Loader2 class="h-4 w-4 animate-spin" />{{ t("doltVersionControl.loadingGraph") }}</div>
+ <div v-else-if="commits.length === 0 && !showWorkingTree" class="flex h-32 items-center justify-center text-xs text-muted-foreground">{{ t("doltVersionControl.noCommits") }}</div>
+ <div v-else class="relative min-w-max" :style="{ height: `${graphHeight}px` }">
+ <svg class="pointer-events-none absolute left-0 top-0 z-10" :width="graphWidth" :height="graphHeight" aria-hidden="true">
+ <line v-if="showWorkingTree && commits.length" :x1="laneX(workingTreeLane)" :y1="rowY(0)" :x2="laneX(workingTreeLane)" :y2="commitRowY(0)" :stroke="graphColor(workingTreeLane, workingTreeRef)" stroke-width="2" stroke-dasharray="3 4" stroke-linecap="round" />
+ <path v-for="edge in graphEdges" :key="edge.key" :d="edge.path" fill="none" :stroke="edge.color" stroke-width="2" stroke-linecap="round" />
+ <circle v-if="showWorkingTree" :cx="laneX(workingTreeLane)" :cy="rowY(0)" r="4.5" :fill="selectedRevisionKeySet.has('working') ? graphColor(workingTreeLane, workingTreeRef) : 'var(--background)'" :stroke="graphColor(workingTreeLane, workingTreeRef)" stroke-width="2" />
+ <circle
+ v-for="(row, index) in graphLayout.rows"
+ :key="`node-${commits[index]?.hash}`"
+ :cx="laneX(row.lane)"
+ :cy="commitRowY(index)"
+ r="4.5"
+ :fill="selectedRevisionKeySet.has(`commit:${commits[index]?.hash}`) ? graphColor(row.lane, row.nodeRef) : 'var(--background)'"
+ :stroke="graphColor(row.lane, row.nodeRef)"
+ stroke-width="2"
+ />
+ </svg>
+ <CustomContextMenu v-if="showWorkingTree" :items="workingTreeContextMenuItems" v-slot="{ onContextMenu, isOpen }">
+ <button
+ type="button"
+ class="dolt-commit-row dolt-working-tree-row absolute left-0 grid w-full min-w-[760px] items-center text-left text-xs"
+ :class="{ 'dolt-commit-row-active': isOpen || selectedRevisionKeySet.has('working') }"
+ :style="{ top: '0px', gridTemplateColumns: `${graphWidth}px minmax(240px, 1fr) 150px 155px` }"
+ :title="workingTreeTitle"
+ @click="selectWorkingTree"
+ @contextmenu="openWorkingTreeContextMenu($event, onContextMenu)"
+ >
+ <span aria-hidden="true"></span>
+ <span class="flex min-w-0 items-center gap-1.5 px-2">
+ <GitCommitHorizontal class="h-3.5 w-3.5 shrink-0 text-amber-600 dark:text-amber-400" />
+ <span class="truncate font-medium">{{ t("doltVersionControl.workingTree") }}</span>
+ <span v-if="stagedWorkingChangeCount" class="dolt-working-badge dolt-working-badge-staged">{{ t("doltVersionControl.stagedChanges", { count: stagedWorkingChangeCount }) }}</span>
+ <span v-if="unstagedWorkingChangeCount" class="dolt-working-badge dolt-working-badge-unstaged">{{ t("doltVersionControl.unstagedChanges", { count: unstagedWorkingChangeCount }) }}</span>
+ </span>
+ <span class="truncate px-2 text-muted-foreground">{{ activeBranch }}</span>
+ <span class="px-2 text-muted-foreground">{{ t("doltVersionControl.uncommitted") }}</span>
+ </button>
+ </CustomContextMenu>
+ <CustomContextMenu v-for="(commitItem, commitIndex) in commits" :key="commitItem.hash" :items="() => commitContextMenuItems(commitItem)" v-slot="{ onContextMenu, isOpen }">
+ <button
+ type="button"
+ class="dolt-commit-row absolute left-0 grid w-full min-w-[760px] items-center text-left text-xs"
+ :class="{ 'dolt-commit-row-active': isOpen || selectedRevisionKeySet.has(`commit:${commitItem.hash}`) }"
+ :style="{ top: `${(commitIndex + graphRowOffset) * COMMIT_ROW_HEIGHT}px`, gridTemplateColumns: `${graphWidth}px minmax(240px, 1fr) 150px 155px` }"
+ @click="selectCommit(commitItem, $event)"
+ @contextmenu="openCommitContextMenu($event, commitItem, onContextMenu)"
+ >
+ <span aria-hidden="true"></span>
+ <span class="flex min-w-0 items-center gap-1.5 px-2">
+ <GitCommitHorizontal class="h-3.5 w-3.5 shrink-0 text-muted-foreground" />
+ <span class="truncate">{{ commitItem.message || t("doltVersionControl.noMessage") }}</span>
+ <span v-for="refItem in refsByCommit.get(commitItem.hash)" :key="`${commitItem.hash}-${refItem.kind}-${refItem.name}`" class="dolt-ref-badge" :class="refItem.kind === 'branch' ? 'dolt-ref-badge-branch' : 'dolt-ref-badge-tag'" :style="refBadgeStyle(refItem)">{{
+ refItem.name
+ }}</span>
+ <span class="ml-auto shrink-0 font-mono text-[11px] text-muted-foreground">{{ shortHash(commitItem.hash) }}</span>
+ </span>
+ <span class="truncate px-2 text-muted-foreground" :title="commitItem.email">{{ commitItem.committer }}</span>
+ <span class="truncate px-2 text-muted-foreground">{{ formatDate(commitItem.date) }}</span>
+ </button>
+ </CustomContextMenu>
+ </div>
+ </DoltScrollArea>
+ </Pane>
+ </Splitpanes>
+ </Pane>
+ </Splitpanes>
+
+ <DoltCellDiffDialog v-model:open="diffCellDetailOpen" :target="diffCellDetailTarget" :table-name="selectedChange?.tableName || selectedTableName" :from-revision="revisionLabel(comparedFrom)" :to-revision="revisionLabel(comparedTo)" />
+
+ <Dialog :open="branchDialog !== null" @update:open="(open) => !open && closeBranchDialog()">
+ <DialogContent class="sm:max-w-md">
+ <DialogHeader>
+ <DialogTitle>{{ mutationDialogTitle }}</DialogTitle>
+ <DialogDescription>{{ mutationDialogDescription }}</DialogDescription>
+ </DialogHeader>
+ <div v-if="createsNamedRef" class="space-y-3 py-2">
+ <div class="space-y-1.5">
+ <label class="text-xs font-medium">{{ branchDialog === "create-tag" ? t("doltVersionControl.tagName") : t("doltVersionControl.branchName") }}</label
+ ><Input v-model="branchNameDraft" autofocus :placeholder="branchDialog === 'create-tag' ? t('doltVersionControl.tagNamePlaceholder') : t('doltVersionControl.branchNamePlaceholder')" @keydown.enter.prevent="submitBranchOperation" />
+ </div>
+ <div class="text-xs text-muted-foreground">{{ t("doltVersionControl.branchSource", { revision: revisionLabel(branchSourceRevision) }) }}</div>
+ </div>
+ <div v-if="mutationError" class="rounded border border-destructive/30 bg-destructive/10 px-2.5 py-2 text-xs text-destructive">{{ mutationError }}</div>
+ <DialogFooter>
+ <Button variant="ghost" :disabled="mutationLoading" @click="closeBranchDialog">{{ t("common.cancel") }}</Button>
+ <Button :variant="branchDialog === 'delete' || branchDialog === 'delete-tag' ? 'destructive' : 'default'" :disabled="mutationLoading || (createsNamedRef && !branchNameDraft.trim())" @click="submitBranchOperation">
+ <Loader2 v-if="mutationLoading" class="mr-1.5 h-3.5 w-3.5 animate-spin" />
+ {{ mutationDialogTitle }}
+ </Button>
+ </DialogFooter>
+ </DialogContent>
+ </Dialog>
+
+ <Dialog :open="commitDialogOpen" @update:open="(open) => !open && closeCommitDialog()">
+ <DialogContent class="sm:max-w-md">
+ <DialogHeader>
+ <DialogTitle>{{ t("doltVersionControl.commitWorkingTree") }}</DialogTitle>
+ <DialogDescription>{{ t("doltVersionControl.commitWorkingTreeDescription") }}</DialogDescription>
+ </DialogHeader>
+ <div class="space-y-1.5 py-2">
+ <label class="text-xs font-medium" for="dolt-commit-message">{{ t("doltVersionControl.commitMessage") }}</label>
+ <Input id="dolt-commit-message" v-model="commitMessageDraft" autofocus :placeholder="t('doltVersionControl.commitMessagePlaceholder')" @keydown.enter.prevent="submitWorkingTreeCommit" />
+ </div>
+ <div v-if="commitError" class="rounded border border-destructive/30 bg-destructive/10 px-2.5 py-2 text-xs text-destructive">{{ commitError }}</div>
+ <DialogFooter>
+ <Button variant="ghost" :disabled="mutationLoading" @click="closeCommitDialog">{{ t("common.cancel") }}</Button>
+ <Button :disabled="mutationLoading || !commitMessageDraft.trim()" @click="submitWorkingTreeCommit">
+ <Loader2 v-if="mutationLoading" class="mr-1.5 h-3.5 w-3.5 animate-spin" />
+ {{ t("doltVersionControl.commitWorkingTree") }}
+ </Button>
+ </DialogFooter>
+ </DialogContent>
+ </Dialog>
+
+ <Dialog :open="discardWorkingTreeDialogOpen" @update:open="(open) => !open && closeDiscardWorkingTreeDialog()">
+ <DialogContent class="sm:max-w-md">
+ <DialogHeader>
+ <div class="mb-1 flex h-9 w-9 items-center justify-center rounded-md bg-destructive/10 text-destructive"><TriangleAlert class="h-5 w-5" /></div>
+ <DialogTitle>{{ t("doltVersionControl.discardWorkingTree") }}</DialogTitle>
+ <DialogDescription>{{ t("doltVersionControl.discardWorkingTreeDescription") }}</DialogDescription>
+ </DialogHeader>
+ <div class="rounded border border-border/70 bg-muted/25 px-3 py-2 text-xs">
+ <div class="mb-1 font-medium text-muted-foreground">{{ t("doltVersionControl.sqlPreview") }}</div>
+ <pre class="dolt-sql-preview">{{ discardWorkingTreeSqlPreview }}</pre>
+ </div>
+ <div v-if="discardWorkingTreeError" class="rounded border border-destructive/30 bg-destructive/10 px-2.5 py-2 text-xs text-destructive">{{ discardWorkingTreeError }}</div>
+ <DialogFooter>
+ <Button variant="ghost" :disabled="mutationLoading" @click="closeDiscardWorkingTreeDialog">{{ t("common.cancel") }}</Button>
+ <Button variant="destructive" :disabled="mutationLoading" @click="submitDiscardWorkingTree">
+ <Loader2 v-if="mutationLoading" class="mr-1.5 h-3.5 w-3.5 animate-spin" />
+ {{ t("doltVersionControl.discardWorkingTree") }}
+ </Button>
+ </DialogFooter>
+ </DialogContent>
+ </Dialog>
+
+ <Dialog :open="commitHistoryOperation !== null" @update:open="(open) => !open && closeCommitHistoryDialog()">
+ <DialogContent class="sm:max-w-md">
+ <DialogHeader>
+ <div class="mb-1 flex h-9 w-9 items-center justify-center rounded-md bg-destructive/10 text-destructive"><TriangleAlert class="h-5 w-5" /></div>
+ <DialogTitle>{{ commitHistoryOperationTitle }}</DialogTitle>
+ <DialogDescription>{{ commitHistoryOperationDescription }}</DialogDescription>
+ </DialogHeader>
+ <div v-if="commitHistoryTarget" class="space-y-2 rounded border border-border/70 bg-muted/25 px-3 py-2.5 text-xs">
+ <div class="flex items-center gap-2">
+ <span class="shrink-0 font-mono text-muted-foreground">{{ shortHash(commitHistoryTarget.hash) }}</span>
+ <span class="min-w-0 truncate font-medium">{{ commitHistoryTarget.message || t("doltVersionControl.noMessage") }}</span>
+ </div>
+ <div class="text-destructive">{{ t("doltVersionControl.highRiskConfirmation") }}</div>
+ </div>
+ <div class="rounded border border-border/70 bg-muted/25 px-3 py-2 text-xs">
+ <div class="mb-1 font-medium text-muted-foreground">{{ t("doltVersionControl.sqlPreview") }}</div>
+ <pre class="dolt-sql-preview">{{ commitHistoryOperationSql }}</pre>
+ </div>
+ <div v-if="commitHistoryError" class="rounded border border-destructive/30 bg-destructive/10 px-2.5 py-2 text-xs text-destructive">{{ commitHistoryError }}</div>
+ <DialogFooter>
+ <Button variant="ghost" :disabled="mutationLoading" @click="closeCommitHistoryDialog">{{ t("common.cancel") }}</Button>
+ <Button variant="destructive" :disabled="mutationLoading" @click="submitCommitHistoryOperation">
+ <Loader2 v-if="mutationLoading" class="mr-1.5 h-3.5 w-3.5 animate-spin" />
+ {{ commitHistoryOperationTitle }}
+ </Button>
+ </DialogFooter>
+ </DialogContent>
+ </Dialog>
+ </div>
+</template>
+
+<style scoped>
+.dolt-scope-selectors {
+ display: flex;
+ min-width: 0;
+ max-width: min(46vw, 480px);
+ align-items: center;
+ gap: 4px;
+}
+
+.dolt-scope-trigger {
+ width: max-content;
+ max-width: min(240px, 23vw);
+ flex-shrink: 1;
+ border-color: transparent;
+ background: color-mix(in srgb, var(--muted) 28%, transparent);
+ padding-right: 6px;
+ padding-left: 7px;
+ box-shadow: none;
+}
+
+.dolt-scope-trigger-database {
+ min-width: min(128px, 23vw);
+}
+
+.dolt-scope-trigger-branch {
+ min-width: min(112px, 23vw);
+}
+
+.dolt-scope-trigger:hover:not(:disabled) {
+ border-color: var(--border);
+ background: color-mix(in srgb, var(--muted) 48%, transparent);
+}
+
+.dolt-comparison-controls {
+ display: flex;
+ width: fit-content;
+ max-width: min(50vw, 480px);
+ min-width: 0;
+ align-items: center;
+ gap: 2px;
+}
+
+.dolt-sql-preview {
+ margin: 0;
+ overflow-x: auto;
+ white-space: pre-wrap;
+ overflow-wrap: anywhere;
+ font-family: var(--font-mono);
+ font-size: 11px;
+ line-height: 1.45;
+ color: var(--foreground);
+}
+
+.dolt-main-splitpanes,
+.dolt-diff-splitpanes,
+.dolt-history-splitpanes {
+ overflow: hidden;
+}
+
+.dolt-diff-result {
+ display: flex;
+ height: 100%;
+ min-height: 0;
+ flex-direction: column;
+ overflow: hidden;
+}
+
+.dolt-diff-pair-grid {
+ display: grid;
+ grid-template-columns: repeat(2, minmax(0, 1fr));
+ width: 100%;
+ min-height: 0;
+ flex: 1;
+ overflow: hidden;
+}
+
+.dolt-diff-side {
+ display: flex;
+ min-width: 0;
+ min-height: 0;
+ flex-direction: column;
+ overflow: hidden;
+ border-right: 1px solid var(--border);
+}
+
+.dolt-diff-side:last-child {
+ border-right: 0;
+}
+
+.dolt-diff-side-header {
+ display: flex;
+ height: 28px;
+ flex-shrink: 0;
+ align-items: center;
+ border-bottom: 1px solid var(--border);
+ background: color-mix(in srgb, var(--muted) 40%, transparent);
+ padding: 0 8px;
+ overflow: hidden;
+ text-overflow: ellipsis;
+ white-space: nowrap;
+ font-family: var(--font-mono);
+ font-size: 11px;
+ color: var(--muted-foreground);
+}
+
+.dolt-workspace :deep(.splitpanes__pane) {
+ min-width: 0;
+ min-height: 0;
+}
+
+.dolt-workspace :deep(.splitpanes--vertical > .splitpanes__splitter) {
+ position: relative;
+ width: 1px;
+ flex: 0 0 1px;
+ border: 0;
+ background: var(--border);
+ cursor: col-resize;
+}
+
+.dolt-workspace :deep(.splitpanes--horizontal > .splitpanes__splitter) {
+ position: relative;
+ height: 1px;
+ flex: 0 0 1px;
+ border: 0;
+ background: var(--border);
+ cursor: row-resize;
+}
+
+.dolt-workspace :deep(.splitpanes--vertical > .splitpanes__splitter::before) {
+ position: absolute;
+ z-index: 2;
+ top: 0;
+ bottom: 0;
+ left: -2px;
+ width: 5px;
+ content: "";
+}
+
+.dolt-workspace :deep(.splitpanes--horizontal > .splitpanes__splitter::before) {
+ position: absolute;
+ z-index: 2;
+ top: -2px;
+ right: 0;
+ left: 0;
+ height: 5px;
+ content: "";
+}
+
+.dolt-workspace :deep(.splitpanes__splitter:hover) {
+ background: var(--primary);
+}
+
+.dolt-ref-row,
+.dolt-change-row {
+ display: flex;
+ width: 100%;
+ min-height: 26px;
+ align-items: center;
+ gap: 6px;
+ padding: 4px 8px;
+ text-align: left;
+}
+
+.dolt-ref-row,
+.dolt-commit-row {
+ user-select: none;
+ -webkit-user-select: none;
+}
+
+.dolt-ref-row:hover,
+.dolt-change-row:hover,
+.dolt-commit-row:hover {
+ background: color-mix(in srgb, var(--muted) 55%, transparent);
+}
+
+.dolt-ref-row-active,
+.dolt-change-row-active,
+.dolt-commit-row-active {
+ background: var(--accent);
+ color: var(--accent-foreground);
+}
+
+.dolt-ref-row-viewing {
+ box-shadow: inset 2px 0 0 var(--primary);
+}
+
+.dolt-branch-tree-toggle {
+ display: inline-flex;
+ width: 14px;
+ flex: 0 0 14px;
+ align-items: center;
+ justify-content: center;
+ color: var(--muted-foreground);
+}
+
+.dolt-branch-tree-toggle-empty {
+ visibility: hidden;
+}
+
+.dolt-commit-row {
+ height: 30px;
+ display: grid;
+ border-bottom: 1px solid color-mix(in srgb, var(--border) 45%, transparent);
+}
+
+.dolt-working-tree-row {
+ border-bottom-style: dashed;
+ border-bottom-color: color-mix(in srgb, rgb(217 119 6) 45%, var(--border));
+}
+
+.dolt-working-tree-row:not(.dolt-commit-row-active) {
+ background: color-mix(in srgb, rgb(217 119 6) 7%, transparent);
+}
+
+.dolt-working-badge {
+ flex-shrink: 0;
+ border: 1px solid;
+ border-radius: 3px;
+ padding: 0 4px;
+ font-size: 10px;
+ font-weight: 500;
+ line-height: 16px;
+}
+
+.dolt-working-badge-staged {
+ border-color: rgb(22 163 74 / 0.4);
+ background: rgb(22 163 74 / 0.1);
+ color: rgb(21 128 61);
+}
+
+.dolt-working-badge-unstaged {
+ border-color: rgb(217 119 6 / 0.45);
+ background: rgb(217 119 6 / 0.1);
+ color: rgb(180 83 9);
+}
+
+.dolt-ref-badge,
+.dolt-change-kind {
+ max-width: 130px;
+ flex-shrink: 0;
+ overflow: hidden;
+ text-overflow: ellipsis;
+ white-space: nowrap;
+ border: 1px solid var(--border);
+ border-radius: 3px;
+ padding: 1px 5px;
+ font-size: 10px;
+ line-height: 15px;
+ color: var(--muted-foreground);
+}
+
+.dolt-change-symbol {
+ display: inline-flex;
+ width: 14px;
+ flex: 0 0 14px;
+ align-items: center;
+ justify-content: center;
+ font-size: 14px;
+ font-weight: 700;
+ line-height: 16px;
+}
+
+.dolt-change-flags {
+ display: inline-flex;
+ flex: 0 0 auto;
+ align-items: center;
+ gap: 3px;
+ color: var(--muted-foreground);
+ font-size: 10px;
+ font-weight: 600;
+ line-height: 15px;
+}
+
+.dolt-change-flag {
+ min-width: 14px;
+ border: 1px solid color-mix(in srgb, currentColor 30%, transparent);
+ border-radius: 3px;
+ padding: 0 3px;
+ text-align: center;
+}
+
+.dolt-ref-badge-branch {
+ border-color: color-mix(in srgb, var(--dolt-ref-color) 45%, transparent);
+ background: color-mix(in srgb, var(--dolt-ref-color) 9%, transparent);
+ color: var(--dolt-ref-color);
+}
+
+.dolt-ref-badge-tag {
+ border-color: color-mix(in srgb, var(--dolt-ref-color) 45%, transparent);
+ border-style: dashed;
+ background: color-mix(in srgb, var(--dolt-ref-color) 9%, transparent);
+ color: var(--dolt-ref-color);
+}
+
+.dolt-change-added {
+ border-color: rgb(22 163 74 / 0.35);
+ color: rgb(21 128 61);
+}
+
+.dolt-change-removed {
+ border-color: rgb(220 38 38 / 0.35);
+ color: rgb(185 28 28);
+}
+
+.dolt-change-modified {
+ border-color: rgb(47 111 219 / 0.35);
+ color: rgb(47 111 219);
+}
+
+.dolt-change-schema {
+ border-color: rgb(124 58 237 / 0.35);
+ color: rgb(109 40 217);
+}
+
+.dolt-change-mixed {
+ border-color: rgb(217 119 6 / 0.35);
+ color: rgb(180 83 9);
+}
+
+.dolt-diff-side :deep(.dolt-grid-cell-added) {
+ background-color: rgb(22 163 74 / 0.2) !important;
+ box-shadow: inset 2px 0 0 rgb(22 163 74 / 0.75);
+}
+
+.dolt-diff-side :deep(.dolt-grid-cell-removed) {
+ background-color: rgb(220 38 38 / 0.2) !important;
+ box-shadow: inset 2px 0 0 rgb(220 38 38 / 0.75);
+}
+
+.dolt-diff-side :deep(.dolt-grid-cell-modified) {
+ background-color: rgb(234 179 8 / 0.22) !important;
+ box-shadow: inset 2px 0 0 rgb(202 138 4 / 0.8);
+}
+
+.dolt-diff-side :deep(.dolt-grid-cell-structural-missing) {
+ background-color: color-mix(in srgb, var(--muted) 38%, transparent) !important;
+ background-image: repeating-linear-gradient(-45deg, transparent, transparent 5px, rgb(100 116 139 / 0.08) 5px, rgb(100 116 139 / 0.08) 7px);
+}
+
+.dolt-diff-side :deep(.dolt-grid-header-added),
+.dolt-diff-side :deep(.dolt-grid-header-added-missing) {
+ border-bottom: 2px solid rgb(22 163 74 / 0.8) !important;
+ background-color: rgb(22 163 74 / 0.16) !important;
+ color: rgb(21 128 61);
+}
+
+.dolt-diff-side :deep(.dolt-grid-header-removed),
+.dolt-diff-side :deep(.dolt-grid-header-removed-missing) {
+ border-bottom: 2px solid rgb(220 38 38 / 0.8) !important;
+ background-color: rgb(220 38 38 / 0.16) !important;
+ color: rgb(185 28 28);
+}
+
+.dolt-diff-side :deep(.dolt-grid-header-added-missing),
+.dolt-diff-side :deep(.dolt-grid-header-removed-missing) {
+ opacity: 0.58;
+ background-image: repeating-linear-gradient(-45deg, transparent, transparent 5px, rgb(100 116 139 / 0.1) 5px, rgb(100 116 139 / 0.1) 7px);
+}
+
+.dolt-diff-side :deep([data-column-header-actions]) {
+ display: none;
+}
+</style>
diff --git a/apps/desktop/src/components/layout/AppTabBar.vue b/apps/desktop/src/components/layout/AppTabBar.vue
index 97b0b36a49..ab285dffac 100644
--- a/apps/desktop/src/components/layout/AppTabBar.vue
+++ b/apps/desktop/src/components/layout/AppTabBar.vue
@@ -2,7 +2,7 @@
import { computed, ref, watch, nextTick, onUnmounted } from "vue";
import type { CSSProperties } from "vue";
import { useI18n } from "vue-i18n";
-import { X, Pin, ChevronDown, Table2, Code2, TableProperties, PencilRuler, KeyRound, Pencil, Package, Lock, Copy, AlertTriangle, Network, Minimize2, Maximize2, Settings, CalendarClock, Activity, Gauge, ShieldCheck, Database } from "@lucide/vue";
+import { X, Pin, ChevronDown, Table2, Code2, TableProperties, PencilRuler, KeyRound, Pencil, Package, Lock, Copy, AlertTriangle, Network, Minimize2, Maximize2, Settings, CalendarClock, Activity, Gauge, ShieldCheck, Database, GitBranch } from "@lucide/vue";
import CustomContextMenu, { type ContextMenuItem } from "@/components/ui/CustomContextMenu.vue";
import { Tooltip, TooltipTrigger, TooltipContent } from "@/components/ui/tooltip";
import { Popover, PopoverContent, PopoverTrigger } from "@/components/ui/popover";
@@ -536,6 +536,7 @@ function tabMenuIcon(tab: QueryTab) {
if (tab.mode === "dameng-jobs") return CalendarClock;
if (tab.mode === "processlist" || tab.mode === "sqlserver-trace") return Activity;
if (tab.mode === "mysql-dashboard" || tab.mode === "postgres-dashboard" || tab.mode === "nacos-dashboard") return Gauge;
+ if (tab.mode === "dolt-version-control") return GitBranch;
return Code2;
}
@@ -687,6 +688,7 @@ function onOverflowItemKeydown(event: KeyboardEvent, tabId: string, kind: "regul
<CalendarClock v-else-if="tab.mode === 'dameng-jobs'" class="h-3.5 w-3.5" />
<Activity v-else-if="tab.mode === 'processlist' || tab.mode === 'sqlserver-trace'" class="h-3.5 w-3.5" />
<Gauge v-else-if="tab.mode === 'mysql-dashboard' || tab.mode === 'postgres-dashboard' || tab.mode === 'nacos-dashboard'" class="h-3.5 w-3.5" />
+ <GitBranch v-else-if="tab.mode === 'dolt-version-control'" class="h-3.5 w-3.5" />
<Code2 v-else class="h-3.5 w-3.5" />
</span>
<input
@@ -885,6 +887,7 @@ function onOverflowItemKeydown(event: KeyboardEvent, tabId: string, kind: "regul
<CalendarClock v-else-if="tab.mode === 'dameng-jobs'" class="h-3.5 w-3.5" />
<Activity v-else-if="tab.mode === 'processlist' || tab.mode === 'sqlserver-trace'" class="h-3.5 w-3.5" />
<Gauge v-else-if="tab.mode === 'mysql-dashboard' || tab.mode === 'postgres-dashboard' || tab.mode === 'nacos-dashboard'" class="h-3.5 w-3.5" />
+ <GitBranch v-else-if="tab.mode === 'dolt-version-control'" class="h-3.5 w-3.5" />
<Code2 v-else class="h-3.5 w-3.5" />
</span>
<input
diff --git a/apps/desktop/src/components/layout/ContentArea.vue b/apps/desktop/src/components/layout/ContentArea.vue
index 19e0700500..d61c2bfd32 100644
--- a/apps/desktop/src/components/layout/ContentArea.vue
+++ b/apps/desktop/src/components/layout/ContentArea.vue
@@ -96,6 +96,7 @@ const MqttAdminConsole = defineAsyncComponent(() => import("@/components/mqtt/Mq
const NacosAdminConsole = defineAsyncComponent(() => import("@/components/nacos/NacosAdminConsole.vue"));
const NacosAccessControlConsole = defineAsyncComponent(() => import("@/components/nacos/NacosAccessControlConsole.vue"));
const NacosDashboard = defineAsyncComponent(() => import("@/components/nacos/NacosDashboard.vue"));
+const DoltVersionControl = defineAsyncComponent(() => import("@/components/dolt/DoltVersionControl.vue"));
const DatabaseBrowser = defineAsyncComponent(() => import("@/components/objects/DatabaseBrowser.vue"));
const ObjectBrowser = defineAsyncComponent(() => import("@/components/objects/ObjectBrowser.vue"));
const TableStructureEditor = defineAsyncComponent(() => import("@/components/structure/TableStructureEditor.vue"));
@@ -1022,7 +1023,19 @@ async function executeRedisCommand(command: string): Promise<boolean> {
return (await redisKeyBrowserRef.value?.executeCommand?.(command)) ?? false;
}
-defineExpose({ focusSearch, refreshData, refreshQueryEditorCompletionCache, handleModRTarget, requestQueryEditorExecute, requestQueryEditorExecuteInNewResultTab, acceptQueryEditorExecutionViewport, pasteClipboardAsSqlInCondition, applyTableStructureChanges, insertRedisCommand, executeRedisCommand });
+defineExpose({
+ focusSearch,
+ refreshData,
+ refreshQueryEditorCompletionCache,
+ handleModRTarget,
+ requestQueryEditorExecute,
+ requestQueryEditorExecuteInNewResultTab,
+ acceptQueryEditorExecutionViewport,
+ pasteClipboardAsSqlInCondition,
+ applyTableStructureChanges,
+ insertRedisCommand,
+ executeRedisCommand,
+});
</script>
<template>
@@ -2200,6 +2213,12 @@ defineExpose({ focusSearch, refreshData, refreshQueryEditorCompletionCache, hand
</div>
</template>
+ <template v-else-if="activeTab.mode === 'dolt-version-control'">
+ <div class="min-h-0 flex-1">
+ <DoltVersionControl :key="activeTab.id" :connection-id="activeTab.connectionId" :database="activeTab.database" :initial-branch="activeTab.workspaceBranch" />
+ </div>
+ </template>
+
<template v-else-if="activeTab.mode === 'dameng-jobs' && activeConnection">
<DamengJobAdmin :key="activeTab.id" :connection="activeConnection" />
</template>
diff --git a/apps/desktop/src/components/sidebar/SidebarTreeRuntimeHost.vue b/apps/desktop/src/components/sidebar/SidebarTreeRuntimeHost.vue
index aa8d609078..14fa4c96a2 100644
--- a/apps/desktop/src/components/sidebar/SidebarTreeRuntimeHost.vue
+++ b/apps/desktop/src/components/sidebar/SidebarTreeRuntimeHost.vue
@@ -56,6 +56,7 @@ import {
Info,
X,
Settings2,
+ GitBranch,
} from "@lucide/vue";
import type { ContextMenuItem } from "@/components/ui/CustomContextMenu.vue";
import { CONNECTION_ATTEMPT_CANCELLED_MESSAGE, useConnectionStore } from "@/stores/connectionStore";
@@ -168,6 +169,7 @@ import { buildXuguCompileSql } from "@/lib/database/xuguCompileSql";
import type { SidebarDataOpenRequest } from "@/lib/sidebar/sidebarDataOpenCoordinator";
import { createSidebarActionTarget, findSidebarActionTarget, releaseRemovedSidebarActionTarget, type SidebarActionTarget } from "@/lib/sidebar/sidebarActionTarget";
import { createSidebarMenuContext, normalizeSidebarMenuDescriptors } from "@/lib/sidebar/sidebarTreeMenuDescriptors";
+import { driverProfileDatabaseWorkspace } from "@/lib/database/driverProfileExtensions";
import type { SidebarDangerDialogRequest } from "@/lib/sidebar/sidebarDangerDialog";
import {
fallbackCreateDatabaseCharset,
@@ -1448,6 +1450,41 @@ async function openDatabaseBrowser() {
}
}
+async function openProfileDatabaseWorkspace() {
+ const node = activeNode.value;
+ if (!node.connectionId) return;
+ const config = connectionStore.getConfig(node.connectionId);
+ const workspace = driverProfileDatabaseWorkspace(config?.driver_profile);
+ if (!workspace?.entryScopes.includes("database") || node.type !== "database" || !node.database) return;
+ try {
+ await connectionStore.ensureConnected(node.connectionId);
+ connectionStore.activeConnectionId = node.connectionId;
+ const target = workspace.resolveTarget?.(node.database, "database") ?? { database: node.database };
+ queryStore.openDriverProfileWorkspace(node.connectionId, target.database, t(workspace.tabTitleKey), workspace.mode, workspace.tabScope, target.branch);
+ } catch (e: any) {
+ toast(t("connection.connectFailed", { message: translateBackendError(t, e) }), 5000);
+ }
+}
+
+async function openProfileConnectionWorkspace() {
+ const node = activeNode.value;
+ if (node.type !== "connection" || !node.connectionId) return;
+ const config = connectionStore.getConfig(node.connectionId);
+ const workspace = driverProfileDatabaseWorkspace(config?.driver_profile);
+ if (!workspace?.entryScopes.includes("connection")) return;
+ try {
+ await connectionStore.ensureConnected(node.connectionId);
+ connectionStore.activeConnectionId = node.connectionId;
+ const options = await getDatabaseOptions(node.connectionId);
+ const database = resolveDefaultDatabase(config!, options);
+ if (!database) return;
+ const target = workspace.resolveTarget?.(database, "connection") ?? { database };
+ queryStore.openDriverProfileWorkspace(node.connectionId, target.database, t(workspace.tabTitleKey), workspace.mode, workspace.tabScope, target.branch);
+ } catch (e: any) {
+ toast(t("connection.connectFailed", { message: translateBackendError(t, e) }), 5000);
+ }
+}
+
async function openUserAdmin() {
const node = activeNode.value;
if (!node.connectionId) return;
@@ -4504,6 +4541,10 @@ function buildConnectionSidebarMenu(context: SidebarMenuFactoryContext): boolean
if (supportsQueryActions) {
items.push({ label: t("contextMenu.newQuery"), action: newQuery, icon: TerminalSquare });
}
+ const connectionWorkspace = node.connectionId ? driverProfileDatabaseWorkspace(connectionStore.getConfig(node.connectionId)?.driver_profile) : undefined;
+ if (connectionWorkspace?.entryScopes.includes("connection")) {
+ items.push({ label: t(connectionWorkspace.menuLabelKey), action: openProfileConnectionWorkspace, icon: GitBranch });
+ }
if (canOpenConnectionDatabaseBrowser.value) {
items.push({ label: t("contextMenu.openDatabaseBrowser"), action: openDatabaseBrowser, icon: TableProperties });
}
@@ -4696,6 +4737,10 @@ function buildDatabaseSidebarMenu(context: SidebarMenuFactoryContext): boolean {
const sqlHistoryMenu = savedSqlHistorySubmenu();
if (sqlHistoryMenu) items.push(sqlHistoryMenu);
}
+ const profileWorkspace = node.type === "database" && node.connectionId ? driverProfileDatabaseWorkspace(connectionStore.getConfig(node.connectionId)?.driver_profile) : undefined;
+ if (profileWorkspace?.entryScopes.includes("database")) {
+ items.push({ label: t(profileWorkspace.menuLabelKey), action: openProfileDatabaseWorkspace, icon: GitBranch });
+ }
if (node.type === "database" && currentDatabaseType() !== "cloudflare-d1") {
if (!isNodeDefaultDatabase.value) {
items.push({ label: t("contextMenu.setDefaultDatabase"), action: setNodeAsDefaultDatabase, icon: Database });
diff --git a/apps/desktop/src/i18n/locales/en.ts b/apps/desktop/src/i18n/locales/en.ts
index 543d08d941..94ba2e2c1b 100644
--- a/apps/desktop/src/i18n/locales/en.ts
+++ b/apps/desktop/src/i18n/locales/en.ts
@@ -8162,4 +8162,104 @@ export default {
registerInstance: "Register instance",
deregister: "Deregister",
},
+ doltVersionControl: {
+ title: "Dolt Version Control",
+ open: "Version Control",
+ branches: "Branches",
+ branchTreeView: "Tree view",
+ branchFlatView: "Flat view",
+ expandBranch: "Expand branch group",
+ collapseBranch: "Collapse branch group",
+ tags: "Tags",
+ filterRefs: "Filter branches and tags",
+ noBranches: "No branches",
+ noTags: "No tags",
+ unknownBranch: "Unknown branch",
+ switchDatabase: "Switch database",
+ switchBranch: "Switch branch",
+ workingTree: "Working tree",
+ stagedChanges: "Staged {count}",
+ unstagedChanges: "Unstaged {count}",
+ uncommitted: "Uncommitted",
+ stageAllChanges: "Stage all changes",
+ commitWorkingTree: "Commit working tree",
+ commitWorkingTreeDescription: "Enter a commit message to stage and commit the working tree changes.",
+ commitMessage: "Commit message",
+ commitMessagePlaceholder: "For example: Fix order status",
+ commitMessageRequired: "Enter a commit message.",
+ changesStaged: "Working tree changes staged",
+ workingTreeCommitted: "Working tree changes committed",
+ comparison: "Current comparison",
+ swapComparison: "Swap comparison sides",
+ noRevision: "No revision",
+ compareCurrent: "Compare with current branch",
+ checkoutBranch: "Switch to branch",
+ branchCheckedOut: "Switched to branch {name}",
+ graph: "Graph",
+ commit: "Commit",
+ author: "Author",
+ date: "Date",
+ loadingGraph: "Loading commit graph...",
+ noCommits: "No commits found",
+ noMessage: "No commit message",
+ changedTables: "Changed tables",
+ loadingDiff: "Loading revision differences...",
+ noChanges: "No table changes found between these revisions.",
+ rowDiff: "Row differences",
+ rows: "{count} rows",
+ loadingRows: "Loading row differences...",
+ selectTable: "Select a changed table",
+ noRowChanges: "No row changes were returned. The change may be schema-only.",
+ createBranch: "Create branch",
+ createTag: "Create tag",
+ mergeBranch: "Merge branch",
+ deleteBranch: "Delete branch",
+ deleteTag: "Delete tag",
+ createBranchDescription: "Create a branch from the selected revision or current branch.",
+ createTagDescription: "Create a tag from the selected revision or current branch.",
+ mergeBranchDescription: "Merge branch {name} into the active branch.",
+ deleteBranchDescription: "Delete branch {name}. This operation cannot be undone.",
+ deleteTagDescription: "Delete tag {name}. This operation cannot be undone.",
+ branchName: "Branch name",
+ branchNamePlaceholder: "feature/my-branch",
+ tagName: "Tag name",
+ tagNamePlaceholder: "v1.0.0",
+ branchSource: "Source revision: {revision}",
+ branchNameRequired: "Enter a branch name.",
+ tagNameRequired: "Enter a tag name.",
+ branchCreated: "Branch {name} created",
+ branchMerged: "Branch {name} merged",
+ branchDeleted: "Branch {name} deleted",
+ tagCreated: "Tag {name} created",
+ tagDeleted: "Tag {name} deleted",
+ copyHash: "Copy commit hash",
+ revertCommit: "Revert this commit",
+ hardResetToCommit: "Hard reset current branch to this commit",
+ revertCommitTitle: "Revert commit",
+ hardResetTitle: "Hard reset current branch",
+ revertCommitDescription: "Create a new commit that reverses the changes introduced by commit {hash}.",
+ hardResetDescription: "Hard reset branch {branch} to commit {hash}. Commits after it and all staged or unstaged working tree changes will be removed from the current state.",
+ highRiskConfirmation: "This is a high-risk operation. Confirm the target commit before continuing.",
+ revertCommitComplete: "Reverted commit {hash}",
+ hardResetComplete: "Current branch hard-reset to {hash}",
+ discardWorkingTree: "Discard working tree changes",
+ discardWorkingTreeDescription: "Discard all staged and unstaged working tree changes. This cannot be undone.",
+ discardWorkingTreeComplete: "Working tree changes discarded",
+ sqlPreview: "SQL preview",
+ hashCopied: "Commit hash copied",
+ copyCurrentValue: "Copy current value",
+ copyBeforeValue: "Copy before value",
+ copyAfterValue: "Copy after value",
+ cellValueCopied: "Cell value copied",
+ viewCellDiff: "View difference details",
+ cellDiffTitle: "{table}.{column} difference",
+ cellDiffFormat: "Comparison format",
+ cellDiffFormatAuto: "Auto",
+ cellDiffFormatRaw: "Raw",
+ cellDiffDetectedFormat: "Detected: {format}",
+ cellDiffFormatFailed: "Formatting failed; showing raw value: {message}",
+ cellNullValue: "NULL",
+ cellRowMissing: "Row does not exist",
+ cellColumnMissing: "Column does not exist",
+ },
};
diff --git a/apps/desktop/src/i18n/locales/es.ts b/apps/desktop/src/i18n/locales/es.ts
index 90c3089a79..1c0e0ef57c 100644
--- a/apps/desktop/src/i18n/locales/es.ts
+++ b/apps/desktop/src/i18n/locales/es.ts
@@ -7942,4 +7942,104 @@ export default withEnglishFallback({
fieldContextCode: "Context code",
rawPayload: "Traza en bruto",
},
+ doltVersionControl: {
+ title: "Control de versiones de Dolt",
+ open: "Control de versiones",
+ branches: "Ramas",
+ branchTreeView: "Vista de árbol",
+ branchFlatView: "Vista plana",
+ expandBranch: "Expandir grupo de ramas",
+ collapseBranch: "Contraer grupo de ramas",
+ tags: "Etiquetas",
+ filterRefs: "Filtrar ramas y etiquetas",
+ noBranches: "No hay ramas",
+ noTags: "No hay etiquetas",
+ unknownBranch: "Rama desconocida",
+ switchDatabase: "Cambiar base de datos",
+ switchBranch: "Cambiar rama",
+ workingTree: "Árbol de trabajo",
+ stagedChanges: "Preparados {count}",
+ unstagedChanges: "Sin preparar {count}",
+ uncommitted: "Sin confirmar",
+ stageAllChanges: "Preparar todos los cambios",
+ commitWorkingTree: "Confirmar árbol de trabajo",
+ commitWorkingTreeDescription: "Escribe un mensaje para preparar y confirmar los cambios del árbol de trabajo.",
+ commitMessage: "Mensaje de confirmación",
+ commitMessagePlaceholder: "Por ejemplo: Corregir estado del pedido",
+ commitMessageRequired: "Escribe un mensaje de confirmación.",
+ changesStaged: "Cambios del árbol preparados",
+ workingTreeCommitted: "Cambios del árbol confirmados",
+ comparison: "Comparación actual",
+ swapComparison: "Intercambiar lados de comparación",
+ noRevision: "Sin revisión",
+ compareCurrent: "Comparar con la rama actual",
+ checkoutBranch: "Cambiar a la rama",
+ branchCheckedOut: "Cambiado a la rama {name}",
+ graph: "Grafo",
+ commit: "Commit",
+ author: "Autor",
+ date: "Fecha",
+ loadingGraph: "Cargando grafo de commits...",
+ noCommits: "No se encontraron commits",
+ noMessage: "Sin mensaje de commit",
+ changedTables: "Tablas modificadas",
+ loadingDiff: "Cargando diferencias de revisión...",
+ noChanges: "No se encontraron cambios entre estas revisiones.",
+ rowDiff: "Diferencias de filas",
+ rows: "{count} filas",
+ loadingRows: "Cargando diferencias de filas...",
+ selectTable: "Selecciona una tabla modificada",
+ noRowChanges: "No se devolvieron cambios de filas; el cambio puede ser solo de esquema.",
+ createBranch: "Crear rama",
+ createTag: "Crear etiqueta",
+ mergeBranch: "Fusionar rama",
+ deleteBranch: "Eliminar rama",
+ deleteTag: "Eliminar etiqueta",
+ createBranchDescription: "Crea una rama desde la revisión o rama actual seleccionada.",
+ createTagDescription: "Crea una etiqueta desde la revisión o rama actual seleccionada.",
+ mergeBranchDescription: "Fusionar la rama {name} en la rama activa.",
+ deleteBranchDescription: "Eliminar la rama {name}. Esta operación no se puede deshacer.",
+ deleteTagDescription: "Eliminar la etiqueta {name}. Esta operación no se puede deshacer.",
+ branchName: "Nombre de la rama",
+ branchNamePlaceholder: "feature/my-branch",
+ tagName: "Nombre de la etiqueta",
+ tagNamePlaceholder: "v1.0.0",
+ branchSource: "Revisión de origen: {revision}",
+ branchNameRequired: "Introduce un nombre de rama.",
+ tagNameRequired: "Introduce un nombre de etiqueta.",
+ branchCreated: "Rama {name} creada",
+ branchMerged: "Rama {name} fusionada",
+ branchDeleted: "Rama {name} eliminada",
+ tagCreated: "Etiqueta {name} creada",
+ tagDeleted: "Etiqueta {name} eliminada",
+ copyHash: "Copiar hash del commit",
+ revertCommit: "Revertir este commit",
+ hardResetToCommit: "Restablecer forzosamente la rama actual a este commit",
+ revertCommitTitle: "Revertir commit",
+ hardResetTitle: "Restablecer rama actual",
+ revertCommitDescription: "Crea un nuevo commit que revierte los cambios introducidos por {hash}.",
+ hardResetDescription: "Restablece forzosamente la rama {branch} al commit {hash}. Se quitarán del estado actual los commits posteriores y los cambios preparados o sin preparar.",
+ highRiskConfirmation: "Esta es una operación de alto riesgo. Confirma el commit de destino antes de continuar.",
+ revertCommitComplete: "Commit {hash} revertido",
+ hardResetComplete: "Rama actual restablecida a {hash}",
+ discardWorkingTree: "Descartar cambios del área de trabajo",
+ discardWorkingTreeDescription: "Descarta todos los cambios preparados y no preparados. Esta acción no se puede deshacer.",
+ discardWorkingTreeComplete: "Cambios del área de trabajo descartados",
+ sqlPreview: "Vista previa de SQL",
+ hashCopied: "Hash del commit copiado",
+ copyCurrentValue: "Copiar valor actual",
+ copyBeforeValue: "Copiar valor anterior",
+ copyAfterValue: "Copiar valor posterior",
+ cellValueCopied: "Valor de celda copiado",
+ viewCellDiff: "Ver detalles de diferencias",
+ cellDiffTitle: "Diferencia de {table}.{column}",
+ cellDiffFormat: "Formato de comparación",
+ cellDiffFormatAuto: "Automático",
+ cellDiffFormatRaw: "Original",
+ cellDiffDetectedFormat: "Detectado: {format}",
+ cellDiffFormatFailed: "No se pudo formatear; se muestra el valor original: {message}",
+ cellNullValue: "NULL",
+ cellRowMissing: "La fila no existe",
+ cellColumnMissing: "La columna no existe",
+ },
});
diff --git a/apps/desktop/src/i18n/locales/it.ts b/apps/desktop/src/i18n/locales/it.ts
index b65020609a..b8b6105e4e 100644
--- a/apps/desktop/src/i18n/locales/it.ts
+++ b/apps/desktop/src/i18n/locales/it.ts
@@ -7942,4 +7942,104 @@ export default withEnglishFallback({
fieldContextCode: "Context code",
rawPayload: "Traccia grezza",
},
+ doltVersionControl: {
+ title: "Controllo versione Dolt",
+ open: "Controllo versione",
+ branches: "Branch",
+ branchTreeView: "Vista ad albero",
+ branchFlatView: "Vista piatta",
+ expandBranch: "Espandi gruppo di branch",
+ collapseBranch: "Comprimi gruppo di branch",
+ tags: "Tag",
+ filterRefs: "Filtra branch e tag",
+ noBranches: "Nessun branch",
+ noTags: "Nessun tag",
+ unknownBranch: "Branch sconosciuto",
+ switchDatabase: "Cambia database",
+ switchBranch: "Cambia branch",
+ workingTree: "Albero di lavoro",
+ stagedChanges: "In staging {count}",
+ unstagedChanges: "Non in staging {count}",
+ uncommitted: "Non commit",
+ stageAllChanges: "Metti in staging tutte le modifiche",
+ commitWorkingTree: "Esegui commit dell'albero di lavoro",
+ commitWorkingTreeDescription: "Inserisci un messaggio per mettere in staging ed eseguire il commit delle modifiche.",
+ commitMessage: "Messaggio di commit",
+ commitMessagePlaceholder: "Ad esempio: Correggi stato ordine",
+ commitMessageRequired: "Inserisci un messaggio di commit.",
+ changesStaged: "Modifiche messe in staging",
+ workingTreeCommitted: "Modifiche dell'albero di lavoro committate",
+ comparison: "Confronto corrente",
+ swapComparison: "Scambia i lati del confronto",
+ noRevision: "Nessuna revisione",
+ compareCurrent: "Confronta con il branch corrente",
+ checkoutBranch: "Passa al branch",
+ branchCheckedOut: "Passato al branch {name}",
+ graph: "Grafo",
+ commit: "Commit",
+ author: "Autore",
+ date: "Data",
+ loadingGraph: "Caricamento del grafo dei commit...",
+ noCommits: "Nessun commit trovato",
+ noMessage: "Nessun messaggio di commit",
+ changedTables: "Tabelle modificate",
+ loadingDiff: "Caricamento delle differenze...",
+ noChanges: "Nessuna modifica tra queste revisioni.",
+ rowDiff: "Differenze di riga",
+ rows: "{count} righe",
+ loadingRows: "Caricamento delle differenze di riga...",
+ selectTable: "Seleziona una tabella modificata",
+ noRowChanges: "Nessuna modifica di riga; la modifica potrebbe riguardare solo lo schema.",
+ createBranch: "Crea branch",
+ createTag: "Crea tag",
+ mergeBranch: "Unisci branch",
+ deleteBranch: "Elimina branch",
+ deleteTag: "Elimina tag",
+ createBranchDescription: "Crea un branch dalla revisione o dal branch corrente selezionato.",
+ createTagDescription: "Crea un tag dalla revisione o dal branch corrente selezionato.",
+ mergeBranchDescription: "Unisci il branch {name} nel branch attivo.",
+ deleteBranchDescription: "Elimina il branch {name}. Questa operazione non può essere annullata.",
+ deleteTagDescription: "Elimina il tag {name}. Questa operazione non può essere annullata.",
+ branchName: "Nome del branch",
+ branchNamePlaceholder: "feature/my-branch",
+ tagName: "Nome del tag",
+ tagNamePlaceholder: "v1.0.0",
+ branchSource: "Revisione origine: {revision}",
+ branchNameRequired: "Inserisci un nome per il branch.",
+ tagNameRequired: "Inserisci un nome per il tag.",
+ branchCreated: "Branch {name} creato",
+ branchMerged: "Branch {name} unito",
+ branchDeleted: "Branch {name} eliminato",
+ tagCreated: "Tag {name} creato",
+ tagDeleted: "Tag {name} eliminato",
+ copyHash: "Copia hash del commit",
+ revertCommit: "Ripristina questo commit",
+ hardResetToCommit: "Reimposta forzatamente il branch corrente a questo commit",
+ revertCommitTitle: "Ripristina commit",
+ hardResetTitle: "Reimposta il branch corrente",
+ revertCommitDescription: "Crea un nuovo commit che annulla le modifiche introdotte dal commit {hash}.",
+ hardResetDescription: "Reimposta forzatamente il branch {branch} al commit {hash}. I commit successivi e le modifiche in staging o non in staging saranno rimossi dallo stato corrente.",
+ highRiskConfirmation: "Questa è un'operazione ad alto rischio. Conferma il commit di destinazione prima di continuare.",
+ revertCommitComplete: "Commit {hash} ripristinato",
+ hardResetComplete: "Branch corrente reimpostato a {hash}",
+ discardWorkingTree: "Scarta modifiche dell'area di lavoro",
+ discardWorkingTreeDescription: "Scarta tutte le modifiche in staging e non in staging. L'operazione non è reversibile.",
+ discardWorkingTreeComplete: "Modifiche dell'area di lavoro scartate",
+ sqlPreview: "Anteprima SQL",
+ hashCopied: "Hash del commit copiato",
+ copyCurrentValue: "Copia valore corrente",
+ copyBeforeValue: "Copia valore precedente",
+ copyAfterValue: "Copia valore successivo",
+ cellValueCopied: "Valore della cella copiato",
+ viewCellDiff: "Visualizza dettagli differenze",
+ cellDiffTitle: "Differenza di {table}.{column}",
+ cellDiffFormat: "Formato di confronto",
+ cellDiffFormatAuto: "Automatico",
+ cellDiffFormatRaw: "Originale",
+ cellDiffDetectedFormat: "Rilevato: {format}",
+ cellDiffFormatFailed: "Formattazione non riuscita; viene mostrato il valore originale: {message}",
+ cellNullValue: "NULL",
+ cellRowMissing: "La riga non esiste",
+ cellColumnMissing: "La colonna non esiste",
+ },
});
diff --git a/apps/desktop/src/i18n/locales/ja.ts b/apps/desktop/src/i18n/locales/ja.ts
index ccfac6bf93..d0d7bb877d 100644
--- a/apps/desktop/src/i18n/locales/ja.ts
+++ b/apps/desktop/src/i18n/locales/ja.ts
@@ -7995,4 +7995,104 @@ export default withEnglishFallback({
fieldContextCode: "Context Code",
rawPayload: "生トレース",
},
+ doltVersionControl: {
+ title: "Dolt バージョン管理",
+ open: "バージョン管理",
+ branches: "ブランチ",
+ branchTreeView: "ツリービュー",
+ branchFlatView: "フラットビュー",
+ expandBranch: "ブランチグループを展開",
+ collapseBranch: "ブランチグループを折りたたむ",
+ tags: "タグ",
+ filterRefs: "ブランチとタグを絞り込む",
+ noBranches: "ブランチなし",
+ noTags: "タグなし",
+ unknownBranch: "不明なブランチ",
+ switchDatabase: "データベースを切り替え",
+ switchBranch: "ブランチを切り替え",
+ workingTree: "作業ツリー",
+ stagedChanges: "ステージ済み {count}",
+ unstagedChanges: "未ステージ {count}",
+ uncommitted: "未コミット",
+ stageAllChanges: "すべての変更をステージ",
+ commitWorkingTree: "作業ツリーをコミット",
+ commitWorkingTreeDescription: "コミットメッセージを入力すると、作業ツリーの変更をステージしてコミットします。",
+ commitMessage: "コミットメッセージ",
+ commitMessagePlaceholder: "例:注文ステータスを修正",
+ commitMessageRequired: "コミットメッセージを入力してください。",
+ changesStaged: "作業ツリーの変更をステージしました",
+ workingTreeCommitted: "作業ツリーの変更をコミットしました",
+ comparison: "現在の比較",
+ swapComparison: "比較対象を入れ替え",
+ noRevision: "リビジョンなし",
+ compareCurrent: "現在のブランチと比較",
+ checkoutBranch: "ブランチを切り替え",
+ branchCheckedOut: "ブランチ {name} に切り替えました",
+ graph: "グラフ",
+ commit: "コミット",
+ author: "作成者",
+ date: "日時",
+ loadingGraph: "コミットグラフを読み込み中...",
+ noCommits: "コミットがありません",
+ noMessage: "コミットメッセージなし",
+ changedTables: "変更されたテーブル",
+ loadingDiff: "リビジョン差分を読み込み中...",
+ noChanges: "これらのリビジョン間にテーブル変更はありません。",
+ rowDiff: "行の差分",
+ rows: "{count} 行",
+ loadingRows: "行の差分を読み込み中...",
+ selectTable: "変更されたテーブルを選択",
+ noRowChanges: "行の変更はありません。スキーマのみの変更の可能性があります。",
+ createBranch: "ブランチを作成",
+ createTag: "タグを作成",
+ mergeBranch: "ブランチをマージ",
+ deleteBranch: "ブランチを削除",
+ deleteTag: "タグを削除",
+ createBranchDescription: "選択したリビジョンまたは現在のブランチからブランチを作成します。",
+ createTagDescription: "選択したリビジョンまたは現在のブランチからタグを作成します。",
+ mergeBranchDescription: "ブランチ {name} をアクティブなブランチへマージします。",
+ deleteBranchDescription: "ブランチ {name} を削除します。この操作は元に戻せません。",
+ deleteTagDescription: "タグ {name} を削除します。この操作は元に戻せません。",
+ branchName: "ブランチ名",
+ branchNamePlaceholder: "feature/my-branch",
+ tagName: "タグ名",
+ tagNamePlaceholder: "v1.0.0",
+ branchSource: "ソースリビジョン: {revision}",
+ branchNameRequired: "ブランチ名を入力してください。",
+ tagNameRequired: "タグ名を入力してください。",
+ branchCreated: "ブランチ {name} を作成しました",
+ branchMerged: "ブランチ {name} をマージしました",
+ branchDeleted: "ブランチ {name} を削除しました",
+ tagCreated: "タグ {name} を作成しました",
+ tagDeleted: "タグ {name} を削除しました",
+ copyHash: "コミットハッシュをコピー",
+ revertCommit: "このコミットをリバート",
+ hardResetToCommit: "現在のブランチをこのコミットへハードリセット",
+ revertCommitTitle: "コミットをリバート",
+ hardResetTitle: "現在のブランチをハードリセット",
+ revertCommitDescription: "コミット {hash} の変更を打ち消す新しいコミットを作成します。",
+ hardResetDescription: "ブランチ {branch} をコミット {hash} にハードリセットし、それ以降のコミットと作業ツリーのステージ済み・未ステージ変更を現在の状態から削除します。",
+ highRiskConfirmation: "これは高リスク操作です。対象コミットを確認して続行してください。",
+ revertCommitComplete: "コミット {hash} をリバートしました",
+ hardResetComplete: "現在のブランチを {hash} にハードリセットしました",
+ discardWorkingTree: "作業ツリーの変更を破棄",
+ discardWorkingTreeDescription: "ステージ済みと未ステージの作業ツリー変更をすべて破棄します。この操作は元に戻せません。",
+ discardWorkingTreeComplete: "作業ツリーの変更を破棄しました",
+ sqlPreview: "SQL プレビュー",
+ hashCopied: "コミットハッシュをコピーしました",
+ copyCurrentValue: "現在の値をコピー",
+ copyBeforeValue: "変更前の値をコピー",
+ copyAfterValue: "変更後の値をコピー",
+ cellValueCopied: "セルの値をコピーしました",
+ viewCellDiff: "差分の詳細を表示",
+ cellDiffTitle: "{table}.{column} の差分",
+ cellDiffFormat: "比較形式",
+ cellDiffFormatAuto: "自動",
+ cellDiffFormatRaw: "元の値",
+ cellDiffDetectedFormat: "検出結果: {format}",
+ cellDiffFormatFailed: "フォーマットに失敗したため、元の値を表示します: {message}",
+ cellNullValue: "NULL",
+ cellRowMissing: "行が存在しません",
+ cellColumnMissing: "列が存在しません",
+ },
});
diff --git a/apps/desktop/src/i18n/locales/ko.ts b/apps/desktop/src/i18n/locales/ko.ts
index 032634b054..2464dbaaea 100644
--- a/apps/desktop/src/i18n/locales/ko.ts
+++ b/apps/desktop/src/i18n/locales/ko.ts
@@ -7441,4 +7441,104 @@ export default withEnglishFallback({
registerInstance: "인스턴스 등록",
deregister: "등록 해제",
},
+ doltVersionControl: {
+ title: "Dolt 버전 관리",
+ open: "버전 관리",
+ branches: "브랜치",
+ branchTreeView: "트리 보기",
+ branchFlatView: "목록 보기",
+ expandBranch: "브랜치 그룹 펼치기",
+ collapseBranch: "브랜치 그룹 접기",
+ tags: "태그",
+ filterRefs: "브랜치 및 태그 필터",
+ noBranches: "브랜치 없음",
+ noTags: "태그 없음",
+ unknownBranch: "알 수 없는 브랜치",
+ switchDatabase: "데이터베이스 전환",
+ switchBranch: "브랜치 전환",
+ workingTree: "작업 트리",
+ stagedChanges: "스테이징됨 {count}",
+ unstagedChanges: "스테이징 안 됨 {count}",
+ uncommitted: "커밋되지 않음",
+ stageAllChanges: "모든 변경 사항 스테이징",
+ commitWorkingTree: "작업 트리 커밋",
+ commitWorkingTreeDescription: "커밋 메시지를 입력하면 작업 트리 변경 사항을 스테이징하고 커밋합니다.",
+ commitMessage: "커밋 메시지",
+ commitMessagePlaceholder: "예: 주문 상태 수정",
+ commitMessageRequired: "커밋 메시지를 입력하세요.",
+ changesStaged: "작업 트리 변경 사항을 스테이징했습니다",
+ workingTreeCommitted: "작업 트리 변경 사항을 커밋했습니다",
+ comparison: "현재 비교",
+ swapComparison: "비교 대상 바꾸기",
+ noRevision: "리비전 없음",
+ compareCurrent: "현재 브랜치와 비교",
+ checkoutBranch: "브랜치로 전환",
+ branchCheckedOut: "브랜치 {name}(으)로 전환됨",
+ graph: "그래프",
+ commit: "커밋",
+ author: "작성자",
+ date: "날짜",
+ loadingGraph: "커밋 그래프를 불러오는 중...",
+ noCommits: "커밋 없음",
+ noMessage: "커밋 메시지 없음",
+ changedTables: "변경된 테이블",
+ loadingDiff: "리비전 차이를 불러오는 중...",
+ noChanges: "두 리비전 사이에 테이블 변경이 없습니다.",
+ rowDiff: "행 차이",
+ rows: "{count}개 행",
+ loadingRows: "행 차이를 불러오는 중...",
+ selectTable: "변경된 테이블을 선택하세요",
+ noRowChanges: "행 변경이 없습니다. 스키마만 변경되었을 수 있습니다.",
+ createBranch: "브랜치 생성",
+ createTag: "태그 생성",
+ mergeBranch: "브랜치 병합",
+ deleteBranch: "브랜치 삭제",
+ deleteTag: "태그 삭제",
+ createBranchDescription: "선택한 리비전 또는 현재 브랜치에서 새 브랜치를 생성합니다.",
+ createTagDescription: "선택한 리비전 또는 현재 브랜치에서 태그를 생성합니다.",
+ mergeBranchDescription: "브랜치 {name}을(를) 활성 브랜치에 병합합니다.",
+ deleteBranchDescription: "브랜치 {name}을(를) 삭제합니다. 이 작업은 취소할 수 없습니다.",
+ deleteTagDescription: "태그 {name}을(를) 삭제합니다. 이 작업은 취소할 수 없습니다.",
+ branchName: "브랜치 이름",
+ branchNamePlaceholder: "feature/my-branch",
+ tagName: "태그 이름",
+ tagNamePlaceholder: "v1.0.0",
+ branchSource: "소스 리비전: {revision}",
+ branchNameRequired: "브랜치 이름을 입력하세요.",
+ tagNameRequired: "태그 이름을 입력하세요.",
+ branchCreated: "브랜치 {name} 생성됨",
+ branchMerged: "브랜치 {name} 병합됨",
+ branchDeleted: "브랜치 {name} 삭제됨",
+ tagCreated: "태그 {name} 생성됨",
+ tagDeleted: "태그 {name} 삭제됨",
+ copyHash: "커밋 해시 복사",
+ revertCommit: "이 커밋 되돌리기",
+ hardResetToCommit: "현재 브랜치를 이 커밋으로 하드 리셋",
+ revertCommitTitle: "커밋 되돌리기",
+ hardResetTitle: "현재 브랜치 하드 리셋",
+ revertCommitDescription: "커밋 {hash}의 변경 사항을 되돌리는 새 커밋을 생성합니다.",
+ hardResetDescription: "브랜치 {branch}를 커밋 {hash}로 하드 리셋합니다. 이후 커밋과 스테이징 및 미스테이징 작업 트리 변경 사항이 현재 상태에서 제거됩니다.",
+ highRiskConfirmation: "고위험 작업입니다. 계속하기 전에 대상 커밋을 확인하세요.",
+ revertCommitComplete: "커밋 {hash}을(를) 되돌렸습니다",
+ hardResetComplete: "현재 브랜치를 {hash}(으)로 하드 리셋했습니다",
+ discardWorkingTree: "작업 트리 변경 사항 폐기",
+ discardWorkingTreeDescription: "스테이징 및 스테이징되지 않은 작업 트리 변경 사항을 모두 폐기합니다. 되돌릴 수 없습니다.",
+ discardWorkingTreeComplete: "작업 트리 변경 사항을 폐기했습니다",
+ sqlPreview: "SQL 미리보기",
+ hashCopied: "커밋 해시가 복사됨",
+ copyCurrentValue: "현재 값 복사",
+ copyBeforeValue: "변경 전 값 복사",
+ copyAfterValue: "변경 후 값 복사",
+ cellValueCopied: "셀 값을 복사했습니다",
+ viewCellDiff: "차이점 세부 정보 보기",
+ cellDiffTitle: "{table}.{column} 차이점",
+ cellDiffFormat: "비교 형식",
+ cellDiffFormatAuto: "자동",
+ cellDiffFormatRaw: "원본",
+ cellDiffDetectedFormat: "감지됨: {format}",
+ cellDiffFormatFailed: "형식을 지정하지 못해 원본 값을 표시합니다: {message}",
+ cellNullValue: "NULL",
+ cellRowMissing: "행이 존재하지 않습니다",
+ cellColumnMissing: "열이 존재하지 않습니다",
+ },
});
diff --git a/apps/desktop/src/i18n/locales/pt-BR.ts b/apps/desktop/src/i18n/locales/pt-BR.ts
index 7e15fd0e15..e7de4b8908 100644
--- a/apps/desktop/src/i18n/locales/pt-BR.ts
+++ b/apps/desktop/src/i18n/locales/pt-BR.ts
@@ -7944,4 +7944,104 @@ export default withEnglishFallback({
fieldContextCode: "Context code",
rawPayload: "Rastreamento bruto",
},
+ doltVersionControl: {
+ title: "Controle de versão do Dolt",
+ open: "Controle de versão",
+ branches: "Branches",
+ branchTreeView: "Visualização em árvore",
+ branchFlatView: "Visualização em lista",
+ expandBranch: "Expandir grupo de branches",
+ collapseBranch: "Recolher grupo de branches",
+ tags: "Tags",
+ filterRefs: "Filtrar branches e tags",
+ noBranches: "Nenhum branch",
+ noTags: "Nenhuma tag",
+ unknownBranch: "Branch desconhecido",
+ switchDatabase: "Trocar banco de dados",
+ switchBranch: "Trocar branch",
+ workingTree: "Árvore de trabalho",
+ stagedChanges: "Preparadas {count}",
+ unstagedChanges: "Não preparadas {count}",
+ uncommitted: "Não confirmado",
+ stageAllChanges: "Preparar todas as alterações",
+ commitWorkingTree: "Fazer commit da árvore de trabalho",
+ commitWorkingTreeDescription: "Insira uma mensagem para preparar e fazer commit das alterações da árvore de trabalho.",
+ commitMessage: "Mensagem de commit",
+ commitMessagePlaceholder: "Por exemplo: Corrigir status do pedido",
+ commitMessageRequired: "Insira uma mensagem de commit.",
+ changesStaged: "Alterações da árvore preparadas",
+ workingTreeCommitted: "Alterações da árvore confirmadas",
+ comparison: "Comparação atual",
+ swapComparison: "Trocar lados da comparação",
+ noRevision: "Nenhuma revisão",
+ compareCurrent: "Comparar com o branch atual",
+ checkoutBranch: "Mudar para o branch",
+ branchCheckedOut: "Mudou para o branch {name}",
+ graph: "Grafo",
+ commit: "Commit",
+ author: "Autor",
+ date: "Data",
+ loadingGraph: "Carregando grafo de commits...",
+ noCommits: "Nenhum commit encontrado",
+ noMessage: "Sem mensagem de commit",
+ changedTables: "Tabelas alteradas",
+ loadingDiff: "Carregando diferenças de revisão...",
+ noChanges: "Nenhuma alteração de tabela entre essas revisões.",
+ rowDiff: "Diferenças de linhas",
+ rows: "{count} linhas",
+ loadingRows: "Carregando diferenças de linhas...",
+ selectTable: "Selecione uma tabela alterada",
+ noRowChanges: "Nenhuma alteração de linha foi retornada; a mudança pode ser apenas de esquema.",
+ createBranch: "Criar branch",
+ createTag: "Criar tag",
+ mergeBranch: "Mesclar branch",
+ deleteBranch: "Excluir branch",
+ deleteTag: "Excluir tag",
+ createBranchDescription: "Crie um branch a partir da revisão ou do branch atual selecionado.",
+ createTagDescription: "Crie uma tag a partir da revisão ou do branch atual selecionado.",
+ mergeBranchDescription: "Mesclar o branch {name} no branch ativo.",
+ deleteBranchDescription: "Excluir o branch {name}. Esta operação não pode ser desfeita.",
+ deleteTagDescription: "Excluir a tag {name}. Esta operação não pode ser desfeita.",
+ branchName: "Nome do branch",
+ branchNamePlaceholder: "feature/my-branch",
+ tagName: "Nome da tag",
+ tagNamePlaceholder: "v1.0.0",
+ branchSource: "Revisão de origem: {revision}",
+ branchNameRequired: "Digite um nome de branch.",
+ tagNameRequired: "Digite um nome de tag.",
+ branchCreated: "Branch {name} criado",
+ branchMerged: "Branch {name} mesclado",
+ branchDeleted: "Branch {name} excluído",
+ tagCreated: "Tag {name} criada",
+ tagDeleted: "Tag {name} excluída",
+ copyHash: "Copiar hash do commit",
+ revertCommit: "Reverter este commit",
+ hardResetToCommit: "Redefinir forçadamente o branch atual para este commit",
+ revertCommitTitle: "Reverter commit",
+ hardResetTitle: "Redefinir branch atual",
+ revertCommitDescription: "Cria um novo commit que reverte as alterações introduzidas por {hash}.",
+ hardResetDescription: "Redefine forçadamente o branch {branch} para o commit {hash}. Commits posteriores e alterações preparadas ou não preparadas serão removidos do estado atual.",
+ highRiskConfirmation: "Esta é uma operação de alto risco. Confirme o commit de destino antes de continuar.",
+ revertCommitComplete: "Commit {hash} revertido",
+ hardResetComplete: "Branch atual redefinido para {hash}",
+ discardWorkingTree: "Descartar alterações da árvore de trabalho",
+ discardWorkingTreeDescription: "Descarta todas as alterações preparadas e não preparadas. Esta ação não pode ser desfeita.",
+ discardWorkingTreeComplete: "Alterações da árvore de trabalho descartadas",
+ sqlPreview: "Visualização do SQL",
+ hashCopied: "Hash do commit copiado",
+ copyCurrentValue: "Copiar valor atual",
+ copyBeforeValue: "Copiar valor anterior",
+ copyAfterValue: "Copiar valor posterior",
+ cellValueCopied: "Valor da célula copiado",
+ viewCellDiff: "Ver detalhes das diferenças",
+ cellDiffTitle: "Diferença de {table}.{column}",
+ cellDiffFormat: "Formato de comparação",
+ cellDiffFormatAuto: "Automático",
+ cellDiffFormatRaw: "Original",
+ cellDiffDetectedFormat: "Detectado: {format}",
+ cellDiffFormatFailed: "Falha ao formatar; exibindo o valor original: {message}",
+ cellNullValue: "NULL",
+ cellRowMissing: "A linha não existe",
+ cellColumnMissing: "A coluna não existe",
+ },
});
diff --git a/apps/desktop/src/i18n/locales/zh-CN.ts b/apps/desktop/src/i18n/locales/zh-CN.ts
index 71ab057f77..2b4582e1ae 100644
--- a/apps/desktop/src/i18n/locales/zh-CN.ts
+++ b/apps/desktop/src/i18n/locales/zh-CN.ts
@@ -8145,4 +8145,104 @@ export default withEnglishFallback({
registerInstance: "注册实例",
deregister: "注销",
},
+ doltVersionControl: {
+ title: "Dolt 版本控制",
+ open: "版本控制",
+ branches: "分支",
+ branchTreeView: "树状视图",
+ branchFlatView: "平铺视图",
+ expandBranch: "展开分支组",
+ collapseBranch: "收起分支组",
+ tags: "标签",
+ filterRefs: "筛选分支和标签",
+ noBranches: "暂无分支",
+ noTags: "暂无标签",
+ unknownBranch: "未知分支",
+ switchDatabase: "切换数据库",
+ switchBranch: "切换分支",
+ workingTree: "工作区",
+ stagedChanges: "已暂存 {count}",
+ unstagedChanges: "未暂存 {count}",
+ uncommitted: "未提交",
+ stageAllChanges: "暂存所有变更",
+ commitWorkingTree: "提交工作区",
+ commitWorkingTreeDescription: "输入提交消息后,将工作区变更暂存并提交。",
+ commitMessage: "提交消息",
+ commitMessagePlaceholder: "例如:修复订单状态",
+ commitMessageRequired: "请输入提交消息。",
+ changesStaged: "工作区变更已暂存",
+ workingTreeCommitted: "工作区变更已提交",
+ comparison: "当前对比",
+ swapComparison: "交换对比双方",
+ noRevision: "未选择 Revision",
+ compareCurrent: "与当前分支对比",
+ checkoutBranch: "切换到分支",
+ branchCheckedOut: "已切换到分支 {name}",
+ graph: "提交图",
+ commit: "提交",
+ author: "作者",
+ date: "日期",
+ loadingGraph: "正在加载提交图...",
+ noCommits: "暂无提交记录",
+ noMessage: "无提交信息",
+ changedTables: "变更的表",
+ loadingDiff: "正在加载版本差异...",
+ noChanges: "两个 Revision 之间没有表变更。",
+ rowDiff: "行级差异",
+ rows: "{count} 行",
+ loadingRows: "正在加载行级差异...",
+ selectTable: "选择一个发生变更的表",
+ noRowChanges: "未返回行级差异,本次变更可能仅涉及表结构。",
+ createBranch: "创建分支",
+ createTag: "创建标签",
+ mergeBranch: "合并分支",
+ deleteBranch: "删除分支",
+ deleteTag: "删除标签",
+ createBranchDescription: "从当前选中的 Revision 或当前分支创建新分支。",
+ createTagDescription: "从当前选中的 Revision 或当前分支创建标签。",
+ mergeBranchDescription: "将分支 {name} 合并到当前活动分支。",
+ deleteBranchDescription: "删除分支 {name},此操作无法撤销。",
+ deleteTagDescription: "删除标签 {name},此操作无法撤销。",
+ branchName: "分支名称",
+ branchNamePlaceholder: "feature/my-branch",
+ tagName: "标签名称",
+ tagNamePlaceholder: "v1.0.0",
+ branchSource: "来源 Revision:{revision}",
+ branchNameRequired: "请输入分支名称。",
+ tagNameRequired: "请输入标签名称。",
+ branchCreated: "分支 {name} 已创建",
+ branchMerged: "分支 {name} 已合并",
+ branchDeleted: "分支 {name} 已删除",
+ tagCreated: "标签 {name} 已创建",
+ tagDeleted: "标签 {name} 已删除",
+ copyHash: "复制提交哈希",
+ revertCommit: "回退提交",
+ hardResetToCommit: "硬重置到此处",
+ revertCommitTitle: "回退提交",
+ hardResetTitle: "硬重置分支",
+ revertCommitDescription: "将创建一个新提交,反向应用提交 {hash} 的变更。",
+ hardResetDescription: "将当前分支 {branch} 硬重置到提交 {hash},使后续提交脱离当前分支,并丢弃所有暂存和未暂存变更。",
+ highRiskConfirmation: "这是高风险操作,请确认目标提交无误后继续。",
+ revertCommitComplete: "已回退提交 {hash}",
+ hardResetComplete: "当前分支已硬重置到 {hash}",
+ discardWorkingTree: "撤销工作区修改",
+ discardWorkingTreeDescription: "丢弃所有已暂存和未暂存的工作区修改,此操作无法撤销。",
+ discardWorkingTreeComplete: "工作区修改已撤销",
+ sqlPreview: "SQL 预览",
+ hashCopied: "提交哈希已复制",
+ copyCurrentValue: "复制当前值",
+ copyBeforeValue: "复制修改前值",
+ copyAfterValue: "复制修改后值",
+ cellValueCopied: "单元格值已复制",
+ viewCellDiff: "查看差异详情",
+ cellDiffTitle: "{table}.{column} 差异",
+ cellDiffFormat: "对比格式",
+ cellDiffFormatAuto: "自动",
+ cellDiffFormatRaw: "原始",
+ cellDiffDetectedFormat: "已识别:{format}",
+ cellDiffFormatFailed: "格式化失败,已显示原始值:{message}",
+ cellNullValue: "NULL",
+ cellRowMissing: "该行不存在",
+ cellColumnMissing: "该列不存在",
+ },
});
diff --git a/apps/desktop/src/i18n/locales/zh-TW.ts b/apps/desktop/src/i18n/locales/zh-TW.ts
index de8daf1756..806b76ce79 100644
--- a/apps/desktop/src/i18n/locales/zh-TW.ts
+++ b/apps/desktop/src/i18n/locales/zh-TW.ts
@@ -7934,4 +7934,104 @@ export default withEnglishFallback({
rawPayload: "原始軌跡",
traceTopicRouteMissing: "軌跡 Topic 在 NameServer 上沒有路由資訊(CODE: 17)。\n\n常見原因:\n1. Broker 未開啟消息軌跡:在 broker.conf 中設置 traceTopicEnable=true 並重新啟動 Broker\n2. Producer/Consumer 未開啟軌跡:setEnableTrace(true)\n3. 使用了自定義軌跡 Topic,請在上方選擇正確的軌跡 Topic",
},
+ doltVersionControl: {
+ title: "Dolt 版本控制",
+ open: "版本控制",
+ branches: "分支",
+ branchTreeView: "樹狀檢視",
+ branchFlatView: "平鋪檢視",
+ expandBranch: "展開分支群組",
+ collapseBranch: "收合分支群組",
+ tags: "標籤",
+ filterRefs: "篩選分支和標籤",
+ noBranches: "沒有分支",
+ noTags: "沒有標籤",
+ unknownBranch: "未知分支",
+ switchDatabase: "切換資料庫",
+ switchBranch: "切換分支",
+ workingTree: "工作區",
+ stagedChanges: "已暫存 {count}",
+ unstagedChanges: "未暫存 {count}",
+ uncommitted: "未提交",
+ stageAllChanges: "暫存所有變更",
+ commitWorkingTree: "提交工作區",
+ commitWorkingTreeDescription: "輸入提交訊息後,將工作區變更暫存並提交。",
+ commitMessage: "提交訊息",
+ commitMessagePlaceholder: "例如:修正訂單狀態",
+ commitMessageRequired: "請輸入提交訊息。",
+ changesStaged: "工作區變更已暫存",
+ workingTreeCommitted: "工作區變更已提交",
+ comparison: "目前比較",
+ swapComparison: "交換比較雙方",
+ noRevision: "未選擇 Revision",
+ compareCurrent: "與目前分支比較",
+ checkoutBranch: "切換到分支",
+ branchCheckedOut: "已切換到分支 {name}",
+ graph: "提交圖",
+ commit: "提交",
+ author: "作者",
+ date: "日期",
+ loadingGraph: "正在載入提交圖...",
+ noCommits: "沒有提交記錄",
+ noMessage: "沒有提交訊息",
+ changedTables: "變更的資料表",
+ loadingDiff: "正在載入版本差異...",
+ noChanges: "這些 Revision 之間沒有資料表變更。",
+ rowDiff: "資料列差異",
+ rows: "{count} 列",
+ loadingRows: "正在載入資料列差異...",
+ selectTable: "選擇變更的資料表",
+ noRowChanges: "沒有返回資料列變更,這次變更可能只有結構差異。",
+ createBranch: "建立分支",
+ createTag: "建立標籤",
+ mergeBranch: "合併分支",
+ deleteBranch: "刪除分支",
+ deleteTag: "刪除標籤",
+ createBranchDescription: "從選取的 Revision 或目前分支建立新分支。",
+ createTagDescription: "從選取的 Revision 或目前分支建立標籤。",
+ mergeBranchDescription: "將分支 {name} 合併到目前活動分支。",
+ deleteBranchDescription: "刪除分支 {name},此操作無法復原。",
+ deleteTagDescription: "刪除標籤 {name},此操作無法復原。",
+ branchName: "分支名稱",
+ branchNamePlaceholder: "feature/my-branch",
+ tagName: "標籤名稱",
+ tagNamePlaceholder: "v1.0.0",
+ branchSource: "來源 Revision:{revision}",
+ branchNameRequired: "請輸入分支名稱。",
+ tagNameRequired: "請輸入標籤名稱。",
+ branchCreated: "分支 {name} 已建立",
+ branchMerged: "分支 {name} 已合併",
+ branchDeleted: "分支 {name} 已刪除",
+ tagCreated: "標籤 {name} 已建立",
+ tagDeleted: "標籤 {name} 已刪除",
+ copyHash: "複製提交雜湊",
+ revertCommit: "復原提交",
+ hardResetToCommit: "硬重設到此處",
+ revertCommitTitle: "復原提交",
+ hardResetTitle: "硬重設分支",
+ revertCommitDescription: "建立新提交,反向套用提交 {hash} 的變更。",
+ hardResetDescription: "將分支 {branch} 硬重設到提交 {hash},並移除其後提交及目前工作區的暫存與未暫存變更。",
+ highRiskConfirmation: "這是高風險操作,請確認目標提交後再繼續。",
+ revertCommitComplete: "已復原提交 {hash}",
+ hardResetComplete: "目前分支已硬重設到 {hash}",
+ discardWorkingTree: "捨棄工作區修改",
+ discardWorkingTreeDescription: "捨棄所有已暫存與未暫存的工作區修改,此操作無法復原。",
+ discardWorkingTreeComplete: "工作區修改已捨棄",
+ sqlPreview: "SQL 預覽",
+ hashCopied: "提交雜湊已複製",
+ copyCurrentValue: "複製目前值",
+ copyBeforeValue: "複製修改前值",
+ copyAfterValue: "複製修改後值",
+ cellValueCopied: "儲存格值已複製",
+ viewCellDiff: "檢視差異詳情",
+ cellDiffTitle: "{table}.{column} 差異",
+ cellDiffFormat: "比較格式",
+ cellDiffFormatAuto: "自動",
+ cellDiffFormatRaw: "原始",
+ cellDiffDetectedFormat: "已識別:{format}",
+ cellDiffFormatFailed: "格式化失敗,已顯示原始值:{message}",
+ cellNullValue: "NULL",
+ cellRowMissing: "該列不存在",
+ cellColumnMissing: "該欄不存在",
+ },
});
diff --git a/apps/desktop/src/lib/__tests__/database/driverProfileExtensions.spec.ts b/apps/desktop/src/lib/__tests__/database/driverProfileExtensions.spec.ts
index e7594886dc..4efc78fc36 100644
--- a/apps/desktop/src/lib/__tests__/database/driverProfileExtensions.spec.ts
+++ b/apps/desktop/src/lib/__tests__/database/driverProfileExtensions.spec.ts
@@ -1,5 +1,5 @@
import { describe, expect, it } from "vitest";
-import { driverProfileCompletionObjects, driverProfileCompletionTableMetadata, driverProfileCompletionTables, driverProfileExtension, driverProfileObjectTreeProfileForConnection } from "@/lib/database/driverProfileExtensions";
+import { driverProfileCompletionObjects, driverProfileCompletionTableMetadata, driverProfileCompletionTables, driverProfileDatabaseWorkspace, driverProfileExtension, driverProfileObjectTreeProfileForConnection } from "@/lib/database/driverProfileExtensions";
import type { ConnectionConfig } from "@/types/database";
const completionContext = {
@@ -33,6 +33,17 @@ describe("driverProfileExtensions", () => {
expect(driverProfileCompletionObjects("dolt", completionContext).map((object) => object.name)).toContain("DOLT_HASHOF");
expect(driverProfileCompletionTables("dolt", { ...completionContext, suggestTables: true }).map((table) => table.name)).toContain("DOLT_LOG");
expect(driverProfileCompletionTableMetadata("dolt", "dolt_log")).toEqual({ detail: "Dolt system table", boost: -1200 });
+ const workspace = driverProfileDatabaseWorkspace("dolt");
+ expect(workspace).toMatchObject({
+ mode: "dolt-version-control",
+ menuLabelKey: "doltVersionControl.open",
+ tabTitleKey: "doltVersionControl.title",
+ tabScope: "connection",
+ entryScopes: ["connection", "database"],
+ });
+ expect(workspace?.resolveTarget?.("inventory", "connection")).toEqual({ database: "inventory" });
+ expect(workspace?.resolveTarget?.("inventory/feature/orders", "connection")).toEqual({ database: "inventory" });
+ expect(workspace?.resolveTarget?.("inventory/feature/orders", "database")).toEqual({ database: "inventory", branch: "feature/orders" });
});
it("leaves ordinary MySQL without profile capabilities", () => {
@@ -41,5 +52,6 @@ describe("driverProfileExtensions", () => {
expect(driverProfileCompletionObjects("mysql", completionContext)).toEqual([]);
expect(driverProfileCompletionTables("mysql", { ...completionContext, suggestTables: true })).toEqual([]);
expect(driverProfileCompletionTableMetadata("mysql", "dolt_log")).toBeUndefined();
+ expect(driverProfileDatabaseWorkspace("mysql")).toBeUndefined();
});
});
diff --git a/apps/desktop/src/lib/__tests__/dolt/doltCellDiff.spec.ts b/apps/desktop/src/lib/__tests__/dolt/doltCellDiff.spec.ts
new file mode 100644
index 0000000000..06f6304f12
--- /dev/null
+++ b/apps/desktop/src/lib/__tests__/dolt/doltCellDiff.spec.ts
@@ -0,0 +1,69 @@
+import { describe, expect, it } from "vitest";
+import { buildDoltTextDiff, detectDoltCellFormat, doltCellCopyText, doltCellDisplayValue, formatDoltCellText, type DoltDiffCellTarget } from "@/lib/dolt/doltCellDiff";
+
+function target(overrides: Partial<DoltDiffCellTarget> = {}): DoltDiffCellTarget {
+ return {
+ rowIndex: 0,
+ columnIndex: 0,
+ side: "after",
+ columnName: "payload",
+ columnKind: "unchanged",
+ rowKind: "modified",
+ beforeValue: "old",
+ afterValue: "new",
+ ...overrides,
+ };
+}
+
+const labels = { nullValue: "NULL", rowMissing: "Row does not exist", columnMissing: "Column does not exist" };
+
+describe("doltCellDiff", () => {
+ it("distinguishes null values from missing rows and columns", () => {
+ expect(doltCellDisplayValue(target({ beforeValue: null }), "before", labels)).toEqual({ state: "value", text: "NULL", rawText: "", canFormat: false });
+ expect(doltCellDisplayValue(target({ rowKind: "added" }), "before", labels).state).toBe("row-missing");
+ expect(doltCellDisplayValue(target({ columnKind: "added" }), "before", labels).state).toBe("column-missing");
+ expect(doltCellCopyText(target({ beforeValue: null }), "before")).toBe("");
+ expect(doltCellCopyText(target({ rowKind: "added" }), "before")).toBeNull();
+ });
+
+ it("manually formats single-line JSON without changing large number tokens", () => {
+ const display = doltCellDisplayValue(target({ afterValue: '{"id":9007199254740993123,"items":[1,2]}' }), "after", labels);
+ expect(formatDoltCellText(display, "json")).toEqual({
+ text: '{\n "id": 9007199254740993123,\n "items": [\n 1,\n 2\n ]\n}',
+ error: null,
+ });
+ });
+
+ it("manually formats XML and preserves raw text when parsing fails", () => {
+ const valid = doltCellDisplayValue(target({ afterValue: "<root><item>1</item><item>2</item></root>" }), "after", labels);
+ expect(formatDoltCellText(valid, "xml").text).toBe("<root>\n <item>1</item>\n <item>2</item>\n</root>");
+
+ const invalid = doltCellDisplayValue(target({ afterValue: "<root>" }), "after", labels);
+ const result = formatDoltCellText(invalid, "xml");
+ expect(result.text).toBe("<root>");
+ expect(result.error).toMatch(/Unclosed/i);
+ });
+
+ it("automatically detects validated JSON or XML and falls back to raw text", () => {
+ const json = doltCellDisplayValue(target({ beforeValue: '{"value":1}' }), "before", labels);
+ const brokenJson = doltCellDisplayValue(target({ afterValue: '{"value":' }), "after", labels);
+ expect(detectDoltCellFormat([json, brokenJson])).toBe("json");
+
+ const xml = doltCellDisplayValue(target({ beforeValue: "<root><value>1</value></root>" }), "before", labels);
+ expect(detectDoltCellFormat([xml])).toBe("xml");
+ expect(detectDoltCellFormat([json, xml])).toBe("raw");
+ expect(detectDoltCellFormat([doltCellDisplayValue(target({ beforeValue: "plain text" }), "before", labels)])).toBe("raw");
+ });
+
+ it("builds aligned line and character-level modifications", () => {
+ const rows = buildDoltTextDiff("{\n value: 1\n}", "{\n value: 2\n enabled: true\n}");
+ expect(rows.map((row) => row.kind)).toEqual(["equal", "modified", "added", "equal"]);
+ expect(rows[1].beforeSegments.some((segment) => segment.changed && segment.text === "1")).toBe(true);
+ expect(rows[1].afterSegments.some((segment) => segment.changed && segment.text === "2")).toBe(true);
+ expect(rows[2]).toMatchObject({ beforeLineNumber: null, afterLineNumber: 3, afterText: " enabled: true" });
+ });
+
+ it("keeps empty values visible as one aligned row", () => {
+ expect(buildDoltTextDiff("", "")).toEqual([expect.objectContaining({ kind: "equal", beforeLineNumber: 1, afterLineNumber: 1, beforeText: "", afterText: "" })]);
+ });
+});
diff --git a/apps/desktop/src/lib/__tests__/dolt/doltVersionControl.spec.ts b/apps/desktop/src/lib/__tests__/dolt/doltVersionControl.spec.ts
new file mode 100644
index 0000000000..de6d94ace0
--- /dev/null
+++ b/apps/desktop/src/lib/__tests__/dolt/doltVersionControl.spec.ts
@@ -0,0 +1,255 @@
+import { describe, expect, it } from "vitest";
+import type { QueryResult } from "@/types/database";
+import {
+ doltAddAllSql,
+ doltCheckoutBranchSql,
+ doltCommitSql,
+ doltCreateBranchSql,
+ doltCreateTagSql,
+ doltClientSessionScope,
+ doltDeleteBranchSql,
+ doltDeleteTagSql,
+ doltDiffSummarySql,
+ doltDiscardWorkingTreeSql,
+ doltGraphEdgePath,
+ doltGraphEdgeRoute,
+ doltHardResetSql,
+ doltLogSql,
+ doltMergeBranchSql,
+ doltRevertCommitSql,
+ doltRefColorIndexes,
+ doltRefsByCommit,
+ doltStatusSql,
+ doltTableChangeFlags,
+ doltTableChangeKind,
+ doltTableChangeSymbol,
+ doltTableDiffCountSql,
+ doltTableDiffSql,
+ layoutDoltCommitGraph,
+ parseDoltBranches,
+ parseDoltCommits,
+ parseDoltRowDiff,
+ parseDoltStatus,
+ parseDoltTableChanges,
+ parseDoltTags,
+} from "@/lib/dolt/doltVersionControl";
+
+function result(columns: string[], rows: QueryResult["rows"]): QueryResult {
+ return { columns, rows, affected_rows: 0, execution_time_ms: 1 };
+}
+
+describe("doltVersionControl", () => {
+ it("quotes revision and table arguments in generated SQL", () => {
+ expect(doltLogSql("feature/o'hare", 10)).toBe("SELECT * FROM DOLT_LOG('feature/o''hare', '--parents', '--decorate', 'short') LIMIT 10");
+ expect(doltLogSql("feature\\o'hare", 10)).toBe("SELECT * FROM DOLT_LOG('feature\\\\o''hare', '--parents', '--decorate', 'short') LIMIT 10");
+ expect(doltStatusSql()).toBe("SELECT table_name, staged, status FROM dolt_status ORDER BY table_name, staged DESC");
+ expect(doltAddAllSql()).toBe("CALL DOLT_ADD('.')");
+ expect(doltCommitSql("fix user's row")).toBe("CALL DOLT_COMMIT('-m', 'fix user''s row')");
+ expect(doltDiffSummarySql("main", "release'1")).toBe("SELECT * FROM DOLT_DIFF_SUMMARY('main', 'release''1')");
+ expect(doltTableDiffSql("HEAD", "WORKING", "order'items", 25)).toBe("SELECT * FROM DOLT_DIFF('HEAD', 'WORKING', 'order''items') LIMIT 25");
+ expect(doltTableDiffSql("HEAD", "WORKING", "order'items", 25, 50)).toBe("SELECT * FROM DOLT_DIFF('HEAD', 'WORKING', 'order''items') LIMIT 25 OFFSET 50");
+ expect(doltTableDiffCountSql("HEAD", "WORKING", "order'items")).toBe("SELECT COUNT(*) AS row_count FROM DOLT_DIFF('HEAD', 'WORKING', 'order''items')");
+ expect(doltCreateBranchSql("feature/o'hare", "HEAD")).toBe("CALL DOLT_BRANCH('feature/o''hare', 'HEAD')");
+ expect(doltMergeBranchSql("release'1")).toBe("CALL DOLT_MERGE('release''1')");
+ expect(doltCheckoutBranchSql("feature/o'hare")).toBe("CALL DOLT_CHECKOUT('feature/o''hare')");
+ expect(doltRevertCommitSql("abc'123")).toBe("CALL DOLT_REVERT('abc''123')");
+ expect(doltHardResetSql("abc'123")).toBe("CALL DOLT_RESET('--hard', 'abc''123')");
+ expect(doltDiscardWorkingTreeSql()).toBe("CALL DOLT_RESET('--hard', 'HEAD')");
+ expect(doltCreateTagSql("v1'o", "HEAD")).toBe("CALL DOLT_TAG('v1''o', 'HEAD')");
+ expect(doltDeleteTagSql("v0'o")).toBe("CALL DOLT_TAG('-d', 'v0''o')");
+ expect(doltDeleteBranchSql("old'branch")).toBe("CALL DOLT_BRANCH('-d', 'old''branch')");
+ });
+
+ it("builds database-scoped client sessions", () => {
+ expect(doltClientSessionScope("connection-1", "database_a")).toEqual({
+ connectionId: "connection-1",
+ database: "database_a",
+ clientSessionId: "dolt-version-control:connection-1:database_a",
+ });
+ expect(doltClientSessionScope("connection-1", "database_b").clientSessionId).not.toBe(doltClientSessionScope("connection-1", "database_a").clientSessionId);
+ });
+
+ it("parses staged and unstaged working tree changes", () => {
+ const changes = parseDoltStatus(
+ result(
+ ["status", "table_name", "staged"],
+ [
+ ["modified", "orders", true],
+ ["new table", "customers", 0],
+ ],
+ ),
+ );
+
+ expect(changes).toEqual([
+ { tableName: "orders", staged: true, status: "modified" },
+ { tableName: "customers", staged: false, status: "new table" },
+ ]);
+ });
+
+ it("parses Dolt refs, commits, decorations, and table changes by column name", () => {
+ const branchRows = result(["hash", "name"], [["abc123", "main"]]);
+ const tagRows = result(["tag_hash", "tag_name"], [["abc123", "v1.0"]]);
+ const commitRows = result(["commit_hash", "parents", "committer", "email", "date", "message", "refs"], [["abc123", "def456, 789abc", "Ada", "[email protected]", "2026-08-17", "Ship it", "HEAD -> main, tag: v1.0"]]);
+ const changeRows = result(["to_table_name", "from_table_name", "diff_type", "data_change", "schema_change"], [["orders", "orders", "modified", 1, 0]]);
+
+ const branches = parseDoltBranches(branchRows, "main");
+ const tags = parseDoltTags(tagRows);
+ const commits = parseDoltCommits(commitRows);
+
+ expect(branches).toEqual([{ name: "main", hash: "abc123", kind: "branch", active: true }]);
+ expect(tags[0]).toMatchObject({ name: "v1.0", hash: "abc123", kind: "tag" });
+ expect(commits[0]).toMatchObject({ hash: "abc123", parents: ["def456", "789abc"], committer: "Ada", message: "Ship it" });
+ expect(commits[0].refs).toEqual(["main", "tag: v1.0"]);
+ expect(parseDoltTableChanges(changeRows)).toEqual([{ tableName: "orders", fromTableName: "orders", toTableName: "orders", diffType: "modified", dataChange: true, schemaChange: false }]);
+ expect(
+ doltRefsByCommit(commits, [...branches, ...tags])
+ .get("abc123")
+ ?.map((item) => item.name),
+ ).toEqual(["main", "v1.0"]);
+ });
+
+ it("classifies table changes with reference-style symbols and flags", () => {
+ const added = { diffType: "CREATE", dataChange: false, schemaChange: true } as const;
+ const removed = { diffType: "deleted", dataChange: true, schemaChange: true } as const;
+ const modified = { diffType: "modified", dataChange: true, schemaChange: false } as const;
+ const schemaOnly = { diffType: "modified", dataChange: false, schemaChange: true } as const;
+ const metadataOnly = { diffType: "modified", dataChange: false, schemaChange: false } as const;
+
+ expect(doltTableChangeKind(added)).toBe("added");
+ expect(doltTableChangeSymbol(added)).toBe("+");
+ expect(doltTableChangeFlags(added)).toEqual(["schema"]);
+
+ expect(doltTableChangeKind(removed)).toBe("removed");
+ expect(doltTableChangeSymbol(removed)).toBe("-");
+ expect(doltTableChangeFlags(removed)).toEqual(["data", "schema"]);
+
+ expect(doltTableChangeKind(modified)).toBe("modified");
+ expect(doltTableChangeSymbol(modified)).toBe("*");
+ expect(doltTableChangeFlags(modified)).toEqual(["data"]);
+
+ expect(doltTableChangeKind(schemaOnly)).toBe("schema");
+ expect(doltTableChangeSymbol(schemaOnly)).toBe("*");
+ expect(doltTableChangeFlags(schemaOnly)).toEqual(["schema"]);
+
+ expect(doltTableChangeKind(metadataOnly)).toBe("modified");
+ expect(doltTableChangeFlags(metadataOnly)).toEqual(["metadata"]);
+ });
+
+ it("assigns stable lanes to a merge history", () => {
+ const commits = [
+ { hash: "merge", parents: ["main-parent", "feature-parent"], committer: "", email: "", date: "", message: "merge", refs: ["HEAD -> main"] },
+ { hash: "main-parent", parents: ["root"], committer: "", email: "", date: "", message: "main", refs: [] },
+ { hash: "feature-parent", parents: ["root"], committer: "", email: "", date: "", message: "feature", refs: ["feature"] },
+ { hash: "root", parents: [], committer: "", email: "", date: "", message: "root", refs: ["tag: v1"] },
+ ];
+ const refs = [
+ { name: "main", hash: "merge", kind: "branch" as const, active: true },
+ { name: "feature", hash: "feature-parent", kind: "branch" as const, active: false },
+ { name: "v1", hash: "root", kind: "tag" as const, active: false },
+ ];
+
+ const layout = layoutDoltCommitGraph(commits, refs, "main");
+ expect(layout.laneCount).toBeGreaterThanOrEqual(2);
+ expect(layout.rows.map((row) => row.lane)).toEqual([0, 0, 1, 0]);
+ expect(layout.rows.map((row) => row.nodeRef)).toEqual(["main", "main", "feature", "v1"]);
+ expect(layout.rows[0].edges).toEqual([
+ { fromLane: 0, toLane: 0, colorLane: 0, colorRef: "main" },
+ { fromLane: 0, toLane: 1, colorLane: 1, colorRef: "feature" },
+ ]);
+ expect(layout.rows[1].edges).toContainEqual({ fromLane: 1, toLane: 1, colorLane: 1, colorRef: "feature" });
+ expect(layout.rows[2].edges).toContainEqual({ fromLane: 1, toLane: 0, colorLane: 1, colorRef: "feature" });
+ });
+
+ it("keeps the active branch first-parent chain in lane zero when side commits are interleaved", () => {
+ const commits = [
+ { hash: "merge", parents: ["main-2", "feature-2"], committer: "", email: "", date: "", message: "merge", refs: ["HEAD -> main"] },
+ { hash: "feature-2", parents: ["feature-1"], committer: "", email: "", date: "", message: "feature 2", refs: ["feature"] },
+ { hash: "main-2", parents: ["root"], committer: "", email: "", date: "", message: "main 2", refs: [] },
+ { hash: "feature-1", parents: ["root"], committer: "", email: "", date: "", message: "feature 1", refs: [] },
+ { hash: "root", parents: [], committer: "", email: "", date: "", message: "root", refs: [] },
+ ];
+ const refs = [
+ { name: "main", hash: "merge", kind: "branch" as const, active: true },
+ { name: "feature", hash: "feature-2", kind: "branch" as const, active: false },
+ ];
+
+ expect(layoutDoltCommitGraph(commits, refs, "main").rows.map((row) => row.lane)).toEqual([0, 1, 0, 1, 0]);
+ });
+
+ it("starts fork edges at the real parent and ends merge edges at the merge commit", () => {
+ expect(doltGraphEdgeRoute(0, 0, 3, 2)).toBe("direct");
+ expect(doltGraphEdgeRoute(0, 1, 1, 2)).toBe("direct");
+ expect(doltGraphEdgeRoute(0, 1, 3, 1)).toBe("fork");
+ expect(doltGraphEdgeRoute(0, 1, 3, 2)).toBe("merge");
+ expect(doltGraphEdgePath(18, 105, 18, 15)).toBe("M 18 105 L 18 15");
+ expect(doltGraphEdgePath(18, 105, 36, 15, "fork")).toBe("M 18 105 L 36 75 L 36 15");
+ expect(doltGraphEdgePath(18, 105, 54, 15, "fork")).toBe("M 18 105 L 54 75 L 54 15");
+ expect(doltGraphEdgePath(18, 105, 36, 15, "merge")).toBe("M 18 105 L 18 45 L 36 15");
+ expect(doltGraphEdgePath(18, 105, 54, 15, "merge")).toBe("M 18 105 L 18 45 L 54 15");
+ expect(doltGraphEdgePath(18, 45, 36, 15)).toBe("M 18 45 L 36 15");
+ });
+
+ it("deduplicates log decorations against branch and tag records", () => {
+ const commits = [{ hash: "abc123", parents: [], committer: "", email: "", date: "", message: "", refs: ["HEAD -> main", "tag: v1.0", "refs/tags/v2.0"] }];
+ const refs = [
+ { name: "main", hash: "abc123", kind: "branch" as const, active: true },
+ { name: "v1.0", hash: "abc123", kind: "tag" as const, active: false },
+ ];
+
+ expect(doltRefsByCommit(commits, refs).get("abc123")).toEqual([refs[0], refs[1], { name: "v2.0", hash: "abc123", kind: "tag", active: false }]);
+ });
+
+ it("assigns ref colors independently of query order", () => {
+ const first = doltRefColorIndexes(["main", "feature", "v1.0"], 18);
+ const second = doltRefColorIndexes(["v1.0", "main", "feature"], 18);
+
+ expect([...first]).toEqual([...second]);
+ expect(new Set(first.values()).size).toBe(3);
+ });
+
+ it("pairs from/to diff columns and infers row changes", () => {
+ const parsed = parseDoltRowDiff(
+ result(
+ ["from_id", "to_id", "from_name", "to_name", "diff_type", "commit_hash"],
+ [
+ [null, 1, null, "Ada", "added", "abc"],
+ [2, 2, "Old", "New", "modified", "def"],
+ [3, null, "Removed", null, "removed", "ghi"],
+ ],
+ ),
+ );
+ expect(parsed.columns).toEqual(["id", "name"]);
+ expect(parsed.columnKinds).toEqual(["unchanged", "unchanged"]);
+ expect(parsed.rows).toEqual([
+ { kind: "added", before: [null, null], after: [1, "Ada"], changedColumns: ["id", "name"] },
+ { kind: "modified", before: [2, "Old"], after: [2, "New"], changedColumns: ["name"] },
+ { kind: "removed", before: [3, "Removed"], after: [null, null], changedColumns: ["id", "name"] },
+ ]);
+ });
+
+ it("accepts qualified, quoted, and suffix-style diff columns", () => {
+ const parsed = parseDoltRowDiff(result(["d.`id_from`", "d.`id_to`", '"from_name"', '"to_name"', "d.diff_type"], [[1, 1, "Old", "New", "modified"]]));
+
+ expect(parsed).toEqual({
+ columns: ["id", "name"],
+ columnKinds: ["unchanged", "unchanged"],
+ rows: [{ kind: "modified", before: [1, "Old"], after: [1, "New"], changedColumns: ["name"] }],
+ });
+ });
+
+ it("keeps schema-only columns aligned and identifies additions and removals", () => {
+ const parsed = parseDoltRowDiff(result(["from_id", "to_id", "from_legacy", "to_created_at", "diff_type"], [[1, 1, "old", "new", "modified"]]));
+
+ expect(parsed).toEqual({
+ columns: ["id", "legacy", "created_at"],
+ columnKinds: ["unchanged", "removed", "added"],
+ rows: [{ kind: "modified", before: [1, "old", null], after: [1, null, "new"], changedColumns: ["legacy", "created_at"] }],
+ });
+ });
+
+ it("infers schema columns when Dolt returns both sides with one side empty", () => {
+ const parsed = parseDoltRowDiff(result(["from_id", "to_id", "from_legacy", "to_legacy", "from_created_at", "to_created_at", "diff_type"], [[1, 1, "old", null, null, "new", "modified"]]), true);
+
+ expect(parsed.columnKinds).toEqual(["unchanged", "removed", "added"]);
+ });
+});
diff --git a/apps/desktop/src/lib/__tests__/tabs/tabPresentation.spec.ts b/apps/desktop/src/lib/__tests__/tabs/tabPresentation.spec.ts
index 87a73d7fac..32fb9f6267 100644
--- a/apps/desktop/src/lib/__tests__/tabs/tabPresentation.spec.ts
+++ b/apps/desktop/src/lib/__tests__/tabs/tabPresentation.spec.ts
@@ -1,7 +1,7 @@
import { beforeEach, describe, expect, it, vi } from "vitest";
import { createPinia, setActivePinia } from "pinia";
import { useConnectionStore } from "@/stores/connectionStore";
-import { connectionGroupDisplayName, executionSummaryItems, middleEllipsis, queryResultBaseSql, queryResultExecutionSql, resultGridCacheKey, resultGridInstanceKey, resultSourceRange, statementExecutionMarkers, tabTooltipLines, tabularResultItems } from "@/lib/tabs/tabPresentation";
+import { connectionGroupDisplayName, executionSummaryItems, middleEllipsis, queryResultBaseSql, queryResultExecutionSql, resultGridCacheKey, resultGridInstanceKey, resultSourceRange, statementExecutionMarkers, tabDisplayTitle, tabTooltipLines, tabularResultItems } from "@/lib/tabs/tabPresentation";
import { sqlTextFingerprint } from "@/lib/sql/sqlTextFingerprint";
import type { ConnectionConfig, QueryTab } from "@/types/database";
@@ -146,6 +146,14 @@ describe("query result grid identity", () => {
});
describe("tab group presentation", () => {
+ it("uses the live database and branch context for Dolt version control tabs", () => {
+ const store = useConnectionStore();
+ store.connections = [{ id: "conn-1", name: "Production Dolt", db_type: "mysql", driver_profile: "dolt", database: "app" } as ConnectionConfig];
+
+ expect(tabDisplayTitle(queryTab({ mode: "dolt-version-control", title: "Dolt Version Control", workspaceBranch: "feature/orders" }), translate)).toBe("Production Dolt [email protected]/orders");
+ expect(tabDisplayTitle(queryTab({ mode: "dolt-version-control", title: "Dolt Version Control" }), translate)).toBe("Production Dolt VCS@db");
+ });
+
it("adds the full, live group path to tab tooltips", () => {
const store = useConnectionStore();
store.connections = [{ id: "conn-1", name: "PostgreSQL", db_type: "postgres", database: "app" } as ConnectionConfig];
diff --git a/apps/desktop/src/lib/database/doltProfile.ts b/apps/desktop/src/lib/database/doltProfile.ts
index 5d7ec9de5c..89f4e6cadd 100644
--- a/apps/desktop/src/lib/database/doltProfile.ts
+++ b/apps/desktop/src/lib/database/doltProfile.ts
@@ -122,6 +122,16 @@ export function isDoltDriverProfile(driverProfile?: string): boolean {
return driverProfile?.toLowerCase() === DOLT_DRIVER_PROFILE;
}
+export function doltWorkspaceTarget(database: string, source: "connection" | "database") {
+ const separator = database.indexOf("/");
+ if (separator <= 0) return { database };
+ const baseDatabase = database.slice(0, separator);
+ const branch = database.slice(separator + 1);
+ // Connection-level navigation uses the database's default branch. A tree
+ // database entry may explicitly address a Dolt db/branch revision database.
+ return source === "database" && branch ? { database: baseDatabase, branch } : { database: baseDatabase };
+}
+
type DoltConnectionConfig = Pick<ConnectionConfig, "driver_profile"> & Partial<Pick<ConnectionConfig, "external_config">>;
function externalConfigRecord(value: unknown): Record<string, unknown> {
@@ -174,6 +184,14 @@ export function doltSqlRoutineSignatures(driverProfile?: string): Map<string, st
export const DOLT_DRIVER_PROFILE_EXTENSION: DriverProfileExtensionDefinition = {
id: DOLT_DRIVER_PROFILE,
+ databaseWorkspace: {
+ mode: "dolt-version-control",
+ menuLabelKey: "doltVersionControl.open",
+ tabTitleKey: "doltVersionControl.title",
+ tabScope: "connection",
+ entryScopes: ["connection", "database"],
+ resolveTarget: doltWorkspaceTarget,
+ },
objectTreeProfile: doltObjectTreeProfileForConnection,
completionTableMetadata: (tableName) =>
tableName.toLowerCase().startsWith("dolt")
diff --git a/apps/desktop/src/lib/database/driverProfileExtensions.ts b/apps/desktop/src/lib/database/driverProfileExtensions.ts
index f664bb12aa..c159a2c770 100644
--- a/apps/desktop/src/lib/database/driverProfileExtensions.ts
+++ b/apps/desktop/src/lib/database/driverProfileExtensions.ts
@@ -1,6 +1,6 @@
import { DOLT_DRIVER_PROFILE_EXTENSION } from "@/lib/database/doltProfile";
import type { SqlCompletionObject, SqlCompletionTable, SqlStatementKind } from "@/lib/sql/sqlCompletion";
-import type { ConnectionConfig, TableNameFilter, TreeNodeType } from "@/types/database";
+import type { ConnectionConfig, QueryTab, TableNameFilter, TreeNodeType } from "@/types/database";
export type DriverProfileObjectTreeProfile = {
cacheKey: string;
@@ -22,6 +22,25 @@ export type DriverProfileSqlCompletionContext = {
export type DriverProfileCompletionTableMetadata = Pick<SqlCompletionTable, "detail" | "boost">;
+export type DriverProfileWorkspaceTarget = {
+ database: string;
+ branch?: string;
+};
+
+export type DriverProfileWorkspaceScope = "database" | "connection";
+
+export type DriverProfileDatabaseWorkspace = {
+ mode: QueryTab["mode"];
+ menuLabelKey: string;
+ tabTitleKey: string;
+ /** Determines whether tabs are reused per connection or per database. */
+ tabScope: DriverProfileWorkspaceScope;
+ /** Tree levels whose context menu exposes the workspace entry. */
+ entryScopes: readonly DriverProfileWorkspaceScope[];
+ /** Maps a tree database name to the context opened by the workspace. */
+ resolveTarget?: (database: string, source: DriverProfileWorkspaceScope) => DriverProfileWorkspaceTarget;
+};
+
export type DriverProfileExtensionDefinition = {
id: string;
objectTreeProfile?: (config: ConnectionConfig) => DriverProfileObjectTreeProfile | undefined;
@@ -30,6 +49,7 @@ export type DriverProfileExtensionDefinition = {
completionTables?: (context: DriverProfileSqlCompletionContext) => SqlCompletionTable[];
sqlBuiltinTerms?: () => string;
routineSignatures?: () => Map<string, string[]>;
+ databaseWorkspace?: DriverProfileDatabaseWorkspace;
};
export const DRIVER_PROFILE_EXTENSIONS = [DOLT_DRIVER_PROFILE_EXTENSION] as const satisfies readonly DriverProfileExtensionDefinition[];
@@ -69,3 +89,7 @@ export function driverProfileSqlBuiltinTerms(driverProfile?: string): string {
export function driverProfileRoutineSignatures(driverProfile?: string): Map<string, string[]> {
return driverProfileExtension(driverProfile)?.routineSignatures?.() ?? new Map();
}
+
+export function driverProfileDatabaseWorkspace(driverProfile?: string): DriverProfileDatabaseWorkspace | undefined {
+ return driverProfileExtension(driverProfile)?.databaseWorkspace;
+}
diff --git a/apps/desktop/src/lib/dolt/doltCellDiff.ts b/apps/desktop/src/lib/dolt/doltCellDiff.ts
new file mode 100644
index 0000000000..1000f3c2bc
--- /dev/null
+++ b/apps/desktop/src/lib/dolt/doltCellDiff.ts
@@ -0,0 +1,226 @@
+import { diffChars, diffLines, type Change } from "diff";
+import { formatJsonSource } from "@/lib/common/safeJsonFormat";
+import { formatXmlSource } from "@/lib/common/xmlFormat";
+import type { QueryResult } from "@/types/database";
+import type { DoltDiffColumnKind, DoltRowChangeKind } from "@/lib/dolt/doltVersionControl";
+
+export type DoltCellValue = QueryResult["rows"][number][number];
+export type DoltCellSide = "before" | "after";
+export type DoltCellFormat = "raw" | "json" | "xml";
+export type DoltCellFormatMode = "auto" | DoltCellFormat;
+export type DoltCellValueState = "value" | "row-missing" | "column-missing";
+export type DoltTextDiffKind = "equal" | "added" | "removed" | "modified";
+
+export interface DoltDiffCellTarget {
+ rowIndex: number;
+ columnIndex: number;
+ side: DoltCellSide;
+ columnName: string;
+ columnKind: DoltDiffColumnKind;
+ rowKind: DoltRowChangeKind;
+ beforeValue: DoltCellValue;
+ afterValue: DoltCellValue;
+}
+
+export interface DoltCellDisplayValue {
+ state: DoltCellValueState;
+ text: string;
+ rawText: string;
+ canFormat: boolean;
+}
+
+export interface DoltCellFormatResult {
+ text: string;
+ error: string | null;
+}
+
+export interface DoltTextDiffSegment {
+ text: string;
+ changed: boolean;
+}
+
+export interface DoltTextDiffRow {
+ kind: DoltTextDiffKind;
+ beforeLineNumber: number | null;
+ afterLineNumber: number | null;
+ beforeText: string;
+ afterText: string;
+ beforeSegments: DoltTextDiffSegment[];
+ afterSegments: DoltTextDiffSegment[];
+}
+
+const MAX_DETAILED_LINE_DIFF_CHARACTERS = 500_000;
+const MAX_CHARACTER_DIFF_CHARACTERS = 20_000;
+
+export function doltCellValueState(target: DoltDiffCellTarget, side: DoltCellSide): DoltCellValueState {
+ if (side === "before") {
+ if (target.columnKind === "added") return "column-missing";
+ if (target.rowKind === "added") return "row-missing";
+ } else {
+ if (target.columnKind === "removed") return "column-missing";
+ if (target.rowKind === "removed") return "row-missing";
+ }
+ return "value";
+}
+
+export function doltCellDisplayValue(target: DoltDiffCellTarget, side: DoltCellSide, labels: { nullValue: string; rowMissing: string; columnMissing: string }): DoltCellDisplayValue {
+ const state = doltCellValueState(target, side);
+ if (state === "row-missing") return { state, text: labels.rowMissing, rawText: "", canFormat: false };
+ if (state === "column-missing") return { state, text: labels.columnMissing, rawText: "", canFormat: false };
+ const value = side === "before" ? target.beforeValue : target.afterValue;
+ if (value === null) return { state, text: labels.nullValue, rawText: "", canFormat: false };
+ const text = String(value);
+ return { state, text, rawText: text, canFormat: typeof value === "string" };
+}
+
+export function formatDoltCellText(value: DoltCellDisplayValue, format: DoltCellFormat): DoltCellFormatResult {
+ if (format === "raw" || !value.canFormat) return { text: value.text, error: null };
+ try {
+ return {
+ text: format === "json" ? formatJsonSource(value.rawText, 2) : formatXmlSource(value.rawText, " "),
+ error: null,
+ };
+ } catch (error) {
+ return { text: value.text, error: error instanceof Error ? error.message : String(error) };
+ }
+}
+
+export function detectDoltCellFormat(values: readonly DoltCellDisplayValue[]): DoltCellFormat {
+ const candidates = values.filter((value) => value.canFormat && value.rawText.trim()).map((value) => value.rawText.trim());
+ const jsonCandidates = candidates.filter((value) => value.startsWith("{") || value.startsWith("["));
+ const xmlCandidates = candidates.filter((value) => value.startsWith("<"));
+ const hasValidJson = jsonCandidates.some((value) => !formatDoltCellText({ state: "value", text: value, rawText: value, canFormat: true }, "json").error);
+ const hasValidXml = xmlCandidates.some((value) => !formatDoltCellText({ state: "value", text: value, rawText: value, canFormat: true }, "xml").error);
+ if (hasValidJson !== hasValidXml) return hasValidJson ? "json" : "xml";
+ return "raw";
+}
+
+function normalizeLineEndings(value: string): string {
+ return value.replace(/\r\n?/g, "\n");
+}
+
+function linesFromChange(change: Change): string[] {
+ if (!change.value) return [];
+ const lines = change.value.split("\n");
+ if (change.value.endsWith("\n")) lines.pop();
+ return lines;
+}
+
+function unchangedSegments(text: string): DoltTextDiffSegment[] {
+ return text ? [{ text, changed: false }] : [];
+}
+
+function changedSegments(beforeText: string, afterText: string): { before: DoltTextDiffSegment[]; after: DoltTextDiffSegment[] } {
+ if (beforeText.length + afterText.length > MAX_CHARACTER_DIFF_CHARACTERS) {
+ return {
+ before: beforeText ? [{ text: beforeText, changed: true }] : [],
+ after: afterText ? [{ text: afterText, changed: true }] : [],
+ };
+ }
+ const changes = diffChars(beforeText, afterText);
+ return {
+ before: changes.filter((change) => !change.added).map((change) => ({ text: change.value, changed: !!change.removed })),
+ after: changes.filter((change) => !change.removed).map((change) => ({ text: change.value, changed: !!change.added })),
+ };
+}
+
+function appendEqualRows(rows: DoltTextDiffRow[], lines: string[], beforeLine: { value: number }, afterLine: { value: number }) {
+ for (const line of lines) {
+ rows.push({
+ kind: "equal",
+ beforeLineNumber: beforeLine.value++,
+ afterLineNumber: afterLine.value++,
+ beforeText: line,
+ afterText: line,
+ beforeSegments: unchangedSegments(line),
+ afterSegments: unchangedSegments(line),
+ });
+ }
+}
+
+function appendChangedRows(rows: DoltTextDiffRow[], removed: string[], added: string[], beforeLine: { value: number }, afterLine: { value: number }) {
+ const count = Math.max(removed.length, added.length);
+ for (let index = 0; index < count; index += 1) {
+ const beforeText = removed[index];
+ const afterText = added[index];
+ if (beforeText !== undefined && afterText !== undefined) {
+ const segments = changedSegments(beforeText, afterText);
+ rows.push({
+ kind: beforeText === afterText ? "equal" : "modified",
+ beforeLineNumber: beforeLine.value++,
+ afterLineNumber: afterLine.value++,
+ beforeText,
+ afterText,
+ beforeSegments: beforeText === afterText ? unchangedSegments(beforeText) : segments.before,
+ afterSegments: beforeText === afterText ? unchangedSegments(afterText) : segments.after,
+ });
+ } else if (beforeText !== undefined) {
+ rows.push({
+ kind: "removed",
+ beforeLineNumber: beforeLine.value++,
+ afterLineNumber: null,
+ beforeText,
+ afterText: "",
+ beforeSegments: unchangedSegments(beforeText),
+ afterSegments: [],
+ });
+ } else if (afterText !== undefined) {
+ rows.push({
+ kind: "added",
+ beforeLineNumber: null,
+ afterLineNumber: afterLine.value++,
+ beforeText: "",
+ afterText,
+ beforeSegments: [],
+ afterSegments: unchangedSegments(afterText),
+ });
+ }
+ }
+}
+
+function buildFallbackRows(before: string, after: string): DoltTextDiffRow[] {
+ const beforeLines = before.split("\n");
+ const afterLines = after.split("\n");
+ const rows: DoltTextDiffRow[] = [];
+ appendChangedRows(rows, beforeLines, afterLines, { value: 1 }, { value: 1 });
+ return rows;
+}
+
+export function buildDoltTextDiff(beforeValue: string, afterValue: string): DoltTextDiffRow[] {
+ const before = normalizeLineEndings(beforeValue);
+ const after = normalizeLineEndings(afterValue);
+ if (before.length + after.length > MAX_DETAILED_LINE_DIFF_CHARACTERS) return buildFallbackRows(before, after);
+
+ const changes = diffLines(before, after, { newlineIsToken: false });
+ const rows: DoltTextDiffRow[] = [];
+ const beforeLine = { value: 1 };
+ const afterLine = { value: 1 };
+ let index = 0;
+ while (index < changes.length) {
+ const change = changes[index];
+ if (!change.added && !change.removed) {
+ appendEqualRows(rows, linesFromChange(change), beforeLine, afterLine);
+ index += 1;
+ continue;
+ }
+
+ const removed: string[] = [];
+ const added: string[] = [];
+ while (index < changes.length && (changes[index].added || changes[index].removed)) {
+ const changedLines = linesFromChange(changes[index]);
+ if (changes[index].removed) removed.push(...changedLines);
+ else added.push(...changedLines);
+ index += 1;
+ }
+ appendChangedRows(rows, removed, added, beforeLine, afterLine);
+ }
+
+ if (rows.length === 0) appendEqualRows(rows, [""], beforeLine, afterLine);
+ return rows;
+}
+
+export function doltCellCopyText(target: DoltDiffCellTarget, side: DoltCellSide): string | null {
+ if (doltCellValueState(target, side) !== "value") return null;
+ const value = side === "before" ? target.beforeValue : target.afterValue;
+ return value === null ? "" : String(value);
+}
diff --git a/apps/desktop/src/lib/dolt/doltVersionControl.ts b/apps/desktop/src/lib/dolt/doltVersionControl.ts
new file mode 100644
index 0000000000..a1141874f4
--- /dev/null
+++ b/apps/desktop/src/lib/dolt/doltVersionControl.ts
@@ -0,0 +1,631 @@
+import type { QueryResult } from "@/types/database";
+
+export interface DoltRef {
+ name: string;
+ hash: string;
+ kind: "branch" | "tag";
+ active: boolean;
+}
+
+export interface DoltCommit {
+ hash: string;
+ parents: string[];
+ committer: string;
+ email: string;
+ date: string;
+ message: string;
+ refs: string[];
+}
+
+export interface DoltTableChange {
+ tableName: string;
+ fromTableName: string;
+ toTableName: string;
+ diffType: string;
+ dataChange: boolean;
+ schemaChange: boolean;
+}
+
+export type DoltTableChangeKind = "added" | "removed" | "modified" | "schema" | "mixed";
+export type DoltTableChangeFlag = "data" | "schema" | "metadata";
+
+/** Matches Dolt's table-level change classification used by the reference UI. */
+export function doltTableChangeKind(change: Pick<DoltTableChange, "diffType" | "dataChange" | "schemaChange">): DoltTableChangeKind {
+ const normalized = change.diffType.trim().toLowerCase();
+ if (normalized.includes("add") || normalized.includes("create")) return "added";
+ if (normalized.includes("drop") || normalized.includes("remove") || normalized.includes("delete")) return "removed";
+ if (change.schemaChange && change.dataChange) return "mixed";
+ if (change.schemaChange) return "schema";
+ return "modified";
+}
+
+export function doltTableChangeSymbol(change: Pick<DoltTableChange, "diffType" | "dataChange" | "schemaChange">): "+" | "-" | "*" {
+ const kind = doltTableChangeKind(change);
+ return kind === "added" ? "+" : kind === "removed" ? "-" : "*";
+}
+
+export function doltTableChangeFlags(change: Pick<DoltTableChange, "diffType" | "dataChange" | "schemaChange">): DoltTableChangeFlag[] {
+ const flags: DoltTableChangeFlag[] = [];
+ if (change.dataChange) flags.push("data");
+ if (change.schemaChange) flags.push("schema");
+ if (flags.length === 0 && change.diffType.trim()) flags.push("metadata");
+ return flags;
+}
+
+export interface DoltWorkingChange {
+ tableName: string;
+ staged: boolean;
+ status: string;
+}
+
+export type DoltRowChangeKind = "added" | "removed" | "modified";
+export type DoltDiffColumnKind = "unchanged" | "added" | "removed";
+
+export interface DoltDiffRow {
+ kind: DoltRowChangeKind;
+ before: QueryResult["rows"][number];
+ after: QueryResult["rows"][number];
+ changedColumns: string[];
+}
+
+export interface DoltParsedRowDiff {
+ columns: string[];
+ columnKinds: DoltDiffColumnKind[];
+ rows: DoltDiffRow[];
+}
+
+export interface DoltGraphLayout {
+ lane: number;
+ nodeRef: string | null;
+ edges: DoltGraphEdge[];
+ maxLane: number;
+}
+
+export interface DoltGraphEdge {
+ fromLane: number;
+ toLane: number;
+ colorLane: number;
+ colorRef: string | null;
+}
+
+export interface DoltClientSessionScope {
+ connectionId: string;
+ database: string;
+ clientSessionId: string;
+}
+
+export type DoltGraphEdgeRoute = "direct" | "fork" | "merge";
+const DOLT_GRAPH_DIAGONAL_HEIGHT = 30;
+
+export function doltGraphEdgeRoute(parentLane: number, childLane: number, rowDistance: number, childParentCount: number): DoltGraphEdgeRoute {
+ if (parentLane === childLane || rowDistance <= 1) return "direct";
+ if (childParentCount > 1) return "merge";
+ return "fork";
+}
+
+export function doltGraphEdgePath(startX: number, startY: number, targetX: number, targetY: number, route: DoltGraphEdgeRoute = "direct"): string {
+ if (startX === targetX || route === "direct") return `M ${startX} ${startY} L ${targetX} ${targetY}`;
+ const availableHeight = Math.abs(targetY - startY);
+ const diagonalHeight = DOLT_GRAPH_DIAGONAL_HEIGHT;
+ if (diagonalHeight >= availableHeight) return `M ${startX} ${startY} L ${targetX} ${targetY}`;
+ const direction = Math.sign(targetY - startY) || 1;
+ if (route === "fork") return `M ${startX} ${startY} L ${targetX} ${startY + direction * diagonalHeight} L ${targetX} ${targetY}`;
+ return `M ${startX} ${startY} L ${startX} ${targetY - direction * diagonalHeight} L ${targetX} ${targetY}`;
+}
+
+export function doltClientSessionScope(connectionId: string, database: string): DoltClientSessionScope {
+ return {
+ connectionId,
+ database,
+ clientSessionId: `dolt-version-control:${connectionId}:${database}`,
+ };
+}
+
+export function doltSqlLiteral(value: string): string {
+ return `'${value.replace(/\\/g, "\\\\").replace(/'/g, "''")}'`;
+}
+
+export function doltLogSql(revision: string, limit = 500): string {
+ return `SELECT * FROM DOLT_LOG(${doltSqlLiteral(revision)}, '--parents', '--decorate', 'short') LIMIT ${Math.max(1, Math.floor(limit))}`;
+}
+
+export function doltStatusSql(): string {
+ return "SELECT table_name, staged, status FROM dolt_status ORDER BY table_name, staged DESC";
+}
+
+export function doltAddAllSql(): string {
+ return "CALL DOLT_ADD('.')";
+}
+
+export function doltCommitSql(message: string): string {
+ return `CALL DOLT_COMMIT('-m', ${doltSqlLiteral(message)})`;
+}
+
+export function doltDiffSummarySql(fromRevision: string, toRevision: string): string {
+ return `SELECT * FROM DOLT_DIFF_SUMMARY(${doltSqlLiteral(fromRevision)}, ${doltSqlLiteral(toRevision)})`;
+}
+
+export function doltTableDiffSql(fromRevision: string, toRevision: string, tableName: string, limit = 200, offset = 0): string {
+ const normalizedOffset = Math.max(0, Math.floor(offset));
+ return `SELECT * FROM DOLT_DIFF(${doltSqlLiteral(fromRevision)}, ${doltSqlLiteral(toRevision)}, ${doltSqlLiteral(tableName)}) LIMIT ${Math.max(1, Math.floor(limit))}${normalizedOffset > 0 ? ` OFFSET ${normalizedOffset}` : ""}`;
+}
+
+export function doltTableDiffCountSql(fromRevision: string, toRevision: string, tableName: string): string {
+ return `SELECT COUNT(*) AS row_count FROM DOLT_DIFF(${doltSqlLiteral(fromRevision)}, ${doltSqlLiteral(toRevision)}, ${doltSqlLiteral(tableName)})`;
+}
+
+export function doltCreateBranchSql(branchName: string, sourceRevision?: string): string {
+ const source = sourceRevision?.trim();
+ return source ? `CALL DOLT_BRANCH(${doltSqlLiteral(branchName)}, ${doltSqlLiteral(source)})` : `CALL DOLT_BRANCH(${doltSqlLiteral(branchName)})`;
+}
+
+export function doltMergeBranchSql(branchName: string): string {
+ return `CALL DOLT_MERGE(${doltSqlLiteral(branchName)})`;
+}
+
+export function doltCheckoutBranchSql(branchName: string): string {
+ return `CALL DOLT_CHECKOUT(${doltSqlLiteral(branchName)})`;
+}
+
+export function doltRevertCommitSql(revision: string): string {
+ return `CALL DOLT_REVERT(${doltSqlLiteral(revision)})`;
+}
+
+export function doltHardResetSql(revision: string): string {
+ return `CALL DOLT_RESET('--hard', ${doltSqlLiteral(revision)})`;
+}
+
+export function doltDiscardWorkingTreeSql(): string {
+ return doltHardResetSql("HEAD");
+}
+
+export function doltCreateTagSql(tagName: string, sourceRevision?: string): string {
+ const source = sourceRevision?.trim();
+ return source ? `CALL DOLT_TAG(${doltSqlLiteral(tagName)}, ${doltSqlLiteral(source)})` : `CALL DOLT_TAG(${doltSqlLiteral(tagName)})`;
+}
+
+export function doltDeleteTagSql(tagName: string): string {
+ return `CALL DOLT_TAG('-d', ${doltSqlLiteral(tagName)})`;
+}
+
+export function doltDeleteBranchSql(branchName: string): string {
+ return `CALL DOLT_BRANCH('-d', ${doltSqlLiteral(branchName)})`;
+}
+
+function normalizedColumnIndex(result: QueryResult): Map<string, number> {
+ return new Map(result.columns.map((column, index) => [column.trim().toLowerCase(), index]));
+}
+
+function valueFromRow(row: QueryResult["rows"][number], columns: Map<string, number>, names: string[]): string {
+ for (const name of names) {
+ const index = columns.get(name.toLowerCase());
+ if (index !== undefined && row[index] !== null && row[index] !== undefined) return String(row[index]);
+ }
+ return "";
+}
+
+function booleanFromRow(row: QueryResult["rows"][number], columns: Map<string, number>, names: string[]): boolean {
+ const value = valueFromRow(row, columns, names).trim().toLowerCase();
+ return value === "1" || value === "true" || value === "yes";
+}
+
+function parseParents(value: string): string[] {
+ return value
+ .replace(/[;,]/g, " ")
+ .split(/\s+/)
+ .map((parent) => parent.trim())
+ .filter(Boolean);
+}
+
+function parseRefs(value: string): string[] {
+ return value
+ .split(/[,;]/)
+ .map((ref) =>
+ ref
+ .trim()
+ .replace(/^HEAD\s*->\s*/i, "")
+ .replace(/^refs\/tags\//i, "tag: ")
+ .replace(/^refs\/(?:heads|remotes)\//i, ""),
+ )
+ .filter(Boolean);
+}
+
+function decorationRef(decoration: string, hash: string): DoltRef | null {
+ let name = decoration.trim();
+ if (!name) return null;
+
+ name = name.replace(/^HEAD\s*->\s*/i, "").trim();
+ if (!name || name.toUpperCase() === "HEAD") return null;
+
+ let kind: DoltRef["kind"] = "branch";
+ if (/^(?:tag:\s*|refs\/tags\/)/i.test(name)) {
+ kind = "tag";
+ name = name.replace(/^(?:tag:\s*|refs\/tags\/)/i, "").trim();
+ } else {
+ name = name.replace(/^refs\/(?:heads|remotes)\//i, "").trim();
+ }
+ return name ? { name, hash, kind, active: false } : null;
+}
+
+export function parseDoltCommits(result: QueryResult): DoltCommit[] {
+ const columns = normalizedColumnIndex(result);
+ return result.rows
+ .map((row) => ({
+ hash: valueFromRow(row, columns, ["commit_hash", "hash", "commit"]),
+ parents: parseParents(valueFromRow(row, columns, ["parents", "parent_hashes", "parent"])),
+ committer: valueFromRow(row, columns, ["committer", "commit_user", "author", "name"]),
+ email: valueFromRow(row, columns, ["email", "committer_email", "author_email"]),
+ date: valueFromRow(row, columns, ["date", "commit_date", "timestamp"]),
+ message: valueFromRow(row, columns, ["message", "commit_message"]),
+ refs: parseRefs(valueFromRow(row, columns, ["refs", "ref_names", "decorations", "decorate"])),
+ }))
+ .filter((commit) => commit.hash);
+}
+
+export function parseDoltBranches(result: QueryResult, activeBranch: string): DoltRef[] {
+ const columns = normalizedColumnIndex(result);
+ return result.rows
+ .map((row) => {
+ const name = valueFromRow(row, columns, ["name", "branch"]);
+ return {
+ name,
+ hash: valueFromRow(row, columns, ["hash", "commit_hash"]),
+ kind: "branch" as const,
+ active: name === activeBranch,
+ };
+ })
+ .filter((ref) => ref.name);
+}
+
+export function parseDoltTags(result: QueryResult): DoltRef[] {
+ const columns = normalizedColumnIndex(result);
+ return result.rows
+ .map((row) => ({
+ name: valueFromRow(row, columns, ["tag_name", "name", "tag"]),
+ hash: valueFromRow(row, columns, ["tag_hash", "hash", "commit_hash"]),
+ kind: "tag" as const,
+ active: false,
+ }))
+ .filter((ref) => ref.name);
+}
+
+export function parseDoltStatus(result: QueryResult): DoltWorkingChange[] {
+ const columns = normalizedColumnIndex(result);
+ return result.rows
+ .map((row) => ({
+ tableName: valueFromRow(row, columns, ["table_name", "name", "table"]),
+ staged: booleanFromRow(row, columns, ["staged", "is_staged"]),
+ status: valueFromRow(row, columns, ["status", "change_type"]),
+ }))
+ .filter((change) => change.tableName);
+}
+
+export function parseDoltTableChanges(result: QueryResult): DoltTableChange[] {
+ const columns = normalizedColumnIndex(result);
+ return result.rows
+ .map((row) => {
+ const fromTableName = valueFromRow(row, columns, ["from_table_name", "from_table"]);
+ const toTableName = valueFromRow(row, columns, ["to_table_name", "to_table"]);
+ return {
+ tableName: toTableName || fromTableName,
+ fromTableName,
+ toTableName,
+ diffType: valueFromRow(row, columns, ["diff_type", "change_type"]) || "modified",
+ dataChange: booleanFromRow(row, columns, ["data_change", "data_changed"]),
+ schemaChange: booleanFromRow(row, columns, ["schema_change", "schema_changed"]),
+ };
+ })
+ .filter((change) => change.tableName);
+}
+
+const DOLT_DIFF_METADATA_COLUMNS = new Set(["commit", "commit_hash", "commit_date", "from_commit", "to_commit", "from_commit_hash", "to_commit_hash", "from_commit_date", "to_commit_date", "table_name", "from_table_name", "to_table_name", "diff_type", "conflict_type"]);
+
+function diffValue(row: QueryResult["rows"][number], index: number | undefined): QueryResult["rows"][number][number] {
+ return index === undefined ? null : (row[index] ?? null);
+}
+
+function diffKind(value: unknown, hasBefore: boolean, hasAfter: boolean): DoltRowChangeKind {
+ const normalized = String(value ?? "")
+ .trim()
+ .toLowerCase();
+ if (normalized.includes("add") || normalized.includes("insert") || normalized === "new") return "added";
+ if (normalized.includes("remove") || normalized.includes("delete") || normalized.includes("drop") || normalized === "old") return "removed";
+ if (!hasBefore && hasAfter) return "added";
+ if (hasBefore && !hasAfter) return "removed";
+ return "modified";
+}
+
+function normalizedDiffColumnName(column: string): string {
+ const unqualified = column.trim().split(".").pop() ?? column;
+ return unqualified.replace(/^[`"\x5b]|[`"\x5d]$/g, "").trim();
+}
+
+function diffColumnSide(column: string): { side: "from" | "to"; field: string } | null {
+ const name = normalizedDiffColumnName(column);
+ const normalized = name.toLowerCase();
+ if (normalized.startsWith("from_")) return { side: "from", field: name.slice(5) };
+ if (normalized.startsWith("to_")) return { side: "to", field: name.slice(3) };
+ if (normalized.endsWith("_from")) return { side: "from", field: name.slice(0, -5) };
+ if (normalized.endsWith("_to")) return { side: "to", field: name.slice(0, -3) };
+ return null;
+}
+
+export function parseDoltRowDiff(result: QueryResult, schemaChange = false): DoltParsedRowDiff {
+ const pairs = new Map<string, { name: string; fromIndex?: number; toIndex?: number }>();
+ let diffTypeIndex: number | undefined;
+ result.columns.forEach((column, index) => {
+ const normalized = normalizedDiffColumnName(column).toLowerCase();
+ if (normalized === "diff_type") diffTypeIndex = index;
+ const descriptor = diffColumnSide(column);
+ if (!descriptor || !descriptor.field || DOLT_DIFF_METADATA_COLUMNS.has(normalized)) return;
+ const key = descriptor.field.toLowerCase();
+ const pair = pairs.get(key) ?? { name: descriptor.field };
+ if (descriptor.side === "from") pair.fromIndex = index;
+ else pair.toIndex = index;
+ pairs.set(key, pair);
+ });
+
+ const columns = [...pairs.values()];
+ const rows = result.rows.map((row) => {
+ const before = columns.map((pair) => diffValue(row, pair.fromIndex));
+ const after = columns.map((pair) => diffValue(row, pair.toIndex));
+ const hasBefore = before.some((value) => value !== null);
+ const hasAfter = after.some((value) => value !== null);
+ const changedColumns = columns.filter((_, index) => before[index] !== after[index]).map((pair) => pair.name);
+ return {
+ kind: diffKind(diffValue(row, diffTypeIndex), hasBefore, hasAfter),
+ before,
+ after,
+ changedColumns,
+ };
+ });
+
+ const columnKinds = columns.map((pair, index): DoltDiffColumnKind => {
+ if (pair.fromIndex === undefined) return "added";
+ if (pair.toIndex === undefined) return "removed";
+ if (!schemaChange) return "unchanged";
+ const hasBeforeValue = rows.some((row) => row.before[index] !== null && String(row.before[index]).trim() !== "");
+ const hasAfterValue = rows.some((row) => row.after[index] !== null && String(row.after[index]).trim() !== "");
+ if (!hasBeforeValue && hasAfterValue) return "added";
+ if (hasBeforeValue && !hasAfterValue) return "removed";
+ return "unchanged";
+ });
+
+ return {
+ columns: columns.map((pair) => pair.name),
+ columnKinds,
+ rows,
+ };
+}
+
+function matchingHash(hashes: Iterable<string>, candidate: string): string | undefined {
+ for (const hash of hashes) {
+ if (hash === candidate || hash.startsWith(candidate) || candidate.startsWith(hash)) return hash;
+ }
+ return undefined;
+}
+
+export function doltRefsByCommit(commits: readonly DoltCommit[], refs: readonly DoltRef[]): Map<string, DoltRef[]> {
+ const hashes = commits.map((commit) => commit.hash);
+ const result = new Map<string, DoltRef[]>();
+ const seenByHash = new Map<string, Set<string>>();
+ const append = (hash: string, ref: DoltRef) => {
+ const seen = seenByHash.get(hash) ?? new Set<string>();
+ const key = `${ref.kind}:${ref.name}`;
+ if (seen.has(key)) return;
+ seen.add(key);
+ seenByHash.set(hash, seen);
+ const entries = result.get(hash) ?? [];
+ entries.push(ref);
+ result.set(hash, entries);
+ };
+
+ for (const ref of refs) {
+ const hash = matchingHash(hashes, ref.hash);
+ if (!hash) continue;
+ append(hash, ref);
+ }
+ for (const commit of commits) {
+ for (const decoration of commit.refs) {
+ const ref = decorationRef(decoration, commit.hash);
+ if (ref) append(commit.hash, ref);
+ }
+ }
+ for (const entries of result.values()) {
+ entries.sort((left, right) => Number(right.active) - Number(left.active) || (left.kind === right.kind ? left.name.localeCompare(right.name) : left.kind === "branch" ? -1 : 1));
+ }
+ return result;
+}
+
+export function doltRefColorIndexes(refs: Iterable<string>, colorCount: number): Map<string, number> {
+ const normalizedColorCount = Math.max(1, Math.floor(colorCount));
+ const names = [...new Set([...refs].map((ref) => ref.trim()).filter(Boolean))].sort();
+ const result = new Map<string, number>();
+ const used = new Set<number>();
+ for (const name of names) {
+ let hash = 0;
+ for (let index = 0; index < name.length; index += 1) hash = (Math.imul(31, hash) + name.charCodeAt(index)) | 0;
+ const preferred = ((hash % normalizedColorCount) + normalizedColorCount) % normalizedColorCount;
+ let colorIndex = preferred;
+ for (let offset = 0; offset < normalizedColorCount; offset += 1) {
+ const candidate = (preferred + offset) % normalizedColorCount;
+ if (!used.has(candidate)) {
+ colorIndex = candidate;
+ break;
+ }
+ }
+ result.set(name, colorIndex);
+ used.add(colorIndex);
+ }
+ return result;
+}
+
+function primaryGraphRef(refs: readonly DoltRef[], activeBranch: string): string | null {
+ return refs.find((ref) => ref.kind === "branch" && (ref.active || ref.name === activeBranch))?.name ?? refs.find((ref) => ref.kind === "branch" && !ref.name.startsWith("origin/"))?.name ?? refs[0]?.name ?? null;
+}
+
+export function layoutDoltCommitGraph(commits: readonly DoltCommit[], refs: readonly DoltRef[] = [], activeBranch = ""): { rows: DoltGraphLayout[]; laneCount: number } {
+ const knownHashes = new Set(commits.map((commit) => commit.hash));
+ const canonical = (hash: string) => matchingHash(knownHashes, hash) ?? hash;
+ const commitIndexByHash = new Map<string, number>();
+ commits.forEach((commit, index) => {
+ commitIndexByHash.set(commit.hash, index);
+ if (commit.hash.length > 8) commitIndexByHash.set(commit.hash.slice(0, 8), index);
+ });
+ const refByCommit = doltRefsByCommit(commits, refs);
+ const refByHash = new Map<string, string>();
+ for (const commit of commits) {
+ const ref = primaryGraphRef(refByCommit.get(commit.hash) ?? [], activeBranch);
+ if (ref) refByHash.set(commit.hash, ref);
+ }
+
+ // Reserve lane 0 for the active branch's first-parent chain. Dolt returns
+ // merge history in a topological order where side commits can appear between
+ // mainline commits, so lane allocation must be driven by branch ancestry
+ // rather than by the order in which rows happen to be returned.
+ const commitByHash = new Map(commits.map((commit) => [commit.hash, commit]));
+ const activeBranchRef = refs.find((ref) => ref.kind === "branch" && (ref.active || ref.name === activeBranch));
+ let primaryHash = activeBranchRef ? canonical(activeBranchRef.hash) : undefined;
+ if (!primaryHash && activeBranch) {
+ primaryHash = commits.find((commit) => refByCommit.get(commit.hash)?.some((ref) => ref.kind === "branch" && ref.name === activeBranch))?.hash;
+ }
+ if (activeBranch && (!primaryHash || !commitByHash.has(primaryHash))) primaryHash = commits[0]?.hash;
+ const primaryCommitHashes = new Set<string>();
+ while (primaryHash && commitByHash.has(primaryHash) && !primaryCommitHashes.has(primaryHash)) {
+ primaryCommitHashes.add(primaryHash);
+ primaryHash = canonical(commitByHash.get(primaryHash)?.parents[0] ?? "");
+ }
+
+ let lanes: Array<string | null> = [];
+ let laneRefs: Array<string | null> = [];
+ const rows: DoltGraphLayout[] = [];
+ let laneCount = 1;
+
+ const setLane = (values: Array<string | null>, lane: number, value: string | null) => {
+ while (values.length <= lane) values.push(null);
+ values[lane] = value;
+ };
+ const firstEmptyLane = (values: Array<string | null>, startLane: number, blockedLane = -1) => {
+ for (let lane = Math.max(0, startLane); lane < values.length; lane += 1) {
+ if (lane !== blockedLane && values[lane] === null) return lane;
+ }
+ values.push(null);
+ return values.length - 1;
+ };
+
+ for (let rowIndex = 0; rowIndex < commits.length; rowIndex += 1) {
+ const commit = commits[rowIndex];
+ const isPrimaryCommit = primaryCommitHashes.has(commit.hash);
+ let nodeLane = lanes.indexOf(commit.hash);
+ if (isPrimaryCommit) {
+ if (nodeLane > 0) {
+ const laneZeroHash = lanes[0] ?? null;
+ const laneZeroRef = laneRefs[0] ?? null;
+ setLane(lanes, 0, commit.hash);
+ setLane(laneRefs, 0, laneRefs[nodeLane] ?? null);
+ setLane(lanes, nodeLane, laneZeroHash);
+ setLane(laneRefs, nodeLane, laneZeroRef);
+ } else if (nodeLane < 0) {
+ if (lanes[0] && lanes[0] !== commit.hash) {
+ const displacedLane = firstEmptyLane(lanes, 1);
+ setLane(lanes, displacedLane, lanes[0]);
+ setLane(laneRefs, displacedLane, laneRefs[0] ?? null);
+ }
+ nodeLane = 0;
+ setLane(lanes, nodeLane, commit.hash);
+ }
+ nodeLane = 0;
+ } else {
+ if (nodeLane === 0 && primaryCommitHashes.size > 0) {
+ const displacedLane = firstEmptyLane(lanes, 1);
+ setLane(lanes, displacedLane, lanes[0] ?? null);
+ setLane(laneRefs, displacedLane, laneRefs[0] ?? null);
+ setLane(lanes, 0, null);
+ setLane(laneRefs, 0, null);
+ nodeLane = displacedLane;
+ }
+ if (nodeLane < 0) {
+ nodeLane = firstEmptyLane(lanes, primaryCommitHashes.size > 0 ? 1 : rowIndex === 0 ? 0 : 1);
+ setLane(lanes, nodeLane, commit.hash);
+ }
+ }
+ const commitRef = refByHash.get(commit.hash) ?? laneRefs[nodeLane] ?? null;
+ setLane(laneRefs, nodeLane, commitRef);
+
+ const edges: DoltGraphEdge[] = [];
+ const visibleParents = commit.parents.map(canonical).filter((parent) => commitIndexByHash.has(parent));
+ const nextLanes = [...lanes];
+ const nextLaneRefs = [...laneRefs];
+ if (visibleParents.length === 0) {
+ setLane(nextLanes, nodeLane, null);
+ setLane(nextLaneRefs, nodeLane, null);
+ } else {
+ visibleParents.forEach((parent, parentIndex) => {
+ let parentLane: number;
+ if (parentIndex === 0) {
+ const existingParentLane = nextLanes.indexOf(parent);
+ if (existingParentLane >= 0 && existingParentLane !== nodeLane) {
+ parentLane = existingParentLane;
+ } else {
+ for (let lane = 0; lane < nextLanes.length; lane += 1) {
+ if (nextLanes[lane] === parent) nextLanes[lane] = null;
+ }
+ parentLane = nodeLane;
+ setLane(nextLanes, parentLane, parent);
+ }
+ } else {
+ parentLane = nextLanes.indexOf(parent);
+ if (parentLane < 0 || parentLane === nodeLane) {
+ if (parentLane === nodeLane) setLane(nextLanes, parentLane, null);
+ parentLane = firstEmptyLane(nextLanes, 0, nodeLane);
+ }
+ setLane(nextLanes, parentLane, parent);
+ }
+ let parentRef = refByHash.get(parent) ?? nextLaneRefs[parentLane] ?? null;
+ if (parentIndex === 0 && !parentRef) parentRef = laneRefs[nodeLane] ?? null;
+ setLane(nextLaneRefs, parentLane, parentRef);
+ edges.push({ fromLane: nodeLane, toLane: parentLane, colorLane: parentIndex === 0 ? nodeLane : parentLane, colorRef: parentIndex === 0 ? (laneRefs[nodeLane] ?? null) : parentRef });
+ });
+ for (let lane = 0; lane < nextLanes.length; lane += 1) {
+ if (nextLanes[lane] === commit.hash) nextLanes[lane] = null;
+ }
+ }
+
+ for (let lane = 0; lane < lanes.length; lane += 1) {
+ const laneHash = lanes[lane];
+ if (!laneHash || laneHash === commit.hash) continue;
+ const targetLane = nextLanes.indexOf(laneHash);
+ if (targetLane < 0) continue;
+ const colorRef = laneRefs[lane] ?? null;
+ setLane(nextLaneRefs, targetLane, colorRef);
+ edges.push({ fromLane: lane, toLane: targetLane, colorLane: lane, colorRef });
+ }
+
+ const maxLane = Math.max(
+ 0,
+ lanes.reduce((maximum, hash, lane) => (hash ? Math.max(maximum, lane) : maximum), 0),
+ nextLanes.reduce((maximum, hash, lane) => (hash ? Math.max(maximum, lane) : maximum), 0),
+ );
+ rows.push({ lane: nodeLane, nodeRef: laneRefs[nodeLane] ?? null, edges, maxLane });
+ laneCount = Math.max(laneCount, maxLane + 1, nodeLane + 1);
+
+ const seen = new Set<string>();
+ for (let lane = 0; lane < nextLanes.length; lane += 1) {
+ const hash = nextLanes[lane];
+ const targetIndex = hash ? commitIndexByHash.get(hash) : undefined;
+ if (!hash || targetIndex === undefined || targetIndex < rowIndex + 1 || seen.has(hash)) {
+ nextLanes[lane] = null;
+ nextLaneRefs[lane] = null;
+ } else {
+ seen.add(hash);
+ }
+ }
+ while (nextLanes.length > 0 && nextLanes[nextLanes.length - 1] === null) {
+ nextLanes.pop();
+ nextLaneRefs.pop();
+ }
+ lanes = nextLanes;
+ laneRefs = nextLaneRefs.slice(0, nextLanes.length);
+ }
+ return { rows, laneCount };
+}
diff --git a/apps/desktop/src/lib/tabs/tabPresentation.ts b/apps/desktop/src/lib/tabs/tabPresentation.ts
index 1c463c15ab..52191bcdab 100644
--- a/apps/desktop/src/lib/tabs/tabPresentation.ts
+++ b/apps/desktop/src/lib/tabs/tabPresentation.ts
@@ -134,6 +134,10 @@ export function tabDisplayTitle(tab: QueryTab, t: Translate): string {
if (tab.mode === "mqtt") {
return `${connectionDisplayName(tab.connectionId)} - ${t("connection.mqttConsoleTitle")}`;
}
+ if (tab.mode === "dolt-version-control") {
+ const branch = tab.workspaceBranch?.trim();
+ return `${connectionDisplayName(tab.connectionId)} VCS@${database}${branch ? `.${branch}` : ""}`;
+ }
if (tab.mode === "databases") {
if (compact) return t("tabs.databases");
return `${t("tabs.databases")}@${connectionDisplayName(tab.connectionId)}`;
@@ -452,5 +456,6 @@ export function tabModeLabel(tab: QueryTab, t: Translate): string {
if (tab.mode === "databases") return t("tabs.databases");
if (tab.mode === "objects") return t("tabs.objects");
if (tab.mode === "users") return t("tabs.users");
+ if (tab.mode === "dolt-version-control") return t("doltVersionControl.title");
return tab.mode;
}
diff --git a/apps/desktop/src/stores/__tests__/queryStore.database-open.spec.ts b/apps/desktop/src/stores/__tests__/queryStore.database-open.spec.ts
index c21d77d1f6..c6349dc9ef 100644
--- a/apps/desktop/src/stores/__tests__/queryStore.database-open.spec.ts
+++ b/apps/desktop/src/stores/__tests__/queryStore.database-open.spec.ts
@@ -54,6 +54,32 @@ describe("queryStore database open state", () => {
expect(store.tabs.find((tab) => tab.id === firstId)).toMatchObject({ connectionId: "pg-1", database: "", mode: "databases" });
});
+ it("retargets a connection-scoped driver workspace to a database branch", async () => {
+ const { useQueryStore } = await import("@/stores/queryStore");
+ const store = useQueryStore();
+
+ const firstId = store.openDriverProfileWorkspace("dolt-1", "inventory", "Version Control", "dolt-version-control", "connection");
+ const branchId = store.openDriverProfileWorkspace("dolt-1", "analytics", "Version Control", "dolt-version-control", "connection", "feature/orders");
+
+ expect(branchId).toBe(firstId);
+ expect(store.tabs.find((tab) => tab.id === firstId)).toMatchObject({
+ database: "analytics",
+ workspaceBranch: "feature/orders",
+ mode: "dolt-version-control",
+ });
+ });
+
+ it("keeps database-scoped driver workspaces isolated", async () => {
+ const { useQueryStore } = await import("@/stores/queryStore");
+ const store = useQueryStore();
+
+ const inventoryId = store.openDriverProfileWorkspace("profile-1", "inventory", "Workspace", "dolt-version-control", "database");
+ const analyticsId = store.openDriverProfileWorkspace("profile-1", "analytics", "Workspace", "dolt-version-control", "database");
+
+ expect(analyticsId).not.toBe(inventoryId);
+ expect(store.tabs.filter((tab) => tab.mode === "dolt-version-control")).toHaveLength(2);
+ });
+
it("keeps object browser viewport per tab and clears it on schema change", async () => {
const { useQueryStore } = await import("@/stores/queryStore");
const store = useQueryStore();
diff --git a/apps/desktop/src/stores/queryStore.ts b/apps/desktop/src/stores/queryStore.ts
index adbb399c5e..09a267b4fa 100644
--- a/apps/desktop/src/stores/queryStore.ts
+++ b/apps/desktop/src/stores/queryStore.ts
@@ -77,6 +77,7 @@ import type { SavedSqlFile } from "@/types/database";
import i18n from "@/i18n";
import { translateBackendError } from "@/i18n/backend-errors";
import type { SqlExecutionTargetContext } from "@/lib/database/sqlExecutionTargetRegistry";
+import type { DriverProfileWorkspaceScope } from "@/lib/database/driverProfileExtensions";
import type { MultiDbExecutionTarget, MultiDbResultRunExecution } from "@/types/sqlExecution";
const ORACLE_LIKE_METADATA_TYPES = new Set<string>(["oracle", "dameng", "oceanbase-oracle"]);
@@ -1809,6 +1810,32 @@ export const useQueryStore = defineStore("query", () => {
return id;
}
+ function openDriverProfileWorkspace(connectionId: string, database: string, title: string, mode: QueryTab["mode"], tabScope: DriverProfileWorkspaceScope = "database", workspaceBranch?: string) {
+ const existing = tabs.value.find((tab) => tab.mode === mode && tab.connectionId === connectionId && (tabScope === "connection" || tab.database === database));
+ if (existing) {
+ if (existing.database !== database) updateDatabase(existing.id, database);
+ existing.workspaceBranch = workspaceBranch;
+ switchTab(existing.id);
+ return existing.id;
+ }
+
+ const id = uuid();
+ tabs.value.push({
+ id,
+ title,
+ connectionId,
+ database,
+ workspaceBranch,
+ sql: "",
+ isExecuting: false,
+ isCancelling: false,
+ isExplaining: false,
+ mode,
+ });
+ activeTabId.value = id;
+ return id;
+ }
+
function switchTab(tabId: string) {
activeTabId.value = tabId;
settingsStore.settingsPageActive = false;
@@ -6095,6 +6122,7 @@ export const useQueryStore = defineStore("query", () => {
rollbackTransaction,
renameTab,
openDatabaseBrowser,
+ openDriverProfileWorkspace,
openObjectBrowser,
openMongoGridFs,
openMongoBucket,
diff --git a/apps/desktop/src/types/database.ts b/apps/desktop/src/types/database.ts
index f567b81b60..8b22819cac 100644
--- a/apps/desktop/src/types/database.ts
+++ b/apps/desktop/src/types/database.ts
@@ -1101,6 +1101,8 @@ export interface QueryTab {
forceWordWrap?: boolean;
connectionId: string;
database: string;
+ /** Optional branch context for a driver-profile database workspace. */
+ workspaceBranch?: string;
schema?: string;
/** Doris / StarRocks multi-catalog: the external catalog this tab's
* database belongs to (undefined for internal/default catalog). */
@@ -1206,7 +1208,8 @@ export interface QueryTab {
| "processlist"
| "sqlserver-trace"
| "mysql-dashboard"
- | "postgres-dashboard";
+ | "postgres-dashboard"
+ | "dolt-version-control";
/** Ephemeral navigation intent; it is consumed by HBaseBrowser and is not persisted. */
hbaseCreateTableOnOpen?: boolean;
mqTenant?: string;