Database governance built for humans and agents — controlling changes and access across every major database.
Go cicddata-governancedata-maskingdata-securitydatabase-accessdatabase-governancedevopsdevsecopsflywaygitopsliquibasemongodbmysqloraclepostgresqlschema-migrationssecuritysql-clientsqlservertidb
refactor: migrate request JIT drawer and masking reason popover (#20086)
ecmadao57732317d77e
diff --git a/backend/api/v1/masking_evaluator.go b/backend/api/v1/masking_evaluator.goindex 0292cc7c38..dafc6cbb90 100644--- a/backend/api/v1/masking_evaluator.go+++ b/backend/api/v1/masking_evaluator.go@@ -157,11 +157,16 @@ func (m *maskingLevelEvaluator) evaluateGlobalMaskingLevelOfColumn(if pass {semanticTypeID := maskingRule.GetSemanticType()semanticType, ok := m.semanticTypesMap[semanticTypeID]++ ruleTitle := ""+ if maskingRule.Condition != nil && maskingRule.Condition.Title != "" {+ ruleTitle = maskingRule.Condition.Title+ }+ if ruleTitle == "" {+ ruleTitle = maskingRule.Id+ }+if !ok {- ruleTitle := ""- if maskingRule.Condition != nil && maskingRule.Condition.Title != "" {- ruleTitle = maskingRule.Condition.Title- }return &MaskingEvaluation{SemanticTypeID: semanticTypeID,MaskingRuleID: maskingRule.Id,@@ -169,10 +174,7 @@ func (m *maskingLevelEvaluator) evaluateGlobalMaskingLevelOfColumn(ClassificationLevel: classificationLevel,}, nil}- ruleTitle := ""- if maskingRule.Condition != nil && maskingRule.Condition.Title != "" {- ruleTitle = maskingRule.Condition.Title- }+// Get algorithm name from semantic typealgorithmName := getAlgorithmNameFromSemanticType(semanticType)return &MaskingEvaluation{diff --git a/docs/superpowers/specs/2026-04-22-sql-editor-react-migration-stage-10-design.md b/docs/superpowers/specs/2026-04-22-sql-editor-react-migration-stage-10-design.mdnew file mode 100644index 0000000000..1f1476a0dd--- /dev/null+++ b/docs/superpowers/specs/2026-04-22-sql-editor-react-migration-stage-10-design.md@@ -0,0 +1,245 @@+# SQL Editor React Migration — Stage 10 Design++**Date:** 2026-04-22+**Author:** [email protected]+**Status:** Draft++## 1. Goal & non-goals++**Goal:** Fully retire `AccessGrantRequestDrawer.vue` by migrating its 2 remaining Vue callers (`RequestQueryButton.vue` and `MaskingReasonPopover.vue`) to React with full feature parity. This requires building a React `RoleGrantPanel` (since `RequestQueryButton`'s non-JIT flow uses the Vue `RoleGrantPanel`), reusing the existing React `AccessGrantRequestDrawer` (created in Stage 9), and swapping all upstream Vue parents that embed these components.++**Non-goals (Stage 10):**+- Deleting Vue `RoleGrantPanel.vue` — multi-caller pattern, retained for its 4 other Vue callers (`SensitiveData/GrantAccessForm`, `DataExportButton`, `AddProjectMember/AddProjectMemberForm`, `Permission/ComponentPermissionGuard`).+- Deleting Vue `RoleGrantPanel/DatabaseResourceForm/*` — same rationale; React `DatabaseResourceSelector` already exists separately.+- Migrating any other Vue parent (e.g., `VirtualDataBlock`, `ResultViewV1`, `VirtualDataTable`, `DatabaseNode`) — only the 1-line swaps inside them.+- AI plugin bridge, OpenAIButton migration, FolderForm port, TabList migration.+- Refactoring or extracting shared code between the new React `RoleGrantPanel` and the existing `RequestRoleSheet.tsx` (MembersPage flow).++## 2. Architecture++After Stage 9: React `AccessGrantRequestDrawer.tsx` is private to `AccessPane.tsx`. After Stage 10: it remains at the same location (`react/components/sql-editor/AccessGrantRequestDrawer.tsx`) but is also imported by the new React `RequestQueryButton.tsx` and `MaskingReasonPopover.tsx`.++### Component tree++```+[Vue parents — unchanged] [React components]+VirtualDataBlock.vue (Vue) ─► <RequestQueryButton>+ResultViewV1.vue (Vue) ─► <RequestQueryButton>+VirtualDataTable.vue (Vue) ─► <RequestQueryButton>+DatabaseNode.vue (Vue) ─► <RequestQueryButton>+ <MaskingReasonPopover>++[Each React component renders its own children]+RequestQueryButton.tsx ─► RoleGrantPanel.tsx (new)+ OR AccessGrantRequestDrawer.tsx (Stage 9)+MaskingReasonPopover.tsx ─► AccessGrantRequestDrawer.tsx (Stage 9)+AccessPane.tsx (Stage 9) ─► AccessGrantRequestDrawer.tsx (Stage 9)+```++Each Vue parent embeds the React component via `<ReactPageMount page="RequestQueryButton" ... />` etc.++## 3. New React files++### 3.1 `RoleGrantPanel.tsx` (~250 lines)++**Location:** `frontend/src/react/components/sql-editor/RoleGrantPanel.tsx`++(Placed under `sql-editor/` because Stage 10 needs it specifically for the SQL editor request-query flow. If/when the other 4 Vue `RoleGrantPanel` callers migrate, the React version can be lifted to a shared location.)++**Props:**+```tsx+type Props = {+ readonly projectName: string;+ readonly databaseResources: DatabaseResource[];+ readonly placement?: "right" | "bottom" | "top" | "left";+ readonly role: string; // PresetRoleType.SQL_EDITOR_USER for SQL editor flow+ readonly requiredPermissions: Permission[];+ readonly onClose: () => void;+};+```++**Shape:**+- shadcn `Sheet` + `SheetContent` (width="wide" or similar large width)+- Title: `t("issue.title.request-role")`+- Body: form with role select (pre-filled, disabled), database resource selector, expiration picker, reason textarea, issue labels+- Submit creates an issue via `issueServiceClientConnect.createIssue(...)`+- On success: navigate to issue detail page in new tab + close++**Reuses:**+- React `DatabaseResourceSelector` from `@/react/components/DatabaseResourceSelector`+- React `IssueLabelSelect` from `@/react/components/IssueLabelSelect`+- React `RoleSelect` from `@/react/components/RoleSelect` (already exists)+- React `ExpirationPicker` from `@/react/components/ui/expiration-picker`+- shadcn `Sheet`, `Textarea`, `Button`+- `issueServiceClientConnect` from `@/connect`+- `useCurrentUserV1`, `useProjectV1Store`, `pushNotification` from `@/store`++**Mirrors Vue source's:**+- Issue creation logic (CEL expression building, time-bounded role, etc.)+- Project's `enforceIssueTitle` flag enforcement+- `requiredPermissions` propagation++### 3.2 `RequestQueryButton.tsx` (~140 lines)++**Location:** `frontend/src/react/components/sql-editor/RequestQueryButton.tsx`++**Props:**+```tsx+type Props = {+ readonly size?: "sm" | "default";+ readonly text: boolean;+ readonly statement?: string;+ readonly permissionDeniedDetail: PermissionDeniedDetail;+};+```++**Shape:**+- Uses `usePermissionCheck(["bb.accessGrants.create" | "bb.issues.create"], project)` based on JIT detection+- Conditional rendering of Button + state-managed drawer/panel+- JIT flow → opens `<AccessGrantRequestDrawer>` with pre-filled query + targets+- Non-JIT flow → opens `<RoleGrantPanel>` with `role=SQL_EDITOR_USER` + missing resources + required permissions++**Reuses:**+- `AccessGrantRequestDrawer` from `./AccessGrantRequestDrawer`+- `RoleGrantPanel` from `./RoleGrantPanel`+- `FeatureBadge` from `@/react/components/FeatureBadge`+- `PermissionGuard` from `@/react/components/PermissionGuard`+- `useVueState` for `useSQLEditorStore.project`, `useProjectV1Store.getProjectByName`+- `parseStringToResource` from `@/components/RoleGrantPanel/DatabaseResourceForm/common` (shared utility — verify it works in React; it should be pure)++### 3.3 `MaskingReasonPopover.tsx` (~140 lines)++**Location:** `frontend/src/react/components/sql-editor/MaskingReasonPopover.tsx`++**Props:**+```tsx+type Props = {+ readonly reason: MaskingReason;+ readonly statement?: string;+ readonly database?: string;+ readonly onClick?: () => void;+};+```++**Shape:**+- Uses Stage 6 `Popover` primitive with hover trigger+- Trigger: small `EyeOff` icon + optional semantic-type icon+- Content: title, semantic type, algorithm, context, classification level, optional "Request JIT" button+- "Request JIT" button → opens `<AccessGrantRequestDrawer>` with pre-filled query + targets + `unmask=true`++**Reuses:**+- `AccessGrantRequestDrawer` from `./AccessGrantRequestDrawer`+- Stage 6 `Popover` primitive+- `useVueState` for project store + JIT feature check++### 3.4 Test files (one per component)++3 new test files; ~3-5 tests each. Mock pattern follows existing sql-editor tests.++## 4. Vue caller swaps++5 Vue parent files will have 1-line `<RequestQueryButton>` or `<MaskingReasonPopover>` swap to `<ReactPageMount page="..." ... />`:++### 4.1 `EditorCommon/ResultView/VirtualDataBlock.vue`+Find `<RequestQueryButton ... />`. Replace with `<ReactPageMount page="RequestQueryButton" :size :text :statement :permissionDeniedDetail />`. Drop the Vue import.++### 4.2 `EditorCommon/ResultView/ResultViewV1.vue`+Same pattern — find Vue usage, swap to ReactPageMount, drop import.++### 4.3 `EditorCommon/ResultView/DataTable/VirtualDataTable.vue`+Same.++### 4.4 `ConnectionPanel/ConnectionPane/TreeNode/DatabaseNode.vue`+Same — has `<RequestQueryButton>` and possibly `<MaskingReasonPopover>` (verify both during implementation).++### 4.5 Any additional callers — verify via grep++The 5 files above came from earlier audits. Implementer must `rg "RequestQueryButton|MaskingReasonPopover"` first to confirm the complete caller list and adjust scope if a 6th caller surfaces.++## 5. Vue file deletions++After all caller swaps verified:++- `frontend/src/views/sql-editor/EditorCommon/ResultView/RequestQueryButton.vue`+- `frontend/src/views/sql-editor/EditorCommon/ResultView/DataTable/common/MaskingReasonPopover.vue`+- `frontend/src/views/sql-editor/AsidePanel/AccessPane/AccessGrantRequestDrawer.vue`++Verify zero remaining callers of each via `rg` before deleting. The `AsidePanel/AccessPane/` directory will then be fully empty (its `index.ts` was deleted in Stage 9, `AccessPane.vue` and `AccessGrantItem.vue` already deleted in Stage 9). Remove the directory entirely.++**Retained Vue files** (multi-caller, out of scope for deletion):+- `components/RoleGrantPanel/RoleGrantPanel.vue` — 4 other callers+- `components/RoleGrantPanel/DatabaseResourceForm/*` — used by Vue RoleGrantPanel and others+- `components/RoleGrantPanel/MaxRowCountSelect.vue` — used by Vue RoleGrantPanel and others (React port already exists from Stage 6)++## 6. i18n keys++Verify in all 5 React locales; add missing using byte-exact Vue values; convert `{var}` → `{{var}}`:++For `RoleGrantPanel`:+- `issue.title.request-role`+- `common.cancel`, `common.submit`, `common.reason`+- (other keys depending on form fields — implementer audits during implementation)++For `RequestQueryButton`:+- `sql-editor.request-jit`+- `sql-editor.request-query`++For `MaskingReasonPopover`:+- `masking.reason.title`+- `masking.reason.semantic-type`+- `masking.reason.algorithm`+- `masking.reason.context`+- `masking.reason.classification`+- `sql-editor.request-jit` (shared with RequestQueryButton)+- `masking.algorithms.*` (template-style — `formatAlgorithm` in Vue does dynamic key lookup; check if these are in React `dynamic.*` keys or static. May require fallback handling.)++## 7. Verification++### 7.1 Per-stage++- `pnpm fix && check && type-check && test` all green+- ~10-15 new tests across 3 component test files+- No regressions++### 7.2 Manual UX++For RequestQueryButton (mounted via VirtualDataBlock / ResultViewV1 / VirtualDataTable / DatabaseNode):+1. Run a query with insufficient permissions → "Request Query" button appears in error result+2. Click → if project allows JIT and only `bb.sql.select` is missing → AccessGrantRequestDrawer opens with statement + missing databases pre-filled+3. Click in non-JIT scenario → RoleGrantPanel opens with role=SQL_EDITOR_USER + missing resources + required permissions pre-filled+4. Submit either flow → success notification + drawer closes++For MaskingReasonPopover (mounted via DatabaseNode):+5. Hover masked column → popover shows masking reason details+6. If JIT available and statement present → "Request JIT" button → drawer opens with `unmask=true`++For AccessPane (Stage 9, already React):+7. Click Run on grant — still works (uses execute-sql event bridge)++### 7.3 Bridge integrity++Test that the "Request" buttons inside still-Vue ResultView and ConnectionPane work end-to-end:+- Permission denied → button shown+- Click → drawer/panel opens+- Submit → API call succeeds+- Drawer closes properly++## 8. Practical checklist++- [ ] React `RoleGrantPanel.tsx` + test+- [ ] React `RequestQueryButton.tsx` + test+- [ ] React `MaskingReasonPopover.tsx` + test+- [ ] i18n keys verified/added (with `{var}` → `{{var}}` conversion as needed)+- [ ] 5 Vue caller files swapped (`VirtualDataBlock.vue`, `ResultViewV1.vue`, `VirtualDataTable.vue`, `DatabaseNode.vue` for RequestQueryButton; `DatabaseNode.vue` for MaskingReasonPopover — verify caller list during implementation)+- [ ] Vue `RequestQueryButton.vue` deleted+- [ ] Vue `MaskingReasonPopover.vue` deleted+- [ ] Vue `AccessGrantRequestDrawer.vue` deleted (and the now-empty `AsidePanel/AccessPane/` directory)+- [ ] Vue `RoleGrantPanel.vue` retained (4 other callers)+- [ ] `pnpm fix && check && type-check && test` all pass+- [ ] Manual UX from §7.2 verified++## 9. Out of scope (deferred)++- Migrating Vue `RoleGrantPanel.vue` and its DatabaseResourceForm subtree — multi-caller, requires future stage targeting all 4 remaining Vue callers (SensitiveData/GrantAccessForm, DataExportButton, AddProjectMember/AddProjectMemberForm, Permission/ComponentPermissionGuard)+- Refactoring shared code between React `RoleGrantPanel` and `RequestRoleSheet.tsx` — both create issues with similar shape; extraction risks scope creep into MembersPage flow+- Vue parent migrations (`VirtualDataBlock`, `ResultViewV1`, `VirtualDataTable`, `DatabaseNode`) — only the inline embedding lines changediff --git a/frontend/src/react/components/sql-editor/AccessPane.tsx b/frontend/src/react/components/sql-editor/AccessPane.tsxindex d66e8e2cff..34bf4e3195 100644--- a/frontend/src/react/components/sql-editor/AccessPane.tsx+++ b/frontend/src/react/components/sql-editor/AccessPane.tsx@@ -85,11 +85,7 @@ export function AccessPane() {return projectStore.getProjectByName(projectName as string);}, [projectStore, projectName]);- const hasJITFeature = useMemo(- () => hasFeature(PlanFeature.FEATURE_JIT),- // biome-ignore lint/correctness/useExhaustiveDependencies: intentional subset dep list- []- );+ const hasJITFeature = useMemo(() => hasFeature(PlanFeature.FEATURE_JIT), []);// Build scope options for AdvancedSearch (React-compatible, no Vue renderers)const scopeOptions = useMemo((): ScopeOption[] => {@@ -218,14 +214,12 @@ export function AccessPane() {setLoading(false);}},- // biome-ignore lint/correctness/useExhaustiveDependencies: intentional subset dep list[projectName, filter, accessGrantStore, fetchIssuesForPendingGrants]);// Re-fetch when project or filter changesuseEffect(() => {void fetchAccessGrants(true);- // biome-ignore lint/correctness/useExhaustiveDependencies: intentional subset dep list}, [projectName, filter]);// Re-fetch + clear highlight when highlightAccessGrantName changes@@ -239,7 +233,6 @@ export function AccessPane() {}}, 3000);return () => clearTimeout(timer);- // biome-ignore lint/correctness/useExhaustiveDependencies: intentional subset dep list}, [highlightAccessGrantName]);// Responsive small layout detectiondiff --git a/frontend/src/react/components/sql-editor/ContainerChooser.tsx b/frontend/src/react/components/sql-editor/ContainerChooser.tsxindex 26d5c49175..1b091a7e45 100644--- a/frontend/src/react/components/sql-editor/ContainerChooser.tsx+++ b/frontend/src/react/components/sql-editor/ContainerChooser.tsx@@ -65,9 +65,6 @@ export function ContainerChooser() {() => router.currentRoute.value.query.table as string | undefined);const currentTabId = useVueState(() => tabStore.currentTab?.id);- // biome-ignore lint/correctness/useExhaustiveDependencies: handleChange is- // defined inline and reads the live tabStore; omitting it is intentional- // so the effect re-runs only on queryParam or tab switch.useEffect(() => {if (queryParam) handleChange(queryParam);}, [queryParam, currentTabId]);diff --git a/frontend/src/react/components/sql-editor/HistoryPane.tsx b/frontend/src/react/components/sql-editor/HistoryPane.tsxindex 4a8191aca9..8ff49a29ef 100644--- a/frontend/src/react/components/sql-editor/HistoryPane.tsx+++ b/frontend/src/react/components/sql-editor/HistoryPane.tsx@@ -68,8 +68,6 @@ export function HistoryPane() {return () => {if (searchTimerRef.current) clearTimeout(searchTimerRef.current);};- // Intentionally only historyQuery in deps — fetchHistory is stable for the current query- // biome-ignore lint/correctness/useExhaustiveDependencies: intentional subset dep list}, [historyQuery]);const onSearchUpdate = useCallback(@@ -159,7 +157,6 @@ export function HistoryPane() {</div><pclassName="max-w-full text-xs wrap-break-word font-mono line-clamp-3"- // biome-ignore lint/security/noDangerouslySetInnerHtml: utility returns pre-escaped HTML with highlight markupdangerouslySetInnerHTML={{__html: getHighlightHTMLByKeyWords(history.statement,diff --git a/frontend/src/react/components/sql-editor/MaskingReasonPopover.test.tsx b/frontend/src/react/components/sql-editor/MaskingReasonPopover.test.tsxnew file mode 100644index 0000000000..2066e85b5f--- /dev/null+++ b/frontend/src/react/components/sql-editor/MaskingReasonPopover.test.tsx@@ -0,0 +1,259 @@+import type { ReactElement } from "react";+import { act } from "react";+import { createRoot } from "react-dom/client";+import { afterEach, beforeEach, describe, expect, test, vi } from "vitest";++(+ globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }+).IS_REACT_ACT_ENVIRONMENT = true;++const mocks = vi.hoisted(() => ({+ useTranslation: vi.fn(() => ({ t: (key: string) => key })),+ useVueState: vi.fn<(getter: () => unknown) => unknown>(),+ useProjectV1Store: vi.fn(),+ useSQLEditorStore: vi.fn(),+ hasFeature: vi.fn(() => true),+}));++vi.mock("react-i18next", () => ({+ useTranslation: mocks.useTranslation,+}));++vi.mock("@/react/hooks/useVueState", () => ({+ useVueState: mocks.useVueState,+}));++vi.mock("@/store", () => ({+ useProjectV1Store: mocks.useProjectV1Store,+ useSQLEditorStore: mocks.useSQLEditorStore,+ hasFeature: mocks.hasFeature,+}));++vi.mock("@/types/proto-es/v1/subscription_service_pb", () => ({+ PlanFeature: { FEATURE_JIT: 5 },+}));++vi.mock("@/react/components/ui/button", () => ({+ Button: ({+ children,+ onClick,+ disabled,+ }: {+ children: React.ReactNode;+ onClick?: () => void;+ disabled?: boolean;+ }) => (+ <button disabled={disabled} onClick={onClick} data-testid="jit-button">+ {children}+ </button>+ ),+}));++vi.mock("@/react/components/ui/popover", () => ({+ Popover: ({ children }: { children: React.ReactNode }) => (+ <div data-testid="popover-root">{children}</div>+ ),+ PopoverTrigger: ({+ render: renderProp,+ openOnHover,+ delay,+ }: {+ render?: React.ReactElement;+ openOnHover?: boolean;+ delay?: number;+ }) => (+ <div+ data-testid="popover-trigger"+ data-open-on-hover={String(openOnHover ?? false)}+ data-delay={delay}+ >+ {renderProp}+ </div>+ ),+ PopoverContent: ({ children }: { children: React.ReactNode }) => (+ <div data-testid="popover-content">{children}</div>+ ),+}));++vi.mock("./AccessGrantRequestDrawer", () => ({+ AccessGrantRequestDrawer: ({+ onClose,+ unmask,+ }: {+ onClose: () => void;+ unmask?: boolean;+ }) => (+ <div data-testid="access-grant-drawer" data-unmask={String(unmask)}>+ <button data-close-btn onClick={onClose}>+ Close+ </button>+ </div>+ ),+}));++// Stub ResizeObserver+globalThis.ResizeObserver = class ResizeObserver {+ observe() {}+ unobserve() {}+ disconnect() {}+};++let MaskingReasonPopover: typeof import("./MaskingReasonPopover").MaskingReasonPopover;++const renderIntoContainer = (element: ReactElement) => {+ const container = document.createElement("div");+ const root = createRoot(container);+ document.body.appendChild(container);+ return {+ container,+ render: () => {+ act(() => {+ root.render(element);+ });+ },+ unmount: () => {+ act(() => {+ root.unmount();+ });+ container.remove();+ },+ };+};++const makeReason = (overrides?: {+ semanticTypeIcon?: string;+ semanticTypeTitle?: string;+ algorithm?: string;+ context?: string;+ classificationLevel?: string;+}) =>+ ({+ semanticTypeIcon: overrides?.semanticTypeIcon ?? "",+ semanticTypeTitle: overrides?.semanticTypeTitle ?? "",+ algorithm: overrides?.algorithm ?? "",+ context: overrides?.context ?? "",+ classificationLevel: overrides?.classificationLevel ?? "",+ }) as unknown as import("@/types/proto-es/v1/sql_service_pb").MaskingReason;++const setupDefaultMocks = (allowJIT = false) => {+ mocks.useTranslation.mockReturnValue({ t: (key: string) => key });+ mocks.useProjectV1Store.mockReturnValue({+ getProjectByName: vi.fn(() => ({+ name: "projects/proj1",+ allowJustInTimeAccess: allowJIT,+ })),+ });+ mocks.useSQLEditorStore.mockReturnValue({ project: "projects/proj1" });+ mocks.hasFeature.mockReturnValue(true);+ mocks.useVueState.mockImplementation((getter: () => unknown) => getter());+};++beforeEach(async () => {+ vi.clearAllMocks();+ setupDefaultMocks();+ ({ MaskingReasonPopover } = await import("./MaskingReasonPopover"));+});++afterEach(() => {+ document.body.innerHTML = "";+});++describe("MaskingReasonPopover", () => {+ test("renders popover trigger with eye-off icon", () => {+ const { container, render, unmount } = renderIntoContainer(+ <MaskingReasonPopover reason={makeReason()} />+ );+ render();++ // Trigger should be present+ expect(+ container.querySelector("[data-testid='popover-trigger']")+ ).not.toBeNull();+ unmount();+ });++ test("popover trigger has openOnHover enabled with 100ms delay", () => {+ const { container, render, unmount } = renderIntoContainer(+ <MaskingReasonPopover reason={makeReason()} />+ );+ render();++ const trigger = container.querySelector("[data-testid='popover-trigger']");+ expect(trigger).not.toBeNull();+ expect(trigger?.getAttribute("data-open-on-hover")).toBe("true");+ expect(trigger?.getAttribute("data-delay")).toBe("100");+ unmount();+ });++ test("shows masking reason title in popover content", () => {+ const { container, render, unmount } = renderIntoContainer(+ <MaskingReasonPopover reason={makeReason()} />+ );+ render();++ const content = container.querySelector("[data-testid='popover-content']");+ expect(content?.textContent).toContain("masking.reason.title");+ unmount();+ });++ test("shows semantic type when provided", () => {+ const { container, render, unmount } = renderIntoContainer(+ <MaskingReasonPopover+ reason={makeReason({ semanticTypeTitle: "Email" })}+ />+ );+ render();++ expect(container.textContent).toContain("Email");+ expect(container.textContent).toContain("masking.reason.semantic-type");+ unmount();+ });++ test("does not show request-jit button when JIT not available", () => {+ setupDefaultMocks(false);+ const { container, render, unmount } = renderIntoContainer(+ <MaskingReasonPopover reason={makeReason()} statement="SELECT * FROM t" />+ );+ render();++ const buttons = container.querySelectorAll("[data-testid='jit-button']");+ const jitBtn = Array.from(buttons).find((b) =>+ b.textContent?.includes("sql-editor.request-jit")+ );+ expect(jitBtn).toBeUndefined();+ unmount();+ });++ test("shows request-jit button and opens drawer when JIT available and statement provided", async () => {+ setupDefaultMocks(true);+ const { container, render, unmount } = renderIntoContainer(+ <MaskingReasonPopover+ reason={makeReason()}+ statement="SELECT * FROM t"+ database="instances/inst1/databases/db1"+ />+ );+ render();++ expect(+ container.querySelector("[data-testid='access-grant-drawer']")+ ).toBeNull();++ const jitBtn = container.querySelector(+ "[data-testid='jit-button']"+ ) as HTMLButtonElement;+ expect(jitBtn).not.toBeNull();+ expect(jitBtn.textContent).toContain("sql-editor.request-jit");++ await act(async () => {+ jitBtn.click();+ });++ const drawer = container.querySelector(+ "[data-testid='access-grant-drawer']"+ );+ expect(drawer).not.toBeNull();+ expect(drawer?.getAttribute("data-unmask")).toBe("true");+ unmount();+ });+});diff --git a/frontend/src/react/components/sql-editor/MaskingReasonPopover.tsx b/frontend/src/react/components/sql-editor/MaskingReasonPopover.tsxnew file mode 100644index 0000000000..3b36a7c3f3--- /dev/null+++ b/frontend/src/react/components/sql-editor/MaskingReasonPopover.tsx@@ -0,0 +1,161 @@+import { EyeOff } from "lucide-react";+import { useMemo, useState } from "react";+import { useTranslation } from "react-i18next";+import { Button } from "@/react/components/ui/button";+import {+ Popover,+ PopoverContent,+ PopoverTrigger,+} from "@/react/components/ui/popover";+import { useVueState } from "@/react/hooks/useVueState";+import { hasFeature, useProjectV1Store, useSQLEditorStore } from "@/store";+import type { MaskingReason } from "@/types/proto-es/v1/sql_service_pb";+import { PlanFeature } from "@/types/proto-es/v1/subscription_service_pb";+import { AccessGrantRequestDrawer } from "./AccessGrantRequestDrawer";++interface Props {+ readonly reason: MaskingReason;+ readonly statement?: string;+ readonly database?: string;+ readonly onClick?: () => void;+}++export function MaskingReasonPopover({+ reason,+ statement,+ database,+ onClick,+}: Props) {+ const { t } = useTranslation();+ const [showDrawer, setShowDrawer] = useState(false);++ const projectStore = useProjectV1Store();+ const editorStore = useSQLEditorStore();++ const projectName = useVueState(() => editorStore.project);+ const project = useVueState(() => projectStore.getProjectByName(projectName));++ const hasJITFeature = useMemo(+ () =>+ !!project?.allowJustInTimeAccess && hasFeature(PlanFeature.FEATURE_JIT),+ [project]+ );++ const targets = useMemo(() => (database ? [database] : []), [database]);++ const formatAlgorithm = (algorithm: string): string => {+ const algorithmKey = algorithm.toLowerCase().replace(/\s+/g, "-");+ const key = `masking.algorithms.${algorithmKey}`;+ const translated = t(key);+ if (translated === key) {+ return algorithm;+ }+ return translated;+ };++ const handleTriggerClick = () => {+ onClick?.();+ };++ return (+ <>+ <Popover>+ <PopoverTrigger+ openOnHover+ delay={100}+ render={+ <div className="inline-flex items-center gap-0.5 cursor-pointer">+ {reason.semanticTypeIcon && (+ <img+ src={reason.semanticTypeIcon}+ className="size-3 object-contain"+ alt=""+ />+ )}+ <EyeOff+ className="size-3 text-control-placeholder hover:text-control"+ onClick={handleTriggerClick}+ />+ </div>+ }+ />+ <PopoverContent+ side="bottom"+ align="start"+ className="min-w-80 max-w-md"+ >+ <div className="w-full flex flex-col gap-y-2">+ <div className="font-medium flex items-center gap-2">+ {reason.semanticTypeIcon && (+ <img+ src={reason.semanticTypeIcon}+ className="size-4 object-contain"+ alt=""+ />+ )}+ {t("masking.reason.title")}+ </div>++ {reason.semanticTypeTitle && (+ <div className="text-sm">+ <span className="text-control-placeholder">+ {t("masking.reason.semantic-type")}:+ </span>+ <span className="ml-1">{reason.semanticTypeTitle}</span>+ </div>+ )}++ {reason.algorithm && (+ <div className="text-sm">+ <span className="text-control-placeholder">+ {t("masking.reason.algorithm")}:+ </span>+ <span className="ml-1">+ {formatAlgorithm(reason.algorithm)}+ </span>+ </div>+ )}++ {reason.context && (+ <div className="text-sm">+ <span className="text-control-placeholder">+ {t("masking.reason.context")}:+ </span>+ <span className="ml-1">{reason.context}</span>+ </div>+ )}++ {!!reason.classificationLevel && (+ <div className="text-sm">+ <span className="text-control-placeholder">+ {t("masking.reason.classification")}:+ </span>+ <span className="ml-1">{reason.classificationLevel}</span>+ </div>+ )}++ {hasJITFeature && statement && (+ <Button+ size="sm"+ variant="default"+ className="self-start"+ onClick={() => setShowDrawer(true)}+ >+ {t("sql-editor.request-jit")}+ </Button>+ )}+ </div>+ </PopoverContent>+ </Popover>++ {showDrawer && (+ <AccessGrantRequestDrawer+ query={statement}+ targets={targets}+ unmask={true}+ onClose={() => setShowDrawer(false)}+ />+ )}+ </>+ );+}diff --git a/frontend/src/react/components/sql-editor/RequestQueryButton.test.tsx b/frontend/src/react/components/sql-editor/RequestQueryButton.test.tsxnew file mode 100644index 0000000000..ce8fc277d6--- /dev/null+++ b/frontend/src/react/components/sql-editor/RequestQueryButton.test.tsx@@ -0,0 +1,263 @@+import type { ReactElement } from "react";+import { act } from "react";+import { createRoot } from "react-dom/client";+import { afterEach, beforeEach, describe, expect, test, vi } from "vitest";++(+ globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }+).IS_REACT_ACT_ENVIRONMENT = true;++const mocks = vi.hoisted(() => ({+ useTranslation: vi.fn(() => ({ t: (key: string) => key })),+ useVueState: vi.fn<(getter: () => unknown) => unknown>(),+ useProjectV1Store: vi.fn(),+ useSQLEditorStore: vi.fn(),+ hasFeature: vi.fn(() => true),+ parseStringToResource: vi.fn((s: string) => ({+ databaseFullName: s,+ databaseName: s,+ })),+}));++vi.mock("react-i18next", () => ({+ useTranslation: mocks.useTranslation,+}));++vi.mock("@/react/hooks/useVueState", () => ({+ useVueState: mocks.useVueState,+}));++vi.mock("@/store", () => ({+ useProjectV1Store: mocks.useProjectV1Store,+ useSQLEditorStore: mocks.useSQLEditorStore,+ hasFeature: mocks.hasFeature,+}));++vi.mock("@/components/RoleGrantPanel/DatabaseResourceForm/common", () => ({+ parseStringToResource: mocks.parseStringToResource,+}));++vi.mock("@/types", () => ({+ PresetRoleType: { SQL_EDITOR_USER: "roles/sqlEditorUser" },+}));++vi.mock("@/types/proto-es/v1/subscription_service_pb", () => ({+ PlanFeature: {+ FEATURE_JIT: 5,+ FEATURE_REQUEST_ROLE_WORKFLOW: 6,+ },+}));++vi.mock("@/react/components/FeatureBadge", () => ({+ FeatureBadge: () => <span data-testid="feature-badge" />,+}));++vi.mock("@/react/components/PermissionGuard", () => ({+ PermissionGuard: ({+ children,+ }: {+ children: (props: { disabled: boolean }) => React.ReactNode;+ }) => <>{children({ disabled: false })}</>,+}));++vi.mock("@/react/components/ui/button", () => ({+ Button: ({+ children,+ onClick,+ disabled,+ ...rest+ }: {+ children: React.ReactNode;+ onClick?: (e: React.MouseEvent) => void;+ disabled?: boolean;+ [key: string]: unknown;+ }) => (+ <button disabled={disabled} onClick={onClick as () => void} {...rest}>+ {children}+ </button>+ ),+}));++vi.mock("./RoleGrantPanel", () => ({+ RoleGrantPanel: ({ onClose }: { onClose: () => void }) => (+ <div data-testid="role-grant-panel">+ <button data-close-btn onClick={onClose}>+ Close+ </button>+ </div>+ ),+}));++vi.mock("./AccessGrantRequestDrawer", () => ({+ AccessGrantRequestDrawer: ({ onClose }: { onClose: () => void }) => (+ <div data-testid="access-grant-drawer">+ <button data-close-btn onClick={onClose}>+ Close+ </button>+ </div>+ ),+}));++// Stub ResizeObserver+globalThis.ResizeObserver = class ResizeObserver {+ observe() {}+ unobserve() {}+ disconnect() {}+};++let RequestQueryButton: typeof import("./RequestQueryButton").RequestQueryButton;++const renderIntoContainer = (element: ReactElement) => {+ const container = document.createElement("div");+ const root = createRoot(container);+ document.body.appendChild(container);+ return {+ container,+ render: () => {+ act(() => {+ root.render(element);+ });+ },+ unmount: () => {+ act(() => {+ root.unmount();+ });+ container.remove();+ },+ };+};++const makePermissionDeniedDetail = (overrides?: {+ allowJustInTimeAccess?: boolean;+ requiredPermissions?: string[];+ resources?: string[];+}) =>+ ({+ requiredPermissions: overrides?.requiredPermissions ?? ["bb.sql.select"],+ resources: overrides?.resources ?? ["instances/inst1/databases/db1"],+ }) as unknown as import("@/types/proto-es/v1/common_pb").PermissionDeniedDetail;++const setupDefaultMocks = (allowJIT = false, allowRequestRole = true) => {+ mocks.useTranslation.mockReturnValue({ t: (key: string) => key });+ mocks.useProjectV1Store.mockReturnValue({+ getProjectByName: vi.fn(() => ({+ name: "projects/proj1",+ allowJustInTimeAccess: allowJIT,+ allowRequestRole,+ })),+ });+ mocks.useSQLEditorStore.mockReturnValue({ project: "projects/proj1" });+ mocks.hasFeature.mockReturnValue(true);+ mocks.useVueState.mockImplementation((getter: () => unknown) => getter());+};++beforeEach(async () => {+ vi.clearAllMocks();+ setupDefaultMocks();+ ({ RequestQueryButton } = await import("./RequestQueryButton"));+});++afterEach(() => {+ document.body.innerHTML = "";+});++describe("RequestQueryButton", () => {+ test("renders nothing when allowRequestRole is false", () => {+ setupDefaultMocks(false, false);+ const { container, render, unmount } = renderIntoContainer(+ <RequestQueryButton+ text={false}+ permissionDeniedDetail={makePermissionDeniedDetail()}+ />+ );+ render();+ // Should not show a button+ expect(container.querySelector("button")).toBeNull();+ unmount();+ });++ test("renders request-query button in non-JIT mode", () => {+ setupDefaultMocks(false, true);+ const { container, render, unmount } = renderIntoContainer(+ <RequestQueryButton+ text={false}+ permissionDeniedDetail={makePermissionDeniedDetail({+ requiredPermissions: ["bb.sql.select", "bb.issues.create"],+ })}+ />+ );+ render();+ expect(container.textContent).toContain("sql-editor.request-query");+ unmount();+ });++ test("renders request-jit button in JIT mode", () => {+ setupDefaultMocks(true, true);+ const { container, render, unmount } = renderIntoContainer(+ <RequestQueryButton+ text={false}+ permissionDeniedDetail={makePermissionDeniedDetail({+ requiredPermissions: ["bb.sql.select"],+ })}+ />+ );+ render();+ expect(container.textContent).toContain("sql-editor.request-jit");+ unmount();+ });++ test("click in non-JIT mode opens RoleGrantPanel", async () => {+ setupDefaultMocks(false, true);+ const { container, render, unmount } = renderIntoContainer(+ <RequestQueryButton+ text={false}+ permissionDeniedDetail={makePermissionDeniedDetail({+ requiredPermissions: ["bb.issues.create"],+ })}+ />+ );+ render();++ expect(+ container.querySelector("[data-testid='role-grant-panel']")+ ).toBeNull();++ const btn = container.querySelector("button") as HTMLButtonElement;+ await act(async () => {+ btn.click();+ });++ expect(+ container.querySelector("[data-testid='role-grant-panel']")+ ).not.toBeNull();+ unmount();+ });++ test("click in JIT mode opens AccessGrantRequestDrawer", async () => {+ setupDefaultMocks(true, true);+ const { container, render, unmount } = renderIntoContainer(+ <RequestQueryButton+ text={false}+ statement="SELECT 1"+ permissionDeniedDetail={makePermissionDeniedDetail({+ requiredPermissions: ["bb.sql.select"],+ })}+ />+ );+ render();++ expect(+ container.querySelector("[data-testid='access-grant-drawer']")+ ).toBeNull();++ const btn = container.querySelector("button") as HTMLButtonElement;+ await act(async () => {+ btn.click();+ });++ expect(+ container.querySelector("[data-testid='access-grant-drawer']")+ ).not.toBeNull();+ unmount();+ });+});diff --git a/frontend/src/react/components/sql-editor/RequestQueryButton.tsx b/frontend/src/react/components/sql-editor/RequestQueryButton.tsxnew file mode 100644index 0000000000..c84986bff5--- /dev/null+++ b/frontend/src/react/components/sql-editor/RequestQueryButton.tsx@@ -0,0 +1,128 @@+import { ShieldUser } from "lucide-react";+import { useMemo, useState } from "react";+import { useTranslation } from "react-i18next";+import { parseStringToResource } from "@/components/RoleGrantPanel/DatabaseResourceForm/common";+import { FeatureBadge } from "@/react/components/FeatureBadge";+import { PermissionGuard } from "@/react/components/PermissionGuard";+import { Button } from "@/react/components/ui/button";+import { useVueState } from "@/react/hooks/useVueState";+import { hasFeature, useProjectV1Store, useSQLEditorStore } from "@/store";+import type { DatabaseResource, Permission } from "@/types";+import { PresetRoleType } from "@/types";+import type { PermissionDeniedDetail } from "@/types/proto-es/v1/common_pb";+import { PlanFeature } from "@/types/proto-es/v1/subscription_service_pb";+import { AccessGrantRequestDrawer } from "./AccessGrantRequestDrawer";+import { RoleGrantPanel } from "./RoleGrantPanel";++interface Props {+ readonly size?: "sm" | "default";+ readonly text?: boolean;+ readonly statement?: string;+ readonly permissionDeniedDetail: PermissionDeniedDetail;+}++export function RequestQueryButton({+ size = "default",+ text = false,+ statement,+ permissionDeniedDetail,+}: Props) {+ const { t } = useTranslation();++ const [showPanel, setShowPanel] = useState(false);+ const [showJITDrawer, setShowJITDrawer] = useState(false);++ const projectStore = useProjectV1Store();+ const editorStore = useSQLEditorStore();++ const projectName = useVueState(() => editorStore.project);+ const project = useVueState(() => projectStore.getProjectByName(projectName));++ const useJIT = useMemo(+ () =>+ !!project?.allowJustInTimeAccess &&+ permissionDeniedDetail.requiredPermissions.every(+ (perm) => perm === "bb.sql.select"+ ),+ [project, permissionDeniedDetail.requiredPermissions]+ );++ const requiredPermission: Permission = useJIT+ ? "bb.accessGrants.create"+ : "bb.issues.create";++ const requiredFeature = useJIT+ ? PlanFeature.FEATURE_JIT+ : PlanFeature.FEATURE_REQUEST_ROLE_WORKFLOW;++ const hasRequestFeature = hasFeature(requiredFeature);++ const missingResources = useMemo((): DatabaseResource[] => {+ const resources: DatabaseResource[] = [];+ for (const resourceString of permissionDeniedDetail.resources) {+ const resource = parseStringToResource(resourceString);+ if (resource) {+ resources.push(resource);+ }+ }+ return resources;+ }, [permissionDeniedDetail.resources]);++ const available = useMemo(() => !!project?.allowRequestRole, [project]);++ const handleClick = (e: React.MouseEvent) => {+ e.stopPropagation();+ if (useJIT) {+ setShowJITDrawer(true);+ } else {+ setShowPanel(true);+ }+ };++ if (!available) {+ return null;+ }++ return (+ <div>+ <PermissionGuard permissions={[requiredPermission]} project={project}>+ {({ disabled }) => (+ <Button+ size={size}+ variant={text ? "ghost" : "default"}+ disabled={disabled || !hasRequestFeature}+ onClick={handleClick}+ className="gap-x-1"+ >+ {hasRequestFeature ? (+ <ShieldUser className="size-4" />+ ) : (+ <FeatureBadge clickable={false} feature={requiredFeature} />+ )}+ {useJIT+ ? t("sql-editor.request-jit")+ : t("sql-editor.request-query")}+ </Button>+ )}+ </PermissionGuard>++ {showPanel && (+ <RoleGrantPanel+ projectName={projectName}+ databaseResources={missingResources}+ role={PresetRoleType.SQL_EDITOR_USER}+ requiredPermissions={permissionDeniedDetail.requiredPermissions}+ onClose={() => setShowPanel(false)}+ />+ )}++ {showJITDrawer && (+ <AccessGrantRequestDrawer+ query={statement}+ targets={missingResources.map((r) => r.databaseFullName)}+ onClose={() => setShowJITDrawer(false)}+ />+ )}+ </div>+ );+}diff --git a/frontend/src/react/components/sql-editor/RoleGrantPanel.test.tsx b/frontend/src/react/components/sql-editor/RoleGrantPanel.test.tsxnew file mode 100644index 0000000000..f39f675f6f--- /dev/null+++ b/frontend/src/react/components/sql-editor/RoleGrantPanel.test.tsx@@ -0,0 +1,483 @@+import type { ReactElement } from "react";+import { act } from "react";+import { createRoot } from "react-dom/client";+import { afterEach, beforeEach, describe, expect, test, vi } from "vitest";++(+ globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }+).IS_REACT_ACT_ENVIRONMENT = true;++const mocks = vi.hoisted(() => ({+ useTranslation: vi.fn(() => ({ t: (key: string) => key })),+ useVueState: vi.fn<(getter: () => unknown) => unknown>(),+ useCurrentUserV1: vi.fn(),+ useProjectV1Store: vi.fn(),+ useRoleStore: vi.fn(),+ useSettingV1Store: vi.fn(() => ({+ workspaceProfile: { maximumRoleExpiration: undefined },+ })),+ pushNotification: vi.fn(),+ issueServiceClientConnect: {+ createIssue: vi.fn().mockResolvedValue({ name: "projects/proj1/issues/1" }),+ },+ roleHasDatabaseLimitation: vi.fn(() => true),+}));++vi.mock("react-i18next", () => ({+ useTranslation: mocks.useTranslation,+}));++vi.mock("@/react/hooks/useVueState", () => ({+ useVueState: mocks.useVueState,+}));++vi.mock("@/store", () => ({+ useCurrentUserV1: mocks.useCurrentUserV1,+ useProjectV1Store: mocks.useProjectV1Store,+ useRoleStore: mocks.useRoleStore,+ useSettingV1Store: mocks.useSettingV1Store,+ pushNotification: mocks.pushNotification,+}));++vi.mock("@/types", () => ({+ PresetRoleType: {+ PROJECT_OWNER: "roles/projectOwner",+ },+}));++vi.mock("@/connect", () => ({+ issueServiceClientConnect: mocks.issueServiceClientConnect,+}));++vi.mock("@/router", () => ({+ router: {+ resolve: vi.fn(() => ({ fullPath: "/projects/proj1/issues/1" })),+ },+}));++vi.mock("@/router/dashboard/projectV1", () => ({+ PROJECT_V1_ROUTE_ISSUE_DETAIL: "project.issue-detail",+}));++vi.mock("@/utils", () => ({+ displayRoleTitle: vi.fn((r: string) => r),+ extractIssueUID: vi.fn(() => "1"),+ extractProjectResourceName: vi.fn(() => "proj1"),+ formatIssueTitle: vi.fn((title: string) => title),+}));++vi.mock("@/utils/issue/cel", () => ({+ buildConditionExpr: vi.fn(() => ({ expression: "", description: "" })),+}));++vi.mock("@/components/ProjectMember/utils", () => ({+ roleHasDatabaseLimitation: mocks.roleHasDatabaseLimitation,+}));++vi.mock("@/react/components/ui/sheet", () => ({+ Sheet: ({ children, open }: { children: React.ReactNode; open?: boolean }) =>+ open !== false ? <div data-testid="sheet">{children}</div> : null,+ SheetContent: ({ children }: { children: React.ReactNode }) => (+ <div data-testid="sheet-content">{children}</div>+ ),+ SheetHeader: ({ children }: { children: React.ReactNode }) => (+ <div>{children}</div>+ ),+ SheetTitle: ({ children }: { children: React.ReactNode }) => (+ <h2 data-testid="sheet-title">{children}</h2>+ ),+ SheetBody: ({ children }: { children: React.ReactNode }) => (+ <div data-testid="sheet-body">{children}</div>+ ),+ SheetFooter: ({ children }: { children: React.ReactNode }) => (+ <div data-testid="sheet-footer">{children}</div>+ ),+}));++vi.mock("@/react/components/ui/button", () => ({+ Button: ({+ children,+ onClick,+ disabled,+ }: {+ children: React.ReactNode;+ onClick?: () => void;+ disabled?: boolean;+ }) => (+ <button disabled={disabled} onClick={onClick}>+ {children}+ </button>+ ),+}));++vi.mock("@/react/components/ui/textarea", () => ({+ Textarea: ({+ value,+ onChange,+ placeholder,+ }: {+ value: string;+ onChange: (e: { target: { value: string } }) => void;+ placeholder?: string;+ }) => (+ <textarea+ data-testid="reason-textarea"+ value={value}+ placeholder={placeholder}+ onChange={onChange}+ />+ ),+}));++vi.mock("@/react/components/ui/expiration-picker", () => ({+ ExpirationPicker: () => <div data-testid="expiration-picker" />,+}));++vi.mock("@/react/components/IssueLabelSelect", () => ({+ IssueLabelSelect: () => <div data-testid="label-select" />,+}));++vi.mock("@/react/components/RoleSelect", () => ({+ RoleSelect: ({+ value,+ disabled,+ scope,+ }: {+ value: string[];+ onChange: (roles: string[]) => void;+ multiple?: boolean;+ disabled?: boolean;+ scope?: string;+ }) => (+ <div+ data-testid="role-select"+ data-value={value.join(",")}+ data-disabled={String(disabled ?? false)}+ data-scope={scope ?? ""}+ />+ ),+}));++vi.mock("@/react/components/DatabaseResourceSelector", () => ({+ DatabaseResourceSelector: ({+ value,+ onChange,+ }: {+ projectName: string;+ value: { databaseFullName: string }[];+ onChange: (resources: { databaseFullName: string }[]) => void;+ }) => (+ <div+ data-testid="database-resource-selector"+ data-count={value.length}+ onClick={() =>+ onChange([...value, { databaseFullName: "instances/i1/databases/db1" }])+ }+ />+ ),+}));++vi.mock("@/types/proto-es/v1/issue_service_pb", () => ({+ CreateIssueRequestSchema: {},+ Issue_Type: { ROLE_GRANT: 3 },+ IssueSchema: {},+ RoleGrantSchema: {},+}));++vi.mock("@bufbuild/protobuf", () => ({+ create: vi.fn((_, data) => data ?? {}),+}));++vi.mock("@bufbuild/protobuf/wkt", () => ({+ DurationSchema: {},+}));++// Stub ResizeObserver+globalThis.ResizeObserver = class ResizeObserver {+ observe() {}+ unobserve() {}+ disconnect() {}+};++let RoleGrantPanel: typeof import("./RoleGrantPanel").RoleGrantPanel;++const renderIntoContainer = (element: ReactElement) => {+ const container = document.createElement("div");+ const root = createRoot(container);+ document.body.appendChild(container);+ return {+ container,+ render: () => {+ act(() => {+ root.render(element);+ });+ },+ unmount: () => {+ act(() => {+ root.unmount();+ });+ container.remove();+ },+ };+};++const setupDefaultMocks = () => {+ mocks.useTranslation.mockReturnValue({ t: (key: string) => key });+ mocks.useCurrentUserV1.mockReturnValue({+ value: { email: "[email protected]" },+ });+ mocks.useProjectV1Store.mockReturnValue({+ getProjectByName: vi.fn(() => ({+ name: "projects/proj1",+ enforceIssueTitle: false,+ forceIssueLabels: false,+ issueLabels: [],+ })),+ });+ mocks.useRoleStore.mockReturnValue({+ getRoleByName: vi.fn(() => ({+ name: "roles/sqlEditorUser",+ permissions: ["bb.sql.select", "bb.sql.explain"],+ })),+ });+ mocks.roleHasDatabaseLimitation.mockReturnValue(true);+ mocks.useVueState.mockImplementation((getter: () => unknown) => getter());+};++beforeEach(async () => {+ vi.clearAllMocks();+ setupDefaultMocks();+ ({ RoleGrantPanel } = await import("./RoleGrantPanel"));+});++afterEach(() => {+ document.body.innerHTML = "";+});++describe("RoleGrantPanel", () => {+ test("renders with sheet title", () => {+ const onClose = vi.fn();+ const { container, render, unmount } = renderIntoContainer(+ <RoleGrantPanel+ projectName="projects/proj1"+ databaseResources={[{ databaseFullName: "instances/i1/databases/db1" }]}+ role="roles/sqlEditorUser"+ requiredPermissions={[]}+ onClose={onClose}+ />+ );+ render();++ expect(+ container.querySelector("[data-testid='sheet-title']")?.textContent+ ).toBe("issue.title.request-role");+ unmount();+ });++ test("renders RoleSelect as disabled with the correct role value", () => {+ const onClose = vi.fn();+ const { container, render, unmount } = renderIntoContainer(+ <RoleGrantPanel+ projectName="projects/proj1"+ databaseResources={[{ databaseFullName: "instances/i1/databases/db1" }]}+ role="roles/sqlEditorUser"+ requiredPermissions={[]}+ onClose={onClose}+ />+ );+ render();++ const roleSelect = container.querySelector("[data-testid='role-select']");+ expect(roleSelect).not.toBeNull();+ expect(roleSelect?.getAttribute("data-value")).toBe("roles/sqlEditorUser");+ expect(roleSelect?.getAttribute("data-disabled")).toBe("true");+ expect(roleSelect?.getAttribute("data-scope")).toBe("project");+ unmount();+ });++ test("shows required permissions when provided", () => {+ const onClose = vi.fn();+ const { container, render, unmount } = renderIntoContainer(+ <RoleGrantPanel+ projectName="projects/proj1"+ databaseResources={[{ databaseFullName: "instances/i1/databases/db1" }]}+ role="roles/sqlEditorUser"+ requiredPermissions={["bb.sql.select", "bb.sql.explain"]}+ onClose={onClose}+ />+ );+ render();++ expect(container.textContent).toContain("bb.sql.select");+ expect(container.textContent).toContain("bb.sql.explain");+ unmount();+ });++ test("renders database resource selector when role has database limitation", () => {+ mocks.roleHasDatabaseLimitation.mockReturnValue(true);+ const onClose = vi.fn();+ const { container, render, unmount } = renderIntoContainer(+ <RoleGrantPanel+ projectName="projects/proj1"+ databaseResources={[{ databaseFullName: "instances/i1/databases/db1" }]}+ role="roles/sqlEditorUser"+ requiredPermissions={[]}+ onClose={onClose}+ />+ );+ render();++ expect(+ container.querySelector("[data-testid='database-resource-selector']")+ ).not.toBeNull();+ unmount();+ });++ test("does not render database resource selector when role has no database limitation", () => {+ mocks.roleHasDatabaseLimitation.mockReturnValue(false);+ const onClose = vi.fn();+ const { container, render, unmount } = renderIntoContainer(+ <RoleGrantPanel+ projectName="projects/proj1"+ databaseResources={[]}+ role="roles/projectOwner"+ requiredPermissions={[]}+ onClose={onClose}+ />+ );+ render();++ expect(+ container.querySelector("[data-testid='database-resource-selector']")+ ).toBeNull();+ unmount();+ });++ test("submit disabled when database resources empty and role has database limitation", () => {+ mocks.roleHasDatabaseLimitation.mockReturnValue(true);+ const onClose = vi.fn();+ const { container, render, unmount } = renderIntoContainer(+ <RoleGrantPanel+ projectName="projects/proj1"+ databaseResources={[]}+ role="roles/sqlEditorUser"+ requiredPermissions={[]}+ onClose={onClose}+ />+ );+ render();++ const buttons = container.querySelectorAll("button");+ let submitBtn: HTMLButtonElement | null = null;+ for (const btn of Array.from(buttons)) {+ if (btn.textContent?.includes("common.submit")) {+ submitBtn = btn;+ break;+ }+ }+ expect(submitBtn).not.toBeNull();+ expect(submitBtn!.disabled).toBe(true);+ unmount();+ });++ test("cancel button calls onClose", () => {+ const onClose = vi.fn();+ const { container, render, unmount } = renderIntoContainer(+ <RoleGrantPanel+ projectName="projects/proj1"+ databaseResources={[{ databaseFullName: "instances/i1/databases/db1" }]}+ role="roles/sqlEditorUser"+ requiredPermissions={[]}+ onClose={onClose}+ />+ );+ render();++ const buttons = container.querySelectorAll("button");+ let cancelBtn: HTMLButtonElement | null = null;+ for (const btn of Array.from(buttons)) {+ if (btn.textContent?.includes("common.cancel")) {+ cancelBtn = btn;+ break;+ }+ }+ expect(cancelBtn).not.toBeNull();+ act(() => {+ cancelBtn!.click();+ });+ expect(onClose).toHaveBeenCalledOnce();+ unmount();+ });++ test("submit button disabled when reason required but empty", () => {+ mocks.useProjectV1Store.mockReturnValue({+ getProjectByName: vi.fn(() => ({+ name: "projects/proj1",+ enforceIssueTitle: true,+ forceIssueLabels: false,+ issueLabels: [],+ })),+ });++ const onClose = vi.fn();+ const { container, render, unmount } = renderIntoContainer(+ <RoleGrantPanel+ projectName="projects/proj1"+ databaseResources={[{ databaseFullName: "instances/i1/databases/db1" }]}+ role="roles/sqlEditorUser"+ requiredPermissions={[]}+ onClose={onClose}+ />+ );+ render();++ const buttons = container.querySelectorAll("button");+ let submitBtn: HTMLButtonElement | null = null;+ for (const btn of Array.from(buttons)) {+ if (btn.textContent?.includes("common.submit")) {+ submitBtn = btn;+ break;+ }+ }+ expect(submitBtn).not.toBeNull();+ expect(submitBtn!.disabled).toBe(true);+ unmount();+ });++ test("submit calls createIssue when reason not required and db resources provided", async () => {+ mocks.roleHasDatabaseLimitation.mockReturnValue(true);+ const onClose = vi.fn();+ const openSpy = vi.spyOn(window, "open").mockImplementation(() => null);++ const { container, render, unmount } = renderIntoContainer(+ <RoleGrantPanel+ projectName="projects/proj1"+ databaseResources={[{ databaseFullName: "instances/i1/databases/db1" }]}+ role="roles/sqlEditorUser"+ requiredPermissions={[]}+ onClose={onClose}+ />+ );+ render();++ const buttons = container.querySelectorAll("button");+ let submitBtn: HTMLButtonElement | null = null;+ for (const btn of Array.from(buttons)) {+ if (btn.textContent?.includes("common.submit")) {+ submitBtn = btn;+ break;+ }+ }+ expect(submitBtn).not.toBeNull();+ expect(submitBtn!.disabled).toBe(false);++ await act(async () => {+ submitBtn!.click();+ });+ await vi.waitFor(() => {+ expect(mocks.issueServiceClientConnect.createIssue).toHaveBeenCalled();+ });+ openSpy.mockRestore();+ unmount();+ });+});diff --git a/frontend/src/react/components/sql-editor/RoleGrantPanel.tsx b/frontend/src/react/components/sql-editor/RoleGrantPanel.tsxnew file mode 100644index 0000000000..d197d85f09--- /dev/null+++ b/frontend/src/react/components/sql-editor/RoleGrantPanel.tsx@@ -0,0 +1,380 @@+import { create } from "@bufbuild/protobuf";+import { DurationSchema } from "@bufbuild/protobuf/wkt";+import dayjs from "dayjs";+import { useMemo, useState } from "react";+import { useTranslation } from "react-i18next";+import { roleHasDatabaseLimitation } from "@/components/ProjectMember/utils";+import { issueServiceClientConnect } from "@/connect";+import { DatabaseResourceSelector } from "@/react/components/DatabaseResourceSelector";+import { IssueLabelSelect } from "@/react/components/IssueLabelSelect";+import { RoleSelect } from "@/react/components/RoleSelect";+import { Button } from "@/react/components/ui/button";+import { ExpirationPicker } from "@/react/components/ui/expiration-picker";+import {+ Sheet,+ SheetBody,+ SheetContent,+ SheetFooter,+ SheetHeader,+ SheetTitle,+} from "@/react/components/ui/sheet";+import { Textarea } from "@/react/components/ui/textarea";+import { useVueState } from "@/react/hooks/useVueState";+import { router } from "@/router";+import { PROJECT_V1_ROUTE_ISSUE_DETAIL } from "@/router/dashboard/projectV1";+import {+ pushNotification,+ useCurrentUserV1,+ useProjectV1Store,+ useRoleStore,+ useSettingV1Store,+} from "@/store";+import { type DatabaseResource, PresetRoleType } from "@/types";+import {+ CreateIssueRequestSchema,+ Issue_Type,+ IssueSchema,+ RoleGrantSchema,+} from "@/types/proto-es/v1/issue_service_pb";+import {+ displayRoleTitle,+ extractIssueUID,+ extractProjectResourceName,+ formatIssueTitle,+} from "@/utils";+import { buildConditionExpr } from "@/utils/issue/cel";++interface Props {+ readonly projectName: string;+ readonly databaseResources: DatabaseResource[];+ readonly role: string;+ readonly requiredPermissions: string[];+ readonly onClose: () => void;+}++interface RoleGrantPanelInnerProps {+ readonly stableProjectName: string;+ readonly databaseResources: DatabaseResource[];+ readonly role: string;+ readonly requiredPermissions: string[];+ readonly onClose: () => void;+}++function RoleGrantPanelInner({+ stableProjectName,+ databaseResources,+ role,+ requiredPermissions,+ onClose,+}: RoleGrantPanelInnerProps) {+ const { t } = useTranslation();++ const currentUserRef = useCurrentUserV1();+ const currentUser = useVueState(() => currentUserRef.value);++ const projectStore = useProjectV1Store();+ const project = useVueState(() =>+ projectStore.getProjectByName(stableProjectName)+ );++ const roleStore = useRoleStore();+ const selectedRole = useVueState(() => roleStore.getRoleByName(role));++ const settingStore = useSettingV1Store();+ const maximumRoleExpirationDays = useVueState(() => {+ if (role === PresetRoleType.PROJECT_OWNER) return undefined;+ const seconds =+ settingStore.workspaceProfile.maximumRoleExpiration?.seconds;+ if (!seconds) return undefined;+ return Math.floor(Number(seconds) / (60 * 60 * 24));+ });++ const showDatabaseSelector = roleHasDatabaseLimitation(role);++ const [dbResources, setDbResources] =+ useState<DatabaseResource[]>(databaseResources);+ const [reason, setReason] = useState("");+ const [expirationTimestamp, setExpirationTimestamp] = useState<+ string | undefined+ >(undefined);+ const [labels, setLabels] = useState<string[]>([]);+ const [submitting, setSubmitting] = useState(false);++ const minDatetime = dayjs().format("YYYY-MM-DDTHH:mm");+ const maxDatetime = maximumRoleExpirationDays+ ? dayjs().add(maximumRoleExpirationDays, "days").format("YYYY-MM-DDTHH:mm")+ : undefined;++ const reasonRequired = useMemo(+ () => project?.enforceIssueTitle ?? false,+ [project]+ );++ const labelsMisconfigured = useMemo(+ () => !!(project?.forceIssueLabels && project.issueLabels.length === 0),+ [project]+ );++ const expirationIsInPast =+ !!expirationTimestamp &&+ dayjs(expirationTimestamp).unix() <= dayjs().unix();++ const expirationExceedsMax =+ !!expirationTimestamp &&+ !!maximumRoleExpirationDays &&+ dayjs(expirationTimestamp).isAfter(+ dayjs().add(maximumRoleExpirationDays, "days")+ );++ // When the workspace has a maximumRoleExpiration policy, the user must+ // pick an expiration — otherwise the backend treats missing expiration as+ // effectively unbounded (math.MaxInt32 days) and bypasses the cap.+ const expirationRequired = maximumRoleExpirationDays !== undefined;++ const canSubmit = useMemo(() => {+ if (submitting) return false;+ if (reasonRequired && !reason.trim()) return false;+ if (showDatabaseSelector && dbResources.length === 0) return false;+ if (expirationRequired && !expirationTimestamp) return false;+ if (expirationIsInPast) return false;+ if (expirationExceedsMax) return false;+ if (project?.forceIssueLabels && labels.length === 0) return false;+ if (labelsMisconfigured) return false;+ return true;+ }, [+ submitting,+ reasonRequired,+ reason,+ showDatabaseSelector,+ dbResources,+ expirationRequired,+ expirationTimestamp,+ expirationIsInPast,+ expirationExceedsMax,+ project,+ labels,+ labelsMisconfigured,+ ]);++ const handleSubmit = async () => {+ if (!canSubmit) return;+ setSubmitting(true);+ try {+ const trimmedReason = reason.trim();+ const expirationTimestampInMS = expirationTimestamp+ ? dayjs(expirationTimestamp).valueOf()+ : undefined;++ const condition = buildConditionExpr({+ role,+ description: trimmedReason,+ expirationTimestampInMS,+ databaseResources: dbResources.length > 0 ? dbResources : undefined,+ });++ const expiration = expirationTimestamp+ ? create(DurationSchema, {+ seconds: BigInt(+ Math.max(0, dayjs(expirationTimestamp).unix() - dayjs().unix())+ ),+ })+ : undefined;++ const roleGrant = create(RoleGrantSchema, {+ role,+ user: `users/${currentUser.email}`,+ condition,+ expiration,+ });++ const titleDatabaseNames =+ dbResources.length > 0+ ? [...new Set(dbResources.map((r) => r.databaseFullName))]+ : undefined;++ const title = project?.enforceIssueTitle+ ? `[${t("issue.title.request-role")}] ${trimmedReason}`+ : formatIssueTitle(+ t("issue.title.request-specific-role", {+ role: displayRoleTitle(role),+ }),+ titleDatabaseNames+ );++ const newIssue = create(IssueSchema, {+ title,+ description: trimmedReason,+ type: Issue_Type.ROLE_GRANT,+ roleGrant,+ labels,+ });++ const response = await issueServiceClientConnect.createIssue(+ create(CreateIssueRequestSchema, {+ parent: stableProjectName,+ issue: newIssue,+ })+ );++ pushNotification({+ module: "bytebase",+ style: "SUCCESS",+ title: t("common.created"),+ });++ const route = router.resolve({+ name: PROJECT_V1_ROUTE_ISSUE_DETAIL,+ params: {+ projectId: extractProjectResourceName(response.name),+ issueId: extractIssueUID(response.name),+ },+ });+ window.open(route.fullPath, "_blank", "noopener,noreferrer");+ onClose();+ } catch {+ // Error notification pushed by client middleware.+ } finally {+ setSubmitting(false);+ }+ };++ const issueLabels = project?.issueLabels ?? [];+ const forceIssueLabels = !!project?.forceIssueLabels;+ const showLabelSelect = issueLabels.length > 0 || forceIssueLabels;++ return (+ <>+ <SheetHeader>+ <SheetTitle>{t("issue.title.request-role")}</SheetTitle>+ </SheetHeader>+ <SheetBody>+ <div className="flex flex-col gap-y-4">+ {requiredPermissions.length > 0 && (+ <div className="flex flex-col gap-y-1">+ <label className="text-sm font-medium text-control">+ {t("common.required-permission")}+ </label>+ <ul className="list-disc pl-4 text-sm text-control-light">+ {requiredPermissions.map((p) => (+ <li key={p}>{p}</li>+ ))}+ </ul>+ </div>+ )}++ <div className="flex flex-col gap-y-1">+ <label className="text-sm font-medium text-control">+ {t("common.role.self")}+ </label>+ <RoleSelect+ value={[role]}+ onChange={() => {}}+ multiple={false}+ disabled={true}+ scope="project"+ />+ </div>++ {selectedRole && selectedRole.permissions.length > 0 && (+ <div className="flex flex-col gap-y-1">+ <label className="text-sm font-medium text-control">+ {t("common.permissions")} ({selectedRole.permissions.length})+ </label>+ <div className="max-h-[10em] overflow-auto border border-control-border rounded-sm p-2">+ <ul className="list-none">+ {selectedRole.permissions.map((p) => (+ <li key={p} className="text-sm leading-5">+ {p}+ </li>+ ))}+ </ul>+ </div>+ </div>+ )}++ <div className="flex flex-col gap-y-1">+ <label className="text-sm font-medium text-control">+ {t("common.reason")}+ {reasonRequired && <span className="text-error ml-0.5">*</span>}+ </label>+ <Textarea+ value={reason}+ onChange={(e) => setReason(e.target.value)}+ placeholder={t("common.reason")}+ rows={3}+ />+ </div>++ {showDatabaseSelector && (+ <div className="flex flex-col gap-y-1">+ <label className="text-sm font-medium text-control">+ {t("common.databases")}+ <span className="text-error ml-0.5">*</span>+ </label>+ <DatabaseResourceSelector+ projectName={stableProjectName}+ value={dbResources}+ onChange={setDbResources}+ />+ </div>+ )}++ <div className="flex flex-col gap-y-1">+ <label className="text-sm font-medium text-control">+ {t("common.expiration")}+ {expirationRequired && (+ <span className="text-error ml-0.5">*</span>+ )}+ </label>+ <ExpirationPicker+ value={expirationTimestamp}+ onChange={setExpirationTimestamp}+ minDate={minDatetime}+ maxDate={maxDatetime}+ />+ </div>++ {showLabelSelect && (+ <IssueLabelSelect+ labels={issueLabels}+ selected={labels}+ required={forceIssueLabels}+ onChange={setLabels}+ />+ )}+ </div>+ </SheetBody>+ <SheetFooter>+ <Button variant="outline" onClick={onClose} disabled={submitting}>+ {t("common.cancel")}+ </Button>+ <Button disabled={!canSubmit} onClick={() => void handleSubmit()}>+ {t("common.submit")}+ </Button>+ </SheetFooter>+ </>+ );+}++export function RoleGrantPanel({+ projectName,+ databaseResources,+ role,+ requiredPermissions,+ onClose,+}: Props) {+ return (+ <Sheet open={true} onOpenChange={(next) => !next && onClose()}>+ <SheetContent width="standard">+ <RoleGrantPanelInner+ key={projectName}+ stableProjectName={projectName}+ databaseResources={databaseResources}+ role={role}+ requiredPermissions={requiredPermissions}+ onClose={onClose}+ />+ </SheetContent>+ </Sheet>+ );+}diff --git a/frontend/src/react/components/sql-editor/SchemaChooser.tsx b/frontend/src/react/components/sql-editor/SchemaChooser.tsxindex cb13fd977f..163998c572 100644--- a/frontend/src/react/components/sql-editor/SchemaChooser.tsx+++ b/frontend/src/react/components/sql-editor/SchemaChooser.tsx@@ -65,9 +65,6 @@ export function SchemaChooser() {() => router.currentRoute.value.query.schema as string | undefined);const currentTabId = useVueState(() => tabStore.currentTab?.id);- // biome-ignore lint/correctness/useExhaustiveDependencies: handleChange is- // defined inline and reads the live tabStore; omitting it is intentional- // so the effect re-runs only on queryParam or tab switch.useEffect(() => {if (queryParam) handleChange(queryParam);}, [queryParam, currentTabId]);diff --git a/frontend/src/react/locales/en-US.json b/frontend/src/react/locales/en-US.jsonindex a24783d71c..e7a2abdefc 100644--- a/frontend/src/react/locales/en-US.json+++ b/frontend/src/react/locales/en-US.json@@ -1419,6 +1419,15 @@"visit-prjects": "Visit Projects"}},+ "masking": {+ "reason": {+ "algorithm": "Masking method",+ "classification": "Classification level",+ "context": "Rule",+ "semantic-type": "Semantic type",+ "title": "Why is this data masked?"+ }+ },"multi-factor": {"auth-code": "Authentication code","other-methods": {@@ -2461,6 +2470,8 @@},"request-access": "Request Access","request-data-access": "Request Data Access",+ "request-jit": "Request just-in-time access",+ "request-query": "Request query","result-limit": {"self": "Result limit"},diff --git a/frontend/src/react/locales/es-ES.json b/frontend/src/react/locales/es-ES.jsonindex 441ffaf3d6..cd46181812 100644--- a/frontend/src/react/locales/es-ES.json+++ b/frontend/src/react/locales/es-ES.json@@ -1419,6 +1419,15 @@"visit-prjects": "Visitar Proyectos"}},+ "masking": {+ "reason": {+ "algorithm": "Método de enmascaramiento",+ "classification": "Nivel de clasificación",+ "context": "Regla",+ "semantic-type": "Tipo semántico",+ "title": "¿Por qué están enmascarados estos datos?"+ }+ },"multi-factor": {"auth-code": "Código de autenticación","other-methods": {@@ -2461,6 +2470,8 @@},"request-access": "Request Access","request-data-access": "Request Data Access",+ "request-jit": "Request just-in-time access",+ "request-query": "Solicitar consulta","result-limit": {"self": "Límite de resultados"},diff --git a/frontend/src/react/locales/ja-JP.json b/frontend/src/react/locales/ja-JP.jsonindex 5b7fdd2adc..5a0cca98ef 100644--- a/frontend/src/react/locales/ja-JP.json+++ b/frontend/src/react/locales/ja-JP.json@@ -1419,6 +1419,15 @@"visit-prjects": "プロジェクトを開く"}},+ "masking": {+ "reason": {+ "algorithm": "マスキング方法",+ "classification": "分類レベル",+ "context": "ルール",+ "semantic-type": "セマンティックタイプ",+ "title": "なぜこのデータはマスクされていますか?"+ }+ },"multi-factor": {"auth-code": "認証コード","other-methods": {@@ -2461,6 +2470,8 @@},"request-access": "Request Access","request-data-access": "Request Data Access",+ "request-jit": "Request just-in-time access",+ "request-query": "リクエストクエリ","result-limit": {"self": "結果の制限"},diff --git a/frontend/src/react/locales/vi-VN.json b/frontend/src/react/locales/vi-VN.jsonindex 3e2b843a03..081c1ba9c7 100644--- a/frontend/src/react/locales/vi-VN.json+++ b/frontend/src/react/locales/vi-VN.json@@ -1419,6 +1419,15 @@"visit-prjects": "Truy cập Dự án"}},+ "masking": {+ "reason": {+ "algorithm": "Phương pháp che dữ liệu",+ "classification": "Mức phân loại",+ "context": "Quy tắc",+ "semantic-type": "Loại ngữ nghĩa",+ "title": "Tại sao dữ liệu này bị che?"+ }+ },"multi-factor": {"auth-code": "Mã xác thực","other-methods": {@@ -2461,6 +2470,8 @@},"request-access": "Request Access","request-data-access": "Request Data Access",+ "request-jit": "Request just-in-time access",+ "request-query": "Yêu cầu truy vấn","result-limit": {"self": "Giới hạn kết quả"},diff --git a/frontend/src/react/locales/zh-CN.json b/frontend/src/react/locales/zh-CN.jsonindex 23f056d68f..fb07aa2b4f 100644--- a/frontend/src/react/locales/zh-CN.json+++ b/frontend/src/react/locales/zh-CN.json@@ -1419,6 +1419,15 @@"visit-prjects": "访问项目"}},+ "masking": {+ "reason": {+ "algorithm": "遮盖方法",+ "classification": "分类级别",+ "context": "规则",+ "semantic-type": "语义类型",+ "title": "为什么这些数据被遮盖?"+ }+ },"multi-factor": {"auth-code": "认证码","other-methods": {@@ -2461,6 +2470,8 @@},"request-access": "申请访问","request-data-access": "申请数据访问",+ "request-jit": "申请即时访问",+ "request-query": "请求查询","result-limit": {"self": "结果限制"},diff --git a/frontend/src/react/pages/settings/SemanticTypesPage.tsx b/frontend/src/react/pages/settings/SemanticTypesPage.tsxindex f53f1f05af..352dfb5073 100644--- a/frontend/src/react/pages/settings/SemanticTypesPage.tsx+++ b/frontend/src/react/pages/settings/SemanticTypesPage.tsx@@ -118,14 +118,6 @@ export function SemanticTypesPage() {algorithm?: Algorithm;} | null>(null);- // Deferred side-effect queue: state updaters push actions here,- // and a useEffect flushes them after React commits.- const pendingActionRef = useRef<(() => void)[]>([]);- useEffect(() => {- const actions = pendingActionRef.current.splice(0);- for (const action of actions) action();- });-const semanticTypeSettingValue = useVueState(() => {const setting = settingStore.getSettingByName(Setting_SettingName.SEMANTIC_TYPES@@ -195,39 +187,35 @@ export function SemanticTypesPage() {const onRemove = useCallback((index: number) => {- setItems((prev) => {- const next = [...prev];- const removed = next.splice(index, 1)[0];- if (removed.mode !== "CREATE") {- const types = next- .filter((d) => d.mode === "NORMAL")- .map((d) => d.item);- pendingActionRef.current.push(() =>- upsertSetting(types, t("common.deleted"))- );- }- return next;- });+ const current = items[index];+ if (!current) return;+ const next = [...items];+ next.splice(index, 1);+ setItems(next);+ if (current.mode !== "CREATE") {+ const types = next+ .filter((d) => d.mode === "NORMAL")+ .map((d) => d.item);+ void upsertSetting(types, t("common.deleted"));+ }},- [upsertSetting, t]+ [upsertSetting, t, items]);const onConfirm = useCallback((index: number) => {- setItems((prev) => {- const next = [...prev];- const item = next[index];- const wasCreate = item.mode === "CREATE";- next[index] = { ...item, dirty: false, mode: "NORMAL" };- const types = next- .filter((d) => d.mode === "NORMAL")- .map((d) => d.item);- const msg = t(wasCreate ? "common.created" : "common.updated");- pendingActionRef.current.push(() => upsertSetting(types, msg));- return next;- });+ const current = items[index];+ if (!current) return;+ const msg = t(+ current.mode === "CREATE" ? "common.created" : "common.updated"+ );+ const next = [...items];+ next[index] = { ...current, dirty: false, mode: "NORMAL" };+ setItems(next);+ const types = next.filter((d) => d.mode === "NORMAL").map((d) => d.item);+ void upsertSetting(types, msg);},- [upsertSetting, t]+ [upsertSetting, t, items]);const onCancel = useCallback(@@ -281,34 +269,34 @@ export function SemanticTypesPage() {const drawer = algorithmDrawerRef.current;if (drawer === null) return;const { index } = drawer;- setItems((prev) => {- const next = [...prev];- const current = next[index];- if (!current) return prev;- const updated: SemanticItem = {- ...current,- dirty: true,- item: { ...current.item, algorithm },- };- if (updated.item.title) {- updated.dirty = false;- updated.mode = "NORMAL";- next[index] = updated;- const types = next- .filter((d) => d.mode === "NORMAL")- .map((d) => d.item);- const msg = t(- current.mode === "CREATE" ? "common.created" : "common.updated"- );- pendingActionRef.current.push(() => upsertSetting(types, msg));- } else {- next[index] = updated;- }- return next;- });+ const current = items[index];+ if (!current) return;+ const updated: SemanticItem = {+ ...current,+ dirty: true,+ item: { ...current.item, algorithm },+ };+ if (updated.item.title) {+ updated.dirty = false;+ updated.mode = "NORMAL";+ const next = [...items];+ next[index] = updated;+ setItems(next);+ const types = next+ .filter((d) => d.mode === "NORMAL")+ .map((d) => d.item);+ const msg = t(+ current.mode === "CREATE" ? "common.created" : "common.updated"+ );+ void upsertSetting(types, msg);+ } else {+ const next = [...items];+ next[index] = updated;+ setItems(next);+ }setAlgorithmDrawer(null);},- [upsertSetting, t]+ [upsertSetting, t, items]);const onOpenAlgorithmDrawer = useCallback(@@ -320,39 +308,32 @@ export function SemanticTypesPage() {const onTemplateApply = useCallback((template: SemanticTypeSetting_SemanticType) => {- setItems((prev) => {- if (prev.find((item) => item.item.id === template.id)) {- pendingActionRef.current.push(() =>- pushNotification({- module: "bytebase",- style: "INFO",- title: t(- "settings.sensitive-data.semantic-types.template.duplicate-warning",- { title: template.title }- ),- })- );- return prev;- }- const newItem: SemanticItem = {- dirty: false,- mode: "NORMAL",- item: create(SemanticTypeSetting_SemanticTypeSchema, {- ...template,- }),- };- const next = [...prev, newItem];- const types = next- .filter((d) => d.mode === "NORMAL")- .map((d) => d.item);- pendingActionRef.current.push(() =>- upsertSetting(types, t("common.created"))- );- return next;- });+ if (items.find((item) => item.item.id === template.id)) {+ pushNotification({+ module: "bytebase",+ style: "INFO",+ title: t(+ "settings.sensitive-data.semantic-types.template.duplicate-warning",+ { title: template.title }+ ),+ });+ setShowTemplateDrawer(false);+ return;+ }+ const newItem: SemanticItem = {+ dirty: false,+ mode: "NORMAL",+ item: create(SemanticTypeSetting_SemanticTypeSchema, {+ ...template,+ }),+ };+ const next = [...items, newItem];+ setItems(next);+ const types = next.filter((d) => d.mode === "NORMAL").map((d) => d.item);+ void upsertSetting(types, t("common.created"));setShowTemplateDrawer(false);},- [upsertSetting, t]+ [upsertSetting, t, items]);const isConfirmDisabled = (data: SemanticItem): boolean => {diff --git a/frontend/src/views/sql-editor/AsidePanel/AccessPane/AccessGrantRequestDrawer.vue b/frontend/src/views/sql-editor/AsidePanel/AccessPane/AccessGrantRequestDrawer.vuedeleted file mode 100644index fda132a89d..0000000000--- a/frontend/src/views/sql-editor/AsidePanel/AccessPane/AccessGrantRequestDrawer.vue+++ /dev/null@@ -1,273 +0,0 @@-<template>- <Drawer- :show="true"- width="auto"- @update:show="(show: boolean) => !show && $emit('close')"- >- <DrawerContent- :title="$t('sql-editor.request-data-access')"- :closable="true"- class="w-[40rem] max-w-[100vw]"- >- <div class="flex flex-col gap-y-6">- <div class="flex flex-col gap-y-2">- <div class="text-sm font-medium text-control">- {{ $t("common.databases") }}- <RequiredStar class="ml-0.5" />- </div>- <DatabaseSelect- :value="form.targets"- :project-name="editorStore.project"- :multiple="true"- @update:value="- (val) => (form.targets = (val as string[] | undefined) ?? [])- "- />- </div>-- <div class="flex flex-col gap-y-2">- <div class="text-sm font-medium text-control">- {{ $t("common.statement") }}- <RequiredStar class="ml-0.5" />- </div>- <BBAttention type="info">- {{ $t("sql-editor.only-select-allowed") }}- </BBAttention>- <MonacoEditor- class="border rounded-[3px] h-40"- :content="form.query"- language="sql"- :auto-complete-context="autoCompleteContext"- @update:content="form.query = $event"- />- </div>-- <div class="flex flex-col gap-y-2">- <div class="text-sm font-medium text-control">- {{ $t("sql-editor.grant-type-unmask") }}- </div>- <div class="flex flex-col gap-y-1">- <NCheckbox v-model:checked="form.unmask">- {{ $t("sql-editor.access-type-unmask") }}- </NCheckbox>- </div>- </div>-- <div class="flex flex-col gap-y-2">- <div class="text-sm font-medium text-control">- {{ $t("common.expiration") }}- <RequiredStar class="ml-0.5" />- </div>- <NSelect- v-model:value="form.duration"- :options="durationOptions"- />- <NDatePicker- v-if="form.duration === -1"- v-model:value="form.customExpireTime"- type="datetime"- :is-date-disabled="isDateDisabled"- clearable- :actions="null"- :update-value-on-close="true"- />- </div>-- <div class="flex flex-col gap-y-2">- <div class="text-sm font-medium text-control">- {{ $t("common.reason") }}- <RequiredStar class="ml-0.5" />- </div>- <NInput- v-model:value="form.reason"- type="textarea"- :rows="3"- />- </div>- </div>-- <template #footer>- <div class="flex items-center justify-end gap-x-2">- <NButton @click="$emit('close')">- {{ $t("common.cancel") }}- </NButton>- <NButton- type="primary"- :disabled="!allowSubmit"- :loading="isRequesting"- @click="handleSubmit"- >- {{ $t("common.submit") }}- </NButton>- </div>- </template>- </DrawerContent>- </Drawer>-</template>--<script lang="ts" setup>-import { create } from "@bufbuild/protobuf";-import { DurationSchema, TimestampSchema } from "@bufbuild/protobuf/wkt";-import dayjs from "dayjs";-import { NButton, NCheckbox, NDatePicker, NInput, NSelect } from "naive-ui";-import { computed, reactive, ref } from "vue";-import { useI18n } from "vue-i18n";-import { useRouter } from "vue-router";-import { BBAttention } from "@/bbkit";-import { MonacoEditor } from "@/components/MonacoEditor";-import RequiredStar from "@/components/RequiredStar.vue";-import { DatabaseSelect, Drawer, DrawerContent } from "@/components/v2";-import { accessGrantServiceClientConnect } from "@/connect";-import { PROJECT_V1_ROUTE_ISSUE_DETAIL } from "@/router/dashboard/projectV1";-import {- pushNotification,- useCurrentUserV1,- useSQLEditorStore,- useSQLEditorTabStore,-} from "@/store";-import {- AccessGrant_Status,- AccessGrantSchema,- CreateAccessGrantRequestSchema,-} from "@/types/proto-es/v1/access_grant_service_pb";-import {- extractDatabaseResourceName,- extractIssueUID,- extractProjectResourceName,-} from "@/utils";-import { useSQLEditorContext } from "../../context";--const props = withDefaults(- defineProps<{- // Pre-selected database resource names.- // Format: "instances/{instance}/databases/{database}"- targets?: string[];- // Pre-filled SQL statement.- query?: string;- // Pre-check the "Unmask" access type checkbox.- unmask?: boolean;- }>(),- {- targets: undefined,- query: "",- unmask: false,- }-);--const emit = defineEmits<{- (event: "close"): void;-}>();--const { t } = useI18n();-const router = useRouter();-const currentUser = useCurrentUserV1();-const editorStore = useSQLEditorStore();-const tabStore = useSQLEditorTabStore();-const isRequesting = ref(false);-const { asidePanelTab, highlightAccessGrantName } = useSQLEditorContext();--// Default to the currently connected database if no targets provided.-const defaultTargets = computed(() => {- if (props.targets) return props.targets;- const database = tabStore.currentTab?.connection?.database;- return database ? [database] : [];-});--const form = reactive({- targets: [...defaultTargets.value],- query: props.query,- unmask: props.unmask,- duration: 4,- customExpireTime: undefined as number | undefined,- reason: "",-});--const autoCompleteContext = computed(() => {- const db = form.targets[0];- if (!db) return undefined;- const { instance } = extractDatabaseResourceName(db);- return { instance, database: db };-});--const durationOptions = computed(() => [- { label: t("sql-editor.duration-hours", { hours: 1 }), value: 1 },- { label: t("sql-editor.duration-hours", { hours: 4 }), value: 4 },- { label: t("sql-editor.duration-day", { days: 1 }), value: 24 },- { label: t("sql-editor.duration-days", { days: 7 }), value: 168 },- { label: t("common.custom"), value: -1 },-]);--const isDateDisabled = (date: number) => {- if (date < dayjs().startOf("day").valueOf()) {- return true;- }- return false;-};--const allowSubmit = computed(() => {- if (form.targets.length === 0) return false;- if (!form.query.trim()) return false;- if (!form.reason) return false;- if (form.duration === -1 && !form.customExpireTime) return false;- return true;-});--const handleSubmit = async () => {- if (isRequesting.value) return;- isRequesting.value = true;- try {- const accessGrant = create(AccessGrantSchema, {- creator: `users/${currentUser.value.email}`,- targets: form.targets,- query: form.query,- unmask: form.unmask,- reason: form.reason,- expiration:- form.duration === -1- ? {- case: "expireTime" as const,- value: create(TimestampSchema, {- seconds: BigInt(Math.floor(form.customExpireTime! / 1000)),- nanos: (form.customExpireTime! % 1000) * 1000000,- }),- }- : {- case: "ttl" as const,- value: create(DurationSchema, {- seconds: BigInt(form.duration * 3600),- }),- },- });-- const response = await accessGrantServiceClientConnect.createAccessGrant(- create(CreateAccessGrantRequestSchema, {- parent: editorStore.project,- accessGrant,- })- );-- pushNotification({- module: "bytebase",- style: "SUCCESS",- title: t("common.created"),- });-- if (response.status === AccessGrant_Status.PENDING && response.issue) {- const route = router.resolve({- name: PROJECT_V1_ROUTE_ISSUE_DETAIL,- params: {- projectId: extractProjectResourceName(response.issue),- issueId: extractIssueUID(response.issue),- },- });- window.open(route.fullPath, "_blank");- } else {- asidePanelTab.value = "ACCESS";- highlightAccessGrantName.value = response.name;- }- emit("close");- } finally {- isRequesting.value = false;- }-};-</script>diff --git a/frontend/src/views/sql-editor/ConnectionPanel/ConnectionPane/TreeNode/DatabaseNode.vue b/frontend/src/views/sql-editor/ConnectionPanel/ConnectionPane/TreeNode/DatabaseNode.vueindex c24f026688..9f02599125 100644--- a/frontend/src/views/sql-editor/ConnectionPanel/ConnectionPane/TreeNode/DatabaseNode.vue+++ b/frontend/src/views/sql-editor/ConnectionPanel/ConnectionPane/TreeNode/DatabaseNode.vue@@ -24,15 +24,16 @@@click.stop.prevent="$emit('click')"/>- <RequestQueryButton+ <ReactPageMountv-if="!canQuery"+ page="RequestQueryButton"class="ml-auto":text="true"- :permission-denied-detail="create(PermissionDeniedDetailSchema, {+ :permissionDeniedDetail="create(PermissionDeniedDetailSchema, {resources: [database.name],requiredPermissions: ['bb.sql.select']})"- :size="'tiny'"+ size="sm"/></div></template>@@ -42,11 +43,11 @@ import { create } from "@bufbuild/protobuf";import { NCheckbox, NTooltip } from "naive-ui";import { computed } from "vue";import { RichDatabaseName } from "@/components/v2";+import ReactPageMount from "@/react/ReactPageMount.vue";import { useSQLEditorTabStore } from "@/store";import type { SQLEditorTreeNode as TreeNode } from "@/types";import { PermissionDeniedDetailSchema } from "@/types/proto-es/v1/common_pb";import { isDatabaseV1Queryable } from "@/utils";-import RequestQueryButton from "../../../EditorCommon/ResultView/RequestQueryButton.vue";const props = defineProps<{node: TreeNode;diff --git a/frontend/src/views/sql-editor/EditorCommon/ResultView/DataTable/VirtualDataTable.vue b/frontend/src/views/sql-editor/EditorCommon/ResultView/DataTable/VirtualDataTable.vueindex 08e79a51be..d9af3482ff 100644--- a/frontend/src/views/sql-editor/EditorCommon/ResultView/DataTable/VirtualDataTable.vue+++ b/frontend/src/views/sql-editor/EditorCommon/ResultView/DataTable/VirtualDataTable.vue@@ -60,8 +60,9 @@<br v-else class="min-h-4 inline-flex" /></span>- <MaskingReasonPopover+ <ReactPageMountv-if="getMaskingReason && getMaskingReason(columnIndex)"+ page="MaskingReasonPopover":reason="getMaskingReason(columnIndex)!":statement="statement":database="database.name"@@ -207,6 +208,7 @@ import { useWindowSize, watchDebounced } from "@vueuse/core";import { head, last } from "lodash-es";import { NPerformantEllipsis, NVirtualList } from "naive-ui";import { computed, nextTick, onMounted, onUnmounted, ref } from "vue";+import ReactPageMount from "@/react/ReactPageMount.vue";import { DEBOUNCE_SEARCH_DELAY } from "@/types";import type { Database } from "@/types/proto-es/v1/database_service_pb";import type { MaskingReason } from "@/types/proto-es/v1/sql_service_pb";@@ -219,7 +221,6 @@ import {useBinaryFormatContext,} from "./common/binary-format-store";import ColumnSortedIcon from "./common/ColumnSortedIcon.vue";-import MaskingReasonPopover from "./common/MaskingReasonPopover.vue";import { useSelectionContext } from "./common/selection-logic";import type {ResultTableColumn,diff --git a/frontend/src/views/sql-editor/EditorCommon/ResultView/DataTable/common/MaskingReasonPopover.vue b/frontend/src/views/sql-editor/EditorCommon/ResultView/DataTable/common/MaskingReasonPopover.vuedeleted file mode 100644index 532cd5c326..0000000000--- a/frontend/src/views/sql-editor/EditorCommon/ResultView/DataTable/common/MaskingReasonPopover.vue+++ /dev/null@@ -1,124 +0,0 @@-<template>- <NPopover trigger="hover" :delay="100">- <template #trigger>- <div class="inline-flex items-center gap-0.5">- <!-- Show semantic type icon if available -->- <img- v-if="props.reason.semanticTypeIcon"- :src="props.reason.semanticTypeIcon"- class="w-3 h-3 object-contain"- alt=""- />- <EyeOffIcon- class="w-3 h-3 cursor-pointer text-gray-500 hover:text-gray-700"- @click="handleClick"- />- </div>- </template>- <div class="flex flex-col gap-y-2 max-w-sm">- <div class="font-medium flex items-center gap-2">- <img- v-if="props.reason.semanticTypeIcon"- :src="props.reason.semanticTypeIcon"- class="w-4 h-4 object-contain"- alt=""- />- {{ $t("masking.reason.title") }}- </div>-- <div v-if="props.reason.semanticTypeTitle" class="text-sm">- <span class="text-gray-500"- >{{ $t("masking.reason.semantic-type") }}:</span- >- <span class="ml-1">{{ props.reason.semanticTypeTitle }}</span>- </div>-- <div v-if="props.reason.algorithm" class="text-sm">- <span class="text-gray-500">{{ $t("masking.reason.algorithm") }}:</span>- <span class="ml-1">{{ formatAlgorithm(props.reason.algorithm) }}</span>- </div>-- <div v-if="props.reason.context" class="text-sm">- <span class="text-gray-500">{{ $t("masking.reason.context") }}:</span>- <span class="ml-1">{{ props.reason.context }}</span>- </div>-- <div v-if="props.reason.classificationLevel" class="text-sm">- <span class="text-gray-500"- >{{ $t("masking.reason.classification") }}:</span- >- <span class="ml-1">{{ props.reason.classificationLevel }}</span>- </div>-- <div v-if="hasJITFeature && statement" class="mb-2">- <NButton- size="small"- type="primary"- tertiary- @click="showDrawer = true"- >- {{ $t("sql-editor.request-jit") }}- </NButton>- </div>- </div>- </NPopover>-- <AccessGrantRequestDrawer- v-if="showDrawer"- :query="statement"- :targets="targets"- :unmask="true"- @close="showDrawer = false"- />-</template>--<script setup lang="ts">-import { EyeOffIcon } from "lucide-vue-next";-import { NButton, NPopover } from "naive-ui";-import { computed, ref } from "vue";-import { useI18n } from "vue-i18n";-import { hasFeature, useProjectV1Store, useSQLEditorStore } from "@/store";-import type { MaskingReason } from "@/types/proto-es/v1/sql_service_pb";-import { PlanFeature } from "@/types/proto-es/v1/subscription_service_pb";-import AccessGrantRequestDrawer from "@/views/sql-editor/AsidePanel/AccessPane/AccessGrantRequestDrawer.vue";--const props = defineProps<{- reason: MaskingReason;- statement?: string;- database?: string;-}>();--const emit = defineEmits<{- (event: "click"): void;-}>();--const { t } = useI18n();-const showDrawer = ref(false);-const editorStore = useSQLEditorStore();-const projectStore = useProjectV1Store();--const project = computed(() =>- projectStore.getProjectByName(editorStore.project)-);--const hasJITFeature = computed(- () =>- project.value.allowJustInTimeAccess && hasFeature(PlanFeature.FEATURE_JIT)-);--const targets = computed(() => (props.database ? [props.database] : []));--const formatAlgorithm = (algorithm: string): string => {- const algorithmKey = algorithm.toLowerCase().replace(/\s+/g, "-");- const key = `masking.algorithms.${algorithmKey}`;- const translated = t(key);- if (translated === key) {- return algorithm;- }- return translated;-};--const handleClick = () => {- emit("click");-};-</script>diff --git a/frontend/src/views/sql-editor/EditorCommon/ResultView/RequestQueryButton.vue b/frontend/src/views/sql-editor/EditorCommon/ResultView/RequestQueryButton.vuedeleted file mode 100644index 53cadee33a..0000000000--- a/frontend/src/views/sql-editor/EditorCommon/ResultView/RequestQueryButton.vue+++ /dev/null@@ -1,127 +0,0 @@-<template>- <div v-if="available">- <PermissionGuardWrapper- v-slot="slotProps"- :project="project"- :permissions="[requiredPermission]"- >- <NButton- type="primary"- :text="text"- :size="size"- :disabled="slotProps.disabled || !hasRequestFeature"- @click="onClick"- >- <template #icon>- <ShieldUserIcon v-if="hasRequestFeature" class="w-4 h-4" />- <FeatureBadge v-else :clickable="false" :feature="requiredFeature" />- </template>- {{ useJIT ? $t("sql-editor.request-jit") : $t("sql-editor.request-query") }}- </NButton>- </PermissionGuardWrapper>-- <RoleGrantPanel- v-if="showPanel"- :project-name="project.name"- :database-resources="missingResources"- :placement="'right'"- :role="PresetRoleType.SQL_EDITOR_USER"- :required-permissions="permissionDeniedDetail.requiredPermissions"- @close="showPanel = false"- />- <AccessGrantRequestDrawer- v-if="showJITDrawer"- :query="statement"- :targets="missingResources.map(r => r.databaseFullName)"- @close="showJITDrawer = false"- />- </div>-</template>--<script setup lang="ts">-import { ShieldUserIcon } from "lucide-vue-next";-import { NButton } from "naive-ui";-import { computed, ref } from "vue";-import { FeatureBadge } from "@/components/FeatureGuard";-import PermissionGuardWrapper from "@/components/Permission/PermissionGuardWrapper.vue";-import RoleGrantPanel from "@/components/RoleGrantPanel";-import { parseStringToResource } from "@/components/RoleGrantPanel/DatabaseResourceForm/common";-import { hasFeature, useProjectV1Store, useSQLEditorStore } from "@/store";-import {- type DatabaseResource,- type Permission,- PresetRoleType,-} from "@/types";-import { type PermissionDeniedDetail } from "@/types/proto-es/v1/common_pb";-import { PlanFeature } from "@/types/proto-es/v1/subscription_service_pb";-import AccessGrantRequestDrawer from "@/views/sql-editor/AsidePanel/AccessPane/AccessGrantRequestDrawer.vue";--const props = withDefaults(- defineProps<{- size?: "tiny" | "medium";- text: boolean;- statement?: string;- permissionDeniedDetail: PermissionDeniedDetail;- }>(),- {- size: "medium",- }-);--const showPanel = ref(false);-const showJITDrawer = ref(false);-const editorStore = useSQLEditorStore();-const projectStore = useProjectV1Store();--const project = computed(() =>- projectStore.getProjectByName(editorStore.project)-);--const useJIT = computed(() => {- return (- project.value.allowJustInTimeAccess &&- props.permissionDeniedDetail.requiredPermissions.every(- (p) => p === "bb.sql.select"- )- );-});--const requiredPermission = computed(- (): Permission =>- useJIT.value ? "bb.accessGrants.create" : "bb.issues.create"-);--const requiredFeature = computed(() =>- useJIT.value- ? PlanFeature.FEATURE_JIT- : PlanFeature.FEATURE_REQUEST_ROLE_WORKFLOW-);--const hasRequestFeature = computed(() => hasFeature(requiredFeature.value));--const missingResources = computed((): DatabaseResource[] => {- const resources: DatabaseResource[] = [];- for (const resourceString of props.permissionDeniedDetail.resources) {- const resource = parseStringToResource(resourceString);- if (resource) {- resources.push(resource);- }- }- return resources;-});--const available = computed(() => {- return project.value.allowRequestRole;-});--const onClick = (e: MouseEvent) => {- e.stopPropagation();- e.preventDefault();-- if (useJIT.value) {- showJITDrawer.value = true;- } else {- showPanel.value = true;- }-};-</script>diff --git a/frontend/src/views/sql-editor/EditorCommon/ResultView/ResultViewV1.vue b/frontend/src/views/sql-editor/EditorCommon/ResultView/ResultViewV1.vueindex 8ae649fc68..fc637f7bdb 100644--- a/frontend/src/views/sql-editor/EditorCommon/ResultView/ResultViewV1.vue+++ b/frontend/src/views/sql-editor/EditorCommon/ResultView/ResultViewV1.vue@@ -15,11 +15,12 @@@execute="$emit('execute', $event)"><template #suffix>- <RequestQueryButton+ <ReactPageMountv-if="!!permissionDeniedError"+ page="RequestQueryButton":text="false":statement="executeParams.statement"- :permission-denied-detail="permissionDeniedError"+ :permissionDeniedDetail="permissionDeniedError"/></template></ErrorView>@@ -71,11 +72,12 @@@execute="$emit('execute', $event)"><template #suffix>- <RequestQueryButton+ <ReactPageMountv-if="!!permissionDeniedError"+ page="RequestQueryButton":text="false":statement="result.statement"- :permission-denied-detail="permissionDeniedError"+ :permissionDeniedDetail="permissionDeniedError"/></template></ErrorView>@@ -135,11 +137,12 @@@execute="$emit('execute', $event)"><template #suffix>- <RequestQueryButton+ <ReactPageMountv-if="!!permissionDeniedError"+ page="RequestQueryButton":text="false":statement="resultSet.results[0]?.statement"- :permission-denied-detail="permissionDeniedError"+ :permissionDeniedDetail="permissionDeniedError"/><SyncDatabaseButtonv-else-if="resultSet.error.includes('resource not found')"@@ -193,6 +196,7 @@ import type {} from "@/components/DataExportButton.vue";import DataExportButton from "@/components/DataExportButton.vue";import { isDisallowChangeDatabaseError } from "@/composables/useExecuteSQL";+import ReactPageMount from "@/react/ReactPageMount.vue";import { useSQLEditorStore, useSQLEditorTabStore, useSQLStore } from "@/store";import { usePolicyV1Store } from "@/store/modules/v1/policy";import type { SQLEditorQueryParams, SQLResultSetV1 } from "@/types";@@ -205,7 +209,6 @@ import { ExportRequestSchema } from "@/types/proto-es/v1/sql_service_pb";import { extractDatabaseResourceName } from "@/utils";import EmptyView from "./EmptyView.vue";import ErrorView from "./ErrorView";-import RequestQueryButton from "./RequestQueryButton.vue";import SingleResultViewV1 from "./SingleResultViewV1.vue";type ViewMode = "SINGLE-RESULT" | "MULTI-RESULT" | "EMPTY" | "ERROR";diff --git a/frontend/src/views/sql-editor/EditorCommon/ResultView/VirtualDataBlock.vue b/frontend/src/views/sql-editor/EditorCommon/ResultView/VirtualDataBlock.vueindex 493f8a8656..442b210242 100644--- a/frontend/src/views/sql-editor/EditorCommon/ResultView/VirtualDataBlock.vue+++ b/frontend/src/views/sql-editor/EditorCommon/ResultView/VirtualDataBlock.vue@@ -39,8 +39,9 @@<div class="min-w-28 text-left flex items-center font-medium pt-1"><div class="flex items-center gap-x-1">{{ column.name }}- <MaskingReasonPopover+ <ReactPageMountv-if="getMaskingReason && getMaskingReason(columnIndex)"+ page="MaskingReasonPopover":reason="getMaskingReason(columnIndex)!":statement="statement":database="database.name"@@ -72,6 +73,7 @@import { NVirtualList } from "naive-ui";import { computed, ref } from "vue";import { CopyButton } from "@/components/v2";+import ReactPageMount from "@/react/ReactPageMount.vue";import type { Database } from "@/types/proto-es/v1/database_service_pb";import type {MaskingReason,@@ -79,7 +81,6 @@ import type {} from "@/types/proto-es/v1/sql_service_pb";import { type SearchParams } from "@/utils";import { useBinaryFormatContext } from "./DataTable/common/binary-format-store";-import MaskingReasonPopover from "./DataTable/common/MaskingReasonPopover.vue";import type {ResultTableColumn,ResultTableRow,