Skip to content

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

chore: optimize access grant item (#21617)

ecmadao04a6fea038e4
diff --git a/frontend/src/locales/en-US.json b/frontend/src/locales/en-US.json
index ff8bd5d1c1..4113f0c818 100644
--- a/frontend/src/locales/en-US.json
+++ b/frontend/src/locales/en-US.json
@@ -359,6 +359,7 @@
"google-chat": "Google Chat",
"group": "Group",
"groups": "Groups",
+ "hide": "Hide",
"history": "History",
"home": "Home",
"id": "ID",
diff --git a/frontend/src/locales/es-ES.json b/frontend/src/locales/es-ES.json
index eff692a47b..1c7496d9df 100644
--- a/frontend/src/locales/es-ES.json
+++ b/frontend/src/locales/es-ES.json
@@ -359,6 +359,7 @@
"google-chat": "Google Chat",
"group": "Grupo",
"groups": "Grupos",
+ "hide": "Ocultar",
"history": "Historial",
"home": "Inicio",
"id": "ID",
diff --git a/frontend/src/locales/ja-JP.json b/frontend/src/locales/ja-JP.json
index 99c85f6f3d..558a56c808 100644
--- a/frontend/src/locales/ja-JP.json
+++ b/frontend/src/locales/ja-JP.json
@@ -359,6 +359,7 @@
"google-chat": "Google Chat",
"group": "グループ",
"groups": "グループ",
+ "hide": "隠す",
"history": "履歴",
"home": "ホームページ",
"id": "ID",
diff --git a/frontend/src/locales/vi-VN.json b/frontend/src/locales/vi-VN.json
index d6b044355b..2838507c9f 100644
--- a/frontend/src/locales/vi-VN.json
+++ b/frontend/src/locales/vi-VN.json
@@ -359,6 +359,7 @@
"google-chat": "Google Chat",
"group": "Nhóm",
"groups": "Nhóm",
+ "hide": "Ẩn",
"history": "Lịch sử",
"home": "Trang chủ",
"id": "ID",
diff --git a/frontend/src/locales/zh-CN.json b/frontend/src/locales/zh-CN.json
index 35999b7dc4..ad54d29c6f 100644
--- a/frontend/src/locales/zh-CN.json
+++ b/frontend/src/locales/zh-CN.json
@@ -359,6 +359,7 @@
"google-chat": "Google Chat",
"group": "组",
"groups": "分组",
+ "hide": "隐藏",
"history": "历史记录",
"home": "主页",
"id": "ID",
diff --git a/frontend/src/modules/sql-editor/components/AccessGrantItem.test.tsx b/frontend/src/modules/sql-editor/components/AccessGrantItem.test.tsx
index 1a2390ad81..26f3481692 100644
--- a/frontend/src/modules/sql-editor/components/AccessGrantItem.test.tsx
+++ b/frontend/src/modules/sql-editor/components/AccessGrantItem.test.tsx
@@ -14,6 +14,12 @@ const mocks = vi.hoisted(() => ({
readStatus: vi.fn(),
getAccessGrantDisplayStatusText: vi.fn(),
getAccessGrantStatusTagType: vi.fn(),
+ batchGetOrFetchDatabases: vi.fn().mockResolvedValue([]),
+}));
+
+vi.mock("@/stores/app", () => ({
+ useAppStore: (selector: (state: unknown) => unknown) =>
+ selector({ batchGetOrFetchDatabases: mocks.batchGetOrFetchDatabases }),
}));
vi.mock("@/components/DatabaseTargetDisplay", () => ({
@@ -71,17 +77,31 @@ vi.mock("@/components/ui/tooltip", () => ({
Tooltip: ({
children,
content,
+ onOpenChange,
}: {
children: React.ReactNode;
content?: React.ReactNode;
+ onOpenChange?: (open: boolean) => void;
}) => (
<span data-testid="tooltip" data-has-content={Boolean(content)}>
{children}
+ {onOpenChange && (
+ <button data-open-tooltip onClick={() => onOpenChange(true)} />
+ )}
</span>
),
}));
vi.mock("@/components/ui/button", () => ({
+ buttonVariants: ({
+ appearance,
+ size,
+ className,
+ }: {
+ appearance?: string;
+ size?: string;
+ className?: string;
+ }) => `button-${appearance}-${size} ${className ?? ""}`,
Button: ({
children,
onClick,
@@ -163,6 +183,7 @@ beforeEach(async () => {
mocks.readStatus.mockReturnValue("ACTIVE");
mocks.getAccessGrantDisplayStatusText.mockReturnValue("Active");
mocks.getAccessGrantStatusTagType.mockReturnValue("success");
+ mocks.batchGetOrFetchDatabases.mockResolvedValue([]);
({ AccessGrantItem } = await import("./AccessGrantItem"));
});
@@ -210,6 +231,67 @@ describe("AccessGrantItem", () => {
unmount();
});
+ test("hydrates remaining targets when their tooltip opens", () => {
+ const grant = makeGrant({
+ targets: [
+ "instances/inst1/databases/db1",
+ "instances/inst2/databases/db2",
+ "instances/inst3/databases/db3",
+ ],
+ });
+ const { container, render, unmount } = renderIntoContainer(
+ <AccessGrantItem
+ grant={grant as never}
+ onRun={vi.fn()}
+ onRequest={vi.fn()}
+ />
+ );
+ render();
+
+ act(() => {
+ container.querySelector<HTMLButtonElement>("[data-open-tooltip]")?.click();
+ });
+
+ expect(mocks.batchGetOrFetchDatabases).toHaveBeenCalledWith(
+ ["instances/inst3/databases/db3"],
+ true
+ );
+ unmount();
+ });
+
+ test("retries remaining target hydration after a failed request", async () => {
+ mocks.batchGetOrFetchDatabases
+ .mockRejectedValueOnce(new Error("temporary failure"))
+ .mockResolvedValueOnce([]);
+ const grant = makeGrant({
+ targets: [
+ "instances/inst1/databases/db1",
+ "instances/inst2/databases/db2",
+ "instances/inst3/databases/db3",
+ ],
+ });
+ const { container, render, unmount } = renderIntoContainer(
+ <AccessGrantItem
+ grant={grant as never}
+ onRun={vi.fn()}
+ onRequest={vi.fn()}
+ />
+ );
+ render();
+
+ const tooltipTrigger = container.querySelector<HTMLButtonElement>(
+ "[data-open-tooltip]"
+ );
+ act(() => tooltipTrigger?.click());
+ await act(async () => {
+ await Promise.resolve();
+ });
+ act(() => tooltipTrigger?.click());
+
+ expect(mocks.batchGetOrFetchDatabases).toHaveBeenCalledTimes(2);
+ unmount();
+ });
+
test("renders status badge with correct label for ACTIVE status", () => {
mocks.readStatus.mockReturnValue("ACTIVE");
mocks.getAccessGrantDisplayStatusText.mockReturnValue("Active");
@@ -254,6 +336,88 @@ describe("AccessGrantItem", () => {
unmount();
});
+ test("expands and hides a visually clamped statement", () => {
+ mocks.useTranslation.mockReturnValue({
+ t: (key: string) =>
+ ({ "common.show-more": "Show more", "common.hide": "Hide" })[
+ key
+ ] ?? key,
+ });
+ const scrollHeight = vi
+ .spyOn(HTMLElement.prototype, "scrollHeight", "get")
+ .mockReturnValue(48);
+ const clientHeight = vi
+ .spyOn(HTMLElement.prototype, "clientHeight", "get")
+ .mockReturnValue(32);
+ const { container, render, unmount } = renderIntoContainer(
+ <AccessGrantItem
+ grant={
+ makeGrant({
+ query: `SELECT /*\n${"x".repeat(200)}`,
+ }) as never
+ }
+ onRun={vi.fn()}
+ onRequest={vi.fn()}
+ />
+ );
+ render();
+
+ const statement = container.querySelector("p");
+ const toggle = Array.from(container.querySelectorAll("button")).find(
+ (button) => button.textContent === "Show more"
+ );
+ expect(toggle).toBeDefined();
+ expect(statement?.className).toContain("line-clamp-2");
+
+ act(() => toggle?.click());
+ expect(toggle?.textContent).toBe("Hide");
+ expect(statement?.className).not.toContain("line-clamp-2");
+
+ act(() => toggle?.click());
+ expect(toggle?.textContent).toBe("Show more");
+ expect(statement?.className).toContain("line-clamp-2");
+ unmount();
+ scrollHeight.mockRestore();
+ clientHeight.mockRestore();
+ });
+
+ test("uses secondary button styling for View issue", () => {
+ const { container, render, unmount } = renderIntoContainer(
+ <AccessGrantItem
+ grant={makeGrant({ issue: "projects/proj1/issues/issue1" }) as never}
+ onRun={vi.fn()}
+ onRequest={vi.fn()}
+ />
+ );
+ render();
+
+ const issueLink = container.querySelector("a");
+ expect(issueLink?.className).toContain("button-secondary-xs");
+ unmount();
+ });
+
+ test("keeps action hover visible when the item is hovered", () => {
+ mocks.readStatus.mockReturnValue("REJECTED");
+ const { container, render, unmount } = renderIntoContainer(
+ <AccessGrantItem
+ grant={
+ makeGrant({ issue: "projects/proj1/issues/issue1" }) as never
+ }
+ onRun={vi.fn()}
+ onRequest={vi.fn()}
+ />
+ );
+ render();
+
+ expect(
+ container.querySelector("[data-re-request-btn]")?.className
+ ).toContain("hover:!bg-control-bg-hover");
+ expect(container.querySelector("a")?.className).toContain(
+ "hover:!bg-control-bg-hover"
+ );
+ unmount();
+ });
+
test("Run button shows only for ACTIVE status", () => {
mocks.readStatus.mockReturnValue("ACTIVE");
const grant = makeGrant();
diff --git a/frontend/src/modules/sql-editor/components/AccessGrantItem.tsx b/frontend/src/modules/sql-editor/components/AccessGrantItem.tsx
index 0b7a6ae7a7..8832ecc863 100644
--- a/frontend/src/modules/sql-editor/components/AccessGrantItem.tsx
+++ b/frontend/src/modules/sql-editor/components/AccessGrantItem.tsx
@@ -1,11 +1,13 @@
+import { useLayoutEffect, useRef, useState } from "react";
import { useTranslation } from "react-i18next";
import { DatabaseTargetDisplay } from "@/components/DatabaseTargetDisplay";
import { RouterLink } from "@/components/RouterLink";
import { Badge } from "@/components/ui/badge";
-import { Button } from "@/components/ui/button";
+import { Button, buttonVariants } from "@/components/ui/button";
import { Tooltip } from "@/components/ui/tooltip";
import { useTimeReading } from "@/hooks/useTimeReading";
import { cn } from "@/lib/utils";
+import { useAppStore } from "@/stores/app";
import type { AccessGrant } from "@/types/proto-es/v1/access_grant_service_pb";
import type { Issue } from "@/types/proto-es/v1/issue_service_pb";
import {
@@ -41,6 +43,33 @@ export function AccessGrantItem({
onRequest,
}: Props) {
const { t } = useTranslation();
+ const batchGetOrFetchDatabases = useAppStore(
+ (state) => state.batchGetOrFetchDatabases
+ );
+ const statementRef = useRef<HTMLParagraphElement>(null);
+ const hydratedRemainingTargets = useRef<string | undefined>(undefined);
+ const [isStatementExpanded, setIsStatementExpanded] = useState(false);
+ const [isStatementTruncated, setIsStatementTruncated] = useState(false);
+
+ useLayoutEffect(() => {
+ setIsStatementExpanded(false);
+ }, [grant.query]);
+
+ useLayoutEffect(() => {
+ if (isStatementExpanded) return;
+ const statement = statementRef.current;
+ if (!statement) return;
+
+ const check = () => {
+ setIsStatementTruncated(statement.scrollHeight > statement.clientHeight);
+ };
+ check();
+ if (typeof ResizeObserver === "undefined") return;
+
+ const observer = new ResizeObserver(check);
+ observer.observe(statement);
+ return () => observer.disconnect();
+ }, [grant.query, isStatementExpanded]);
// Two readings, each on its own boundary. The countdown's last step lands on
// the deadline, the same instant the status turns expired, so the status
@@ -85,6 +114,18 @@ export function AccessGrantItem({
const visibleTargets = grant.targets.slice(0, 2);
const remainingTargetCount = grant.targets.length - visibleTargets.length;
+ const remainingTargets = grant.targets.slice(visibleTargets.length);
+ const handleTargetTooltipOpen = (open: boolean) => {
+ if (!open || remainingTargets.length === 0) return;
+ const targetKey = remainingTargets.join("\u0000");
+ if (hydratedRemainingTargets.current === targetKey) return;
+ hydratedRemainingTargets.current = targetKey;
+ void batchGetOrFetchDatabases(remainingTargets, true).catch(() => {
+ if (hydratedRemainingTargets.current === targetKey) {
+ hydratedRemainingTargets.current = undefined;
+ }
+ });
+ };
const databaseTargets = (
<div className="flex w-full min-w-0 flex-col gap-y-1">
{visibleTargets.map((target, index) => (
@@ -109,7 +150,6 @@ export function AccessGrantItem({
? grant.issue
: `/${grant.issue}`
: "";
-
return (
<div
className={cn(
@@ -153,24 +193,29 @@ export function AccessGrantItem({
)}
</div>
- <Tooltip
- content={
- <pre className="max-w-lg whitespace-pre-wrap text-xs">
- {grant.query}
- </pre>
- }
- side="right"
- >
+ <div className="w-full min-w-0">
<p
+ ref={statementRef}
className={cn(
- "w-full min-w-0 text-xs wrap-anywhere whitespace-pre-wrap font-mono line-clamp-2",
+ "w-full min-w-0 text-xs wrap-anywhere whitespace-pre-wrap font-mono",
+ !isStatementExpanded && "line-clamp-2",
(isExpired || isRejectedOrCanceled) &&
"line-through text-control-placeholder"
)}
>
{grant.query}
</p>
- </Tooltip>
+ {isStatementTruncated && (
+ <Button
+ appearance="link"
+ size="xs"
+ className="h-auto px-0"
+ onClick={() => setIsStatementExpanded((expanded) => !expanded)}
+ >
+ {isStatementExpanded ? t("common.hide") : t("common.show-more")}
+ </Button>
+ )}
+ </div>
<div className="w-full flex flex-col gap-y-2">
{remainingTargetCount === 0 ? (
@@ -189,6 +234,7 @@ export function AccessGrantItem({
</div>
}
side="right"
+ onOpenChange={handleTargetTooltipOpen}
>
{databaseTargets}
</Tooltip>
@@ -215,6 +261,7 @@ export function AccessGrantItem({
<Button
appearance="secondary"
size="xs"
+ className="hover:!bg-control-bg-hover"
data-re-request-btn
onClick={(e) => {
e.stopPropagation();
@@ -230,7 +277,11 @@ export function AccessGrantItem({
target="_blank"
rel="noopener noreferrer"
onClick={(e) => e.stopPropagation()}
- className="inline-flex items-center justify-center h-6 text-xs px-2 rounded-xs hover:bg-control-bg text-control"
+ className={buttonVariants({
+ appearance: "secondary",
+ size: "xs",
+ className: "hover:!bg-control-bg-hover",
+ })}
>
{t("sql-editor.view-issue")}
</RouterLink>
diff --git a/frontend/src/modules/sql-editor/components/AccessPane.test.tsx b/frontend/src/modules/sql-editor/components/AccessPane.test.tsx
index 7fcbd3f4f4..a76c8f7218 100644
--- a/frontend/src/modules/sql-editor/components/AccessPane.test.tsx
+++ b/frontend/src/modules/sql-editor/components/AccessPane.test.tsx
@@ -22,6 +22,7 @@ const mocks = vi.hoisted(() => ({
},
setHighlightAccessGrantName: vi.fn(),
searchMyAccessGrants: vi.fn(),
+ batchGetOrFetchDatabases: vi.fn().mockResolvedValue([]),
fetchDatabases: vi
.fn()
.mockResolvedValue({ databases: [], nextPageToken: "" }),
@@ -50,6 +51,7 @@ vi.mock("@/stores/app", () => ({
useAppStore: (selector: (state: unknown) => unknown) =>
selector({
searchMyAccessGrants: mocks.searchMyAccessGrants,
+ batchGetOrFetchDatabases: mocks.batchGetOrFetchDatabases,
fetchDatabases: mocks.fetchDatabases,
getOrFetchDatabaseByName: mocks.getOrFetchDatabaseByName,
fetchIssueByName: mocks.fetchIssueByName,
@@ -267,6 +269,7 @@ const setupDefaultMocks = () => {
});
mocks.fetchIssueByName.mockResolvedValue({});
+ mocks.batchGetOrFetchDatabases.mockResolvedValue([]);
mocks.fetchDatabases.mockResolvedValue({ databases: [], nextPageToken: "" });
mocks.getOrFetchDatabaseByName.mockResolvedValue({});
@@ -387,6 +390,59 @@ describe("AccessPane", () => {
unmount();
});
+ test("hydrates visible grant targets without delaying the list", async () => {
+ let resolveHydration: (() => void) | undefined;
+ mocks.batchGetOrFetchDatabases.mockImplementation(
+ () =>
+ new Promise<void>((resolve) => {
+ resolveHydration = resolve;
+ })
+ );
+ const grants = [
+ {
+ ...makeGrant("grant1"),
+ targets: [
+ "instances/inst1/databases/db1",
+ "instances/inst1/databases/db2",
+ "instances/inst1/databases/db3",
+ ],
+ },
+ {
+ ...makeGrant("grant2"),
+ targets: [
+ "instances/inst2/databases/db4",
+ "instances/inst2/databases/db5",
+ ],
+ },
+ ];
+ mocks.searchMyAccessGrants.mockResolvedValue({
+ accessGrants: grants,
+ nextPageToken: "",
+ });
+
+ const { container, render, unmount } = renderIntoContainer(<AccessPane />);
+ render();
+
+ await act(async () => {
+ await new Promise((r) => setTimeout(r, 0));
+ });
+
+ expect(
+ container.querySelectorAll("[data-testid='access-grant-item']")
+ ).toHaveLength(2);
+ expect(mocks.batchGetOrFetchDatabases).toHaveBeenCalledWith(
+ [
+ "instances/inst1/databases/db1",
+ "instances/inst1/databases/db2",
+ "instances/inst2/databases/db4",
+ "instances/inst2/databases/db5",
+ ],
+ true
+ );
+ resolveHydration?.();
+ unmount();
+ });
+
test("click Request access grant → drawer opens", async () => {
const { container, render, unmount } = renderIntoContainer(<AccessPane />);
render();
diff --git a/frontend/src/modules/sql-editor/components/AccessPane.tsx b/frontend/src/modules/sql-editor/components/AccessPane.tsx
index 92ead383e4..5b206446f6 100644
--- a/frontend/src/modules/sql-editor/components/AccessPane.tsx
+++ b/frontend/src/modules/sql-editor/components/AccessPane.tsx
@@ -43,6 +43,9 @@ export function AccessPane() {
(state) => state.searchMyAccessGrants
);
const fetchDatabases = useAppStore((state) => state.fetchDatabases);
+ const batchGetOrFetchDatabases = useAppStore(
+ (state) => state.batchGetOrFetchDatabases
+ );
const getOrFetchDatabaseByName = useAppStore(
(state) => state.getOrFetchDatabaseByName
);
@@ -256,12 +259,27 @@ export function AccessPane() {
setAccessGrantList((prev) => [...prev, ...response.accessGrants]);
}
setNextPageToken(response.nextPageToken);
+ const visibleTargets = response.accessGrants.flatMap((grant) =>
+ grant.targets.slice(0, 2)
+ );
+ if (visibleTargets.length > 0) {
+ void batchGetOrFetchDatabases(visibleTargets, true).catch(() => {
+ // The resource path remains a readable fallback for targets that
+ // no longer exist or cannot be loaded.
+ });
+ }
await fetchIssuesForPendingGrants(response.accessGrants);
} finally {
setLoading(false);
}
},
- [projectName, filter, searchMyAccessGrants, fetchIssuesForPendingGrants]
+ [
+ projectName,
+ filter,
+ searchMyAccessGrants,
+ batchGetOrFetchDatabases,
+ fetchIssuesForPendingGrants,
+ ]
);
// Re-fetch when project or filter changes