Skip to content

Database governance built for humans and agents — controlling changes and access across every major database.

fix: sql editor (#20394)

ecmadao1a5457b4a847
diff --git a/frontend/src/react/components/monaco/MonacoEditor.test.tsx b/frontend/src/react/components/monaco/MonacoEditor.test.tsx
index 233be146ca..46d77c32bb 100644
--- a/frontend/src/react/components/monaco/MonacoEditor.test.tsx
+++ b/frontend/src/react/components/monaco/MonacoEditor.test.tsx
@@ -26,6 +26,7 @@ const mocks = vi.hoisted(() => {
const editor = {
addAction: vi.fn(() => subscription),
createDecorationsCollection: vi.fn(() => ({ clear: vi.fn() })),
+ deltaDecorations: vi.fn(() => []),
dispose: vi.fn(),
focus: vi.fn(),
getContentHeight: vi.fn(() => 120),
diff --git a/frontend/src/react/components/monaco/MonacoEditor.tsx b/frontend/src/react/components/monaco/MonacoEditor.tsx
index e938348bbc..ba35148eb6 100644
--- a/frontend/src/react/components/monaco/MonacoEditor.tsx
+++ b/frontend/src/react/components/monaco/MonacoEditor.tsx
@@ -140,7 +140,12 @@ export function MonacoEditor({
const containerRef = useRef<HTMLDivElement>(null);
const editorRef = useRef<IStandaloneCodeEditor | null>(null);
const modelRef = useRef<ITextModel | null>(null);
- const activeDecorationRef = useRef<{ clear(): void } | null>(null);
+ // Track decoration IDs (not a collection object). `editor.deltaDecorations`
+ // is atomic — swapping IDs replaces or removes decorations in a single
+ // model edit. The previous `createDecorationsCollection().clear()`
+ // approach silently no-op'd in some cases (observed after the model
+ // mutated between ticks), leaving stale highlights on screen.
+ const activeDecorationIdsRef = useRef<string[]>([]);
const contentRef = useRef(safeContent);
const languageRef = useRef(safeLanguage);
const readOnlyRef = useRef(readOnly);
@@ -220,25 +225,28 @@ export function MonacoEditor({
? selection
: resolveActiveRangeByCursor(ranges, cursorPosition);
- activeDecorationRef.current?.clear();
- activeDecorationRef.current = null;
- if (
+ const willDraw = !!(
enableDecorations &&
activeRange &&
(!selection || selection.isEmpty())
- ) {
- activeDecorationRef.current = editor.createDecorationsCollection([
- {
- range: activeRange,
- options: {
- isWholeLine: false,
- shouldFillLineOnLineBreak: true,
- className: "bg-gray-200",
- },
- },
- ]);
- }
-
+ );
+ const nextDecorations =
+ willDraw && activeRange
+ ? [
+ {
+ range: activeRange,
+ options: {
+ isWholeLine: false,
+ shouldFillLineOnLineBreak: true,
+ className: "bg-gray-200",
+ },
+ },
+ ]
+ : [];
+ activeDecorationIdsRef.current = editor.deltaDecorations(
+ activeDecorationIdsRef.current,
+ nextDecorations
+ );
onActiveContentChangeRef.current?.(
activeRange ? model.getValueInRange(activeRange) : ""
);
@@ -399,8 +407,10 @@ export function MonacoEditor({
ws.removeEventListener("message", messageHandler!)
);
}
- activeDecorationRef.current?.clear();
- activeDecorationRef.current = null;
+ if (editorRef.current && activeDecorationIdsRef.current.length > 0) {
+ editorRef.current.deltaDecorations(activeDecorationIdsRef.current, []);
+ }
+ activeDecorationIdsRef.current = [];
if (editorRef.current) {
storeViewState(editorRef.current, modelRef.current);
}
@@ -683,15 +693,27 @@ const resolveActiveRangeByCursor = (
if (!position) return undefined;
for (const range of ranges) {
if (range.endLineNumber < position.lineNumber) continue;
+ if (range.startLineNumber > position.lineNumber) break;
+ // Cursor line is inside [startLine, endLine]. Apply column gates only
+ // at the boundary lines. LSP ranges (and the Monaco conversion used
+ // here) are END-EXCLUSIVE, so `position.column >= range.endColumn` on
+ // the end line means the cursor sits past the last covered position
+ // and is NOT inside the range — e.g. cursor at the start of the
+ // blank line that follows `SELECT 1;\n` was incorrectly matching the
+ // statement range that ends at that exact position.
if (
- range.startLineNumber <= position.lineNumber &&
- range.endLineNumber >= position.lineNumber
+ range.startLineNumber === position.lineNumber &&
+ position.column < range.startColumn
) {
- if (range.endColumn >= position.column) {
- return range;
- }
+ continue;
}
- if (range.startLineNumber > position.lineNumber) break;
+ if (
+ range.endLineNumber === position.lineNumber &&
+ position.column >= range.endColumn
+ ) {
+ continue;
+ }
+ return range;
}
return undefined;
};
@@ -801,7 +823,10 @@ const processStatementRangeMessage = (
endColumn: range.end.character + 1,
}));
ref.current.set(payload.params.uri, ranges);
- } catch {
- // ignore
+ } catch (e) {
+ console.debug("[sql-editor:statementRanges] failed to parse LSP message", {
+ data: message.data,
+ error: e,
+ });
}
};
diff --git a/frontend/src/react/components/sql-editor/TerminalPanel/CompactSQLEditor.tsx b/frontend/src/react/components/sql-editor/TerminalPanel/CompactSQLEditor.tsx
index c9b36c9905..cf59d1c405 100644
--- a/frontend/src/react/components/sql-editor/TerminalPanel/CompactSQLEditor.tsx
+++ b/frontend/src/react/components/sql-editor/TerminalPanel/CompactSQLEditor.tsx
@@ -20,9 +20,8 @@ import { languageOfEngineV1 } from "@/types/sqlEditor/editor";
import { instanceV1AllowsExplain } from "@/utils";
import { sqlEditorEvents } from "@/views/sql-editor/events";
import {
- checkCursorAtFirstLine,
+ checkCursorAtFirst,
checkCursorAtLast,
- checkCursorAtLastLine,
checkIsEnterEndsStatement,
} from "./utils";
@@ -169,13 +168,9 @@ export function CompactSQLEditor({
"cursorAtLast",
checkCursorAtLast(editor)
);
- const cursorAtFirstLine = editor.createContextKey<boolean>(
- "cursorAtFirstLine",
- checkCursorAtFirstLine(editor)
- );
- const cursorAtLastLine = editor.createContextKey<boolean>(
- "cursorAtLastLine",
- checkCursorAtLastLine(editor)
+ const cursorAtFirst = editor.createContextKey<boolean>(
+ "cursorAtFirst",
+ checkCursorAtFirst(editor)
);
const subscriptions: IDisposable[] = [];
@@ -189,8 +184,7 @@ export function CompactSQLEditor({
subscriptions.push(
editor.onDidChangeCursorPosition(() => {
cursorAtLast.set(checkCursorAtLast(editor));
- cursorAtFirstLine.set(checkCursorAtFirstLine(editor));
- cursorAtLastLine.set(checkCursorAtLastLine(editor));
+ cursorAtFirst.set(checkCursorAtFirst(editor));
})
);
@@ -228,15 +222,18 @@ export function CompactSQLEditor({
() => execute(false),
"!readonly && isEnterEndsStatement && cursorAtLast && editorTextFocus && !suggestWidgetVisible && !renameInputVisible && !inSnippetMode && !quickFixWidgetVisible"
);
+ // History only fires at the cursor extremes — beginning of input for
+ // Up, end of input for Down. Inside the buffer the arrows behave as
+ // normal cursor navigation, so multi-line edits aren't trapped.
editor.addCommand(
monaco.KeyCode.UpArrow,
() => propsRef.current.onHistory("up", editor),
- "isTerminalEditor && !readonly && !content && editorTextFocus && !suggestWidgetVisible && !renameInputVisible && !inSnippetMode && !quickFixWidgetVisible"
+ "isTerminalEditor && !readonly && cursorAtFirst && editorTextFocus && !suggestWidgetVisible && !renameInputVisible && !inSnippetMode && !quickFixWidgetVisible"
);
editor.addCommand(
monaco.KeyCode.DownArrow,
() => propsRef.current.onHistory("down", editor),
- "isTerminalEditor && !readonly && cursorAtLastLine && editorTextFocus && !suggestWidgetVisible && !renameInputVisible && !inSnippetMode && !quickFixWidgetVisible"
+ "isTerminalEditor && !readonly && cursorAtLast && editorTextFocus && !suggestWidgetVisible && !renameInputVisible && !inSnippetMode && !quickFixWidgetVisible"
);
// Stash the readonly key so the outer effect can flip it on
diff --git a/frontend/src/react/components/sql-editor/TerminalPanel/useHistory.ts b/frontend/src/react/components/sql-editor/TerminalPanel/useHistory.ts
index e83823af80..489f632646 100644
--- a/frontend/src/react/components/sql-editor/TerminalPanel/useHistory.ts
+++ b/frontend/src/react/components/sql-editor/TerminalPanel/useHistory.ts
@@ -8,17 +8,24 @@ import { minmax } from "@/utils";
const MAX_HISTORY_ITEM_COUNT = 1000;
interface HistoryState {
+ // Position in `list`. `list.length` means "live tail" (no history loaded).
index: number;
+ // Snapshots of FINALIZED query items, captured at the moment a new tail
+ // gets appended (so the captured statement is the one that was actually
+ // executed, not the empty initial value).
list: WebTerminalQueryItemV1[];
}
/**
* React port of `frontend/src/views/sql-editor/EditorPanel/TerminalPanel/useHistory.ts`.
+ *
* Tracks an in-memory command history per ADMIN-mode tab so the up/down
- * arrow keys cycle through previously executed statements (replacing the
- * editor's current statement). Mirrors the Vue composable exactly:
- * push on every new query item, move respecting bounds, clear current
- * statement when stepping past the tail.
+ * arrow keys cycle through previously executed statements. Differs from the
+ * Vue original in HOW it captures snapshots: Vue mutated reactive proxies in
+ * place, so it could safely push the live tail at creation time and read its
+ * statement later. zustand replaces items immutably on every patch, so we
+ * push only when an item is *finalized* (a new tail just got appended,
+ * meaning the prior tail's statement is locked in).
*/
export function useHistory() {
const tabStore = useSQLEditorTabStore();
@@ -27,13 +34,16 @@ export function useHistory() {
);
const historyByTabIdRef = useRef(new Map<string, HistoryState>());
- // The selector returns the (immutable) tail item from zustand; React
- // re-renders whenever the underlying array changes.
const currentTabId = useVueState(() => tabStore.currentTab?.id);
- const currentQuery = useSQLEditorStore((s) => {
+ // Subscribe to the tail item's id. The id changes only when a new tail is
+ // appended (the slice patches statement updates in place by id, preserving
+ // it). Tracking the id — not the list length — lets detection survive
+ // after the list hits its 20-item cap and length stops growing on each
+ // append.
+ const currentTailId = useSQLEditorStore((s) => {
if (!currentTabId) return undefined;
const list = s.webTerminalQueryItemsByTabId[currentTabId];
- return list && list.length > 0 ? list[list.length - 1] : undefined;
+ return list && list.length > 0 ? list[list.length - 1].id : undefined;
});
const currentStack = (): HistoryState | undefined => {
@@ -43,7 +53,7 @@ export function useHistory() {
const map = historyByTabIdRef.current;
const existed = map.get(tab.id);
if (existed) return existed;
- const initial: HistoryState = { index: -1, list: [] };
+ const initial: HistoryState = { index: 0, list: [] };
map.set(tab.id, initial);
return initial;
};
@@ -55,31 +65,45 @@ export function useHistory() {
if (stack.list.length > MAX_HISTORY_ITEM_COUNT) {
stack.list.shift();
}
- stack.index = stack.list.length - 1;
+ // After push, position the cursor "past the tail" so Up goes one back.
+ stack.index = stack.list.length;
};
- // Push the new query item onto the per-tab history only when a new
- // command row is created — not on every keystroke. The Vue original
- // got this for free because `updateWebTerminalQueryItem` mutated the
- // tail in place, so the `computed(() => list[length-1])` kept the
- // same reference across edits. The zustand slice replaces the tail
- // immutably (`{...item, ...patch}`), so the selector returns a new
- // identity on every statement edit; gate on `id` to recover the
- // original semantics.
- const lastPushedIdRef = useRef<string | undefined>(undefined);
+ // Detect a new live tail being appended via tail-id change. When the id
+ // moves to a fresh one, the previous tail (whose id we just rotated off)
+ // is now finalized — its statement is locked in. The finalized item is at
+ // `length - 2` in the current list regardless of whether the list grew or
+ // was capped (cap evicts oldest from the head, so position from the tail
+ // is stable).
+ const lastTabIdRef = useRef<string | undefined>(undefined);
+ const lastSeenTailIdRef = useRef<string | undefined>(undefined);
useEffect(() => {
- if (!currentQuery) return;
- if (currentQuery.id === lastPushedIdRef.current) return;
- lastPushedIdRef.current = currentQuery.id;
- push(currentQuery);
- }, [currentQuery]);
+ if (lastTabIdRef.current !== currentTabId) {
+ lastTabIdRef.current = currentTabId;
+ lastSeenTailIdRef.current = currentTailId;
+ return;
+ }
+ if (currentTailId && currentTailId !== lastSeenTailIdRef.current) {
+ const tab = tabStore.currentTab;
+ if (tab && tab.mode === "ADMIN") {
+ const items =
+ useSQLEditorStore.getState().webTerminalQueryItemsByTabId[tab.id];
+ if (items && items.length >= 2) {
+ const finalized = items[items.length - 2];
+ if (finalized?.statement) push(finalized);
+ }
+ }
+ }
+ lastSeenTailIdRef.current = currentTailId;
+ }, [currentTailId, currentTabId, tabStore]);
const move = (direction: "up" | "down") => {
const stack = currentStack();
if (!stack) return;
const { index, list } = stack;
+ if (list.length === 0) return;
const delta = direction === "up" ? -1 : 1;
- const nextIndex = minmax(index + delta, 0, list.length - 1);
+ const nextIndex = minmax(index + delta, 0, list.length);
if (nextIndex === index) return;
const tab = tabStore.currentTab;
@@ -89,7 +113,8 @@ export function useHistory() {
const tail = tabItems?.[tabItems.length - 1];
if (!tail) return;
- if (nextIndex === list.length - 1) {
+ if (nextIndex === list.length) {
+ // Stepped past the newest entry — back to the live (empty) tail.
updateWebTerminalQueryItem(tab.id, tail.id, { statement: "" });
} else {
const historyQuery = list[nextIndex];
diff --git a/frontend/src/react/components/sql-editor/TerminalPanel/utils.ts b/frontend/src/react/components/sql-editor/TerminalPanel/utils.ts
index 0d8c1f4414..dde360a94a 100644
--- a/frontend/src/react/components/sql-editor/TerminalPanel/utils.ts
+++ b/frontend/src/react/components/sql-editor/TerminalPanel/utils.ts
@@ -33,6 +33,13 @@ export const checkCursorAtLast = (
return false;
};
+export const checkCursorAtFirst = (
+ editor: Editor.IStandaloneCodeEditor
+): boolean => {
+ const cursor = editor.getPosition();
+ return cursor?.lineNumber === 1 && cursor?.column === 1;
+};
+
export const checkCursorAtFirstLine = (
editor: Editor.IStandaloneCodeEditor
): boolean => {