Skip to content

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

fix(sql-editor): restore LSP status tooltip (#20311)

rebelicef2d0347c6c60
diff --git a/frontend/src/react/components/monaco/MonacoEditor.test.tsx b/frontend/src/react/components/monaco/MonacoEditor.test.tsx
new file mode 100644
index 0000000000..233be146ca
--- /dev/null
+++ b/frontend/src/react/components/monaco/MonacoEditor.test.tsx
@@ -0,0 +1,223 @@
+import { readFileSync } from "node:fs";
+import { resolve } from "node:path";
+import { act, createElement } from "react";
+import { createRoot } from "react-dom/client";
+import { beforeEach, describe, expect, test, vi } from "vitest";
+import { MonacoEditor } from "./MonacoEditor";
+
+const mocks = vi.hoisted(() => {
+ const connectionSnapshot = {
+ state: "ready",
+ heartbeat: {
+ counter: 1,
+ timer: undefined,
+ timestamp: 1_714_000_000_000,
+ },
+ };
+ const model = {
+ uri: {
+ toString: () => "file:///test.sql",
+ },
+ getLanguageId: () => "sql",
+ getValue: () => "select 1",
+ getValueInRange: () => "",
+ };
+ const subscription = { dispose: vi.fn() };
+ const editor = {
+ addAction: vi.fn(() => subscription),
+ createDecorationsCollection: vi.fn(() => ({ clear: vi.fn() })),
+ dispose: vi.fn(),
+ focus: vi.fn(),
+ getContentHeight: vi.fn(() => 120),
+ getModel: vi.fn(() => model),
+ getPosition: vi.fn(() => null),
+ getSelection: vi.fn(() => null),
+ getValue: vi.fn(() => "select 1"),
+ onDidChangeCursorPosition: vi.fn(() => subscription),
+ onDidChangeCursorSelection: vi.fn(() => subscription),
+ onDidChangeModel: vi.fn(() => subscription),
+ onDidChangeModelContent: vi.fn(() => subscription),
+ onDidContentSizeChange: vi.fn(() => subscription),
+ setModel: vi.fn(),
+ setValue: vi.fn(),
+ updateOptions: vi.fn(),
+ };
+ return {
+ connectionSnapshot,
+ editor,
+ model,
+ subscription,
+ };
+});
+
+vi.mock("react-i18next", () => ({
+ useTranslation: () => ({
+ t: (key: string, params?: Record<string, string>) => {
+ const translations: Record<string, string> = {
+ "sql-editor.web-socket.connection-status.title": "Language server",
+ "sql-editor.web-socket.connection-status.connected": "connected",
+ "sql-editor.web-socket.connection-status.last-heartbeat":
+ "Last heartbeat at {{time}}",
+ };
+ return (translations[key] ?? key).replace("{{time}}", params?.time ?? "");
+ },
+ }),
+}));
+
+vi.mock("@/react/components/ui/tooltip", () => ({
+ Tooltip: ({
+ children,
+ content,
+ }: {
+ children: React.ReactNode;
+ content: React.ReactNode;
+ }) => (
+ <div data-testid="tooltip">
+ {children}
+ <div data-testid="tooltip-content">{content}</div>
+ </div>
+ ),
+}));
+
+vi.mock("@/types", () => ({
+ UNKNOWN_ID: "UNKNOWN_ID",
+}));
+
+vi.mock("@/utils", () => ({
+ extractDatabaseResourceName: () => ({ databaseName: "db" }),
+ extractInstanceResourceName: () => "instance",
+ formatAbsoluteDateTime: () => "2024-04-25 12:26:40",
+ isDev: () => true,
+}));
+
+vi.mock("@/utils/v1/position", () => ({
+ batchConvertPositionToMonacoPosition: vi.fn(() => []),
+}));
+
+vi.mock("./core", () => ({
+ createMonacoEditor: vi.fn(async () => mocks.editor),
+ getResolvedTheme: vi.fn(() => "vs"),
+ loadMonacoEditor: vi.fn(async () => ({
+ editor: {
+ EditorOption: {
+ readOnly: 1,
+ },
+ setTheme: vi.fn(),
+ TrackedRangeStickiness: {
+ AlwaysGrowsWhenTypingAtEdges: 1,
+ },
+ },
+ KeyCode: {
+ KeyF: 1,
+ },
+ KeyMod: {
+ Alt: 1,
+ Shift: 2,
+ },
+ Range: vi.fn(),
+ })),
+ setMonacoModelLanguage: vi.fn(async () => undefined),
+}));
+
+vi.mock("./lsp-client", () => ({
+ executeCommand: vi.fn(async () => undefined),
+ getConnectionStateSnapshot: vi.fn(() => mocks.connectionSnapshot),
+ getConnectionWebSocket: vi.fn(() => undefined),
+ initializeLSPClient: vi.fn(async () => ({})),
+ subscribeConnectionState: vi.fn(() => () => undefined),
+}));
+
+vi.mock("./suggest-icons", () => ({
+ ensureSuggestOverrideStyle: vi.fn(() => ({ remove: vi.fn() })),
+}));
+
+vi.mock("./text-model", () => ({
+ getOrCreateTextModel: vi.fn(async () => mocks.model),
+ restoreViewState: vi.fn(),
+ storeViewState: vi.fn(),
+}));
+
+vi.mock("./utils", () => ({
+ buildAdviceHoverMessage: vi.fn(() => ""),
+ configureMonacoMessages: vi.fn(),
+ extensionNameOfLanguage: vi.fn(() => "sql"),
+ formatEditorContent: vi.fn(async () => undefined),
+ trySetContentWithUndo: vi.fn(),
+}));
+
+const renderIntoContainer = async (
+ element: ReturnType<typeof createElement>
+) => {
+ const container = document.createElement("div");
+ const root = createRoot(container);
+
+ act(() => {
+ root.render(element);
+ });
+ await new Promise((resolve) => setTimeout(resolve, 0));
+
+ return {
+ container,
+ unmount: () =>
+ act(() => {
+ root.unmount();
+ }),
+ };
+};
+
+beforeEach(() => {
+ vi.clearAllMocks();
+});
+
+describe("MonacoEditor", () => {
+ test("keeps the legacy heartbeat interpolation text", () => {
+ const locale = JSON.parse(
+ readFileSync(resolve("src/react/locales/en-US.json"), "utf-8")
+ ) as {
+ "sql-editor": {
+ "web-socket": {
+ "connection-status": {
+ "last-heartbeat": string;
+ };
+ };
+ };
+ };
+
+ expect(
+ locale["sql-editor"]["web-socket"]["connection-status"]["last-heartbeat"]
+ ).toBe("Last heartbeat at {{time}}");
+ });
+
+ test("shows the LSP connection status tooltip content", async () => {
+ const { container, unmount } = await renderIntoContainer(
+ createElement(MonacoEditor, {
+ content: "select 1",
+ enableDecorations: true,
+ })
+ );
+
+ expect(
+ container.querySelector("[data-testid='tooltip-content']")
+ ).toHaveTextContent("Language server");
+ expect(
+ container.querySelector("[data-testid='tooltip-content']")
+ ).toHaveTextContent("connected");
+ expect(
+ container.querySelector("[data-testid='tooltip-content']")
+ ).toHaveTextContent("Last heartbeat at 2024-04-25 12:26:40");
+
+ unmount();
+ });
+
+ test("hides the LSP connection status tooltip when LSP is disabled", async () => {
+ const { container, unmount } = await renderIntoContainer(
+ createElement(MonacoEditor, {
+ content: "select 1",
+ })
+ );
+
+ expect(container.querySelector("[data-testid='tooltip']")).toBeNull();
+
+ unmount();
+ });
+});
diff --git a/frontend/src/react/components/monaco/MonacoEditor.tsx b/frontend/src/react/components/monaco/MonacoEditor.tsx
index 163965345d..e938348bbc 100644
--- a/frontend/src/react/components/monaco/MonacoEditor.tsx
+++ b/frontend/src/react/components/monaco/MonacoEditor.tsx
@@ -11,6 +11,7 @@ import {
useSyncExternalStore,
} from "react";
import { useTranslation } from "react-i18next";
+import { Tooltip } from "@/react/components/ui/tooltip";
import { cn } from "@/react/lib/utils";
import type { Language, SQLDialect } from "@/types";
import { UNKNOWN_ID } from "@/types";
@@ -18,6 +19,7 @@ import { PositionSchema } from "@/types/proto-es/v1/common_pb";
import {
extractDatabaseResourceName,
extractInstanceResourceName,
+ formatAbsoluteDateTime,
} from "@/utils";
import { batchConvertPositionToMonacoPosition } from "@/utils/v1/position";
import {
@@ -556,6 +558,40 @@ export function MonacoEditor({
}, [autoCompleteContext, readOnly, ready]);
const height = clampMeasuredHeight(contentHeight);
+ let connectionStateText = t(
+ "sql-editor.web-socket.connection-status.disconnected"
+ );
+ if (connection.state === "ready") {
+ connectionStateText = t(
+ "sql-editor.web-socket.connection-status.connected"
+ );
+ } else if (
+ connection.state === "initial" ||
+ connection.state === "reconnecting"
+ ) {
+ connectionStateText = t(
+ "sql-editor.web-socket.connection-status.connecting"
+ );
+ }
+ const connectionHeartbeatText =
+ connection.state === "ready" && connection.heartbeat.timestamp
+ ? t("sql-editor.web-socket.connection-status.last-heartbeat", {
+ time: formatAbsoluteDateTime(connection.heartbeat.timestamp),
+ })
+ : "";
+ const connectionStatusTooltip = (
+ <div className="flex flex-col gap-1">
+ <div className="inline-flex gap-1">
+ <span>{t("sql-editor.web-socket.connection-status.title")}</span>
+ <span>{connectionStateText}</span>
+ </div>
+ {connectionHeartbeatText && (
+ <div className="text-xs text-control-placeholder">
+ {connectionHeartbeatText}
+ </div>
+ )}
+ </div>
+ );
if (initFailed) {
return (
@@ -602,20 +638,22 @@ export function MonacoEditor({
)}
<div className="absolute right-[18px] top-[3px] z-30 flex items-center justify-end gap-1">
{cornerPrefix}
- {ready && !readOnly && (
- <div className="flex h-4 w-4 cursor-default items-center justify-center opacity-60">
- <div
- className={cn(
- "h-3 w-3 rounded-full",
- connection.state === "ready"
- ? "bg-success"
- : connection.state === "initial" ||
- connection.state === "reconnecting"
- ? "bg-warning"
- : "bg-control-placeholder"
- )}
- />
- </div>
+ {ready && !readOnly && shouldEnableLSP && (
+ <Tooltip content={connectionStatusTooltip} side="bottom">
+ <div className="flex h-4 w-4 cursor-pointer items-center justify-center opacity-60 transition-all hover:opacity-100">
+ <div
+ className={cn(
+ "h-3 w-3 rounded-full",
+ connection.state === "ready"
+ ? "bg-success"
+ : connection.state === "initial" ||
+ connection.state === "reconnecting"
+ ? "bg-warning"
+ : "bg-control-placeholder"
+ )}
+ />
+ </div>
+ </Tooltip>
)}
{cornerSuffix}
</div>
diff --git a/frontend/src/react/locales/en-US.json b/frontend/src/react/locales/en-US.json
index c400b3a29a..9a32d549f5 100644
--- a/frontend/src/react/locales/en-US.json
+++ b/frontend/src/react/locales/en-US.json
@@ -2834,6 +2834,13 @@
"view-schema-text": "View schema text",
"visualize-explain": "Visualize Explain",
"web-socket": {
+ "connection-status": {
+ "connected": "connected",
+ "connecting": "connecting",
+ "disconnected": "disconnected",
+ "last-heartbeat": "Last heartbeat at {{time}}",
+ "title": "Language server"
+ },
"errors": {
"description": "Auto Completion might be limited or disabled.",
"disconnected": "WebSocket disconnected",
diff --git a/frontend/src/react/locales/es-ES.json b/frontend/src/react/locales/es-ES.json
index cf1aae2620..58bffb54d2 100644
--- a/frontend/src/react/locales/es-ES.json
+++ b/frontend/src/react/locales/es-ES.json
@@ -2822,6 +2822,13 @@
"view-schema-text": "Ver texto del esquema",
"visualize-explain": "Visualizar explicación",
"web-socket": {
+ "connection-status": {
+ "connected": "conectado",
+ "connecting": "conectando",
+ "disconnected": "desconectado",
+ "last-heartbeat": "Último heartbeat a las {{time}}",
+ "title": "Servidor de lenguaje"
+ },
"errors": {
"description": "Auto Completion might be limited or disabled.",
"disconnected": "WebSocket disconnected",
diff --git a/frontend/src/react/locales/ja-JP.json b/frontend/src/react/locales/ja-JP.json
index 99cdc949de..9a25bdf8de 100644
--- a/frontend/src/react/locales/ja-JP.json
+++ b/frontend/src/react/locales/ja-JP.json
@@ -2822,6 +2822,13 @@
"view-schema-text": "テキストの表示 スキーマ",
"visualize-explain": "視覚化の説明",
"web-socket": {
+ "connection-status": {
+ "connected": "接続済み",
+ "connecting": "接続中",
+ "disconnected": "切断済み",
+ "last-heartbeat": "最終ハートビート {{time}}",
+ "title": "言語サーバー"
+ },
"errors": {
"description": "Auto Completion might be limited or disabled.",
"disconnected": "WebSocket disconnected",
diff --git a/frontend/src/react/locales/vi-VN.json b/frontend/src/react/locales/vi-VN.json
index 5bb65615b4..613ed5fd36 100644
--- a/frontend/src/react/locales/vi-VN.json
+++ b/frontend/src/react/locales/vi-VN.json
@@ -2822,6 +2822,13 @@
"view-schema-text": "Xem văn bản lược đồ",
"visualize-explain": "Trực quan hóa Giải thích",
"web-socket": {
+ "connection-status": {
+ "connected": "đã kết nối",
+ "connecting": "đang kết nối",
+ "disconnected": "đã ngắt kết nối",
+ "last-heartbeat": "Heartbeat gần nhất lúc {{time}}",
+ "title": "Máy chủ ngôn ngữ"
+ },
"errors": {
"description": "Auto Completion might be limited or disabled.",
"disconnected": "WebSocket disconnected",
diff --git a/frontend/src/react/locales/zh-CN.json b/frontend/src/react/locales/zh-CN.json
index 7c97e323e1..67af2e8b11 100644
--- a/frontend/src/react/locales/zh-CN.json
+++ b/frontend/src/react/locales/zh-CN.json
@@ -2822,6 +2822,13 @@
"view-schema-text": "查看文本 Schema",
"visualize-explain": "可视化 Explain",
"web-socket": {
+ "connection-status": {
+ "connected": "已连接",
+ "connecting": "连接中",
+ "disconnected": "已断开",
+ "last-heartbeat": "上次心跳时间 {{time}}",
+ "title": "语言服务器"
+ },
"errors": {
"description": "Auto Completion might be limited or disabled.",
"disconnected": "WebSocket disconnected",