Skip to content

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

feat: onboarding guide for "mask sensitive data" scenario (#21440)

ecmadao2cd1864afe65
diff --git a/backend/api/v1/subscription_service.go b/backend/api/v1/subscription_service.go
index 651f3e7bae..64ad4b69ae 100644
--- a/backend/api/v1/subscription_service.go
+++ b/backend/api/v1/subscription_service.go
@@ -123,8 +123,8 @@ func (s *SubscriptionService) UploadLicense(ctx context.Context, req *connect.Re
// StartTrial starts a free trial for an eligible SaaS workspace.
func (s *SubscriptionService) StartTrial(ctx context.Context, _ *connect.Request[v1pb.StartTrialRequest]) (*connect.Response[v1pb.Subscription], error) {
- if !s.profile.SaaS || s.profile.Mode != common.ReleaseModeDev {
- return nil, connect.NewError(connect.CodeUnimplemented, errors.New("trial is only available in SaaS development mode"))
+ if !s.profile.SaaS {
+ return nil, connect.NewError(connect.CodeUnimplemented, errors.New("trial is only available in SaaS mode"))
}
workspaceID := common.GetWorkspaceIDFromContext(ctx)
diff --git a/backend/api/v1/subscription_service_trial_test.go b/backend/api/v1/subscription_service_trial_test.go
index 5e96adf6a4..7771b99ad9 100644
--- a/backend/api/v1/subscription_service_trial_test.go
+++ b/backend/api/v1/subscription_service_trial_test.go
@@ -51,11 +51,11 @@ func TestSubscriptionServiceStartTrial(t *testing.T) {
privateKey, err := rsa.GenerateKey(rand.Reader, 2048)
require.NoError(t, err)
privateKeyPEM := pem.EncodeToMemory(&pem.Block{Type: "RSA PRIVATE KEY", Bytes: x509.MarshalPKCS1PrivateKey(privateKey)})
- licenseService, err := enterprise.NewLicenseService(common.ReleaseModeDev, stores, true, string(privateKeyPEM))
+ licenseService, err := enterprise.NewLicenseService(common.ReleaseModeProd, stores, true, string(privateKeyPEM))
require.NoError(t, err)
setLicenseServicePublicKey(t, licenseService, &privateKey.PublicKey)
- service := NewSubscriptionService(&config.Profile{SaaS: true, Mode: common.ReleaseModeDev}, stores, licenseService)
+ service := NewSubscriptionService(&config.Profile{SaaS: true, Mode: common.ReleaseModeProd}, stores, licenseService)
createWorkspace := func(t *testing.T, workspace string) context.Context {
t.Helper()
_, err := stores.GetDB().ExecContext(ctx, `INSERT INTO workspace (resource_id) VALUES ($1)`, workspace)
@@ -155,15 +155,17 @@ func TestSubscriptionServiceStartTrial(t *testing.T) {
require.Equal(t, connect.CodeUnimplemented, connect.CodeOf(err))
})
- t.Run("rejects SaaS production", func(t *testing.T) {
- requestContext := createWorkspace(t, "saas-production")
- productionService := NewSubscriptionService(&config.Profile{SaaS: true, Mode: common.ReleaseModeProd}, stores, licenseService)
- _, err := productionService.StartTrial(requestContext, connect.NewRequest(&v1pb.StartTrialRequest{}))
- require.Equal(t, connect.CodeUnimplemented, connect.CodeOf(err))
+ t.Run("starts trial in SaaS development", func(t *testing.T) {
+ requestContext := createWorkspace(t, "saas-development")
+ developmentService := NewSubscriptionService(&config.Profile{SaaS: true, Mode: common.ReleaseModeDev}, stores, licenseService)
+ response, err := developmentService.StartTrial(requestContext, connect.NewRequest(&v1pb.StartTrialRequest{}))
+ require.NoError(t, err)
+ require.Equal(t, v1pb.PlanType_ENTERPRISE, response.Msg.Plan)
+ require.True(t, response.Msg.Trialing)
})
- t.Run("rejects license upload in SaaS development", func(t *testing.T) {
- requestContext := createWorkspace(t, "saas-development-upload")
+ t.Run("rejects license upload in SaaS production", func(t *testing.T) {
+ requestContext := createWorkspace(t, "saas-production-upload")
_, err := service.UploadLicense(requestContext, connect.NewRequest(&v1pb.UploadLicenseRequest{}))
require.Equal(t, connect.CodeUnimplemented, connect.CodeOf(err))
})
diff --git a/frontend/scripts/check-i18n.mjs b/frontend/scripts/check-i18n.mjs
index 9af44b96a4..0a2d7f3a24 100644
--- a/frontend/scripts/check-i18n.mjs
+++ b/frontend/scripts/check-i18n.mjs
@@ -63,6 +63,7 @@ const DYNAMIC_PREFIXES = [
// definitions and translated through those definitions at render time.
"settings.profile.enable-sample-databases",
"settings.profile.setup-scenario.create-database-change.",
+ "settings.profile.setup-scenario.mark-sensitive-data.",
"settings.profile.setup-scenario.query-data.",
"settings.profile.setup-scenario.workspace-usage.",
// Workspace setup guide step definitions store label and description keys;
diff --git a/frontend/src/components/FeatureAttention.test.tsx b/frontend/src/components/FeatureAttention.test.tsx
index f932b2c3b6..ece426e1a8 100644
--- a/frontend/src/components/FeatureAttention.test.tsx
+++ b/frontend/src/components/FeatureAttention.test.tsx
@@ -1,3 +1,4 @@
+import { Code, ConnectError } from "@connectrpc/connect";
import type { ReactElement } from "react";
import { act } from "react";
import { createRoot } from "react-dom/client";
@@ -20,6 +21,7 @@ const mocks = vi.hoisted(() => ({
useSubscriptionState: vi.fn(),
useServerState: vi.fn(),
useAppStore: vi.fn(),
+ startTrial: vi.fn(),
hasWorkspacePermissionV2: vi.fn(() => true),
autoSubscriptionRoute: vi.fn(() => "/subscription"),
routerPush: vi.fn(),
@@ -95,13 +97,17 @@ const renderIntoContainer = (element: ReactElement) => {
};
beforeEach(async () => {
+ mocks.startTrial.mockReset();
+ mocks.startTrial.mockResolvedValue(undefined);
mocks.useTranslation.mockReset();
mocks.useTranslation.mockReturnValue({
t: (key: string) => key,
});
mocks.useSubscriptionState.mockReset();
mocks.useSubscriptionState.mockReturnValue({
+ canStartTrial: false,
isTrialing: false,
+ startTrial: mocks.startTrial,
trialingDays: 14,
});
mocks.useServerState.mockReset();
@@ -180,9 +186,97 @@ describe("FeatureAttention", () => {
unmount();
});
+ test("starts an eligible SaaS trial from the feature attention", async () => {
+ mocks.useSubscriptionState.mockReturnValue({
+ canStartTrial: true,
+ isTrialing: false,
+ startTrial: mocks.startTrial,
+ trialingDays: 14,
+ });
+ const { container, render, unmount } = renderIntoContainer(
+ <FeatureAttention feature={PlanFeature.FEATURE_AUDIT_LOG} />
+ );
+
+ render();
+
+ const actionButton = [...container.querySelectorAll("button")].find(
+ (button) => button.textContent?.includes("subscription.plan.try")
+ );
+ expect(actionButton).toBeDefined();
+ await act(async () => {
+ actionButton?.dispatchEvent(
+ new MouseEvent("click", { bubbles: true, cancelable: true })
+ );
+ await Promise.resolve();
+ });
+
+ expect(mocks.startTrial).toHaveBeenCalledOnce();
+ unmount();
+ });
+
+ test.each([
+ new ConnectError("temporarily unavailable", Code.Unavailable),
+ new ConnectError("server failure", Code.Internal),
+ new Error("network failure"),
+ ])("keeps trial activation retryable after %s", async (error) => {
+ mocks.startTrial.mockRejectedValueOnce(error);
+ mocks.useSubscriptionState.mockReturnValue({
+ canStartTrial: true,
+ isTrialing: false,
+ startTrial: mocks.startTrial,
+ trialingDays: 14,
+ });
+ const { container, render, unmount } = renderIntoContainer(
+ <FeatureAttention feature={PlanFeature.FEATURE_DATA_MASKING} />
+ );
+ render();
+ const button = container.querySelector("button");
+ expect(button).not.toBeNull();
+ await act(async () => {
+ button?.dispatchEvent(new MouseEvent("click", { bubbles: true }));
+ });
+ expect(button?.textContent).toBe("subscription.plan.try");
+ expect(button?.disabled).toBe(false);
+ await act(async () => {
+ button?.dispatchEvent(new MouseEvent("click", { bubbles: true }));
+ });
+ expect(mocks.startTrial).toHaveBeenCalledTimes(2);
+ expect(mocks.routerPush).not.toHaveBeenCalled();
+ unmount();
+ });
+
+ test("opens plan details after a definitive trial rejection", async () => {
+ mocks.startTrial.mockRejectedValueOnce(
+ new ConnectError("not eligible", Code.FailedPrecondition)
+ );
+ mocks.useSubscriptionState.mockReturnValue({
+ canStartTrial: true,
+ isTrialing: false,
+ startTrial: mocks.startTrial,
+ trialingDays: 14,
+ });
+ const { container, render, unmount } = renderIntoContainer(
+ <FeatureAttention feature={PlanFeature.FEATURE_DATA_MASKING} />
+ );
+ render();
+ const button = container.querySelector("button");
+ await act(async () => {
+ button?.dispatchEvent(new MouseEvent("click", { bubbles: true }));
+ });
+ expect(button?.textContent).toBe("common.learn-more");
+ act(() => {
+ button?.dispatchEvent(new MouseEvent("click", { bubbles: true }));
+ });
+ expect(mocks.startTrial).toHaveBeenCalledOnce();
+ expect(mocks.routerPush).toHaveBeenCalledWith("/subscription");
+ unmount();
+ });
+
test("does not show assignment attention in unified instance license mode", () => {
mocks.useSubscriptionState.mockReturnValue({
+ canStartTrial: false,
isTrialing: false,
+ startTrial: mocks.startTrial,
trialingDays: 14,
});
mocks.useServerState.mockReturnValue({
diff --git a/frontend/src/components/FeatureAttention.tsx b/frontend/src/components/FeatureAttention.tsx
index e6bb354156..09a7ae8b33 100644
--- a/frontend/src/components/FeatureAttention.tsx
+++ b/frontend/src/components/FeatureAttention.tsx
@@ -1,3 +1,5 @@
+import { Code, ConnectError } from "@connectrpc/connect";
+import { LoaderCircle } from "lucide-react";
import { useState } from "react";
import { useTranslation } from "react-i18next";
import { router } from "@/app/router";
@@ -27,9 +29,12 @@ export function FeatureAttention({
instance?: Instance | InstanceResource;
}) {
const { t } = useTranslation();
- const { trialingDays, isTrialing } = useSubscriptionState();
+ const { canStartTrial, isTrialing, startTrial, trialingDays } =
+ useSubscriptionState();
const { totalInstanceCount, activatedInstanceCount } = useServerState();
const [showInstanceAssignment, setShowInstanceAssignment] = useState(false);
+ const [startingTrial, setStartingTrial] = useState(false);
+ const [trialRejected, setTrialRejected] = useState(false);
const hasFeature = useAppStore((state) => state.hasInstanceFeature(feature));
const instanceMissingLicense = useAppStore((state) =>
@@ -88,14 +93,25 @@ export function FeatureAttention({
descriptionText = `${featureDesc}\n${attention}`;
}
- const hasPermission = hasWorkspacePermissionV2("bb.settings.set");
+ const canManageSettings = hasWorkspacePermissionV2("bb.settings.set");
+ const canManageSubscription = hasWorkspacePermissionV2(
+ "bb.subscription.manage"
+ );
+ const canOfferTrial = canStartTrial && !trialRejected;
+ const hasPermission = canOfferTrial
+ ? canManageSubscription
+ : canManageSettings || (trialRejected && canManageSubscription);
let actionText = "";
if (hasPermission) {
if (!hasFeature) {
- actionText = t("subscription.request-n-days-trial", {
- days: trialingDays,
- });
+ actionText = canOfferTrial
+ ? t("subscription.plan.try")
+ : trialRejected
+ ? t("common.learn-more")
+ : t("subscription.request-n-days-trial", {
+ days: trialingDays,
+ });
} else if (
!hasUnifiedInstanceLicense &&
hasWorkspacePermissionV2("bb.instances.update")
@@ -104,8 +120,25 @@ export function FeatureAttention({
}
}
- const onAction = () => {
+ const onAction = async () => {
if (!hasFeature) {
+ if (canOfferTrial) {
+ setStartingTrial(true);
+ try {
+ await startTrial();
+ } catch (error) {
+ if (ConnectError.from(error).code === Code.FailedPrecondition) {
+ setTrialRejected(true);
+ }
+ } finally {
+ setStartingTrial(false);
+ }
+ return;
+ }
+ if (trialRejected) {
+ void router.push(autoSubscriptionRoute());
+ return;
+ }
window.open(ENTERPRISE_INQUIRE_LINK, "_blank");
return;
}
@@ -131,8 +164,10 @@ export function FeatureAttention({
appearance="solid"
size="sm"
className="shrink-0 whitespace-nowrap"
- onClick={onAction}
+ disabled={startingTrial}
+ onClick={() => void onAction()}
>
+ {startingTrial && <LoaderCircle className="animate-spin" />}
{actionText}
</Button>
</div>
diff --git a/frontend/src/components/ui/feature-modal.test.tsx b/frontend/src/components/ui/feature-modal.test.tsx
index 605b7fa6c4..3df9512378 100644
--- a/frontend/src/components/ui/feature-modal.test.tsx
+++ b/frontend/src/components/ui/feature-modal.test.tsx
@@ -1,3 +1,4 @@
+import { Code, ConnectError } from "@connectrpc/connect";
import { act, type ReactElement } from "react";
import { createRoot } from "react-dom/client";
import { beforeEach, describe, expect, test, vi } from "vitest";
@@ -7,12 +8,15 @@ import { beforeEach, describe, expect, test, vi } from "vitest";
).IS_REACT_ACT_ENVIRONMENT = true;
const mocks = vi.hoisted(() => ({
+ cancelDismissal: vi.fn(),
captureFeatureGateMetric: vi.fn(),
useSubscriptionState: vi.fn(),
useAppStore: vi.fn(),
instanceMissingLicense: false,
requiredPlan: 1, // TEAM
showTrial: false,
+ canStartTrial: false,
+ startTrial: vi.fn(),
trialingDays: 14,
hasWorkspacePermissionV2: vi.fn().mockReturnValue(true),
}));
@@ -78,13 +82,13 @@ vi.mock("@/components/ui/dialog", () => ({
}: {
open: boolean;
children: React.ReactNode;
- onOpenChange: (v: boolean) => void;
+ onOpenChange: (v: boolean, details: { cancel: () => void }) => void;
}) => (
<div data-testid="dialog" data-open={String(open)}>
{open ? children : null}
<button
data-testid="dialog-close"
- onClick={() => onOpenChange(false)}
+ onClick={() => onOpenChange(false, { cancel: mocks.cancelDismissal })}
type="button"
/>
</div>
@@ -97,12 +101,19 @@ vi.mock("@/components/ui/dialog", () => ({
),
DialogClose: ({
children,
+ disabled,
"aria-label": ariaLabel,
}: {
children: React.ReactNode;
+ disabled?: boolean;
"aria-label"?: string;
}) => (
- <button data-testid="dialog-close-x" aria-label={ariaLabel} type="button">
+ <button
+ data-testid="dialog-close-x"
+ aria-label={ariaLabel}
+ disabled={disabled}
+ type="button"
+ >
{children}
</button>
),
@@ -112,11 +123,18 @@ vi.mock("@/components/ui/button", () => ({
Button: ({
children,
onClick,
+ disabled,
}: {
children: React.ReactNode;
onClick?: () => void;
+ disabled?: boolean;
}) => (
- <button data-testid="button" onClick={onClick} type="button">
+ <button
+ data-testid="button"
+ onClick={onClick}
+ disabled={disabled}
+ type="button"
+ >
{children}
</button>
),
@@ -149,9 +167,13 @@ beforeEach(async () => {
mocks.instanceMissingLicense = false;
mocks.requiredPlan = 1;
mocks.showTrial = false;
+ mocks.canStartTrial = false;
+ mocks.startTrial.mockResolvedValue(undefined);
mocks.trialingDays = 14;
mocks.useSubscriptionState.mockReturnValue({
+ canStartTrial: mocks.canStartTrial,
showTrial: mocks.showTrial,
+ startTrial: mocks.startTrial,
trialingDays: mocks.trialingDays,
});
mocks.useAppStore.mockImplementation(
@@ -268,4 +290,189 @@ describe("FeatureModal", () => {
);
unmount();
});
+
+ test("starts an eligible SaaS trial and continues the guarded action", async () => {
+ mocks.canStartTrial = true;
+ mocks.useSubscriptionState.mockReturnValue({
+ canStartTrial: true,
+ showTrial: false,
+ startTrial: mocks.startTrial,
+ trialingDays: 14,
+ });
+ const onOpenChange = vi.fn();
+ const onFeatureUnlocked = vi.fn();
+ const { container, render, unmount } = renderIntoContainer(
+ <FeatureModal
+ open
+ feature={1}
+ onOpenChange={onOpenChange}
+ onFeatureUnlocked={onFeatureUnlocked}
+ />
+ );
+ render();
+
+ const button = [...container.querySelectorAll("[data-testid='button']")].find(
+ (element) => element.textContent === "subscription.plan.try"
+ );
+ expect(button).toBeDefined();
+ await act(async () => {
+ button?.dispatchEvent(new MouseEvent("click", { bubbles: true }));
+ await Promise.resolve();
+ });
+
+ expect(mocks.startTrial).toHaveBeenCalledOnce();
+ expect(onOpenChange).toHaveBeenCalledWith(false);
+ expect(onFeatureUnlocked).toHaveBeenCalledOnce();
+ unmount();
+ });
+
+ test.each([false, true])(
+ "blocks dismissal during trial activation (failed: %s)",
+ async (failed) => {
+ let resolveTrial!: () => void;
+ let rejectTrial!: (error: unknown) => void;
+ mocks.startTrial.mockReturnValueOnce(
+ new Promise<void>((resolve, reject) => {
+ resolveTrial = resolve;
+ rejectTrial = reject;
+ })
+ );
+ mocks.useSubscriptionState.mockReturnValue({
+ canStartTrial: true,
+ showTrial: false,
+ startTrial: mocks.startTrial,
+ trialingDays: 14,
+ });
+ const onOpenChange = vi.fn();
+ const onFeatureUnlocked = vi.fn();
+ const { container, render, unmount } = renderIntoContainer(
+ <FeatureModal
+ open
+ feature={1}
+ onOpenChange={onOpenChange}
+ onFeatureUnlocked={onFeatureUnlocked}
+ />
+ );
+ render();
+ const button = container.querySelector<HTMLButtonElement>(
+ "[data-testid='button']"
+ );
+ act(() => {
+ button?.dispatchEvent(new MouseEvent("click", { bubbles: true }));
+ });
+ expect(mocks.startTrial).toHaveBeenCalledOnce();
+ expect(button?.disabled).toBe(true);
+
+ const closeButton = container.querySelector<HTMLButtonElement>(
+ "[data-testid='dialog-close-x']"
+ );
+ expect(closeButton?.disabled).toBe(true);
+ act(() => {
+ container.querySelector("[data-testid='dialog-close']")?.dispatchEvent(
+ new MouseEvent("click", { bubbles: true })
+ );
+ });
+ expect(mocks.cancelDismissal).toHaveBeenCalledOnce();
+ expect(onOpenChange).not.toHaveBeenCalled();
+
+ await act(async () => {
+ if (failed) {
+ rejectTrial(new ConnectError("unavailable", Code.Unavailable));
+ } else {
+ resolveTrial();
+ }
+ });
+ if (failed) {
+ expect(onFeatureUnlocked).not.toHaveBeenCalled();
+ expect(onOpenChange).not.toHaveBeenCalled();
+ expect(closeButton?.disabled).toBe(false);
+ act(() => {
+ container.querySelector("[data-testid='dialog-close']")?.dispatchEvent(
+ new MouseEvent("click", { bubbles: true })
+ );
+ });
+ expect(mocks.cancelDismissal).toHaveBeenCalledOnce();
+ } else {
+ expect(onFeatureUnlocked).toHaveBeenCalledOnce();
+ }
+ expect(onOpenChange).toHaveBeenCalledWith(false);
+ unmount();
+ }
+ );
+
+ test.each([
+ new ConnectError("temporarily unavailable", Code.Unavailable),
+ new ConnectError("server failure", Code.Internal),
+ new Error("network failure"),
+ ])("keeps trial activation retryable after %s", async (error) => {
+ mocks.startTrial.mockRejectedValueOnce(error);
+ mocks.useSubscriptionState.mockReturnValue({
+ canStartTrial: true,
+ showTrial: false,
+ startTrial: mocks.startTrial,
+ trialingDays: 14,
+ });
+ const onOpenChange = vi.fn();
+ const onFeatureUnlocked = vi.fn();
+ const { container, render, unmount } = renderIntoContainer(
+ <FeatureModal
+ open
+ feature={1}
+ onOpenChange={onOpenChange}
+ onFeatureUnlocked={onFeatureUnlocked}
+ />
+ );
+ render();
+ const button = container.querySelector<HTMLButtonElement>(
+ "[data-testid='button']"
+ );
+ expect(button).not.toBeNull();
+ await act(async () => {
+ button?.dispatchEvent(new MouseEvent("click", { bubbles: true }));
+ });
+ expect(button?.textContent).toBe("subscription.plan.try");
+ expect(button?.disabled).toBe(false);
+ expect(onOpenChange).not.toHaveBeenCalled();
+ expect(onFeatureUnlocked).not.toHaveBeenCalled();
+ await act(async () => {
+ button?.dispatchEvent(new MouseEvent("click", { bubbles: true }));
+ });
+ expect(mocks.startTrial).toHaveBeenCalledTimes(2);
+ expect(onOpenChange).toHaveBeenCalledWith(false);
+ expect(onFeatureUnlocked).toHaveBeenCalledOnce();
+ unmount();
+ });
+
+ test("falls back to plan details when trial activation is rejected", async () => {
+ mocks.startTrial.mockRejectedValue(
+ new ConnectError("not eligible", Code.FailedPrecondition)
+ );
+ mocks.useSubscriptionState.mockReturnValue({
+ canStartTrial: true,
+ showTrial: false,
+ startTrial: mocks.startTrial,
+ trialingDays: 14,
+ });
+ const onOpenChange = vi.fn();
+ const { container, render, unmount } = renderIntoContainer(
+ <FeatureModal open feature={1} onOpenChange={onOpenChange} />
+ );
+ render();
+
+ const startButton = [
+ ...container.querySelectorAll("[data-testid='button']"),
+ ].find((element) => element.textContent === "subscription.plan.try");
+ await act(async () => {
+ startButton?.dispatchEvent(new MouseEvent("click", { bubbles: true }));
+ await Promise.resolve();
+ });
+
+ expect(onOpenChange).not.toHaveBeenCalled();
+ expect(
+ [...container.querySelectorAll("[data-testid='button']")].some(
+ (element) => element.textContent === "common.learn-more"
+ )
+ ).toBe(true);
+ unmount();
+ });
});
diff --git a/frontend/src/components/ui/feature-modal.tsx b/frontend/src/components/ui/feature-modal.tsx
index 07e03d02b7..b8b14c0fd6 100644
--- a/frontend/src/components/ui/feature-modal.tsx
+++ b/frontend/src/components/ui/feature-modal.tsx
@@ -1,5 +1,6 @@
-import { Lock, Sparkles, X } from "lucide-react";
-import { useEffect, useRef } from "react";
+import { Code, ConnectError } from "@connectrpc/connect";
+import { LoaderCircle, Lock, Sparkles, X } from "lucide-react";
+import { useEffect, useRef, useState } from "react";
import { useTranslation } from "react-i18next";
import { captureFeatureGateMetric } from "@/app/analytics/feature-gate";
import { router } from "@/app/router";
@@ -29,6 +30,7 @@ type Props = {
readonly feature: PlanFeature | undefined;
readonly instance?: Instance | InstanceResource;
readonly onOpenChange: (open: boolean) => void;
+ readonly onFeatureUnlocked?: () => void;
};
const planLabel: Record<number, string> = {
@@ -44,11 +46,23 @@ const planLabel: Record<number, string> = {
* - Required plan above FREE → plan name + trial or contact-admin line.
* - Required plan equals FREE → trial-for-days line.
*/
-export function FeatureModal({ open, feature, instance, onOpenChange }: Props) {
+export function FeatureModal({
+ open,
+ feature,
+ instance,
+ onOpenChange,
+ onFeatureUnlocked,
+}: Props) {
const { t } = useTranslation();
- const { showTrial, trialingDays } = useSubscriptionState();
- const hasPermission = hasWorkspacePermissionV2("bb.settings.set");
+ const { canStartTrial, showTrial, startTrial, trialingDays } =
+ useSubscriptionState();
+ const canManageSettings = hasWorkspacePermissionV2("bb.settings.set");
+ const canManageSubscription = hasWorkspacePermissionV2(
+ "bb.subscription.manage"
+ );
const wasOpenRef = useRef(false);
+ const [startingTrial, setStartingTrial] = useState(false);
+ const [trialRejected, setTrialRejected] = useState(false);
const resolvedFeature = feature ?? PlanFeature.FEATURE_UNSPECIFIED;
const instanceMissingLicense = useAppStore((state) =>
@@ -61,6 +75,7 @@ export function FeatureModal({ open, feature, instance, onOpenChange }: Props) {
useEffect(() => {
const isOpen = open && !!feature;
if (isOpen && !wasOpenRef.current) {
+ setTrialRejected(false);
captureFeatureGateMetric(
"locked feature clicked",
resolvedFeature,
@@ -81,6 +96,12 @@ export function FeatureModal({ open, feature, instance, onOpenChange }: Props) {
const close = () => onOpenChange(false);
+ const canOfferTrial =
+ canStartTrial && !instanceMissingLicense && !trialRejected;
+ const hasPermission = canOfferTrial
+ ? canManageSubscription
+ : canManageSettings || (trialRejected && canManageSubscription);
+
const confirmLabel = instanceMissingLicense
? t("subscription.instance-assignment.assign-license")
: t("common.learn-more");
@@ -100,6 +121,21 @@ export function FeatureModal({ open, feature, instance, onOpenChange }: Props) {
close();
};
+ const handleStartTrial = async () => {
+ setStartingTrial(true);
+ try {
+ await startTrial();
+ close();
+ onFeatureUnlocked?.();
+ } catch (error) {
+ if (ConnectError.from(error).code === Code.FailedPrecondition) {
+ setTrialRejected(true);
+ }
+ } finally {
+ setStartingTrial(false);
+ }
+ };
+
const requiredPlanLabel = t(
`subscription.plan.${planLabel[requiredPlan] ?? "enterprise"}.title`
);
@@ -108,17 +144,24 @@ export function FeatureModal({ open, feature, instance, onOpenChange }: Props) {
: t("subscription.contact-to-upgrade");
return (
- <Dialog open={open} onOpenChange={onOpenChange}>
+ <Dialog
+ open={open}
+ onOpenChange={(nextOpen, details) => {
+ if (startingTrial) {
+ details.cancel();
+ return;
+ }
+ onOpenChange(nextOpen);
+ }}
+ >
<DialogContent className="max-w-2xl">
<div>
<div className="flex items-center justify-between border-b pb-2 mb-4">
<DialogTitle className="text-base font-medium">{title}</DialogTitle>
- {/* The Dialog primitive has no built-in close button; render one
- explicitly so users can dismiss the paywall regardless of
- which CTA path renders below. */}
<DialogClose
aria-label={t("common.close")}
- className="rounded-xs p-1 text-control hover:bg-control-bg focus:outline-hidden focus-visible:ring-2 focus-visible:ring-accent cursor-pointer"
+ disabled={startingTrial}
+ className="rounded-xs p-1 text-control hover:bg-control-bg focus:outline-hidden focus-visible:ring-2 focus-visible:ring-accent cursor-pointer disabled:cursor-not-allowed disabled:opacity-50"
>
<X className="size-4" />
</DialogClose>
@@ -164,6 +207,15 @@ export function FeatureModal({ open, feature, instance, onOpenChange }: Props) {
<Button variant="default" onClick={close}>
{t("common.ok")}
</Button>
+ ) : canOfferTrial ? (
+ <Button
+ variant="default"
+ disabled={startingTrial}
+ onClick={() => void handleStartTrial()}
+ >
+ {startingTrial && <LoaderCircle className="animate-spin" />}
+ {t("subscription.plan.try")}
+ </Button>
) : showTrial && !instanceMissingLicense ? (
<Button
variant="default"
diff --git a/frontend/src/components/ui/select.test.tsx b/frontend/src/components/ui/select.test.tsx
index 094349e6be..099b221fcc 100644
--- a/frontend/src/components/ui/select.test.tsx
+++ b/frontend/src/components/ui/select.test.tsx
@@ -1,6 +1,7 @@
import * as stylex from "@stylexjs/stylex";
import { act, type CSSProperties, type ReactNode } from "react";
import { createRoot } from "react-dom/client";
+import { cleanup, fireEvent, render, screen } from "@testing-library/react";
import { afterEach, describe, expect, test, vi } from "vitest";
import { Select, SelectContent, SelectItem, SelectTrigger } from "./select";
import {
@@ -59,7 +60,7 @@ vi.mock("@base-ui/react/select", () => ({
</div>
),
ItemIndicator: ({ children }: { children: ReactNode }) => <>{children}</>,
- ItemText: ({ children }: { children: ReactNode }) => <>{children}</>,
+ ItemText: ({ children }: { children: ReactNode }) => <span>{children}</span>,
},
}));
@@ -155,6 +156,95 @@ describe("SelectContent", () => {
});
});
+describe("Select multi-select chips", () => {
+ afterEach(cleanup);
+
+ async function loadSelect() {
+ vi.resetModules();
+ vi.doUnmock("@base-ui/react/select");
+ return import("./select");
+ }
+
+ test("removes a labeled chip without opening the dropdown and restores the placeholder", async () => {
+ const { Select, SelectTrigger, SelectValue } = await loadSelect();
+ const onValueChange = vi.fn();
+ const props = {
+ multiple: true as const,
+ items: { email: "Email", phone: "Phone" },
+ onValueChange,
+ };
+ const view = render(
+ <Select {...props} value={["email", "phone"]}>
+ <SelectTrigger aria-label="Columns">
+ <SelectValue placeholder="Select columns" />
+ </SelectTrigger>
+ </Select>
+ );
+
+ const remove = screen.getAllByRole("button");
+ expect(remove).toHaveLength(2);
+ expect(remove[0]?.closest("button button")).toBeNull();
+ fireEvent.pointerDown(remove[0]!, { pointerType: "mouse" });
+ fireEvent.mouseDown(remove[0]!);
+ fireEvent.click(remove[0]!);
+ expect(onValueChange.mock.calls[0]?.[0]).toEqual(["phone"]);
+ expect(screen.getByRole("combobox")).toHaveAttribute("aria-expanded", "false");
+
+ view.rerender(
+ <Select {...props} value={[]}>
+ <SelectTrigger aria-label="Columns">
+ <SelectValue placeholder="Select columns" />
+ </SelectTrigger>
+ </Select>
+ );
+ expect(screen.getByText("Select columns")).toBeTruthy();
+ expect(screen.queryAllByRole("button")).toHaveLength(0);
+ });
+
+ test("honors cancellation of chip removal", async () => {
+ const { Select, SelectTrigger, SelectValue } = await loadSelect();
+ render(
+ <Select
+ multiple
+ defaultValue={["Email"]}
+ onValueChange={(_, details) => details.cancel()}
+ >
+ <SelectTrigger>
+ <SelectValue />
+ </SelectTrigger>
+ </Select>
+ );
+ fireEvent.click(screen.getByRole("button"));
+ expect(screen.getByText("Email")).toBeTruthy();
+ });
+
+ test("supports removing uncontrolled values and hides removal when disabled or read-only", async () => {
+ const { Select, SelectTrigger, SelectValue } = await loadSelect();
+ const view = render(
+ <Select multiple defaultValue={["Email", "Phone"]}>
+ <SelectTrigger>
+ <SelectValue />
+ </SelectTrigger>
+ </Select>
+ );
+ fireEvent.click(screen.getAllByRole("button")[0]!);
+ expect(screen.queryByText("Email")).toBeNull();
+ expect(screen.getByText("Phone")).toBeTruthy();
+
+ for (const state of [{ disabled: true }, { readOnly: true }]) {
+ view.rerender(
+ <Select multiple value={["Phone"]} {...state}>
+ <SelectTrigger>
+ <SelectValue />
+ </SelectTrigger>
+ </Select>
+ );
+ expect(screen.queryAllByRole("button")).toHaveLength(0);
+ expect(screen.getByText("Phone")).toBeTruthy();
+ }
+ });
+});
+
describe("SelectTrigger", () => {
afterEach(() => {
document.body.innerHTML = "";
@@ -208,6 +298,8 @@ describe("SelectItem", () => {
stylex.props(menuRowStyle("sm")).className ?? ""
);
expect(option?.className).toContain(menuRowStateClassName);
+ expect(option?.firstElementChild?.textContent).toBe("Alpha");
+ expect(option?.lastElementChild?.querySelector("svg")).not.toBeNull();
await act(async () => {
root.unmount();
diff --git a/frontend/src/components/ui/select.tsx b/frontend/src/components/ui/select.tsx
index 83d636354c..a15024d784 100644
--- a/frontend/src/components/ui/select.tsx
+++ b/frontend/src/components/ui/select.tsx
@@ -1,12 +1,21 @@
import { Select as BaseSelect } from "@base-ui/react/select";
import * as stylex from "@stylexjs/stylex";
import { cva } from "class-variance-authority";
-import { Check, ChevronDown } from "lucide-react";
-import type { ComponentProps } from "react";
+import { Check, ChevronDown, X } from "lucide-react";
+import {
+ type ComponentProps,
+ createContext,
+ type MouseEvent,
+ type ReactNode,
+ useContext,
+ useState,
+} from "react";
+import { useTranslation } from "react-i18next";
import { cn } from "@/lib/utils";
import { getLayerRoot, LAYER_SURFACE_CLASS } from "./layer";
import {
type ControlSize,
+ controlMinHeightStyle,
controlSizeStyle,
menuRowStateClassName,
menuRowStyle,
@@ -14,7 +23,95 @@ import {
} from "./styles.stylex";
// ---- Root ----
-const Select = BaseSelect.Root;
+const SelectContext = createContext<{
+ multiple: boolean;
+ disabled: boolean;
+ getLabel: (value: unknown) => ReactNode;
+ removeValue: (value: unknown, event: MouseEvent<HTMLButtonElement>) => void;
+} | null>(null);
+
+function Select<Value, Multiple extends boolean | undefined = false>(
+ props: BaseSelect.Root.Props<Value, Multiple>
+) {
+ type ChangedValue = Parameters<NonNullable<typeof props.onValueChange>>[0];
+ const [uncontrolledValue, setUncontrolledValue] = useState(
+ (props.defaultValue ?? (props.multiple ? [] : null)) as ChangedValue
+ );
+ const value = props.value === undefined ? uncontrolledValue : props.value;
+ const disabled = !!(props.disabled || props.readOnly);
+
+ const handleValueChange = (
+ nextValue: ChangedValue,
+ details: BaseSelect.Root.ChangeEventDetails
+ ) => {
+ props.onValueChange?.(nextValue, details);
+ if (!details.isCanceled && props.value === undefined) {
+ setUncontrolledValue(nextValue);
+ }
+ };
+
+ const getLabel = (itemValue: unknown): ReactNode => {
+ if (props.itemToStringLabel) {
+ return props.itemToStringLabel(itemValue as Value);
+ }
+ if (itemValue && typeof itemValue === "object" && "label" in itemValue) {
+ return itemValue.label as ReactNode;
+ }
+ if (Array.isArray(props.items)) {
+ const items = props.items.flatMap((item) =>
+ "items" in item ? item.items : [item]
+ );
+ return (
+ items.find((item) =>
+ props.isItemEqualToValue
+ ? props.isItemEqualToValue(item.value, itemValue as Value)
+ : Object.is(item.value, itemValue)
+ )?.label ?? String(itemValue)
+ );
+ }
+ return (
+ (props.items as Record<string, ReactNode> | undefined)?.[
+ String(itemValue)
+ ] ?? String(itemValue)
+ );
+ };
+
+ return (
+ <SelectContext.Provider
+ value={{
+ multiple: !!props.multiple,
+ disabled,
+ getLabel,
+ removeValue: (itemValue, event) => {
+ if (disabled || !Array.isArray(value)) return;
+ const details: BaseSelect.Root.ChangeEventDetails = {
+ reason: "none",
+ event: event.nativeEvent,
+ trigger: event.currentTarget,
+ isCanceled: false,
+ isPropagationAllowed: false,
+ cancel() {
+ details.isCanceled = true;
+ },
+ allowPropagation() {
+ details.isPropagationAllowed = true;
+ },
+ };
+ handleValueChange(
+ value.filter((item) => !Object.is(item, itemValue)) as ChangedValue,
+ details
+ );
+ },
+ }}
+ >
+ <BaseSelect.Root
+ {...props}
+ value={value}
+ onValueChange={handleValueChange}
+ />
+ </SelectContext.Provider>
+ );
+}
// ---- Trigger ----
const selectTriggerVariants = cva(
@@ -38,24 +135,99 @@ function SelectTrigger({
style,
...props
}: SelectTriggerProps) {
- const stylexProps = stylex.props(controlSizeStyle(size));
+ const context = useContext(SelectContext);
+ const multiple = !!context?.multiple;
+ const stylexProps = stylex.props(
+ multiple ? controlMinHeightStyle(size) : controlSizeStyle(size)
+ );
return (
- <BaseSelect.Trigger
- {...props}
- ref={ref}
- className={cn(selectTriggerVariants(), stylexProps.className, className)}
- style={{ ...stylexProps.style, ...style }}
+ <SelectContext.Provider
+ value={
+ context
+ ? { ...context, disabled: context.disabled || !!props.disabled }
+ : null
+ }
>
- {children}
- <BaseSelect.Icon>
- <ChevronDown className="size-3.5 opacity-50 shrink-0" />
- </BaseSelect.Icon>
- </BaseSelect.Trigger>
+ <BaseSelect.Trigger
+ {...props}
+ // Chip removal buttons cannot be nested inside a native button.
+ {...(multiple ? { render: <div />, nativeButton: false } : {})}
+ ref={ref}
+ className={cn(
+ selectTriggerVariants(),
+ stylexProps.className,
+ multiple &&
+ "py-1 aria-disabled:pointer-events-none aria-disabled:opacity-50",
+ className
+ )}
+ style={{ ...stylexProps.style, ...style }}
+ >
+ {children}
+ <BaseSelect.Icon>
+ <ChevronDown className="size-3.5 opacity-50 shrink-0" />
+ </BaseSelect.Icon>
+ </BaseSelect.Trigger>
+ </SelectContext.Provider>
);
}
// ---- Value ----
-const SelectValue = BaseSelect.Value;
+function SelectValue({
+ children,
+ className,
+ ...props
+}: ComponentProps<typeof BaseSelect.Value>) {
+ const context = useContext(SelectContext);
+ const { t } = useTranslation();
+ if (!context?.multiple || children != null) {
+ return (
+ <BaseSelect.Value {...props} className={className}>
+ {children}
+ </BaseSelect.Value>
+ );
+ }
+ return (
+ <BaseSelect.Value
+ {...props}
+ className={cn("flex min-w-0 flex-1 flex-wrap gap-1", className)}
+ >
+ {(values: unknown[]) =>
+ !Array.isArray(values) || values.length === 0
+ ? props.placeholder
+ : values.map((value, index) => (
+ <span
+ key={index}
+ className="inline-flex max-w-full min-w-0 items-center gap-x-1 rounded-xs bg-control-bg px-1.5 py-0.5 text-xs"
+ >
+ <span className="min-w-0 truncate">
+ {context.getLabel(value)}
+ </span>
+ {!context.disabled && (
+ <button
+ type="button"
+ aria-label={`${t("common.remove")} ${String(context.getLabel(value))}`}
+ title={t("common.remove")}
+ className="shrink-0 hover:text-error focus-visible:outline-hidden focus-visible:ring-2 focus-visible:ring-accent"
+ onPointerDown={(event) => event.stopPropagation()}
+ onMouseDown={(event) => event.stopPropagation()}
+ onKeyDown={(event) => event.stopPropagation()}
+ onClick={(event) => {
+ event.stopPropagation();
+ event.currentTarget
+ .closest<HTMLElement>('[role="combobox"]')
+ ?.focus();
+ context.removeValue(value, event);
+ }}
+ >
+ <X className="size-3" />
+ </button>
+ )}
+ </span>
+ ))
+ }
+ </BaseSelect.Value>
+ );
+}
// ---- Portal + Positioner + Popup ----
type SelectContentProps = ComponentProps<typeof BaseSelect.Popup> & {
@@ -120,12 +292,14 @@ function SelectItem({
className={cn(stylexProps.className, menuRowStateClassName, className)}
style={{ ...stylexProps.style, ...props.style }}
>
+ <BaseSelect.ItemText className="min-w-0 flex-1">
+ {children}
+ </BaseSelect.ItemText>
<span className="flex size-4 shrink-0 items-center justify-center">
<BaseSelect.ItemIndicator>
<Check className="size-3.5" />
</BaseSelect.ItemIndicator>
</span>
- <BaseSelect.ItemText>{children}</BaseSelect.ItemText>
</BaseSelect.Item>
);
}
diff --git a/frontend/src/hooks/useAppState.ts b/frontend/src/hooks/useAppState.ts
index 7cfd662816..e591395eed 100644
--- a/frontend/src/hooks/useAppState.ts
+++ b/frontend/src/hooks/useAppState.ts
@@ -82,6 +82,8 @@ export function useSubscriptionState() {
const currentPlan = useAppStore((state) => state.currentPlan());
const isFreePlan = useAppStore((state) => state.isFreePlan());
const isTrialing = useAppStore((state) => state.isTrialing());
+ const canStartTrial = useAppStore((state) => state.canStartTrial());
+ const startTrial = useAppStore((state) => state.startTrial);
const isExpired = useAppStore((state) => state.isExpired());
const daysBeforeExpire = useAppStore((state) => state.daysBeforeExpire());
const trialingDays = useAppStore((state) => state.trialingDays());
@@ -104,6 +106,8 @@ export function useSubscriptionState() {
currentPlan,
isFreePlan,
isTrialing,
+ canStartTrial,
+ startTrial,
isExpired,
daysBeforeExpire,
trialingDays,
diff --git a/frontend/src/lib/column-data-table/utils.test.ts b/frontend/src/lib/column-data-table/utils.test.ts
new file mode 100644
index 0000000000..dfb947b799
--- /dev/null
+++ b/frontend/src/lib/column-data-table/utils.test.ts
@@ -0,0 +1,99 @@
+import { create } from "@bufbuild/protobuf";
+import { expect, test, vi } from "vitest";
+import {
+ type DatabaseCatalog,
+ DatabaseCatalogSchema,
+} from "@/types/proto-es/v1/database_catalog_service_pb";
+import { updateColumnCatalog } from "./utils";
+
+const mocks = vi.hoisted(() => ({
+ getOrFetchDatabaseCatalog: vi.fn(),
+ updateDatabaseCatalog: vi.fn<(catalog: DatabaseCatalog) => Promise<void>>(
+ async () => {}
+ ),
+ pushNotification: vi.fn(),
+}));
+
+vi.mock("@/stores/app", () => ({
+ useAppStore: { getState: () => mocks },
+}));
+vi.mock("@/stores", () => ({ pushNotification: mocks.pushNotification }));
+vi.mock("@/lib/i18n", () => ({
+ default: { t: (key: string) => `translated:${key}` },
+}));
+
+test("updates multiple columns and uses the provided localized notification", async () => {
+ const catalog = create(DatabaseCatalogSchema, {
+ name: "instances/instance/databases/database/catalog",
+ schemas: [
+ {
+ name: "public",
+ tables: [
+ {
+ name: "customers",
+ classification: "sensitive",
+ kind: {
+ case: "columns",
+ value: {
+ columns: [
+ { name: "email", labels: { owner: "sales" } },
+ { name: "id", semanticType: "existing" },
+ ],
+ },
+ },
+ },
+ ],
+ },
+ ],
+ });
+ mocks.getOrFetchDatabaseCatalog.mockResolvedValue(catalog);
+
+ await updateColumnCatalog({
+ database: "instances/instance/databases/database",
+ schema: "public",
+ table: "customers",
+ column: ["email", "phone"],
+ columnCatalog: { semanticType: "bb.default" },
+ notification: "Updated",
+ });
+
+ expect(mocks.updateDatabaseCatalog).toHaveBeenCalledTimes(1);
+ expect(mocks.updateDatabaseCatalog.mock.calls[0]?.[0]).toMatchObject({
+ schemas: [
+ {
+ tables: [
+ {
+ classification: "sensitive",
+ kind: {
+ case: "columns",
+ value: {
+ columns: [
+ {
+ name: "email",
+ semanticType: "bb.default",
+ labels: { owner: "sales" },
+ },
+ { name: "id", semanticType: "existing" },
+ { name: "phone", semanticType: "bb.default" },
+ ],
+ },
+ },
+ },
+ ],
+ },
+ ],
+ });
+ expect(catalog.schemas[0]?.tables[0]?.kind).toMatchObject({
+ case: "columns",
+ value: {
+ columns: [
+ { name: "email", semanticType: "" },
+ { name: "id", semanticType: "existing" },
+ ],
+ },
+ });
+ expect(mocks.pushNotification).toHaveBeenCalledTimes(1);
+ expect(mocks.pushNotification).toHaveBeenCalledWith(
+ expect.objectContaining({ title: "Updated" })
+ );
+});
diff --git a/frontend/src/lib/column-data-table/utils.ts b/frontend/src/lib/column-data-table/utils.ts
index afc119b263..6406739b59 100644
--- a/frontend/src/lib/column-data-table/utils.ts
+++ b/frontend/src/lib/column-data-table/utils.ts
@@ -1,6 +1,5 @@
import { create } from "@bufbuild/protobuf";
import { cloneDeep } from "lodash-es";
-import i18n from "@/lib/i18n";
import { pushNotification } from "@/stores";
import { useAppStore } from "@/stores/app";
import type {
@@ -25,7 +24,7 @@ export const updateColumnCatalog = async ({
database: string;
schema: string;
table: string;
- column: string;
+ column: string | string[];
columnCatalog: Partial<ColumnCatalog>;
notification: string;
}) => {
@@ -60,29 +59,31 @@ export const updateColumnCatalog = async ({
}
const columns = targetTable.kind.value.columns || [];
- const columnIndex = columns.findIndex((c) => c.name === column);
- if (columnIndex < 0) {
- columns.push(
- create(ColumnCatalogSchema, {
- name: column,
- semanticType: columnCatalog.semanticType,
- labels: columnCatalog.labels,
- classification: columnCatalog.classification,
- objectSchema: columnCatalog.objectSchema,
- })
- );
- } else {
- columns[columnIndex] = {
- ...columns[columnIndex],
- ...columnCatalog,
- };
+ for (const name of Array.isArray(column) ? column : [column]) {
+ const columnIndex = columns.findIndex((c) => c.name === name);
+ if (columnIndex < 0) {
+ columns.push(
+ create(ColumnCatalogSchema, {
+ name,
+ semanticType: columnCatalog.semanticType,
+ labels: columnCatalog.labels,
+ classification: columnCatalog.classification,
+ objectSchema: columnCatalog.objectSchema,
+ })
+ );
+ } else {
+ columns[columnIndex] = {
+ ...columns[columnIndex],
+ ...columnCatalog,
+ };
+ }
}
await dbCatalogStore.updateDatabaseCatalog(pendingUpdateCatalog);
pushNotification({
module: "bytebase",
style: "SUCCESS",
- title: i18n.t(notification),
+ title: notification,
});
};
@@ -91,13 +92,13 @@ export const updateTableCatalog = async ({
schema,
table,
tableCatalog,
- notification = "common.updated",
+ notification,
}: {
database: string;
schema: string;
table: string;
tableCatalog: Partial<TableCatalog>;
- notification?: string;
+ notification: string;
}) => {
const dbCatalogStore = useAppStore.getState();
const catalog = await dbCatalogStore.getOrFetchDatabaseCatalog({ database });
@@ -132,6 +133,6 @@ export const updateTableCatalog = async ({
pushNotification({
module: "bytebase",
style: "SUCCESS",
- title: i18n.t(notification),
+ title: notification,
});
};
diff --git a/frontend/src/lib/productIntro.ts b/frontend/src/lib/productIntro.ts
index 6bd98292b8..57b5ef32fb 100644
--- a/frontend/src/lib/productIntro.ts
+++ b/frontend/src/lib/productIntro.ts
@@ -16,6 +16,7 @@ export const AI_ASSISTANT_PRODUCT_INTRO = "ai-assistant";
export const DOMAIN_RESTRICTION_PRODUCT_INTRO = "domain-restriction";
export const CREATE_USER_PRODUCT_INTRO = "create-user";
export const GRANT_ACCESS_PRODUCT_INTRO = "grant-access";
+export const MARK_SENSITIVE_DATA_PRODUCT_INTRO = "mark-sensitive-data";
export type ProductIntroOptions = {
id: string;
diff --git a/frontend/src/locales/en-US.json b/frontend/src/locales/en-US.json
index ae28e02486..ce8694e274 100644
--- a/frontend/src/locales/en-US.json
+++ b/frontend/src/locales/en-US.json
@@ -847,6 +847,9 @@
"project-instance-synced-create-change-description": "Your database is ready in this project. Create a governed database change to continue.",
"project-instance-synced-create-change-title": "Ready to create a database change",
"project-instance-synced-description": "Your database is ready in this project. Start by querying data in SQL Editor, or create a governed database change when needed.",
+ "project-instance-synced-mark-sensitive-data-action": "Mark sensitive data",
+ "project-instance-synced-mark-sensitive-data-description": "Your database is ready in this project. Mark a sensitive column to apply data masking.",
+ "project-instance-synced-mark-sensitive-data-title": "Ready to protect sensitive data",
"project-instance-synced-query-data-description": "Your database is ready in this project. Open SQL Editor to query it.",
"project-instance-synced-query-data-title": "Database ready to query",
"project-instance-synced-sql-editor-action": "Open SQL Editor",
@@ -2861,6 +2864,7 @@
"email": "Email",
"enable-sample-databases": "Enable sample databases",
"enable-sample-databases-create-change": "Enable sample databases as a safe database change target",
+ "enable-sample-databases-mark-sensitive-data": "Enable sample databases to try data masking immediately",
"enable-sample-databases-query-data": "Enable sample databases to start querying immediately",
"password": "Password",
"password-confirm": "Password Confirm",
@@ -2877,6 +2881,10 @@
"description": "Define a change and create a traceable issue.",
"title": "Create a database change"
},
+ "mark-sensitive-data": {
+ "description": "Identify sensitive columns and apply masking.",
+ "title": "Mark sensitive data"
+ },
"outcome-title": "What would you like to do with Bytebase?",
"query-data": {
"description": "Open SQL Editor and run a statement against a database.",
@@ -3641,21 +3649,20 @@
},
"workspace-setup-guide": {
"actions": {
- "change": "Create database change",
"query": "Go to SQL Editor"
},
+ "all-steps-completed": "All steps completed",
"descriptions": {
"add-teammate": "Invite a teammate and grant them workspace access.",
"create-database-change": "Define a database change and create its issue.",
"database": "Open a database and explore its schemas and tables.",
"instance": "Connect an instance so Bytebase can sync its databases.",
+ "mark-sensitive-data": "Open the selected database and assign a semantic type to a sensitive column.",
"project": "Create a project to organize databases and changes.",
"query-data": "Open the selected database in SQL Editor and run any statement."
},
"dismiss": "Dismiss guide",
"generic": {
- "completion-description": "You explored how your project, instance, and database connect.",
- "completion-title": "Your database workspace is ready",
"title": "Set up Bytebase"
},
"getting-started": "Getting started",
@@ -3668,6 +3675,9 @@
"grant-access-title": "Grant workspace access",
"instance-description": "Create an instance so Bytebase can connect to your database server.",
"instance-title": "Connect the instance",
+ "mark-sensitive-data-description": "Select a column and assign a semantic type so Bytebase can apply data masking.",
+ "mark-sensitive-data-title": "Mark sensitive data",
+ "mark-sensitive-fields-description": "Open a table or collection and assign semantic types to sensitive fields in its catalog.",
"project-description": "Create a project first. Databases can be synced into it after the instance is connected.",
"project-title": "Create a project",
"transfer-description": "Select one or more databases, then transfer them to the project.",
@@ -3678,13 +3688,12 @@
"product-model": "How Bytebase works",
"scenarios": {
"create-database-change": {
- "completion-description": "Your database change now has a traceable issue in Bytebase.",
- "completion-title": "You created your first database change",
"title": "Create a database change"
},
+ "mark-sensitive-data": {
+ "title": "Mark sensitive data"
+ },
"query-data": {
- "completion-description": "You opened SQL Editor and ran a statement against your database.",
- "completion-title": "You ran your first statement",
"title": "Query Data"
}
},
@@ -3694,6 +3703,7 @@
"create-database-change": "Create database change",
"database": "Explore database",
"instance": "Connect instance",
+ "mark-sensitive-data": "Mark sensitive data",
"project": "Create project",
"query-data": "Query data"
},
diff --git a/frontend/src/locales/es-ES.json b/frontend/src/locales/es-ES.json
index 00d9cd5d54..d3533977ea 100644
--- a/frontend/src/locales/es-ES.json
+++ b/frontend/src/locales/es-ES.json
@@ -847,6 +847,9 @@
"project-instance-synced-create-change-description": "Tu base de datos está lista en este proyecto. Crea un cambio de base de datos gobernado para continuar.",
"project-instance-synced-create-change-title": "Base de datos lista para cambios",
"project-instance-synced-description": "Tu base de datos está lista en este proyecto. Empieza consultando datos en SQL Editor, o crea un cambio de base de datos gobernado cuando lo necesites.",
+ "project-instance-synced-mark-sensitive-data-action": "Marcar datos sensibles",
+ "project-instance-synced-mark-sensitive-data-description": "Tu base de datos está lista en este proyecto. Marca una columna sensible para aplicar enmascaramiento de datos.",
+ "project-instance-synced-mark-sensitive-data-title": "Lista para proteger datos sensibles",
"project-instance-synced-query-data-description": "Tu base de datos está lista en este proyecto. Abre SQL Editor para consultarla.",
"project-instance-synced-query-data-title": "Base de datos lista para consultar",
"project-instance-synced-sql-editor-action": "Abrir SQL Editor",
@@ -2861,6 +2864,7 @@
"email": "Correo electrónico",
"enable-sample-databases": "Habilitar bases de datos de ejemplo",
"enable-sample-databases-create-change": "Habilitar bases de datos de ejemplo como destino seguro para el cambio",
+ "enable-sample-databases-mark-sensitive-data": "Habilitar bases de datos de ejemplo para probar el enmascaramiento de datos de inmediato",
"enable-sample-databases-query-data": "Habilitar bases de datos de ejemplo para empezar a consultar de inmediato",
"password": "Contraseña",
"password-confirm": "Confirmar contraseña",
@@ -2877,6 +2881,10 @@
"description": "Defina un cambio y cree una incidencia rastreable.",
"title": "Crear un cambio de base de datos"
},
+ "mark-sensitive-data": {
+ "description": "Identifica columnas sensibles y aplica enmascaramiento de datos.",
+ "title": "Marcar datos sensibles"
+ },
"outcome-title": "¿Qué le gustaría hacer con Bytebase?",
"query-data": {
"description": "Abra SQL Editor y ejecute una sentencia en una base de datos.",
@@ -3641,21 +3649,20 @@
},
"workspace-setup-guide": {
"actions": {
- "change": "Crear cambio de base de datos",
"query": "Ir a SQL Editor"
},
+ "all-steps-completed": "Todos los pasos completados",
"descriptions": {
"add-teammate": "Invite a un compañero y concédale acceso al espacio de trabajo.",
"create-database-change": "Define un cambio de base de datos y crea su incidencia.",
"database": "Abre una base de datos y explora sus esquemas y tablas.",
"instance": "Conecta una instancia para que Bytebase pueda sincronizar sus bases de datos.",
+ "mark-sensitive-data": "Abre la base de datos seleccionada y asigna un tipo semántico a una columna sensible.",
"project": "Crea un proyecto para organizar bases de datos y cambios.",
"query-data": "Abre la base de datos seleccionada en SQL Editor y ejecuta cualquier sentencia."
},
"dismiss": "Cerrar guía",
"generic": {
- "completion-description": "Exploraste cómo se conectan tu proyecto, instancia y base de datos.",
- "completion-title": "Tu espacio de trabajo de bases de datos está listo",
"title": "Configurar Bytebase"
},
"getting-started": "Primeros pasos",
@@ -3668,6 +3675,9 @@
"grant-access-title": "Conceder acceso al espacio de trabajo",
"instance-description": "Crea una instancia para que Bytebase pueda conectarse a tu servidor de base de datos.",
"instance-title": "Conectar la instancia",
+ "mark-sensitive-data-description": "Selecciona una columna y asigna un tipo semántico para que Bytebase pueda aplicar enmascaramiento de datos.",
+ "mark-sensitive-data-title": "Marcar datos sensibles",
+ "mark-sensitive-fields-description": "Abre una tabla o colección y asigna tipos semánticos a los campos sensibles de su catálogo.",
"project-description": "Crea primero un proyecto. Las bases de datos se pueden sincronizar en él después de conectar la instancia.",
"project-title": "Crear un proyecto",
"transfer-description": "Selecciona una o más bases de datos y transfiérelas al proyecto.",
@@ -3678,13 +3688,12 @@
"product-model": "Cómo funciona Bytebase",
"scenarios": {
"create-database-change": {
- "completion-description": "Tu cambio de base de datos ya tiene una incidencia rastreable en Bytebase.",
- "completion-title": "Creaste tu primer cambio de base de datos",
"title": "Crear un cambio de base de datos"
},
+ "mark-sensitive-data": {
+ "title": "Marcar datos sensibles"
+ },
"query-data": {
- "completion-description": "Abriste SQL Editor y ejecutaste una sentencia en tu base de datos.",
- "completion-title": "Ejecutaste tu primera sentencia",
"title": "Consultar datos"
}
},
@@ -3694,6 +3703,7 @@
"create-database-change": "Crear cambio de base de datos",
"database": "Explorar base de datos",
"instance": "Conectar instancia",
+ "mark-sensitive-data": "Marcar datos sensibles",
"project": "Crear proyecto",
"query-data": "Consultar datos"
},
diff --git a/frontend/src/locales/ja-JP.json b/frontend/src/locales/ja-JP.json
index 8d8222ae72..5040a6565c 100644
--- a/frontend/src/locales/ja-JP.json
+++ b/frontend/src/locales/ja-JP.json
@@ -847,6 +847,9 @@
"project-instance-synced-create-change-description": "このプロジェクトでデータベースを利用できます。管理されたデータベース変更を作成して続行してください。",
"project-instance-synced-create-change-title": "データベース変更の準備ができました",
"project-instance-synced-description": "このプロジェクトでデータベースを利用できるようになりました。まず SQL Editor でデータをクエリし、必要に応じて管理されたデータベース変更を作成できます。",
+ "project-instance-synced-mark-sensitive-data-action": "機密データをマーク",
+ "project-instance-synced-mark-sensitive-data-description": "このプロジェクトでデータベースを利用できます。機密カラムをマークしてデータマスキングを適用します。",
+ "project-instance-synced-mark-sensitive-data-title": "機密データを保護する準備ができました",
"project-instance-synced-query-data-description": "このプロジェクトでデータベースを利用できます。SQL Editor を開いてクエリしてください。",
"project-instance-synced-query-data-title": "データベースをクエリする準備ができました",
"project-instance-synced-sql-editor-action": "SQL Editor を開く",
@@ -2861,6 +2864,7 @@
"email": "メールアドレス",
"enable-sample-databases": "サンプルデータベースを有効にする",
"enable-sample-databases-create-change": "安全な変更対象としてサンプルデータベースを有効にする",
+ "enable-sample-databases-mark-sensitive-data": "データマスキングをすぐに試せるようサンプルデータベースを有効にする",
"enable-sample-databases-query-data": "すぐにクエリを試せるようサンプルデータベースを有効にする",
"password": "パスワード",
"password-confirm": "パスワードの確認",
@@ -2877,6 +2881,10 @@
"description": "変更を定義し、追跡可能なイシューを作成します。",
"title": "データベース変更を作成"
},
+ "mark-sensitive-data": {
+ "description": "機密カラムを特定してデータマスキングを適用します。",
+ "title": "機密データをマーク"
+ },
"outcome-title": "Bytebase で何をしたいですか?",
"query-data": {
"description": "SQL Editor を開き、データベースでステートメントを実行します。",
@@ -3641,21 +3649,20 @@
},
"workspace-setup-guide": {
"actions": {
- "change": "データベース変更を作成",
"query": "SQL Editor に移動"
},
+ "all-steps-completed": "すべてのステップが完了しました",
"descriptions": {
"add-teammate": "チームメンバーを招待し、ワークスペースへのアクセスを付与します。",
"create-database-change": "データベース変更を定義し、そのイシューを作成します。",
"database": "データベースを開き、スキーマとテーブルを確認します。",
"instance": "Bytebase がデータベースを同期できるようにインスタンスを接続します。",
+ "mark-sensitive-data": "選択したデータベースを開き、機密カラムにセマンティックタイプを割り当てます。",
"project": "データベースと変更を整理するプロジェクトを作成します。",
"query-data": "選択したデータベースを SQL Editor で開き、任意のステートメントを実行します。"
},
"dismiss": "ガイドを閉じる",
"generic": {
- "completion-description": "プロジェクト、インスタンス、データベースのつながりを確認しました。",
- "completion-title": "データベースワークスペースの準備ができました",
"title": "Bytebase をセットアップ"
},
"getting-started": "はじめに",
@@ -3668,6 +3675,9 @@
"grant-access-title": "ワークスペースアクセスを付与",
"instance-description": "Bytebase がデータベースサーバーに接続できるようにインスタンスを作成します。",
"instance-title": "インスタンスを接続",
+ "mark-sensitive-data-description": "カラムを選択してセマンティックタイプを割り当て、Bytebase がデータマスキングを適用できるようにします。",
+ "mark-sensitive-data-title": "機密データをマーク",
+ "mark-sensitive-fields-description": "テーブルまたはコレクションを開き、カタログ内の機密フィールドにセマンティックタイプを割り当てます。",
"project-description": "まずプロジェクトを作成します。インスタンス接続後、データベースをそのプロジェクトに同期できます。",
"project-title": "プロジェクトを作成",
"transfer-description": "1つ以上のデータベースを選択し、プロジェクトに転送します。",
@@ -3678,13 +3688,12 @@
"product-model": "Bytebase の仕組み",
"scenarios": {
"create-database-change": {
- "completion-description": "データベース変更が Bytebase の追跡可能なイシューになりました。",
- "completion-title": "最初のデータベース変更を作成しました",
"title": "データベース変更を作成"
},
+ "mark-sensitive-data": {
+ "title": "機密データをマーク"
+ },
"query-data": {
- "completion-description": "SQL Editor を開き、データベースでステートメントを実行しました。",
- "completion-title": "最初のステートメントを実行しました",
"title": "データをクエリ"
}
},
@@ -3694,6 +3703,7 @@
"create-database-change": "データベース変更を作成",
"database": "データベースを確認",
"instance": "インスタンスを接続",
+ "mark-sensitive-data": "機密データをマーク",
"project": "プロジェクトを作成",
"query-data": "データをクエリ"
},
diff --git a/frontend/src/locales/vi-VN.json b/frontend/src/locales/vi-VN.json
index 43ad5d9e38..e2395f9871 100644
--- a/frontend/src/locales/vi-VN.json
+++ b/frontend/src/locales/vi-VN.json
@@ -847,6 +847,9 @@
"project-instance-synced-create-change-description": "Cơ sở dữ liệu của bạn đã sẵn sàng trong dự án này. Hãy tạo một thay đổi cơ sở dữ liệu được quản trị để tiếp tục.",
"project-instance-synced-create-change-title": "Cơ sở dữ liệu đã sẵn sàng để thay đổi",
"project-instance-synced-description": "Cơ sở dữ liệu của bạn đã sẵn sàng trong dự án này. Hãy bắt đầu bằng cách truy vấn dữ liệu trong SQL Editor, hoặc tạo thay đổi cơ sở dữ liệu được quản trị khi cần.",
+ "project-instance-synced-mark-sensitive-data-action": "Đánh dấu dữ liệu nhạy cảm",
+ "project-instance-synced-mark-sensitive-data-description": "Cơ sở dữ liệu của bạn đã sẵn sàng trong dự án này. Đánh dấu một cột nhạy cảm để áp dụng che dữ liệu.",
+ "project-instance-synced-mark-sensitive-data-title": "Sẵn sàng bảo vệ dữ liệu nhạy cảm",
"project-instance-synced-query-data-description": "Cơ sở dữ liệu của bạn đã sẵn sàng trong dự án này. Hãy mở SQL Editor để truy vấn.",
"project-instance-synced-query-data-title": "Cơ sở dữ liệu đã sẵn sàng để truy vấn",
"project-instance-synced-sql-editor-action": "Mở SQL Editor",
@@ -2861,6 +2864,7 @@
"email": "Email",
"enable-sample-databases": "Bật cơ sở dữ liệu mẫu",
"enable-sample-databases-create-change": "Bật cơ sở dữ liệu mẫu làm đích thay đổi an toàn",
+ "enable-sample-databases-mark-sensitive-data": "Bật cơ sở dữ liệu mẫu để thử che dữ liệu ngay",
"enable-sample-databases-query-data": "Bật cơ sở dữ liệu mẫu để bắt đầu truy vấn ngay",
"password": "Mật khẩu",
"password-confirm": "Xác nhận mật khẩu",
@@ -2877,6 +2881,10 @@
"description": "Xác định thay đổi và tạo issue có thể theo dõi.",
"title": "Tạo thay đổi cơ sở dữ liệu"
},
+ "mark-sensitive-data": {
+ "description": "Xác định các cột nhạy cảm và áp dụng che dữ liệu.",
+ "title": "Đánh dấu dữ liệu nhạy cảm"
+ },
"outcome-title": "Bạn muốn làm gì với Bytebase?",
"query-data": {
"description": "Mở SQL Editor và chạy một câu lệnh trên cơ sở dữ liệu.",
@@ -3641,21 +3649,20 @@
},
"workspace-setup-guide": {
"actions": {
- "change": "Tạo thay đổi cơ sở dữ liệu",
"query": "Đi tới SQL Editor"
},
+ "all-steps-completed": "Đã hoàn thành tất cả các bước",
"descriptions": {
"add-teammate": "Mời một thành viên và cấp quyền truy cập không gian làm việc.",
"create-database-change": "Xác định thay đổi cơ sở dữ liệu và tạo issue cho thay đổi đó.",
"database": "Mở một cơ sở dữ liệu và khám phá schema cùng các bảng của cơ sở dữ liệu đó.",
"instance": "Kết nối một instance để Bytebase có thể đồng bộ các cơ sở dữ liệu.",
+ "mark-sensitive-data": "Mở cơ sở dữ liệu đã chọn và gán kiểu ngữ nghĩa cho một cột nhạy cảm.",
"project": "Tạo một dự án để tổ chức cơ sở dữ liệu và các thay đổi.",
"query-data": "Mở cơ sở dữ liệu đã chọn trong SQL Editor và chạy bất kỳ câu lệnh nào."
},
"dismiss": "Đóng hướng dẫn",
"generic": {
- "completion-description": "Bạn đã khám phá cách dự án, instance và cơ sở dữ liệu kết nối với nhau.",
- "completion-title": "Không gian làm việc cơ sở dữ liệu của bạn đã sẵn sàng",
"title": "Thiết lập Bytebase"
},
"getting-started": "Bắt đầu",
@@ -3668,6 +3675,9 @@
"grant-access-title": "Cấp quyền truy cập không gian làm việc",
"instance-description": "Tạo instance để Bytebase có thể kết nối tới máy chủ cơ sở dữ liệu của bạn.",
"instance-title": "Kết nối instance",
+ "mark-sensitive-data-description": "Chọn một cột và gán kiểu ngữ nghĩa để Bytebase có thể áp dụng che dữ liệu.",
+ "mark-sensitive-data-title": "Đánh dấu dữ liệu nhạy cảm",
+ "mark-sensitive-fields-description": "Mở bảng hoặc bộ sưu tập và gán kiểu ngữ nghĩa cho các trường nhạy cảm trong catalog.",
"project-description": "Tạo một dự án trước. Cơ sở dữ liệu có thể được đồng bộ vào dự án đó sau khi instance được kết nối.",
"project-title": "Tạo dự án",
"transfer-description": "Chọn một hoặc nhiều cơ sở dữ liệu, sau đó chuyển chúng vào dự án.",
@@ -3678,13 +3688,12 @@
"product-model": "Cách Bytebase hoạt động",
"scenarios": {
"create-database-change": {
- "completion-description": "Thay đổi cơ sở dữ liệu của bạn hiện có một issue có thể theo dõi trong Bytebase.",
- "completion-title": "Bạn đã tạo thay đổi cơ sở dữ liệu đầu tiên",
"title": "Tạo thay đổi cơ sở dữ liệu"
},
+ "mark-sensitive-data": {
+ "title": "Đánh dấu dữ liệu nhạy cảm"
+ },
"query-data": {
- "completion-description": "Bạn đã mở SQL Editor và chạy một câu lệnh trên cơ sở dữ liệu.",
- "completion-title": "Bạn đã chạy câu lệnh đầu tiên",
"title": "Truy vấn dữ liệu"
}
},
@@ -3694,6 +3703,7 @@
"create-database-change": "Tạo thay đổi cơ sở dữ liệu",
"database": "Khám phá cơ sở dữ liệu",
"instance": "Kết nối instance",
+ "mark-sensitive-data": "Đánh dấu dữ liệu nhạy cảm",
"project": "Tạo dự án",
"query-data": "Truy vấn dữ liệu"
},
diff --git a/frontend/src/locales/zh-CN.json b/frontend/src/locales/zh-CN.json
index a9156aa77a..3dffd56481 100644
--- a/frontend/src/locales/zh-CN.json
+++ b/frontend/src/locales/zh-CN.json
@@ -847,6 +847,9 @@
"project-instance-synced-create-change-description": "你的数据库已在此项目中就绪。请创建受管数据库变更以继续。",
"project-instance-synced-create-change-title": "数据库已可进行变更",
"project-instance-synced-description": "你的数据库已在此项目中就绪。可以先在 SQL Editor 中查询数据,也可以在需要时创建受管数据库变更。",
+ "project-instance-synced-mark-sensitive-data-action": "标记敏感数据",
+ "project-instance-synced-mark-sensitive-data-description": "你的数据库已在此项目中就绪。标记敏感列以应用数据脱敏。",
+ "project-instance-synced-mark-sensitive-data-title": "数据库已可保护敏感数据",
"project-instance-synced-query-data-description": "你的数据库已在此项目中就绪。请打开 SQL Editor 进行查询。",
"project-instance-synced-query-data-title": "数据库已可查询",
"project-instance-synced-sql-editor-action": "打开 SQL Editor",
@@ -2861,6 +2864,7 @@
"email": "邮箱",
"enable-sample-databases": "启用示例数据库",
"enable-sample-databases-create-change": "启用示例数据库作为安全的变更目标",
+ "enable-sample-databases-mark-sensitive-data": "启用示例数据库以立即试用数据脱敏",
"enable-sample-databases-query-data": "启用示例数据库以立即开始查询",
"password": "密码",
"password-confirm": "确认密码",
@@ -2877,6 +2881,10 @@
"description": "定义变更并创建可追踪的工单。",
"title": "创建数据库变更"
},
+ "mark-sensitive-data": {
+ "description": "识别敏感列并应用数据脱敏。",
+ "title": "标记敏感数据"
+ },
"outcome-title": "您想使用 Bytebase 做什么?",
"query-data": {
"description": "打开 SQL Editor 并对数据库运行一条语句。",
@@ -3641,21 +3649,20 @@
},
"workspace-setup-guide": {
"actions": {
- "change": "创建数据库变更",
"query": "前往 SQL Editor"
},
+ "all-steps-completed": "所有步骤已完成",
"descriptions": {
"add-teammate": "邀请团队成员并授予工作空间访问权限。",
"create-database-change": "定义数据库变更并创建对应工单。",
"database": "打开数据库,浏览其中的 schema 和表。",
"instance": "连接实例,以便 Bytebase 同步其中的数据库。",
+ "mark-sensitive-data": "打开所选数据库,为敏感列分配语义类型。",
"project": "创建项目来组织数据库和变更。",
"query-data": "在 SQL Editor 中打开所选数据库并运行任意语句。"
},
"dismiss": "关闭指南",
"generic": {
- "completion-description": "你已了解项目、实例和数据库之间的连接关系。",
- "completion-title": "你的数据库工作空间已准备就绪",
"title": "设置 Bytebase"
},
"getting-started": "入门指南",
@@ -3668,6 +3675,9 @@
"grant-access-title": "授予工作空间访问权限",
"instance-description": "创建实例,让 Bytebase 可以连接到你的数据库服务器。",
"instance-title": "连接实例",
+ "mark-sensitive-data-description": "选择一列并分配语义类型,以便 Bytebase 应用数据脱敏。",
+ "mark-sensitive-data-title": "标记敏感数据",
+ "mark-sensitive-fields-description": "打开表或集合,在其目录中为敏感字段分配语义类型。",
"project-description": "先创建一个项目。实例连接后,数据库可以同步到该项目中。",
"project-title": "创建项目",
"transfer-description": "选择一个或多个数据库,然后转移到项目。",
@@ -3678,13 +3688,12 @@
"product-model": "Bytebase 的运作方式",
"scenarios": {
"create-database-change": {
- "completion-description": "你的数据库变更现在已在 Bytebase 中创建为可追踪工单。",
- "completion-title": "你已创建第一个数据库变更",
"title": "创建数据库变更"
},
+ "mark-sensitive-data": {
+ "title": "标记敏感数据"
+ },
"query-data": {
- "completion-description": "你已打开 SQL Editor 并对数据库运行了一条语句。",
- "completion-title": "你已运行第一条语句",
"title": "查询数据"
}
},
@@ -3694,6 +3703,7 @@
"create-database-change": "创建数据库变更",
"database": "浏览数据库",
"instance": "连接实例",
+ "mark-sensitive-data": "标记敏感数据",
"project": "创建项目",
"query-data": "查询数据"
},
diff --git a/frontend/src/modules/workspace-setup-guide/WorkspaceSetupGuide.test.tsx b/frontend/src/modules/workspace-setup-guide/WorkspaceSetupGuide.test.tsx
index 02c12d4eab..44aa1ceb88 100644
--- a/frontend/src/modules/workspace-setup-guide/WorkspaceSetupGuide.test.tsx
+++ b/frontend/src/modules/workspace-setup-guide/WorkspaceSetupGuide.test.tsx
@@ -26,6 +26,7 @@ const guideContext = (
hasExploredDatabase: false,
hasRunStatement: false,
hasCreatedChangeIssue: false,
+ hasMarkedSensitiveData: false,
isSaaS: false,
hasOtherHumanUser: false,
hasOtherWorkspaceMember: false,
@@ -695,7 +696,7 @@ describe("WorkspaceSetupGuide", () => {
});
});
- test("shows generic completion with both next actions", () => {
+ test("keeps completed steps visible and clickable without extra actions", () => {
mocks.guideContext = guideContext({
hasProject: true,
hasInstance: true,
@@ -706,11 +707,24 @@ describe("WorkspaceSetupGuide", () => {
render(<WorkspaceSetupGuide />);
+ const steps = screen.getAllByTestId(/^setup-step-/);
+ expect(steps).toHaveLength(3);
+ for (const step of steps) {
+ expect(step).toBeEnabled();
+ expect(step.querySelector("svg.text-success")).toBeInTheDocument();
+ }
+ expect(screen.queryByTestId("completion-title")).not.toBeInTheDocument();
expect(
- screen.getByText("workspace-setup-guide.generic.completion-title")
- ).toBeVisible();
- expect(screen.getByText("workspace-setup-guide.actions.change")).toBeVisible();
- expect(screen.getByText("workspace-setup-guide.actions.query")).toBeVisible();
+ screen.queryByText("workspace-setup-guide.actions.change")
+ ).not.toBeInTheDocument();
+ expect(
+ screen.queryByText("workspace-setup-guide.actions.query")
+ ).not.toBeInTheDocument();
+ fireEvent.click(screen.getByTestId("setup-step-create-project"));
+ expect(mocks.routerPush).toHaveBeenCalledWith({
+ name: "workspace.project",
+ query: { intro: "create-project" },
+ });
expect(screen.queryByTestId("complete-guide")).not.toBeInTheDocument();
fireEvent.click(screen.getByTestId("dismiss-guide"));
expect(mocks.saveIntroStateByKey).toHaveBeenCalledWith({
@@ -719,7 +733,7 @@ describe("WorkspaceSetupGuide", () => {
});
});
- test("compacts completion actions only when the completion row overflows", () => {
+ test("shows completed progress in the compact step menu only when steps overflow", async () => {
mocks.guideContext = guideContext({
hasProject: true,
hasInstance: true,
@@ -730,19 +744,15 @@ describe("WorkspaceSetupGuide", () => {
render(<WorkspaceSetupGuide />);
- const guideBar = screen.getByTestId("workspace-setup-guide");
- const completionTitle = screen.getByTestId("completion-title");
- Object.defineProperty(guideBar, "clientWidth", {
- configurable: true,
- value: 800,
- });
- Object.defineProperty(completionTitle, "clientWidth", {
+ const viewport = screen.getByTestId("guide-step-viewport");
+ const measurement = screen.getByTestId("guide-step-measurement");
+ Object.defineProperty(viewport, "clientWidth", {
configurable: true,
- value: 160,
+ value: 500,
});
- Object.defineProperty(completionTitle, "scrollWidth", {
+ Object.defineProperty(measurement, "scrollWidth", {
configurable: true,
- value: 260,
+ value: 900,
});
act(() => {
@@ -751,24 +761,24 @@ describe("WorkspaceSetupGuide", () => {
}
});
+ expect(screen.getByTestId("compact-step-navigator")).toBeVisible();
expect(
- screen.queryByText("workspace-setup-guide.generic.completion-description")
- ).not.toBeInTheDocument();
- expect(
- screen.queryByText("workspace-setup-guide.actions.change")
- ).not.toBeInTheDocument();
- expect(screen.getByTestId("sql-editor-action")).toHaveAttribute(
- "data-size",
- "sm"
- );
+ screen.getByText("workspace-setup-guide.all-steps-completed")
+ ).toBeVisible();
+ expect(screen.queryByTestId("compact-active-step")).not.toBeInTheDocument();
+ fireEvent.click(screen.getByTestId("open-step-list"));
+ const items = await screen.findAllByRole("menuitem");
+ expect(items).toHaveLength(3);
+ for (const item of items) {
+ expect(item).not.toHaveAttribute("aria-disabled", "true");
+ expect(item.querySelector("svg.text-success")).toBeInTheDocument();
+ }
+ fireEvent.click(items[0]);
+ expect(mocks.routerPush).toHaveBeenCalled();
- Object.defineProperty(guideBar, "clientWidth", {
- configurable: true,
- value: 900,
- });
- Object.defineProperty(completionTitle, "clientWidth", {
+ Object.defineProperty(measurement, "scrollWidth", {
configurable: true,
- value: 260,
+ value: 400,
});
act(() => {
for (const callback of resizeObserverCallbacks) {
@@ -776,50 +786,55 @@ describe("WorkspaceSetupGuide", () => {
}
});
+ expect(screen.getByTestId("guide-step-list")).toBeVisible();
expect(
- screen.getByText("workspace-setup-guide.generic.completion-description")
- ).toBeVisible();
- expect(screen.getByText("workspace-setup-guide.actions.change")).toBeVisible();
- expect(screen.getByTestId("sql-editor-action")).not.toHaveAttribute(
- "data-size"
- );
+ screen.queryByTestId("compact-step-navigator")
+ ).not.toBeInTheDocument();
});
- test("Query completion offers a database change", () => {
- mocks.scenarioId = "query-data";
+ test.each([
+ "query-data",
+ "create-database-change",
+ "mark-sensitive-data",
+ ] as const)("keeps all steps after %s completes", (scenarioId) => {
+ mocks.scenarioId = scenarioId;
mocks.guideContext = guideContext({
hasProject: true,
hasInstance: true,
hasExploredDatabase: true,
hasRunStatement: true,
- databaseProjectName: "projects/app",
- databaseName: "instances/sample/databases/employee",
- });
-
- render(<WorkspaceSetupGuide />);
-
- expect(screen.getByText("workspace-setup-guide.actions.change")).toBeVisible();
- expect(screen.queryByText("workspace-setup-guide.actions.query")).not.toBeInTheDocument();
- });
-
- test("change completion offers SQL Editor", () => {
- mocks.scenarioId = "create-database-change";
- mocks.guideContext = guideContext({
- hasProject: true,
- hasInstance: true,
- hasExploredDatabase: true,
hasCreatedChangeIssue: true,
+ hasMarkedSensitiveData: true,
databaseProjectName: "projects/app",
databaseName: "instances/sample/databases/employee",
});
render(<WorkspaceSetupGuide />);
- expect(screen.getByText("workspace-setup-guide.actions.query")).toBeVisible();
- expect(screen.getByTestId("sql-editor-action")).not.toHaveAttribute(
- "data-size"
- );
- expect(screen.queryByText("workspace-setup-guide.actions.change")).not.toBeInTheDocument();
+ const steps = screen.getAllByTestId(/^setup-step-/);
+ expect(steps).toHaveLength(scenarioId === "mark-sensitive-data" ? 5 : 4);
+ for (const step of steps) {
+ expect(step).toBeEnabled();
+ expect(step.querySelector("svg.text-success")).toBeInTheDocument();
+ }
+ expect(screen.queryByTestId("completion-title")).not.toBeInTheDocument();
+ expect(
+ screen.queryByText("workspace-setup-guide.actions.change")
+ ).not.toBeInTheDocument();
+ expect(
+ screen.queryByText("workspace-setup-guide.actions.query")
+ ).not.toBeInTheDocument();
+ if (scenarioId !== "create-database-change") {
+ fireEvent.click(screen.getByTestId("setup-step-query-data"));
+ expect(mocks.routerPush).toHaveBeenCalledWith({
+ name: "sql-editor.database",
+ params: {
+ project: "app",
+ instance: "sample",
+ database: "employee",
+ },
+ });
+ }
});
test("records the initial guide progress once", () => {
@@ -829,6 +844,8 @@ describe("WorkspaceSetupGuide", () => {
hasInstance: true,
hasExploredDatabase: true,
hasCreatedChangeIssue: true,
+ databaseProjectName: "projects/app",
+ databaseName: "instances/sample/databases/employee",
});
render(<WorkspaceSetupGuide />);
@@ -847,11 +864,11 @@ describe("WorkspaceSetupGuide", () => {
completed_steps: [
"create-project",
"connect-instance",
+ "explore-database",
"create-database-change",
],
- completed_step_count: 3,
+ completed_step_count: 4,
total_step_count: 4,
- next_step: "explore-database",
observation: "initial",
},
});
diff --git a/frontend/src/modules/workspace-setup-guide/WorkspaceSetupGuide.tsx b/frontend/src/modules/workspace-setup-guide/WorkspaceSetupGuide.tsx
index c7c06b60f3..5ee87d6386 100644
--- a/frontend/src/modules/workspace-setup-guide/WorkspaceSetupGuide.tsx
+++ b/frontend/src/modules/workspace-setup-guide/WorkspaceSetupGuide.tsx
@@ -37,7 +37,7 @@ import {
readGuideWorkspaceUsage,
readSelectedGuideScenarioId,
} from "./selection";
-import { GUIDE_STEP_REGISTRY } from "./steps";
+import { GUIDE_STEP_DEFINITIONS } from "./steps";
import type { GuideAction, GuideStepId, ResolvedGuideStep } from "./types";
import { useGuideContext } from "./useGuideContext";
@@ -76,10 +76,6 @@ export function WorkspaceSetupGuide() {
const [productModelOpen, setProductModelOpen] = useState(false);
const [selectedStepId, setSelectedStepId] = useState<GuideStepId>();
const [stepsOverflow, setStepsOverflow] = useState(false);
- const [completionCompact, setCompletionCompact] = useState(false);
- const guideBarRef = useRef<HTMLDivElement>(null);
- const completionTitleRef = useRef<HTMLDivElement>(null);
- const completionWideWidthRef = useRef(0);
const stepViewportRef = useRef<HTMLDivElement>(null);
const stepMeasurementRef = useRef<HTMLDivElement>(null);
const analyticsJourneyRef = useRef<string | undefined>(undefined);
@@ -92,7 +88,7 @@ export function WorkspaceSetupGuide() {
() =>
resolveGuide({
journey,
- definitions: GUIDE_STEP_REGISTRY,
+ definitions: GUIDE_STEP_DEFINITIONS,
context,
selectedStepId,
}),
@@ -118,10 +114,6 @@ export function WorkspaceSetupGuide() {
: -1;
useLayoutEffect(() => {
- if (guide.complete) {
- setStepsOverflow(false);
- return;
- }
const viewport = stepViewportRef.current;
const measurement = stepMeasurementRef.current;
if (!viewport || !measurement) return;
@@ -134,46 +126,7 @@ export function WorkspaceSetupGuide() {
observer.observe(measurement);
updateOverflow();
return () => observer.disconnect();
- }, [guide.complete, guide.steps, i18n.resolvedLanguage]);
-
- useLayoutEffect(() => {
- completionWideWidthRef.current = 0;
- setCompletionCompact(false);
- }, [i18n.resolvedLanguage, journey.id]);
-
- useLayoutEffect(() => {
- if (!guide.complete) {
- completionWideWidthRef.current = 0;
- setCompletionCompact(false);
- return;
- }
- const guideBar = guideBarRef.current;
- const completionTitle = completionTitleRef.current;
- if (!guideBar || !completionTitle) return;
-
- const updateOverflow = () => {
- if (guideBar.clientWidth === 0) return;
- if (completionCompact) {
- if (guideBar.clientWidth >= completionWideWidthRef.current) {
- setCompletionCompact(false);
- }
- return;
- }
-
- const clippedWidth =
- completionTitle.scrollWidth - completionTitle.clientWidth;
- if (clippedWidth > 0) {
- completionWideWidthRef.current = guideBar.clientWidth + clippedWidth;
- setCompletionCompact(true);
- }
- };
- const observer = new ResizeObserver(updateOverflow);
- observer.observe(guideBar);
- observer.observe(completionTitle);
- updateOverflow();
- return () => observer.disconnect();
- }, [completionCompact, guide.complete, i18n.resolvedLanguage, journey.id]);
-
+ }, [guide.steps, i18n.resolvedLanguage]);
const captureGuideMetric = (
event: BehaviorMetricName,
properties: Record<string, unknown> = {}
@@ -249,7 +202,6 @@ export function WorkspaceSetupGuide() {
action_type: action.type,
});
};
-
const onSelectStep = (step: ResolvedGuideStep) => {
setSelectedStepId(step.definition.id);
const action = step.actions.select;
@@ -274,14 +226,9 @@ export function WorkspaceSetupGuide() {
return null;
}
- const hasDatabaseTarget =
- !!context.databaseName && !!context.databaseProjectName;
- const completionPrimaryAction = journey.completionActions[0];
-
return (
<>
<div
- ref={guideBarRef}
data-testid="workspace-setup-guide"
className="flex w-full shrink-0 items-center gap-x-2 border-t border-block-border bg-background px-4 py-3 shadow-[0_-2px_10px_rgba(0,0,0,0.04)] 2xl:gap-x-4 2xl:px-5 2xl:py-4"
>
@@ -305,231 +252,190 @@ export function WorkspaceSetupGuide() {
</Tooltip>
)}
</div>
- {guide.complete ? (
- <div className="min-w-0 flex-1">
- <div
- ref={completionTitleRef}
- data-testid="completion-title"
- className="truncate text-sm font-medium whitespace-nowrap text-main"
- >
- {t(journey.completionTitleKey)}
- </div>
- {!completionCompact && (
- <div className="truncate text-sm text-control-light">
- {t(journey.completionDescriptionKey)}
- </div>
- )}
- </div>
- ) : (
+ <div
+ ref={stepViewportRef}
+ data-testid="guide-step-viewport"
+ className="relative min-w-0 flex-1 overflow-hidden pr-1 2xl:pr-2"
+ >
<div
- ref={stepViewportRef}
- data-testid="guide-step-viewport"
- className="relative min-w-0 flex-1 overflow-hidden pr-1 2xl:pr-2"
+ ref={stepMeasurementRef}
+ data-testid="guide-step-measurement"
+ aria-hidden
+ className="pointer-events-none invisible absolute left-0 top-0 flex w-max items-center gap-x-2 2xl:gap-x-3"
>
- <div
- ref={stepMeasurementRef}
- data-testid="guide-step-measurement"
- aria-hidden
- className="pointer-events-none invisible absolute left-0 top-0 flex w-max items-center gap-x-2 2xl:gap-x-3"
- >
- {guide.steps.map((step, index) => (
- <div
- key={step.definition.id}
- className="inline-flex items-center gap-x-2 2xl:gap-x-3"
+ {guide.steps.map((step, index) => (
+ <div
+ key={step.definition.id}
+ className="inline-flex items-center gap-x-2 2xl:gap-x-3"
+ >
+ <Button
+ type="button"
+ appearance="secondary"
+ tabIndex={-1}
+ className="inline-flex h-auto items-center justify-start gap-x-1 rounded-sm px-2.5 py-1.5 text-sm font-medium whitespace-nowrap 2xl:gap-x-2 2xl:px-3 2xl:py-2 2xl:text-base"
>
- <Button
- type="button"
- appearance="secondary"
- tabIndex={-1}
- className="inline-flex h-auto items-center justify-start gap-x-1 rounded-sm px-2.5 py-1.5 text-sm font-medium whitespace-nowrap 2xl:gap-x-2 2xl:px-3 2xl:py-2 2xl:text-base"
- >
- {step.done ? (
- <CheckCircle className="size-4 2xl:size-5" />
- ) : (
- <Circle className="size-4 2xl:size-5" />
- )}
- <span>{t(step.definition.labelKey)}</span>
- </Button>
- {index < guide.steps.length - 1 && (
- <span className="text-sm 2xl:text-base">&rsaquo;</span>
+ {step.done ? (
+ <CheckCircle className="size-4 2xl:size-5" />
+ ) : (
+ <Circle className="size-4 2xl:size-5" />
)}
- </div>
- ))}
- </div>
+ <span>{t(step.definition.labelKey)}</span>
+ </Button>
+ {index < guide.steps.length - 1 && (
+ <span className="text-sm 2xl:text-base">&rsaquo;</span>
+ )}
+ </div>
+ ))}
+ </div>
- {stepsOverflow && compactStep ? (
- <div
- data-testid="compact-step-navigator"
- className="flex min-w-0 items-center gap-x-2"
- >
- <span className="shrink-0 text-xs text-control-light 2xl:text-sm">
- {t("workspace-setup-guide.step-progress", {
- current: compactStepIndex + 1,
- total: guide.steps.length,
- })}
+ {stepsOverflow && compactStep ? (
+ <div
+ data-testid="compact-step-navigator"
+ className="flex min-w-0 items-center gap-x-2"
+ >
+ {guide.complete ? (
+ <span className="flex min-w-0 flex-1 items-center gap-x-1 text-sm text-control-light 2xl:text-base">
+ <CheckCircle className="size-4 shrink-0 text-success 2xl:size-5" />
+ <span className="truncate">
+ {t("workspace-setup-guide.all-steps-completed")}
+ </span>
</span>
- <BlockTooltip
- content={
- compactStep.blocked
- ? t("workspace-setup-guide.previous-step-required")
- : t(compactStep.definition.descriptionKey)
+ ) : (
+ <>
+ <span className="shrink-0 text-xs text-control-light 2xl:text-sm">
+ {t("workspace-setup-guide.step-progress", {
+ current: compactStepIndex + 1,
+ total: guide.steps.length,
+ })}
+ </span>
+ <BlockTooltip
+ content={
+ compactStep.blocked
+ ? t("workspace-setup-guide.previous-step-required")
+ : t(compactStep.definition.descriptionKey)
+ }
+ >
+ <Button
+ type="button"
+ appearance="secondary"
+ data-testid="compact-active-step"
+ className="inline-flex h-auto w-full min-w-0 items-center justify-start gap-x-1 rounded-sm bg-accent/10 px-2.5 py-1.5 text-sm font-medium text-accent 2xl:gap-x-2 2xl:px-3 2xl:py-2 2xl:text-base"
+ disabled={compactStep.blocked}
+ onClick={() => onSelectStep(compactStep)}
+ >
+ {compactStep.done ? (
+ <CheckCircle className="size-4 shrink-0 text-success 2xl:size-5" />
+ ) : (
+ <Circle className="size-4 shrink-0 2xl:size-5" />
+ )}
+ <span className="truncate">
+ {t(compactStep.definition.labelKey)}
+ </span>
+ </Button>
+ </BlockTooltip>
+ </>
+ )}
+ <DropdownMenu>
+ <DropdownMenuTrigger
+ render={
+ <Button
+ type="button"
+ appearance="secondary"
+ size="sm"
+ data-testid="open-step-list"
+ aria-label={t("workspace-setup-guide.view-all-steps")}
+ title={t("workspace-setup-guide.view-all-steps")}
+ >
+ <ListChecks className="size-4" />
+ </Button>
}
- >
- <Button
- type="button"
- appearance="secondary"
- data-testid="compact-active-step"
- className="inline-flex h-auto w-full min-w-0 items-center justify-start gap-x-1 rounded-sm bg-accent/10 px-2.5 py-1.5 text-sm font-medium text-accent 2xl:gap-x-2 2xl:px-3 2xl:py-2 2xl:text-base"
- disabled={compactStep.blocked}
- onClick={() => onSelectStep(compactStep)}
+ />
+ <DropdownMenuContent align="end" className="w-64">
+ {guide.steps.map((step) => {
+ const highlighted =
+ !guide.complete &&
+ step.definition.id === compactStep.definition.id;
+ return (
+ <DropdownMenuItem
+ key={step.definition.id}
+ className={cn(
+ "gap-x-2",
+ highlighted && "bg-control-bg"
+ )}
+ disabled={step.blocked}
+ onClick={() => onSelectStep(step)}
+ >
+ {step.done ? (
+ <CheckCircle className="size-4 shrink-0 text-success" />
+ ) : (
+ <Circle className="size-4 shrink-0" />
+ )}
+ <span className="truncate">
+ {t(step.definition.labelKey)}
+ </span>
+ </DropdownMenuItem>
+ );
+ })}
+ </DropdownMenuContent>
+ </DropdownMenu>
+ </div>
+ ) : (
+ <div
+ data-testid="guide-step-list"
+ className="flex w-max items-center gap-x-2 2xl:gap-x-3"
+ >
+ {guide.steps.map((step, index) => {
+ const highlighted =
+ step.definition.id === guide.highlightedStep?.definition.id;
+ return (
+ <div
+ key={step.definition.id}
+ className="inline-flex items-center gap-x-2 2xl:gap-x-3"
>
- {compactStep.done ? (
- <CheckCircle className="size-4 shrink-0 text-success 2xl:size-5" />
- ) : (
- <Circle className="size-4 shrink-0 2xl:size-5" />
- )}
- <span className="truncate">
- {t(compactStep.definition.labelKey)}
- </span>
- </Button>
- </BlockTooltip>
- <DropdownMenu>
- <DropdownMenuTrigger
- render={
+ <Tooltip
+ content={
+ step.blocked
+ ? t("workspace-setup-guide.previous-step-required")
+ : t(step.definition.descriptionKey)
+ }
+ >
<Button
type="button"
appearance="secondary"
- size="sm"
- data-testid="open-step-list"
- aria-label={t("workspace-setup-guide.view-all-steps")}
- title={t("workspace-setup-guide.view-all-steps")}
+ data-testid={`setup-step-${step.definition.id}`}
+ className={cn(
+ "inline-flex h-auto items-center justify-start gap-x-1 rounded-sm px-2.5 py-1.5 text-sm font-medium whitespace-nowrap 2xl:gap-x-2 2xl:px-3 2xl:py-2 2xl:text-base",
+ highlighted
+ ? "bg-accent/10 text-accent"
+ : step.done
+ ? "text-control-light"
+ : "text-control"
+ )}
+ disabled={step.blocked}
+ onClick={() => onSelectStep(step)}
>
- <ListChecks className="size-4" />
+ {step.done ? (
+ <CheckCircle className="size-4 text-success 2xl:size-5" />
+ ) : (
+ <Circle className="size-4 2xl:size-5" />
+ )}
+ <span>{t(step.definition.labelKey)}</span>
</Button>
- }
- />
- <DropdownMenuContent align="end" className="w-64">
- {guide.steps.map((step) => {
- const highlighted =
- step.definition.id === compactStep.definition.id;
- return (
- <DropdownMenuItem
- key={step.definition.id}
- className={cn(
- "gap-x-2",
- highlighted && "bg-control-bg"
- )}
- disabled={step.blocked}
- onClick={() => onSelectStep(step)}
- >
- {step.done ? (
- <CheckCircle className="size-4 shrink-0 text-success" />
- ) : (
- <Circle className="size-4 shrink-0" />
- )}
- <span className="truncate">
- {t(step.definition.labelKey)}
- </span>
- </DropdownMenuItem>
- );
- })}
- </DropdownMenuContent>
- </DropdownMenu>
- </div>
- ) : (
- <div
- data-testid="guide-step-list"
- className="flex w-max items-center gap-x-2 2xl:gap-x-3"
- >
- {guide.steps.map((step, index) => {
- const highlighted =
- step.definition.id ===
- guide.highlightedStep?.definition.id;
- return (
- <div
- key={step.definition.id}
- className="inline-flex items-center gap-x-2 2xl:gap-x-3"
- >
- <Tooltip
- content={
- step.blocked
- ? t(
- "workspace-setup-guide.previous-step-required"
- )
- : t(step.definition.descriptionKey)
- }
- >
- <Button
- type="button"
- appearance="secondary"
- data-testid={`setup-step-${step.definition.id}`}
- className={cn(
- "inline-flex h-auto items-center justify-start gap-x-1 rounded-sm px-2.5 py-1.5 text-sm font-medium whitespace-nowrap 2xl:gap-x-2 2xl:px-3 2xl:py-2 2xl:text-base",
- highlighted
- ? "bg-accent/10 text-accent"
- : step.done
- ? "text-control-light"
- : "text-control"
- )}
- disabled={step.blocked}
- onClick={() => onSelectStep(step)}
- >
- {step.done ? (
- <CheckCircle className="size-4 text-success 2xl:size-5" />
- ) : (
- <Circle className="size-4 2xl:size-5" />
- )}
- <span>{t(step.definition.labelKey)}</span>
- </Button>
- </Tooltip>
- {index < guide.steps.length - 1 && (
- <span className="text-sm text-control-light 2xl:text-base">
- &rsaquo;
- </span>
- )}
- </div>
- );
- })}
- </div>
- )}
- </div>
- )}
+ </Tooltip>
+ {index < guide.steps.length - 1 && (
+ <span className="text-sm text-control-light 2xl:text-base">
+ &rsaquo;
+ </span>
+ )}
+ </div>
+ );
+ })}
+ </div>
+ )}
+ </div>
</div>
<div className="ml-auto flex shrink-0 items-center gap-x-2">
- {guide.complete &&
- hasDatabaseTarget &&
- journey.completionActions.includes("create-change") &&
- (!completionCompact ||
- completionPrimaryAction === "create-change") && (
- <Button
- type="button"
- appearance="secondary"
- size={completionCompact ? "sm" : undefined}
- onClick={() => {
- void preCreateIssue(context.databaseProjectName, [
- context.databaseName,
- ]);
- }}
- >
- {t("workspace-setup-guide.actions.change")}
- </Button>
- )}
- {guide.complete &&
- hasDatabaseTarget &&
- journey.completionActions.includes("open-sql-editor") &&
- (!completionCompact ||
- completionPrimaryAction === "open-sql-editor") && (
- <SQLEditorButton
- database={{
- name: context.databaseName,
- project: context.databaseProjectName,
- }}
- openInNewTab
- size={completionCompact ? "sm" : undefined}
- label={t("workspace-setup-guide.actions.query")}
- />
- )}
{!guide.complete && primaryAction?.type === "open-sql-editor" && (
<span
onClickCapture={() => {
diff --git a/frontend/src/modules/workspace-setup-guide/analytics.test.ts b/frontend/src/modules/workspace-setup-guide/analytics.test.ts
index 95d3565906..afbe0d61a3 100644
--- a/frontend/src/modules/workspace-setup-guide/analytics.test.ts
+++ b/frontend/src/modules/workspace-setup-guide/analytics.test.ts
@@ -5,9 +5,6 @@ import type { GuideJourney, ResolvedGuide } from "./types";
const journey: GuideJourney = {
id: "query-data",
scenarioId: "query-data",
- completionTitleKey: "",
- completionDescriptionKey: "",
- completionActions: [],
steps: [
{ stepId: "create-project" },
{ stepId: "connect-instance", dependsOn: ["create-project"] },
diff --git a/frontend/src/modules/workspace-setup-guide/progress.test.ts b/frontend/src/modules/workspace-setup-guide/progress.test.ts
index 92f69f3cd4..6ec6aa49da 100644
--- a/frontend/src/modules/workspace-setup-guide/progress.test.ts
+++ b/frontend/src/modules/workspace-setup-guide/progress.test.ts
@@ -11,6 +11,7 @@ describe("workspace setup guide progress keys", () => {
databaseExplored: "workspace-setup-guide.database-explored",
statementRun: "workspace-setup-guide.statement-run",
changeIssueCreated: "workspace-setup-guide.change-issue-created",
+ sensitiveDataMarked: "workspace-setup-guide.sensitive-data-marked",
teammateAdded: "workspace-setup-guide.teammate-added",
dismissed: "workspace-setup-guide.dismissed",
});
diff --git a/frontend/src/modules/workspace-setup-guide/progress.ts b/frontend/src/modules/workspace-setup-guide/progress.ts
index 5cbea04d8e..5240006af7 100644
--- a/frontend/src/modules/workspace-setup-guide/progress.ts
+++ b/frontend/src/modules/workspace-setup-guide/progress.ts
@@ -4,6 +4,7 @@ export const GUIDE_PROGRESS_KEYS = {
databaseExplored: "workspace-setup-guide.database-explored",
statementRun: "workspace-setup-guide.statement-run",
changeIssueCreated: "workspace-setup-guide.change-issue-created",
+ sensitiveDataMarked: "workspace-setup-guide.sensitive-data-marked",
teammateAdded: "workspace-setup-guide.teammate-added",
dismissed: "workspace-setup-guide.dismissed",
} as const;
diff --git a/frontend/src/modules/workspace-setup-guide/resolve.test.ts b/frontend/src/modules/workspace-setup-guide/resolve.test.ts
index 7693ca7ed3..0e507c49cb 100644
--- a/frontend/src/modules/workspace-setup-guide/resolve.test.ts
+++ b/frontend/src/modules/workspace-setup-guide/resolve.test.ts
@@ -18,6 +18,7 @@ const STEP_IDS: GuideStepId[] = [
"explore-database",
"query-data",
"create-database-change",
+ "mark-sensitive-data",
"add-member",
];
@@ -29,6 +30,7 @@ const createContext = (
hasExploredDatabase: false,
hasRunStatement: false,
hasCreatedChangeIssue: false,
+ hasMarkedSensitiveData: false,
isSaaS: false,
hasOtherHumanUser: false,
hasOtherWorkspaceMember: false,
@@ -46,6 +48,7 @@ const completionById: Record<GuideStepId, keyof GuideContext> = {
"explore-database": "hasExploredDatabase",
"query-data": "hasRunStatement",
"create-database-change": "hasCreatedChangeIssue",
+ "mark-sensitive-data": "hasMarkedSensitiveData",
"add-member": "hasOtherWorkspaceMember",
};
@@ -62,9 +65,6 @@ const definitions = STEP_IDS.map(definition);
const generic: GuideJourney = {
id: "workspace-setup",
- completionTitleKey: "completion.generic.title",
- completionDescriptionKey: "completion.generic.description",
- completionActions: ["open-sql-editor", "create-change"],
steps: [
{ stepId: "create-project" },
{ stepId: "connect-instance", dependsOn: ["create-project"] },
@@ -75,9 +75,6 @@ const generic: GuideJourney = {
const queryData: GuideJourney = {
id: "query-data",
scenarioId: "query-data",
- completionTitleKey: "completion.query.title",
- completionDescriptionKey: "completion.query.description",
- completionActions: ["create-change"],
steps: [
{ stepId: "create-project", kind: "prerequisite" },
{
@@ -137,6 +134,15 @@ describe("validateGuideJourney", () => {
).toThrow(message);
});
+ test("rejects duplicate step definition ids", () => {
+ expect(() =>
+ validateGuideJourney(generic, [
+ ...definitions,
+ definition("create-project"),
+ ])
+ ).toThrow("duplicate step definition");
+ });
+
test("rejects duplicate journey ids", () => {
expect(() =>
validateGuideJourneys([generic, generic], definitions)
diff --git a/frontend/src/modules/workspace-setup-guide/scenarios.test.ts b/frontend/src/modules/workspace-setup-guide/scenarios.test.ts
index 8ab5d2e0fe..f28bb397a5 100644
--- a/frontend/src/modules/workspace-setup-guide/scenarios.test.ts
+++ b/frontend/src/modules/workspace-setup-guide/scenarios.test.ts
@@ -1,23 +1,91 @@
// @vitest-environment node
import { describe, expect, test } from "vitest";
-import { validateGuideJourney } from "./resolve";
+import { resolveGuide, validateGuideJourney } from "./resolve";
import {
CREATE_DATABASE_CHANGE_SCENARIO,
GUIDE_SCENARIO_REGISTRY,
getGuideJourney,
+ MARK_SENSITIVE_DATA_SCENARIO,
QUERY_DATA_SCENARIO,
WORKSPACE_SETUP_JOURNEY,
} from "./scenarios";
-import { GUIDE_STEP_REGISTRY } from "./steps";
+import { GUIDE_STEP_DEFINITIONS } from "./steps";
describe("workspace setup guide journeys", () => {
- test("registers only the two customer scenarios", () => {
+ test("registers the customer scenarios", () => {
expect(Object.keys(GUIDE_SCENARIO_REGISTRY)).toEqual([
"query-data",
"create-database-change",
+ "mark-sensitive-data",
]);
});
+ test("uses workspace setup as visible sensitive-data prerequisites", () => {
+ const journey = getGuideJourney("mark-sensitive-data");
+
+ expect(journey.steps).toEqual([
+ { stepId: "create-project", kind: "prerequisite" },
+ {
+ stepId: "connect-instance",
+ kind: "prerequisite",
+ dependsOn: ["create-project"],
+ },
+ {
+ stepId: "explore-database",
+ kind: "prerequisite",
+ dependsOn: ["connect-instance"],
+ },
+ {
+ stepId: "mark-sensitive-data",
+ dependsOn: ["explore-database"],
+ },
+ { stepId: "query-data", dependsOn: ["mark-sensitive-data"] },
+ ]);
+ });
+
+ test.each([
+ [false, false, true, false],
+ [true, false, false, false],
+ [true, true, false, true],
+ ])(
+ "resolves masking verification with marked=%s and queried=%s",
+ (hasMarkedSensitiveData, hasRunStatement, blocked, complete) => {
+ const databaseName = "projects/test/instances/test/databases/test";
+ const guide = resolveGuide({
+ journey: MARK_SENSITIVE_DATA_SCENARIO,
+ definitions: GUIDE_STEP_DEFINITIONS,
+ context: {
+ hasProject: true,
+ hasInstance: true,
+ hasExploredDatabase: true,
+ hasMarkedSensitiveData,
+ hasRunStatement,
+ hasCreatedChangeIssue: false,
+ isSaaS: true,
+ hasOtherHumanUser: false,
+ hasOtherWorkspaceMember: false,
+ projectName: "projects/test",
+ instanceName: "projects/test/instances/test",
+ databaseProjectName: "projects/test",
+ databaseName,
+ route: { name: "workspace.home", params: {} },
+ },
+ });
+
+ expect(guide.steps.at(-1)).toMatchObject({
+ definition: { id: "query-data" },
+ blocked,
+ actions: {
+ primary: {
+ type: "open-sql-editor",
+ database: { name: databaseName, project: "projects/test" },
+ },
+ },
+ });
+ expect(guide.complete).toBe(complete);
+ }
+ );
+
test("uses an unassigned generic journey when no scenario was selected", () => {
expect(getGuideJourney(undefined)).toBe(WORKSPACE_SETUP_JOURNEY);
expect(WORKSPACE_SETUP_JOURNEY.scenarioId).toBeUndefined();
@@ -83,6 +151,16 @@ describe("workspace setup guide journeys", () => {
"create-database-change",
],
],
+ [
+ "mark-sensitive-data" as const,
+ [
+ "create-project",
+ "connect-instance",
+ "explore-database",
+ "mark-sensitive-data",
+ "query-data",
+ ],
+ ],
])(
"appends the team modifier after the %s journey",
(scenarioId, baseSteps) => {
@@ -120,9 +198,10 @@ describe("workspace setup guide journeys", () => {
WORKSPACE_SETUP_JOURNEY,
QUERY_DATA_SCENARIO,
CREATE_DATABASE_CHANGE_SCENARIO,
+ MARK_SENSITIVE_DATA_SCENARIO,
])("validates $id", (journey) => {
expect(() =>
- validateGuideJourney(journey, GUIDE_STEP_REGISTRY)
+ validateGuideJourney(journey, GUIDE_STEP_DEFINITIONS)
).not.toThrow();
});
});
diff --git a/frontend/src/modules/workspace-setup-guide/scenarios.ts b/frontend/src/modules/workspace-setup-guide/scenarios.ts
index 38806bdfab..079f7c40d3 100644
--- a/frontend/src/modules/workspace-setup-guide/scenarios.ts
+++ b/frontend/src/modules/workspace-setup-guide/scenarios.ts
@@ -1,5 +1,5 @@
import { validateGuideJourneys } from "./resolve";
-import { GUIDE_STEP_REGISTRY } from "./steps";
+import { GUIDE_STEP_DEFINITIONS } from "./steps";
import type {
GuideJourney,
GuideScenarioId,
@@ -8,10 +8,6 @@ import type {
export const WORKSPACE_SETUP_JOURNEY: GuideJourney = {
id: "workspace-setup",
- completionTitleKey: "workspace-setup-guide.generic.completion-title",
- completionDescriptionKey:
- "workspace-setup-guide.generic.completion-description",
- completionActions: ["open-sql-editor", "create-change"],
steps: [
{ stepId: "create-project" },
{ stepId: "connect-instance", dependsOn: ["create-project"] },
@@ -27,11 +23,6 @@ const SCENARIO_PREREQUISITES = WORKSPACE_SETUP_JOURNEY.steps.map((step) => ({
export const QUERY_DATA_SCENARIO: GuideJourney = {
id: "query-data",
scenarioId: "query-data",
- completionTitleKey:
- "workspace-setup-guide.scenarios.query-data.completion-title",
- completionDescriptionKey:
- "workspace-setup-guide.scenarios.query-data.completion-description",
- completionActions: ["create-change"],
steps: [
...SCENARIO_PREREQUISITES,
{ stepId: "query-data", dependsOn: ["explore-database"] },
@@ -41,11 +32,6 @@ export const QUERY_DATA_SCENARIO: GuideJourney = {
export const CREATE_DATABASE_CHANGE_SCENARIO: GuideJourney = {
id: "create-database-change",
scenarioId: "create-database-change",
- completionTitleKey:
- "workspace-setup-guide.scenarios.create-database-change.completion-title",
- completionDescriptionKey:
- "workspace-setup-guide.scenarios.create-database-change.completion-description",
- completionActions: ["open-sql-editor"],
steps: [
...SCENARIO_PREREQUISITES,
{
@@ -55,13 +41,30 @@ export const CREATE_DATABASE_CHANGE_SCENARIO: GuideJourney = {
],
};
+export const MARK_SENSITIVE_DATA_SCENARIO: GuideJourney = {
+ id: "mark-sensitive-data",
+ scenarioId: "mark-sensitive-data",
+ steps: [
+ ...SCENARIO_PREREQUISITES,
+ {
+ stepId: "mark-sensitive-data",
+ dependsOn: ["explore-database"],
+ },
+ { stepId: "query-data", dependsOn: ["mark-sensitive-data"] },
+ ],
+};
+
export const GUIDE_SCENARIO_REGISTRY: Readonly<
Record<GuideScenarioId, GuideJourney>
> = {
"query-data": QUERY_DATA_SCENARIO,
"create-database-change": CREATE_DATABASE_CHANGE_SCENARIO,
+ "mark-sensitive-data": MARK_SENSITIVE_DATA_SCENARIO,
};
+export const isGuideScenarioId = (value: unknown): value is GuideScenarioId =>
+ typeof value === "string" && Object.hasOwn(GUIDE_SCENARIO_REGISTRY, value);
+
export const getGuideJourney = (
scenarioId: GuideScenarioId | undefined,
workspaceUsage?: GuideWorkspaceUsage
@@ -88,5 +91,5 @@ export const getGuideJourney = (
validateGuideJourneys(
[WORKSPACE_SETUP_JOURNEY, ...Object.values(GUIDE_SCENARIO_REGISTRY)],
- GUIDE_STEP_REGISTRY
+ GUIDE_STEP_DEFINITIONS
);
diff --git a/frontend/src/modules/workspace-setup-guide/selection.test.ts b/frontend/src/modules/workspace-setup-guide/selection.test.ts
index ee034e84b2..651aadb278 100644
--- a/frontend/src/modules/workspace-setup-guide/selection.test.ts
+++ b/frontend/src/modules/workspace-setup-guide/selection.test.ts
@@ -3,10 +3,10 @@ import {
storageKeyWorkspaceSetupGuideScenario,
storageKeyWorkspaceSetupGuideWorkspaceUsage,
} from "@/utils/storage-keys";
+import { isGuideScenarioId } from "./scenarios";
import {
clearGuideWorkspaceUsage,
clearSelectedGuideScenarioId,
- isGuideScenarioId,
isGuideWorkspaceUsage,
readGuideWorkspaceUsage,
readSelectedGuideScenarioId,
@@ -72,9 +72,10 @@ describe("workspace setup guide scenario selection", () => {
vi.restoreAllMocks();
});
- test("accepts only registered phase-one scenario ids", () => {
+ test("accepts only registered scenario ids", () => {
expect(isGuideScenarioId("query-data")).toBe(true);
expect(isGuideScenarioId("create-database-change")).toBe(true);
+ expect(isGuideScenarioId("mark-sensitive-data")).toBe(true);
expect(isGuideScenarioId("learn-bytebase-basics")).toBe(false);
expect(isGuideScenarioId("protect-sensitive-data")).toBe(false);
expect(isGuideScenarioId("toString")).toBe(false);
diff --git a/frontend/src/modules/workspace-setup-guide/selection.ts b/frontend/src/modules/workspace-setup-guide/selection.ts
index 1bc02fe6e3..eb110a75f2 100644
--- a/frontend/src/modules/workspace-setup-guide/selection.ts
+++ b/frontend/src/modules/workspace-setup-guide/selection.ts
@@ -9,12 +9,10 @@ import {
storageKeyWorkspaceSetupGuideScenario,
storageKeyWorkspaceSetupGuideWorkspaceUsage,
} from "@/utils/storage-keys";
-import { GUIDE_SCENARIO_REGISTRY } from "./scenarios";
+import { isGuideScenarioId } from "./scenarios";
import type { GuideScenarioId, GuideWorkspaceUsage } from "./types";
-export const isGuideScenarioId = (value: unknown): value is GuideScenarioId =>
- typeof value === "string" &&
- Object.prototype.hasOwnProperty.call(GUIDE_SCENARIO_REGISTRY, value);
+export { isGuideScenarioId };
export const isGuideWorkspaceUsage = (
value: unknown
diff --git a/frontend/src/modules/workspace-setup-guide/steps.test.ts b/frontend/src/modules/workspace-setup-guide/steps.test.ts
index 351e1190f0..7b534c011a 100644
--- a/frontend/src/modules/workspace-setup-guide/steps.test.ts
+++ b/frontend/src/modules/workspace-setup-guide/steps.test.ts
@@ -2,6 +2,7 @@
import { describe, expect, test } from "vitest";
import {
PROJECT_V1_ROUTE_DASHBOARD,
+ PROJECT_V1_ROUTE_DATABASE_DETAIL,
PROJECT_V1_ROUTE_DATABASES,
PROJECT_V1_ROUTE_INSTANCES,
PROJECT_V1_ROUTE_PLAN_DETAIL,
@@ -16,14 +17,12 @@ import {
PRODUCT_INTRO_QUERY_KEY,
PROJECT_INSTANCE_SYNCED_PRODUCT_INTRO,
} from "@/lib/productIntro";
-import { GUIDE_STEP_REGISTRY } from "./steps";
-import type { GuideContext, GuideStepId } from "./types";
+import { GUIDE_STEP_DEFINITIONS } from "./steps";
+import type { GuideContext, GuideStepDefinition, GuideStepId } from "./types";
-const getStepDefinition = (id: GuideStepId) => {
- const definition = GUIDE_STEP_REGISTRY.find((step) => step.id === id);
- if (!definition) throw new Error(`Missing step definition: ${id}`);
- return definition;
-};
+const GUIDE_STEP_BY_ID = Object.fromEntries(
+ GUIDE_STEP_DEFINITIONS.map((definition) => [definition.id, definition])
+) as Record<GuideStepId, GuideStepDefinition>;
const createContext = (
overrides: Partial<GuideContext> = {}
@@ -33,6 +32,7 @@ const createContext = (
hasExploredDatabase: false,
hasRunStatement: false,
hasCreatedChangeIssue: false,
+ hasMarkedSensitiveData: false,
isSaaS: false,
hasOtherHumanUser: false,
hasOtherWorkspaceMember: false,
@@ -44,14 +44,15 @@ const createContext = (
...overrides,
});
-describe("GUIDE_STEP_REGISTRY", () => {
+describe("GUIDE_STEP_DEFINITIONS", () => {
test("contains only reusable resource and customer-action definitions", () => {
- expect(GUIDE_STEP_REGISTRY.map(({ id }) => id)).toEqual([
+ expect(GUIDE_STEP_DEFINITIONS.map(({ id }) => id)).toEqual([
"create-project",
"connect-instance",
"explore-database",
"query-data",
"create-database-change",
+ "mark-sensitive-data",
"add-member",
]);
});
@@ -69,16 +70,17 @@ describe("GUIDE_STEP_REGISTRY", () => {
],
["query-data", { hasRunStatement: true }],
["create-database-change", { hasCreatedChangeIssue: true }],
+ ["mark-sensitive-data", { hasMarkedSensitiveData: true }],
["add-member", { hasOtherWorkspaceMember: true }],
] as const)("uses observable evidence for %s", (stepId, completed) => {
- expect(getStepDefinition(stepId).isComplete(createContext(completed))).toBe(
+ expect(GUIDE_STEP_BY_ID[stepId].isComplete(createContext(completed))).toBe(
true
);
});
test("keeps database exploration incomplete without a concrete target", () => {
expect(
- getStepDefinition("explore-database").isComplete(
+ GUIDE_STEP_BY_ID["explore-database"].isComplete(
createContext({ hasExploredDatabase: true })
)
).toBe(false);
@@ -88,7 +90,7 @@ describe("GUIDE_STEP_REGISTRY", () => {
"always opens the workspace project list with the create highlight",
(context) => {
expect(
- getStepDefinition("create-project").resolveActions(context)
+ GUIDE_STEP_BY_ID["create-project"].resolveActions(context)
).toEqual({
select: {
type: "navigate",
@@ -113,7 +115,7 @@ describe("GUIDE_STEP_REGISTRY", () => {
"always opens the project instance list with the create highlight",
(context) => {
expect(
- getStepDefinition("connect-instance").resolveActions(context)
+ GUIDE_STEP_BY_ID["connect-instance"].resolveActions(context)
).toEqual({
select: {
type: "navigate",
@@ -131,7 +133,7 @@ describe("GUIDE_STEP_REGISTRY", () => {
test("keeps the connect action fixed while its project dependency is blocked", () => {
expect(
- getStepDefinition("connect-instance").resolveActions(createContext())
+ GUIDE_STEP_BY_ID["connect-instance"].resolveActions(createContext())
).toEqual({
select: {
type: "navigate",
@@ -155,7 +157,7 @@ describe("GUIDE_STEP_REGISTRY", () => {
}),
])("always opens the project database page with its highlight", (context) => {
expect(
- getStepDefinition("explore-database").resolveActions(context)
+ GUIDE_STEP_BY_ID["explore-database"].resolveActions(context)
).toEqual({
select: {
type: "navigate",
@@ -174,7 +176,7 @@ describe("GUIDE_STEP_REGISTRY", () => {
"always queries the discovered database when completion is %s",
(hasRunStatement) => {
expect(
- getStepDefinition("query-data").resolveActions(
+ GUIDE_STEP_BY_ID["query-data"].resolveActions(
createContext({
hasRunStatement,
databaseName: "instances/sample/databases/employee",
@@ -182,6 +184,17 @@ describe("GUIDE_STEP_REGISTRY", () => {
})
)
).toEqual({
+ select: {
+ type: "navigate",
+ target: {
+ name: "sql-editor.database",
+ params: {
+ project: "app",
+ instance: "sample",
+ database: "employee",
+ },
+ },
+ },
primary: {
type: "open-sql-editor",
database: {
@@ -193,11 +206,43 @@ describe("GUIDE_STEP_REGISTRY", () => {
}
);
+ test.each([false, true])(
+ "always opens the discovered database catalog when sensitive data completion is %s",
+ (hasMarkedSensitiveData) => {
+ expect(
+ GUIDE_STEP_BY_ID["mark-sensitive-data"].resolveActions(
+ createContext({
+ hasMarkedSensitiveData,
+ databaseName: "instances/sample/databases/employee",
+ databaseProjectName: "projects/app",
+ })
+ )
+ ).toEqual({
+ select: {
+ type: "navigate",
+ target: {
+ name: PROJECT_V1_ROUTE_DATABASE_DETAIL,
+ params: {
+ projectId: "app",
+ instanceId: "sample",
+ databaseName: "employee",
+ },
+ query: {
+ parent: "instances/sample",
+ intro: "mark-sensitive-data",
+ },
+ hash: "#catalog",
+ },
+ },
+ });
+ }
+ );
+
test.each([false, true])(
"always starts a database change when completion is %s",
(hasCreatedChangeIssue) => {
expect(
- getStepDefinition("create-database-change").resolveActions(
+ GUIDE_STEP_BY_ID["create-database-change"].resolveActions(
createContext({
hasCreatedChangeIssue,
databaseName: "instances/sample/databases/employee",
@@ -217,7 +262,7 @@ describe("GUIDE_STEP_REGISTRY", () => {
test("opens Users when self-host has no other human user", () => {
const context = createContext();
- expect(getStepDefinition("add-member").resolveActions(context)).toEqual({
+ expect(GUIDE_STEP_BY_ID["add-member"].resolveActions(context)).toEqual({
select: {
type: "navigate",
target: {
@@ -234,7 +279,7 @@ describe("GUIDE_STEP_REGISTRY", () => {
createContext({ isSaaS: true }),
createContext({ hasOtherHumanUser: true }),
])("opens Members when the teammate can be granted access", (context) => {
- expect(getStepDefinition("add-member").resolveActions(context)).toEqual({
+ expect(GUIDE_STEP_BY_ID["add-member"].resolveActions(context)).toEqual({
select: {
type: "navigate",
target: {
@@ -253,11 +298,12 @@ describe("GUIDE_STEP_REGISTRY", () => {
["explore-database", "workspace.project.database.detail", true],
["query-data", "sql-editor.database", true],
["create-database-change", PROJECT_V1_ROUTE_PLAN_DETAIL, true],
+ ["mark-sensitive-data", PROJECT_V1_ROUTE_DATABASE_DETAIL, true],
["add-member", WORKSPACE_ROUTE_USERS, true],
["add-member", WORKSPACE_ROUTE_MEMBERS, true],
] as const)("matches %s on %s", (stepId, name, expected) => {
expect(
- getStepDefinition(stepId as GuideStepId).matchesRoute({
+ GUIDE_STEP_BY_ID[stepId as GuideStepId].matchesRoute({
name,
params: {},
})
diff --git a/frontend/src/modules/workspace-setup-guide/steps.ts b/frontend/src/modules/workspace-setup-guide/steps.ts
index 50e48d2f09..7638e0e5af 100644
--- a/frontend/src/modules/workspace-setup-guide/steps.ts
+++ b/frontend/src/modules/workspace-setup-guide/steps.ts
@@ -1,5 +1,6 @@
import {
PROJECT_V1_ROUTE_DASHBOARD,
+ PROJECT_V1_ROUTE_DATABASE_DETAIL,
PROJECT_V1_ROUTE_DATABASES,
PROJECT_V1_ROUTE_INSTANCES,
PROJECT_V1_ROUTE_PLAN_DETAIL,
@@ -12,9 +13,12 @@ import {
CREATE_PROJECT_PRODUCT_INTRO,
CREATE_USER_PRODUCT_INTRO,
GRANT_ACCESS_PRODUCT_INTRO,
+ MARK_SENSITIVE_DATA_PRODUCT_INTRO,
PRODUCT_INTRO_QUERY_KEY,
PROJECT_INSTANCE_SYNCED_PRODUCT_INTRO,
} from "@/lib/productIntro";
+import { autoSQLEditorDatabaseRoute } from "@/utils/auto-route";
+import { extractDatabaseResourceName } from "@/utils/v1/database";
import { extractProjectResourceName } from "@/utils/v1/project";
import type {
GuideContext,
@@ -57,7 +61,7 @@ const databaseActions = (context: GuideContext): GuideStepActions => ({
},
});
-export const GUIDE_STEP_REGISTRY: readonly GuideStepDefinition[] = [
+export const GUIDE_STEP_DEFINITIONS: readonly GuideStepDefinition[] = [
{
id: "create-project",
labelKey: "workspace-setup-guide.steps.project",
@@ -105,6 +109,13 @@ export const GUIDE_STEP_REGISTRY: readonly GuideStepDefinition[] = [
matchesRoute: (route) =>
isRouteInside(route.name, SQL_EDITOR_DATABASE_MODULE),
resolveActions: (context) => ({
+ select: {
+ type: "navigate",
+ target: autoSQLEditorDatabaseRoute({
+ name: context.databaseName,
+ project: context.databaseProjectName,
+ }),
+ },
primary: {
type: "open-sql-editor",
database: {
@@ -129,6 +140,38 @@ export const GUIDE_STEP_REGISTRY: readonly GuideStepDefinition[] = [
},
}),
},
+ {
+ id: "mark-sensitive-data",
+ labelKey: "workspace-setup-guide.steps.mark-sensitive-data",
+ descriptionKey: "workspace-setup-guide.descriptions.mark-sensitive-data",
+ isComplete: (context) => context.hasMarkedSensitiveData,
+ matchesRoute: (route) =>
+ isRouteInside(route.name, PROJECT_V1_ROUTE_DATABASE_DETAIL),
+ resolveActions: (context) => {
+ const { instance, instanceName, databaseName } =
+ extractDatabaseResourceName(context.databaseName);
+ return {
+ select: {
+ type: "navigate",
+ target: {
+ name: PROJECT_V1_ROUTE_DATABASE_DETAIL,
+ params: {
+ projectId: extractProjectResourceName(
+ context.databaseProjectName
+ ),
+ instanceId: instanceName,
+ databaseName,
+ },
+ query: {
+ parent: instance,
+ [PRODUCT_INTRO_QUERY_KEY]: MARK_SENSITIVE_DATA_PRODUCT_INTRO,
+ },
+ hash: "#catalog",
+ },
+ },
+ };
+ },
+ },
{
id: "add-member",
labelKey: "workspace-setup-guide.steps.add-teammate",
diff --git a/frontend/src/modules/workspace-setup-guide/types.ts b/frontend/src/modules/workspace-setup-guide/types.ts
index 44c9c69230..90b1eb4030 100644
--- a/frontend/src/modules/workspace-setup-guide/types.ts
+++ b/frontend/src/modules/workspace-setup-guide/types.ts
@@ -6,15 +6,20 @@ export type GuideStepId =
| "explore-database"
| "query-data"
| "create-database-change"
+ | "mark-sensitive-data"
| "add-member";
-export type GuideScenarioId = "query-data" | "create-database-change";
+export type GuideScenarioId =
+ | "query-data"
+ | "create-database-change"
+ | "mark-sensitive-data";
export type GuideWorkspaceUsage = "team" | "solo";
export type GuideJourneyId = "workspace-setup" | GuideScenarioId;
-export type GuideRoute = Pick<ReactRoute, "name" | "params">;
+export type GuideRoute = Pick<ReactRoute, "name" | "params"> &
+ Partial<Pick<ReactRoute, "query">>;
export type GuideContext = {
hasProject: boolean;
@@ -22,6 +27,7 @@ export type GuideContext = {
hasExploredDatabase: boolean;
hasRunStatement: boolean;
hasCreatedChangeIssue: boolean;
+ hasMarkedSensitiveData: boolean;
isSaaS: boolean;
hasOtherHumanUser: boolean;
hasOtherWorkspaceMember: boolean;
@@ -67,14 +73,9 @@ export type GuideJourneyStep = {
dependsOn?: readonly GuideStepId[];
};
-export type GuideCompletionActionId = "open-sql-editor" | "create-change";
-
export type GuideJourney = {
id: GuideJourneyId;
scenarioId?: GuideScenarioId;
- completionTitleKey: string;
- completionDescriptionKey: string;
- completionActions: readonly GuideCompletionActionId[];
steps: readonly GuideJourneyStep[];
};
diff --git a/frontend/src/modules/workspace-setup-guide/useGuideContext.test.tsx b/frontend/src/modules/workspace-setup-guide/useGuideContext.test.tsx
index deeef9d734..0974589dcb 100644
--- a/frontend/src/modules/workspace-setup-guide/useGuideContext.test.tsx
+++ b/frontend/src/modules/workspace-setup-guide/useGuideContext.test.tsx
@@ -1,3 +1,4 @@
+import { create } from "@bufbuild/protobuf";
import { act, renderHook, waitFor } from "@testing-library/react";
import { beforeEach, describe, expect, test, vi } from "vitest";
import {
@@ -7,6 +8,11 @@ import {
} from "@/app/router/handles";
import { planEvents } from "@/lib/plan/events";
import { sqlEditorEvents } from "@/modules/sql-editor/model/events";
+import { DatabaseCatalogSchema } from "@/types/proto-es/v1/database_catalog_service_pb";
+import { Engine } from "@/types/proto-es/v1/common_pb";
+import { getGuideJourney } from "./scenarios";
+import { resolveGuide } from "./resolve";
+import { GUIDE_STEP_DEFINITIONS } from "./steps";
import { GUIDE_PROGRESS_KEYS } from "./progress";
import type {
GuideRoute,
@@ -18,10 +24,12 @@ const mocks = vi.hoisted(() => ({
projectsByName: {} as Record<string, unknown>,
instancesByName: {} as Record<string, unknown>,
databasesByName: {} as Record<string, unknown>,
+ catalogsByName: {} as Record<string, unknown>,
usersByName: {} as Record<string, unknown>,
fetchProjectList: vi.fn(),
fetchInstanceList: vi.fn(),
fetchDatabases: vi.fn(),
+ getOrFetchDatabaseCatalog: vi.fn(),
listUsers: vi.fn(),
introState: {} as Record<string, boolean>,
saveIntroStateByKey: vi.fn(),
@@ -54,6 +62,7 @@ vi.mock("@/stores/app", () => {
projectsByName: mocks.projectsByName,
instancesByName: mocks.instancesByName,
databasesByName: mocks.databasesByName,
+ catalogsByName: mocks.catalogsByName,
usersByName: mocks.usersByName,
workspaceResourceName: () => mocks.workspaceResourceName,
currentUserName: mocks.currentUserName,
@@ -69,6 +78,7 @@ vi.mock("@/stores/app", () => {
fetchProjectList: mocks.fetchProjectList,
fetchInstanceList: mocks.fetchInstanceList,
fetchDatabases: mocks.fetchDatabases,
+ getOrFetchDatabaseCatalog: mocks.getOrFetchDatabaseCatalog,
listUsers: mocks.listUsers,
getIntroStateByKey: (key: string) => mocks.introState[key] ?? false,
saveIntroStateByKey: mocks.saveIntroStateByKey,
@@ -79,6 +89,7 @@ vi.mock("@/stores/app", () => {
});
import {
+ catalogHasMarkedSensitiveData,
hasOtherHumanWorkspaceMember,
useGuideContext,
} from "./useGuideContext";
@@ -99,6 +110,42 @@ const renderGuideContext = (
}
) => renderHook((value) => useGuideContext(value), { initialProps: props });
+const mockDiscoveredDatabase = () => {
+ mocks.fetchProjectList.mockResolvedValue({
+ projects: [{ name: "projects/app" }],
+ nextPageToken: "",
+ });
+ mocks.fetchInstanceList.mockResolvedValue({
+ instances: [{ name: "instances/sample" }],
+ nextPageToken: "",
+ });
+ mocks.fetchDatabases.mockResolvedValue({
+ databases: [
+ {
+ name: "instances/sample/databases/employee",
+ project: "projects/app",
+ },
+ ],
+ nextPageToken: "",
+ });
+};
+
+const catalogWithColumn = (column: {
+ semanticType?: string;
+ classification?: string;
+}) =>
+ ({
+ schemas: [
+ {
+ tables: [
+ {
+ kind: { case: "columns", value: { columns: [column] } },
+ },
+ ],
+ },
+ ],
+ }) as never;
+
describe("useGuideContext", () => {
beforeEach(() => {
vi.clearAllMocks();
@@ -106,6 +153,7 @@ describe("useGuideContext", () => {
mocks.projectsByName = {};
mocks.instancesByName = {};
mocks.databasesByName = {};
+ mocks.catalogsByName = {};
mocks.usersByName = {};
mocks.fetchProjectList.mockResolvedValue({ projects: [], nextPageToken: "" });
mocks.fetchInstanceList.mockResolvedValue({
@@ -113,6 +161,7 @@ describe("useGuideContext", () => {
nextPageToken: "",
});
mocks.fetchDatabases.mockResolvedValue({ databases: [], nextPageToken: "" });
+ mocks.getOrFetchDatabaseCatalog.mockResolvedValue({ schemas: [] });
mocks.listUsers.mockResolvedValue({ users: [], nextPageToken: "" });
mocks.currentUserName = "users/[email protected]";
mocks.isSaaS = false;
@@ -129,6 +178,209 @@ describe("useGuideContext", () => {
});
});
+ test("recognizes only a non-empty column semantic type as marked sensitive data", () => {
+ expect(
+ catalogHasMarkedSensitiveData(
+ catalogWithColumn({ semanticType: "bb.default" })
+ )
+ ).toBe(true);
+ expect(
+ catalogHasMarkedSensitiveData(
+ catalogWithColumn({ classification: "classification.column" })
+ )
+ ).toBe(false);
+ });
+
+ test.each([
+ ["root", { semanticType: "bb.default" }, true],
+ [
+ "nested object field",
+ {
+ kind: {
+ case: "structKind",
+ value: {
+ properties: {
+ contact: {
+ kind: {
+ case: "structKind",
+ value: {
+ properties: {
+ email: { semanticType: "bb.default" },
+ },
+ },
+ },
+ },
+ },
+ },
+ },
+ },
+ true,
+ ],
+ [
+ "array element",
+ {
+ kind: {
+ case: "arrayKind",
+ value: {
+ kind: {
+ kind: {
+ case: "structKind",
+ value: {
+ properties: {
+ email: { semanticType: "bb.default-partial" },
+ },
+ },
+ },
+ },
+ },
+ },
+ },
+ true,
+ ],
+ [
+ "unmarked field",
+ {
+ kind: { case: "structKind", value: { properties: { email: {} } } },
+ },
+ false,
+ ],
+ ["empty array schema", { kind: { case: "arrayKind", value: {} } }, false],
+ ] as const)(
+ "recognizes sensitive data in %s",
+ (_name, objectSchema, expected) => {
+ const catalog = create(DatabaseCatalogSchema, {
+ schemas: [
+ { tables: [{ kind: { case: "objectSchema", value: objectSchema } }] },
+ ],
+ });
+ expect(catalogHasMarkedSensitiveData(catalog)).toBe(expected);
+ },
+ );
+
+ test("loads existing sensitive-data completion for its target database", async () => {
+ mockDiscoveredDatabase();
+ mocks.getOrFetchDatabaseCatalog.mockResolvedValue(
+ catalogWithColumn({ semanticType: "bb.default" })
+ );
+
+ const { result } = renderGuideContext({
+ enabled: true,
+ dismissed: false,
+ route: home,
+ scenarioId: "mark-sensitive-data",
+ });
+
+ await waitFor(() => expect(result.current.contextReady).toBe(true));
+
+ expect(mocks.getOrFetchDatabaseCatalog).toHaveBeenCalledWith({
+ database: "instances/sample/databases/employee",
+ silent: true,
+ });
+ expect(result.current.context.hasMarkedSensitiveData).toBe(true);
+ });
+
+ test.each([
+ [undefined, "instances/other/databases/selected"],
+ ["instances/other", "instances/other/databases/selected"],
+ ["projects/app/instances/other", "projects/app/instances/other/databases/selected"],
+ ])("watches the opened database under %s instead of the discovered target", async (parent, database) => {
+ mockDiscoveredDatabase();
+ const props = {
+ enabled: true,
+ dismissed: false,
+ scenarioId: "mark-sensitive-data" as const,
+ route: {
+ name: PROJECT_V1_ROUTE_DATABASE_DETAIL,
+ params: { projectId: "app", instanceId: "other", databaseName: "selected" },
+ query: { parent },
+ },
+ };
+ mocks.databasesByName = { [database]: { name: database, project: "projects/app" } };
+ const { result, rerender } = renderGuideContext(props);
+ await waitFor(() => expect(result.current.contextReady).toBe(true));
+ expect(result.current.context.databaseName).toBe(database);
+ expect(result.current.context.hasMarkedSensitiveData).toBe(false);
+ mocks.catalogsByName = {
+ [`${database}/catalog`]: catalogWithColumn({ semanticType: "bb.default" }),
+ };
+ rerender(props);
+ await waitFor(() => expect(result.current.context.hasMarkedSensitiveData).toBe(true));
+ expect(mocks.saveIntroStateByKey).toHaveBeenCalledWith({
+ key: GUIDE_PROGRESS_KEYS.sensitiveDataMarked,
+ newState: true,
+ });
+ });
+
+ test.each([
+ home,
+ {
+ name: PROJECT_V1_ROUTE_DATABASE_DETAIL,
+ params: { projectId: "app", instanceId: "redis", databaseName: "0" },
+ },
+ ])("requires a non-Redis target before enabling the masking step on %j", async (route) => {
+ mockDiscoveredDatabase();
+ mocks.introState[GUIDE_PROGRESS_KEYS.databaseExplored] = true;
+ mocks.databasesByName = {
+ "instances/redis/databases/0": {
+ name: "instances/redis/databases/0",
+ project: "projects/app",
+ instanceResource: { engine: Engine.REDIS },
+ },
+ };
+ mocks.fetchDatabases.mockImplementation(async (request) => ({
+ databases: request.filter.excludeEngines?.includes(Engine.REDIS)
+ ? []
+ : [{ name: "instances/redis/databases/0", project: "projects/app" }],
+ nextPageToken: "",
+ }));
+ const { result } = renderGuideContext({
+ enabled: true,
+ dismissed: false,
+ route,
+ scenarioId: "mark-sensitive-data",
+ });
+ await waitFor(() => expect(result.current.contextReady).toBe(true));
+ expect(mocks.fetchDatabases).toHaveBeenCalledWith(expect.objectContaining({
+ filter: { project: "projects/app", excludeEngines: [Engine.REDIS] },
+ }));
+ const guide = resolveGuide({
+ journey: getGuideJourney("mark-sensitive-data"),
+ definitions: GUIDE_STEP_DEFINITIONS,
+ context: result.current.context,
+ });
+ expect(guide.steps.find((step) => step.definition.id === "mark-sensitive-data")?.blocked).toBe(true);
+ });
+
+ test("reacts when the target catalog marks a sensitive column", async () => {
+ mockDiscoveredDatabase();
+
+ const props = {
+ enabled: true,
+ dismissed: false,
+ route: home,
+ scenarioId: "mark-sensitive-data" as const,
+ };
+ const { result, rerender } = renderGuideContext(props);
+
+ await waitFor(() => expect(result.current.contextReady).toBe(true));
+ expect(result.current.context.hasMarkedSensitiveData).toBe(false);
+
+ mocks.catalogsByName = {
+ "instances/sample/databases/employee/catalog": catalogWithColumn({
+ semanticType: "bb.default",
+ }),
+ };
+ rerender(props);
+
+ await waitFor(() =>
+ expect(result.current.context.hasMarkedSensitiveData).toBe(true)
+ );
+ expect(mocks.saveIntroStateByKey).toHaveBeenCalledWith({
+ key: "workspace-setup-guide.sensitive-data-marked",
+ newState: true,
+ });
+ });
+
test("separates discovered resources from learning evidence", async () => {
mocks.fetchProjectList.mockResolvedValue({
projects: [{ name: "projects/app" }],
diff --git a/frontend/src/modules/workspace-setup-guide/useGuideContext.ts b/frontend/src/modules/workspace-setup-guide/useGuideContext.ts
index 254527bb1d..5c30c86672 100644
--- a/frontend/src/modules/workspace-setup-guide/useGuideContext.ts
+++ b/frontend/src/modules/workspace-setup-guide/useGuideContext.ts
@@ -9,7 +9,13 @@ import { useIntroStateByKey } from "@/hooks/useAppState";
import { planEvents } from "@/lib/plan/events";
import { sqlEditorEvents } from "@/modules/sql-editor/model/events";
import { useAppStore } from "@/stores/app";
-import { State } from "@/types/proto-es/v1/common_pb";
+import { catalogResourceName } from "@/stores/app/databaseCatalog";
+import { Engine, State } from "@/types/proto-es/v1/common_pb";
+import type {
+ DatabaseCatalog,
+ ObjectSchema,
+} from "@/types/proto-es/v1/database_catalog_service_pb";
+import { getDatabaseEngine } from "@/utils/v1/database";
import { convertMemberToFullname } from "@/utils/v1/iam";
import { extractProjectResourceName } from "@/utils/v1/project";
import { GUIDE_PROGRESS_KEYS } from "./progress";
@@ -31,6 +37,7 @@ const INITIAL_FACTS: GuideFacts = {
hasExploredDatabase: false,
hasRunStatement: false,
hasCreatedChangeIssue: false,
+ hasMarkedSensitiveData: false,
hasOtherHumanUser: false,
projectName: "",
instanceName: "",
@@ -38,6 +45,35 @@ const INITIAL_FACTS: GuideFacts = {
databaseName: "",
};
+const objectSchemaHasSemanticType = (
+ schema: ObjectSchema | undefined
+): boolean => {
+ if (!schema) return false;
+ if (schema.semanticType) return true;
+ if (schema.kind.case === "structKind") {
+ return Object.values(schema.kind.value.properties).some(
+ objectSchemaHasSemanticType
+ );
+ }
+ if (schema.kind.case === "arrayKind") {
+ return objectSchemaHasSemanticType(schema.kind.value.kind);
+ }
+ return false;
+};
+
+export const catalogHasMarkedSensitiveData = (
+ catalog: Pick<DatabaseCatalog, "schemas"> | undefined
+) =>
+ catalog?.schemas.some((schema) =>
+ schema.tables.some(
+ (table) =>
+ (table.kind?.case === "columns" &&
+ table.kind.value.columns.some((column) => !!column.semanticType)) ||
+ (table.kind?.case === "objectSchema" &&
+ objectSchemaHasSemanticType(table.kind.value))
+ )
+ ) ?? false;
+
export const hasOtherHumanWorkspaceMember = (
policy:
| {
@@ -101,6 +137,19 @@ const isPopulatedProjectDatabaseRoute = (
!!databaseName &&
params.projectId === extractProjectResourceName(databaseProjectName);
+const databaseNameFromRoute = (route: GuideRoute) => {
+ const params = route.params ?? {};
+ if (
+ (route.name !== PROJECT_V1_ROUTE_DATABASE_DETAIL &&
+ route.name !== INSTANCE_ROUTE_DATABASE_DETAIL) ||
+ !hasRouteParams(params, ["instanceId", "databaseName"])
+ ) {
+ return undefined;
+ }
+ const parent = route.query?.parent;
+ return `${typeof parent === "string" ? parent : `instances/${params.instanceId}`}/databases/${params.databaseName}`;
+};
+
export const useGuideContext = ({
enabled,
dismissed,
@@ -121,6 +170,9 @@ export const useGuideContext = ({
const changeIssueCreated = useIntroStateByKey(
GUIDE_PROGRESS_KEYS.changeIssueCreated
);
+ const sensitiveDataMarked = useIntroStateByKey(
+ GUIDE_PROGRESS_KEYS.sensitiveDataMarked
+ );
const serverInfo = useAppStore((state) => state.serverInfo);
const defaultProject = serverInfo?.defaultProject ?? "";
const projectCacheSize = useAppStore(
@@ -147,6 +199,30 @@ export const useGuideContext = ({
);
const [facts, setFacts] = useState<GuideFacts>(INITIAL_FACTS);
const [contextReady, setContextReady] = useState(false);
+ const routeDatabaseName =
+ scenarioId === "mark-sensitive-data"
+ ? databaseNameFromRoute(route)
+ : undefined;
+ const routeDatabase = useAppStore((state) =>
+ routeDatabaseName ? state.databasesByName[routeDatabaseName] : undefined
+ );
+ const useRouteDatabase =
+ !!routeDatabase && getDatabaseEngine(routeDatabase) !== Engine.REDIS;
+ const databaseName = useRouteDatabase
+ ? routeDatabase.name
+ : facts.databaseName;
+ const databaseProjectName = useRouteDatabase
+ ? routeDatabase.project
+ : facts.databaseProjectName;
+ const targetCatalog = useAppStore((state) =>
+ databaseName
+ ? state.catalogsByName[catalogResourceName(databaseName)]
+ : undefined
+ );
+ const hasMarkedSensitiveData =
+ sensitiveDataMarked ||
+ facts.hasMarkedSensitiveData ||
+ catalogHasMarkedSensitiveData(targetCatalog);
const eventTargetRef = useRef<
{ projectName: string; databaseName: string } | undefined
>(undefined);
@@ -168,6 +244,18 @@ export const useGuideContext = ({
record(GUIDE_PROGRESS_KEYS.teammateAdded);
}, [dismissed, enabled, hasOtherWorkspaceMember, workspaceUsage]);
+ useEffect(() => {
+ if (
+ !enabled ||
+ dismissed ||
+ scenarioId !== "mark-sensitive-data" ||
+ !hasMarkedSensitiveData
+ ) {
+ return;
+ }
+ record(GUIDE_PROGRESS_KEYS.sensitiveDataMarked);
+ }, [dismissed, enabled, hasMarkedSensitiveData, scenarioId]);
+
useEffect(() => {
if (!enabled || dismissed) return;
const offStatement = sqlEditorEvents.on(
@@ -264,7 +352,12 @@ export const useGuideContext = ({
? store.fetchDatabases({
parent: workspaceResourceName,
pageSize: 1,
- filter: { project: project.name },
+ filter: {
+ project: project.name,
+ ...(scenarioId === "mark-sensitive-data"
+ ? { excludeEngines: [Engine.REDIS] }
+ : {}),
+ },
silent: true,
})
: Promise.resolve(undefined),
@@ -282,6 +375,15 @@ export const useGuideContext = ({
const database = databases?.databases.find(
({ name, project }) => !!name && !!project
);
+ const catalog =
+ scenarioId === "mark-sensitive-data" && database
+ ? await store
+ .getOrFetchDatabaseCatalog({
+ database: database.name,
+ silent: true,
+ })
+ .catch(() => undefined)
+ : undefined;
const eventTarget = eventTargetRef.current;
setFacts((state) => ({
@@ -292,6 +394,9 @@ export const useGuideContext = ({
hasRunStatement: statementRun || state.hasRunStatement,
hasCreatedChangeIssue:
changeIssueCreated || state.hasCreatedChangeIssue,
+ hasMarkedSensitiveData:
+ catalogHasMarkedSensitiveData(catalog) ||
+ state.hasMarkedSensitiveData,
hasOtherHumanUser: users.users.some(
({ name }) => !!name && name !== currentUserName
),
@@ -322,6 +427,7 @@ export const useGuideContext = ({
instanceCacheSize,
isSaaS,
projectCacheSize,
+ scenarioId,
statementRun,
currentUserName,
userCacheSize,
@@ -330,8 +436,24 @@ export const useGuideContext = ({
]);
const context = useMemo(
- () => ({ ...facts, isSaaS, hasOtherWorkspaceMember, route }),
- [facts, hasOtherWorkspaceMember, isSaaS, route]
+ () => ({
+ ...facts,
+ databaseName,
+ databaseProjectName,
+ hasMarkedSensitiveData,
+ isSaaS,
+ hasOtherWorkspaceMember,
+ route,
+ }),
+ [
+ facts,
+ databaseName,
+ databaseProjectName,
+ hasMarkedSensitiveData,
+ hasOtherWorkspaceMember,
+ isSaaS,
+ route,
+ ]
);
return { context, contextReady };
};
diff --git a/frontend/src/routes/auth/WorkspaceSetupPage.test.tsx b/frontend/src/routes/auth/WorkspaceSetupPage.test.tsx
index 5943d57e5c..5ec5ad055d 100644
--- a/frontend/src/routes/auth/WorkspaceSetupPage.test.tsx
+++ b/frontend/src/routes/auth/WorkspaceSetupPage.test.tsx
@@ -190,6 +190,10 @@ vi.mock("react-i18next", () => ({
"Query data",
"settings.profile.setup-scenario.query-data.description":
"Open SQL Editor and run a statement.",
+ "settings.profile.setup-scenario.mark-sensitive-data.title":
+ "Mark sensitive data",
+ "settings.profile.setup-scenario.mark-sensitive-data.description":
+ "Identify sensitive columns and apply masking.",
"settings.profile.setup-scenario.workspace-usage.title":
"Who will use Bytebase with you?",
"settings.profile.setup-scenario.workspace-usage.team.title":
@@ -211,6 +215,8 @@ vi.mock("react-i18next", () => ({
"Enable sample databases to start querying immediately",
"settings.profile.enable-sample-databases-create-change":
"Enable sample databases as a safe change target",
+ "settings.profile.enable-sample-databases-mark-sensitive-data":
+ "Enable sample databases to try data masking immediately",
"settings.profile.setup-submit": "Setup my workspace",
"instance.prepare-sample-instance-failed":
"Failed to prepare Sample Project Instance.",
@@ -390,8 +396,9 @@ describe("WorkspaceSetupPage", () => {
expect(page.container.textContent).toContain(
"What would you like to do with Bytebase?"
);
- expect(page.container.querySelectorAll("[role='radio']")).toHaveLength(4);
+ expect(page.container.querySelectorAll("[role='radio']")).toHaveLength(5);
expect(page.container.textContent).toContain("Create a database change");
+ expect(page.container.textContent).toContain("Mark sensitive data");
expect(page.container.textContent).toContain("Who will use Bytebase with you?");
expect(page.container.textContent).toContain("My team");
expect(page.container.textContent).toContain("Just me");
diff --git a/frontend/src/routes/auth/WorkspaceSetupPage.tsx b/frontend/src/routes/auth/WorkspaceSetupPage.tsx
index a27a5d2e7a..6266f8051a 100644
--- a/frontend/src/routes/auth/WorkspaceSetupPage.tsx
+++ b/frontend/src/routes/auth/WorkspaceSetupPage.tsx
@@ -417,7 +417,9 @@ export function WorkspaceSetupPage() {
? "settings.profile.enable-sample-databases-query-data"
: selectedScenarioId === "create-database-change"
? "settings.profile.enable-sample-databases-create-change"
- : "settings.profile.enable-sample-databases"
+ : selectedScenarioId === "mark-sensitive-data"
+ ? "settings.profile.enable-sample-databases-mark-sensitive-data"
+ : "settings.profile.enable-sample-databases"
)}
</label>
</div>
diff --git a/frontend/src/routes/auth/WorkspaceSetupQuestionnaireStep.test.tsx b/frontend/src/routes/auth/WorkspaceSetupQuestionnaireStep.test.tsx
index 350dd638c9..c972de07e2 100644
--- a/frontend/src/routes/auth/WorkspaceSetupQuestionnaireStep.test.tsx
+++ b/frontend/src/routes/auth/WorkspaceSetupQuestionnaireStep.test.tsx
@@ -28,6 +28,10 @@ vi.mock("react-i18next", () => ({
"settings.profile.setup-scenario.query-data.title": "Query data",
"settings.profile.setup-scenario.query-data.description":
"Open SQL Editor and run a statement.",
+ "settings.profile.setup-scenario.mark-sensitive-data.title":
+ "Mark sensitive data",
+ "settings.profile.setup-scenario.mark-sensitive-data.description":
+ "Identify sensitive columns and apply masking.",
"settings.profile.setup-scenario.workspace-usage.title":
"Who will use Bytebase with you?",
"settings.profile.setup-scenario.workspace-usage.team.title":
@@ -87,7 +91,7 @@ describe("WorkspaceSetupQuestionnaireStep", () => {
const radios = [...page.container.querySelectorAll("[role='radio']")];
const buttons = [...page.container.querySelectorAll("button")];
- expect(radios).toHaveLength(4);
+ expect(radios).toHaveLength(5);
expect(radios.every((radio) => radio.getAttribute("aria-checked") === "false"))
.toBe(true);
expect(buttons).toHaveLength(1);
@@ -97,6 +101,7 @@ describe("WorkspaceSetupQuestionnaireStep", () => {
expect(page.container.querySelector("h1")).toHaveTextContent(
"What would you like to do with Bytebase?"
);
+ expect(page.container.textContent).toContain("Mark sensitive data");
expect(page.container.textContent).not.toContain(
"Tell us about your setup"
);
diff --git a/frontend/src/routes/auth/WorkspaceSetupQuestionnaireStep.tsx b/frontend/src/routes/auth/WorkspaceSetupQuestionnaireStep.tsx
index 8154169961..d8d3f59048 100644
--- a/frontend/src/routes/auth/WorkspaceSetupQuestionnaireStep.tsx
+++ b/frontend/src/routes/auth/WorkspaceSetupQuestionnaireStep.tsx
@@ -35,6 +35,12 @@ const SCENARIO_OPTIONS: Array<{
titleKey: "settings.profile.setup-scenario.query-data.title",
descriptionKey: "settings.profile.setup-scenario.query-data.description",
},
+ {
+ id: "mark-sensitive-data",
+ titleKey: "settings.profile.setup-scenario.mark-sensitive-data.title",
+ descriptionKey:
+ "settings.profile.setup-scenario.mark-sensitive-data.description",
+ },
];
const WORKSPACE_USAGE_OPTIONS: Array<{
diff --git a/frontend/src/routes/project/ProjectDatabaseDetailPage.test.tsx b/frontend/src/routes/project/ProjectDatabaseDetailPage.test.tsx
index 7015514a26..870d1a549a 100644
--- a/frontend/src/routes/project/ProjectDatabaseDetailPage.test.tsx
+++ b/frontend/src/routes/project/ProjectDatabaseDetailPage.test.tsx
@@ -2,6 +2,11 @@ import type { ReactNode } from "react";
import { act, createElement } from "react";
import { createRoot } from "react-dom/client";
import { beforeEach, describe, expect, test, vi } from "vitest";
+import {
+ MARK_SENSITIVE_DATA_PRODUCT_INTRO,
+ PRODUCT_INTRO_QUERY_KEY,
+} from "@/lib/productIntro";
+import { Engine } from "@/types/proto-es/v1/common_pb";
import {
PROJECT_DATABASE_DETAIL_TAB_OVERVIEW,
PROJECT_DATABASE_DETAIL_TAB_REVISION,
@@ -453,6 +458,62 @@ beforeEach(() => {
});
describe("ProjectDatabaseDetailPage", () => {
+ test.each([
+ [Engine.MONGODB, true, "overview"],
+ [Engine.COSMOSDB, true, "overview"],
+ [Engine.ELASTICSEARCH, true, "overview"],
+ [Engine.POSTGRES, true, "catalog"],
+ [Engine.MONGODB, false, "catalog"],
+ ])(
+ "opens the supported masking tab for engine %s with intro %s",
+ (engine, intro, tab) => {
+ mocks.useProjectDatabaseDetail.mockReturnValue({
+ database: {
+ name: "instances/inst1/databases/db1",
+ project: "projects/proj1",
+ effectiveEnvironment: "environments/prod",
+ instanceResource: { name: "instances/inst1", engine },
+ },
+ ready: true,
+ isDefaultProject: false,
+ });
+ const { container, render, unmount } = renderIntoContainer(
+ createElement(ProjectDatabaseDetailPage, {
+ projectId: "proj1",
+ instanceId: "inst1",
+ databaseName: "db1",
+ routeHash: "#catalog",
+ routeQuery: intro
+ ? {
+ [PRODUCT_INTRO_QUERY_KEY]: MARK_SENSITIVE_DATA_PRODUCT_INTRO,
+ foo: "bar",
+ }
+ : {},
+ }),
+ );
+ render();
+ expect(
+ container
+ .querySelector('[data-testid="tabs"]')
+ ?.getAttribute("data-value"),
+ ).toBe(tab);
+ if (tab === "overview") {
+ expect(mocks.routerReplace).toHaveBeenCalledWith(
+ expect.objectContaining({
+ hash: "#overview",
+ query: {
+ [PRODUCT_INTRO_QUERY_KEY]: MARK_SENSITIVE_DATA_PRODUCT_INTRO,
+ foo: "bar",
+ parent: "instances/inst1",
+ },
+ }),
+ );
+ } else {
+ expect(mocks.routerReplace).not.toHaveBeenCalled();
+ }
+ unmount();
+ },
+ );
test("shows project binding attention for a project instance database", async () => {
mocks.useProjectDatabaseDetail.mockReturnValue({
database: {
diff --git a/frontend/src/routes/project/ProjectDatabaseDetailPage.tsx b/frontend/src/routes/project/ProjectDatabaseDetailPage.tsx
index da203f3c39..ec5b59cd8b 100644
--- a/frontend/src/routes/project/ProjectDatabaseDetailPage.tsx
+++ b/frontend/src/routes/project/ProjectDatabaseDetailPage.tsx
@@ -10,6 +10,10 @@ import { SampleExpirationAlert } from "@/components/SampleExpirationAlert";
import { Alert } from "@/components/ui/alert";
import { Button } from "@/components/ui/button";
import { Tabs, TabsList, TabsTrigger } from "@/components/ui/tabs";
+import {
+ MARK_SENSITIVE_DATA_PRODUCT_INTRO,
+ PRODUCT_INTRO_QUERY_KEY,
+} from "@/lib/productIntro";
import { pushNotification } from "@/stores";
import { useAppStore } from "@/stores/app";
import {
@@ -17,7 +21,12 @@ import {
DatabaseSchema$,
UpdateDatabaseRequestSchema,
} from "@/types/proto-es/v1/database_service_pb";
-import { autoDatabaseRoute, getDatabaseProject } from "@/utils";
+import {
+ autoDatabaseRoute,
+ getDatabaseEngine,
+ getDatabaseProject,
+ instanceV1MaskingForNoSQL,
+} from "@/utils";
import { isProjectInstanceDatabase } from "@/utils/v1/database";
import { DatabaseDetailActions } from "./database-detail/DatabaseDetailActions";
import { DatabaseDetailHeader } from "./database-detail/DatabaseDetailHeader";
@@ -91,8 +100,18 @@ export function ProjectDatabaseDetailPage({
);
useEffect(() => {
- setSelectedTab(parseProjectDatabaseDetailTabHash(hash));
- }, [hash]);
+ const tab = parseProjectDatabaseDetailTabHash(hash);
+ if (
+ detail.ready &&
+ tab === PROJECT_DATABASE_DETAIL_TAB_CATALOG &&
+ query?.[PRODUCT_INTRO_QUERY_KEY] === MARK_SENSITIVE_DATA_PRODUCT_INTRO &&
+ instanceV1MaskingForNoSQL(getDatabaseEngine(detail.database))
+ ) {
+ handleTabChange(PROJECT_DATABASE_DETAIL_TAB_OVERVIEW);
+ return;
+ }
+ setSelectedTab(tab);
+ }, [detail.database, detail.ready, handleTabChange, hash, query]);
const handleSetEnvironment = useCallback(() => {
handleTabChange(PROJECT_DATABASE_DETAIL_TAB_SETTING);
diff --git a/frontend/src/routes/project/ProjectDatabasesPage.test.tsx b/frontend/src/routes/project/ProjectDatabasesPage.test.tsx
index cbae28efbe..aa15c880eb 100644
--- a/frontend/src/routes/project/ProjectDatabasesPage.test.tsx
+++ b/frontend/src/routes/project/ProjectDatabasesPage.test.tsx
@@ -2,13 +2,14 @@ import { act } from "react";
import { createRoot } from "react-dom/client";
import { beforeEach, describe, expect, test, vi } from "vitest";
import { preCreateIssue } from "@/lib/plan/issue";
+import { Engine } from "@/types/proto-es/v1/common_pb";
(
globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }
).IS_REACT_ACT_ENVIRONMENT = true;
const mocks = vi.hoisted(() => ({
- visibleDatabases: [] as { name: string; project?: string }[],
+ visibleDatabases: [] as { name: string; project?: string; instanceResource?: { engine: number } }[],
databasesByName: {} as Record<string, { name: string }>,
instancesByName: {} as Record<string, { name: string; title: string }>,
routerCurrentName: "workspace.project.database",
@@ -20,6 +21,7 @@ const mocks = vi.hoisted(() => ({
scenarioId: undefined as
| "query-data"
| "create-database-change"
+ | "mark-sensitive-data"
| undefined,
removeDatabaseMetadataCache: vi.fn(),
fetchInstance: vi.fn(),
@@ -222,6 +224,7 @@ vi.mock("@/lib/plan/issue", () => ({
vi.mock("@/lib/productIntro", () => ({
CONNECT_DATABASE_PRODUCT_INTRO: "connect-database",
+ MARK_SENSITIVE_DATA_PRODUCT_INTRO: "mark-sensitive-data",
PROJECT_INSTANCE_SYNCED_PRODUCT_INTRO: "project-instance-synced",
PRODUCT_INTRO_QUERY_KEY: "intro",
useProductIntro: mocks.useProductIntro,
@@ -853,6 +856,99 @@ describe("ProjectDatabasesPage", () => {
});
});
+ test("only offers marking sensitive data for its scenario", async () => {
+ mocks.scenarioId = "mark-sensitive-data";
+ mocks.routerCurrentQuery = { intro: "project-instance-synced" };
+ mocks.visibleDatabases = [
+ {
+ name: "projects/demo/instances/prod/databases/app",
+ project: "projects/demo",
+ },
+ ];
+ const container = document.createElement("div");
+ const root = createRoot(container);
+
+ await act(async () => {
+ root.render(<ProjectDatabasesPage projectId="demo" />);
+ });
+
+ expect(container.textContent).toContain(
+ "db.project-instance-synced-mark-sensitive-data-title"
+ );
+ expect(container.textContent).toContain(
+ "db.project-instance-synced-mark-sensitive-data-description"
+ );
+ expect(container.textContent).toContain(
+ "db.project-instance-synced-mark-sensitive-data-action"
+ );
+ expect(container.textContent).not.toContain(
+ "db.project-instance-synced-sql-editor-action"
+ );
+ expect(container.textContent).not.toContain(
+ "db.project-instance-synced-action"
+ );
+
+ const markButton = Array.from(container.querySelectorAll("button")).find(
+ (button) =>
+ button.textContent?.includes(
+ "db.project-instance-synced-mark-sensitive-data-action"
+ )
+ ) as HTMLButtonElement;
+ await act(async () => {
+ markButton.click();
+ });
+
+ expect(mocks.routerPush).toHaveBeenCalledWith({
+ name: "workspace.project.database.detail",
+ params: {
+ projectId: "demo",
+ instanceId: "prod",
+ databaseName: "app",
+ },
+ query: {
+ parent: "projects/demo/instances/prod",
+ intro: "mark-sensitive-data",
+ },
+ hash: "#catalog",
+ });
+
+ act(() => {
+ root.unmount();
+ });
+ });
+
+ test.each([false, true])("excludes Redis from the masking action (supported target: %s)", async (hasSupportedTarget) => {
+ mocks.scenarioId = "mark-sensitive-data";
+ mocks.routerCurrentQuery = { intro: "project-instance-synced" };
+ mocks.visibleDatabases = [{
+ name: "projects/demo/instances/redis/databases/0",
+ project: "projects/demo",
+ instanceResource: { engine: Engine.REDIS },
+ }];
+ if (hasSupportedTarget) mocks.visibleDatabases.push({
+ name: "projects/demo/instances/prod/databases/app",
+ project: "projects/demo",
+ instanceResource: { engine: Engine.POSTGRES },
+ });
+ const container = document.createElement("div");
+ const root = createRoot(container);
+ await act(async () => root.render(<ProjectDatabasesPage projectId="demo" />));
+ const button = Array.from(container.querySelectorAll("button")).find(
+ (button) => button.textContent?.includes("db.project-instance-synced-mark-sensitive-data-action")
+ );
+ expect(button).toBeDefined();
+ expect(button?.disabled).toBe(!hasSupportedTarget);
+ await act(async () => button?.click());
+ if (hasSupportedTarget) {
+ expect(mocks.routerPush).toHaveBeenCalledWith(expect.objectContaining({
+ params: { projectId: "demo", instanceId: "prod", databaseName: "app" },
+ }));
+ } else {
+ expect(mocks.routerPush).not.toHaveBeenCalled();
+ }
+ act(() => root.unmount());
+ });
+
test("shows database next actions when requested by the setup guide", async () => {
mocks.routerCurrentQuery = { intro: "project-instance-synced" };
mocks.visibleDatabases = [
diff --git a/frontend/src/routes/project/ProjectDatabasesPage.tsx b/frontend/src/routes/project/ProjectDatabasesPage.tsx
index c98ad6a13b..83e0212fc6 100644
--- a/frontend/src/routes/project/ProjectDatabasesPage.tsx
+++ b/frontend/src/routes/project/ProjectDatabasesPage.tsx
@@ -46,6 +46,7 @@ import type { DatabaseFilter } from "@/lib/databaseFilter";
import { preCreateIssue } from "@/lib/plan/issue";
import {
CONNECT_DATABASE_PRODUCT_INTRO,
+ MARK_SENSITIVE_DATA_PRODUCT_INTRO,
PRODUCT_INTRO_QUERY_KEY,
PROJECT_INSTANCE_SYNCED_PRODUCT_INTRO,
useProductIntro,
@@ -74,6 +75,7 @@ import {
} from "@/types/proto-es/v1/database_service_pb";
import { unknownDatabase } from "@/types/v1/database";
import {
+ autoDatabaseRoute,
engineNameV1,
extractInstanceResourceName,
getDefaultPagination,
@@ -82,6 +84,7 @@ import {
PERMISSIONS_FOR_DATABASE_CREATE_ISSUE,
supportedEngineV1List,
} from "@/utils";
+import { getDatabaseEngine } from "@/utils/v1/database";
import { extractProjectResourceName } from "@/utils/v1/project";
const fetchAvailableInstanceCount = async (
@@ -561,6 +564,7 @@ export function ProjectDatabasesPage({ projectId }: { projectId: string }) {
),
showCreateChange: true,
showSqlEditor: false,
+ showMarkSensitiveData: false,
}
: selectedGuideScenarioId === "query-data"
? {
@@ -568,13 +572,25 @@ export function ProjectDatabasesPage({ projectId }: { projectId: string }) {
description: t("db.project-instance-synced-query-data-description"),
showCreateChange: false,
showSqlEditor: true,
+ showMarkSensitiveData: false,
}
- : {
- title: t("db.project-instance-synced-title"),
- description: t("db.project-instance-synced-description"),
- showCreateChange: true,
- showSqlEditor: true,
- };
+ : selectedGuideScenarioId === "mark-sensitive-data"
+ ? {
+ title: t("db.project-instance-synced-mark-sensitive-data-title"),
+ description: t(
+ "db.project-instance-synced-mark-sensitive-data-description"
+ ),
+ showCreateChange: false,
+ showSqlEditor: false,
+ showMarkSensitiveData: true,
+ }
+ : {
+ title: t("db.project-instance-synced-title"),
+ description: t("db.project-instance-synced-description"),
+ showCreateChange: true,
+ showSqlEditor: true,
+ showMarkSensitiveData: false,
+ };
const checkingAvailableInstance =
!hasVisibleDatabase &&
!showSyncingInstanceHint &&
@@ -611,6 +627,22 @@ export function ProjectDatabasesPage({ projectId }: { projectId: string }) {
);
}, [projectName]);
+ const maskingDatabase = visibleDatabases.find(
+ (database) => getDatabaseEngine(database) !== Engine.REDIS
+ );
+ const handleMarkSensitiveData = useCallback(() => {
+ if (!maskingDatabase) return;
+ const target = autoDatabaseRoute(maskingDatabase);
+ void router.push({
+ ...target,
+ query: {
+ ...target.query,
+ [PRODUCT_INTRO_QUERY_KEY]: MARK_SENSITIVE_DATA_PRODUCT_INTRO,
+ },
+ hash: "#catalog",
+ });
+ }, [maskingDatabase]);
+
useProductIntro({
id: CONNECT_DATABASE_PRODUCT_INTRO,
title: t("project.connect-instance-intro-title"),
@@ -776,6 +808,15 @@ export function ProjectDatabasesPage({ projectId }: { projectId: string }) {
</span>
</PermissionGuard>
)}
+ {databaseNextAction.showMarkSensitiveData && (
+ <Button
+ size="sm"
+ disabled={!maskingDatabase}
+ onClick={handleMarkSensitiveData}
+ >
+ {t("db.project-instance-synced-mark-sensitive-data-action")}
+ </Button>
+ )}
</div>
</div>
}
diff --git a/frontend/src/routes/project/database-detail/catalog/MarkSensitiveDataSheet.test.tsx b/frontend/src/routes/project/database-detail/catalog/MarkSensitiveDataSheet.test.tsx
new file mode 100644
index 0000000000..2bc7a318e8
--- /dev/null
+++ b/frontend/src/routes/project/database-detail/catalog/MarkSensitiveDataSheet.test.tsx
@@ -0,0 +1,148 @@
+import { create } from "@bufbuild/protobuf";
+import { cleanup, fireEvent, render, screen } from "@testing-library/react";
+import { afterEach, beforeEach, expect, test, vi } from "vitest";
+import {
+ DatabaseMetadataSchema,
+ DatabaseSchema$,
+} from "@/types/proto-es/v1/database_service_pb";
+import { MarkSensitiveDataSheet } from "./MarkSensitiveDataSheet";
+
+const mocks = vi.hoisted(() => ({
+ metadata: { schemas: [] } as unknown,
+ updateColumnCatalog: vi.fn(async () => {}),
+}));
+
+vi.mock("react-i18next", () => ({
+ useTranslation: () => ({ t: (key: string) => key }),
+}));
+
+vi.mock("@/hooks/useAppDatabaseMetadata", () => ({
+ useAppDatabaseMetadata: () => mocks.metadata,
+}));
+
+vi.mock("@/lib/column-data-table/utils", () => ({
+ updateColumnCatalog: mocks.updateColumnCatalog,
+}));
+
+const props = {
+ database: create(DatabaseSchema$, {
+ name: "instances/instance/databases/database",
+ }),
+ open: true,
+ semanticTypeList: [],
+ onOpenChange: vi.fn(),
+};
+
+beforeEach(() => {
+ vi.clearAllMocks();
+ mocks.metadata = create(DatabaseMetadataSchema, {
+ schemas: [{ name: "public" }, { name: "private" }],
+ });
+});
+
+afterEach(cleanup);
+
+async function selectOption(label: string, name: string) {
+ fireEvent.click(screen.getByLabelText(label));
+ const option = await screen.findByRole("option", { name });
+ fireEvent.pointerDown(option, { pointerType: "mouse" });
+ fireEvent.click(option);
+}
+
+test("applies the semantic type to multiple selected columns in one save", async () => {
+ mocks.metadata = create(DatabaseMetadataSchema, {
+ schemas: [
+ {
+ name: "public",
+ tables: [
+ {
+ name: "customers",
+ columns: [{ name: "email" }, { name: "phone" }],
+ },
+ ],
+ },
+ ],
+ });
+ render(<MarkSensitiveDataSheet {...props} />);
+ await selectOption("common.table", "customers");
+ await selectOption("common.column", "email");
+ const phone = await screen.findByRole("option", { name: "phone" });
+ fireEvent.pointerDown(phone, { pointerType: "mouse" });
+ fireEvent.click(phone);
+ expect(screen.getByRole("option", { name: "email" })).toHaveAttribute(
+ "aria-selected",
+ "true"
+ );
+ expect(phone).toHaveAttribute("aria-selected", "true");
+ fireEvent.keyDown(phone, { key: "Escape" });
+ fireEvent.click(screen.getByRole("button", { name: "common.save" }));
+ expect(mocks.updateColumnCatalog).toHaveBeenCalledExactlyOnceWith({
+ database: props.database.name,
+ schema: "public",
+ table: "customers",
+ column: ["email", "phone"],
+ columnCatalog: { semanticType: "bb.default" },
+ notification: "common.updated",
+ });
+});
+
+test("clears selected columns when switching tables", async () => {
+ mocks.metadata = create(DatabaseMetadataSchema, {
+ schemas: [
+ {
+ name: "public",
+ tables: [
+ { name: "customers", columns: [{ name: "email" }] },
+ { name: "orders", columns: [{ name: "id" }] },
+ ],
+ },
+ ],
+ });
+ render(<MarkSensitiveDataSheet {...props} />);
+ await selectOption("common.table", "customers");
+ await selectOption("common.column", "email");
+ fireEvent.keyDown(screen.getByLabelText("common.column"), { key: "Escape" });
+ await selectOption("common.table", "orders");
+ expect(screen.getByLabelText("common.column").textContent).toBe(
+ "common.select"
+ );
+ expect(screen.getByRole("button", { name: "common.save" })).toBeDisabled();
+});
+
+test("defaults to the first schema without selecting a table or column", () => {
+ render(<MarkSensitiveDataSheet {...props} />);
+
+ expect(screen.getByLabelText("common.schema").textContent).toBe("public");
+ expect(screen.getByLabelText("common.table").hasAttribute("disabled")).toBe(
+ false
+ );
+ expect(screen.getByLabelText("common.table").textContent).toBe("common.select");
+ expect(screen.getByLabelText("common.column")).toHaveAttribute(
+ "aria-disabled", "true"
+ );
+});
+
+test("defaults when metadata arrives and preserves a manual selection until reopened", async () => {
+ mocks.metadata = create(DatabaseMetadataSchema);
+ const view = render(<MarkSensitiveDataSheet {...props} />);
+ expect(screen.getByLabelText("common.table").hasAttribute("disabled")).toBe(
+ true
+ );
+
+ mocks.metadata = create(DatabaseMetadataSchema, {
+ schemas: [{ name: "public" }, { name: "private" }],
+ });
+ view.rerender(<MarkSensitiveDataSheet {...props} />);
+ expect(screen.getByLabelText("common.schema").textContent).toBe("public");
+
+ fireEvent.click(screen.getByLabelText("common.schema"));
+ const option = await screen.findByRole("option", { name: "private" });
+ fireEvent.pointerDown(option, { pointerType: "mouse" });
+ fireEvent.click(option);
+ view.rerender(<MarkSensitiveDataSheet {...props} />);
+ expect(screen.getByLabelText("common.schema").textContent).toBe("private");
+
+ view.rerender(<MarkSensitiveDataSheet {...props} open={false} />);
+ view.rerender(<MarkSensitiveDataSheet {...props} />);
+ expect(screen.getByLabelText("common.schema").textContent).toBe("public");
+});
diff --git a/frontend/src/routes/project/database-detail/catalog/MarkSensitiveDataSheet.tsx b/frontend/src/routes/project/database-detail/catalog/MarkSensitiveDataSheet.tsx
index 9d8e23fff3..b1169cad72 100644
--- a/frontend/src/routes/project/database-detail/catalog/MarkSensitiveDataSheet.tsx
+++ b/frontend/src/routes/project/database-detail/catalog/MarkSensitiveDataSheet.tsx
@@ -38,9 +38,9 @@ export function MarkSensitiveDataSheet({
}: MarkSensitiveDataSheetProps) {
const { t } = useTranslation();
const metadata = useAppDatabaseMetadata(database.name, { autoFetch: open });
- const [schemaIndex, setSchemaIndex] = useState("");
+ const [schemaIndex, setSchemaIndex] = useState("0");
const [tableIndex, setTableIndex] = useState("");
- const [columnName, setColumnName] = useState("");
+ const [columnNames, setColumnNames] = useState<string[]>([]);
const [semanticTypeId, setSemanticTypeId] = useState("bb.default");
const [saving, setSaving] = useState(false);
@@ -51,7 +51,7 @@ export function MarkSensitiveDataSheet({
const canSave =
!!selectedSchema &&
!!selectedTable &&
- !!columnName &&
+ columnNames.length > 0 &&
!!semanticTypeId &&
!saving;
@@ -59,9 +59,9 @@ export function MarkSensitiveDataSheet({
if (open) {
return;
}
- setSchemaIndex("");
+ setSchemaIndex("0");
setTableIndex("");
- setColumnName("");
+ setColumnNames([]);
setSemanticTypeId("bb.default");
setSaving(false);
}, [database.name, open]);
@@ -77,11 +77,11 @@ export function MarkSensitiveDataSheet({
database: database.name,
schema: selectedSchema.name,
table: selectedTable.name,
- column: columnName,
+ column: columnNames,
columnCatalog: {
semanticType: semanticTypeId,
},
- notification: "common.updated",
+ notification: t("common.updated"),
});
onOpenChange(false);
} finally {
@@ -111,7 +111,7 @@ export function MarkSensitiveDataSheet({
onValueChange={(value) => {
setSchemaIndex(value ?? "");
setTableIndex("");
- setColumnName("");
+ setColumnNames([]);
}}
>
<SelectTrigger
@@ -146,7 +146,7 @@ export function MarkSensitiveDataSheet({
disabled={!selectedSchema}
onValueChange={(value) => {
setTableIndex(value ?? "");
- setColumnName("");
+ setColumnNames([]);
}}
>
<SelectTrigger
@@ -171,16 +171,21 @@ export function MarkSensitiveDataSheet({
</FormField>
<FormField>
- <FormLabel htmlFor="mark-sensitive-data-column">
+ <FormLabel
+ id="mark-sensitive-data-column-label"
+ htmlFor="mark-sensitive-data-column"
+ >
{t("common.column")}
</FormLabel>
<Select
- value={columnName}
+ multiple
+ value={columnNames}
disabled={!selectedTable}
- onValueChange={(value) => setColumnName(value ?? "")}
+ onValueChange={setColumnNames}
>
<SelectTrigger
id="mark-sensitive-data-column"
+ aria-labelledby="mark-sensitive-data-column-label"
className="w-full"
>
<SelectValue placeholder={t("common.select")} />
diff --git a/frontend/src/routes/project/database-detail/overview/DatabaseObjectExplorer.test.tsx b/frontend/src/routes/project/database-detail/overview/DatabaseObjectExplorer.test.tsx
index 8fbc7082e7..72e832c77f 100644
--- a/frontend/src/routes/project/database-detail/overview/DatabaseObjectExplorer.test.tsx
+++ b/frontend/src/routes/project/database-detail/overview/DatabaseObjectExplorer.test.tsx
@@ -45,6 +45,7 @@ const mocks = vi.hoisted(() => {
bytesToString: vi.fn((size: number) => `${size} B`),
hasProjectPermissionV2: vi.fn(() => true),
sheetProps: [] as unknown[],
+ useProductIntro: vi.fn(),
useTranslation: vi.fn(() => ({
t: (key: string) => key,
})),
@@ -110,6 +111,11 @@ vi.mock("@/hooks/useDatabaseCatalog", () => ({
useDatabaseCatalog: () => mocks.useDatabaseCatalog(),
}));
+vi.mock("@/lib/productIntro", async (importOriginal) => ({
+ ...(await importOriginal<typeof import("@/lib/productIntro")>()),
+ useProductIntro: mocks.useProductIntro,
+}));
+
vi.mock("@/stores/app/databaseCatalog", () => ({
getColumnCatalog: mocks.getColumnCatalog,
getTableCatalog: mocks.getTableCatalog,
@@ -221,6 +227,7 @@ const makeTable = (name: string) =>
}) as never;
beforeEach(async () => {
+ mocks.useProductIntro.mockClear();
mocks.currentRoute.value.query = {};
mocks.routerReplace.mockReset();
mocks.useTranslation.mockReset();
@@ -295,6 +302,44 @@ beforeEach(async () => {
});
describe("DatabaseObjectExplorer", () => {
+ test.each([
+ [Engine.MONGODB, true, false],
+ [Engine.COSMOSDB, true, false],
+ [Engine.ELASTICSEARCH, true, false],
+ [Engine.POSTGRES, true, true],
+ [Engine.MONGODB, false, true],
+ ])(
+ "offers the NoSQL masking intro for engine %s with update permission %s",
+ (engine, permission, disabled) => {
+ mocks.getDatabaseEngine.mockReturnValue(engine);
+ mocks.hasProjectPermissionV2.mockReturnValue(permission);
+ const { container, render, unmount } = renderIntoContainer(
+ createElement(DatabaseObjectExplorer, {
+ database: makeDatabase(),
+ loading: false,
+ selectedSchemaName: "public",
+ tableSearchKeyword: "",
+ externalTableSearchKeyword: "",
+ onSelectedSchemaNameChange: vi.fn(),
+ onTableSearchKeywordChange: vi.fn(),
+ onExternalTableSearchKeywordChange: vi.fn(),
+ }),
+ );
+ render();
+ expect(mocks.useProductIntro).toHaveBeenCalledWith(
+ expect.objectContaining({
+ id: "mark-sensitive-data",
+ disabled,
+ }),
+ );
+ expect(
+ container.querySelector(
+ '[data-product-intro-target="mark-sensitive-data"]',
+ ),
+ ).not.toBeNull();
+ unmount();
+ },
+ );
test("renders the default schema label when the schema name is empty", async () => {
mocks.dbSchemaStore.mockReturnValue({
getSchemaList: vi.fn(() => [{ name: "" }]),
diff --git a/frontend/src/routes/project/database-detail/overview/DatabaseObjectExplorer.tsx b/frontend/src/routes/project/database-detail/overview/DatabaseObjectExplorer.tsx
index f0ad32263f..088e5030f9 100644
--- a/frontend/src/routes/project/database-detail/overview/DatabaseObjectExplorer.tsx
+++ b/frontend/src/routes/project/database-detail/overview/DatabaseObjectExplorer.tsx
@@ -11,6 +11,10 @@ import {
} from "@/components/ui/select";
import { useAppDatabaseMetadata } from "@/hooks/useAppDatabaseMetadata";
import { useDatabaseCatalog } from "@/hooks/useDatabaseCatalog";
+import {
+ MARK_SENSITIVE_DATA_PRODUCT_INTRO,
+ useProductIntro,
+} from "@/lib/productIntro";
import { getColumnDefaultValuePlaceholder } from "@/modules/schema-editor/core/columnDefaultValue";
import { useAppStore } from "@/stores/app";
import {
@@ -43,6 +47,7 @@ import {
instanceV1SupportsSequence,
instanceV1SupportsTrigger,
} from "@/utils";
+import { instanceV1MaskingForNoSQL } from "@/utils/v1/instance";
import {
type ObjectSectionRow,
ObjectSectionTable,
@@ -120,6 +125,14 @@ export function DatabaseObjectExplorer({
project,
"bb.databaseCatalogs.update"
);
+ useProductIntro({
+ id: MARK_SENSITIVE_DATA_PRODUCT_INTRO,
+ title: t("workspace-setup-guide.intro.mark-sensitive-data-title"),
+ description: t(
+ "workspace-setup-guide.intro.mark-sensitive-fields-description"
+ ),
+ disabled: !canUpdateCatalog || !instanceV1MaskingForNoSQL(databaseEngine),
+ });
const [selectedTableName, setSelectedTableName] = useState(routeTable);
const selectedSchemaMetadata = databaseMetadata.schemas.find(
@@ -381,7 +394,10 @@ export function DatabaseObjectExplorer({
{databaseEngine !== Engine.REDIS && (
<>
- <section className="flex flex-col gap-4">
+ <section
+ className="flex flex-col gap-4"
+ data-product-intro-target={MARK_SENSITIVE_DATA_PRODUCT_INTRO}
+ >
<div className="flex flex-wrap items-center justify-between gap-3">
<div className="text-lg font-medium text-main">
{databaseEngine === Engine.MONGODB
diff --git a/frontend/src/routes/project/database-detail/overview/TableDetailSheet.tsx b/frontend/src/routes/project/database-detail/overview/TableDetailSheet.tsx
index bdbeed1bd9..0fc6093147 100644
--- a/frontend/src/routes/project/database-detail/overview/TableDetailSheet.tsx
+++ b/frontend/src/routes/project/database-detail/overview/TableDetailSheet.tsx
@@ -975,6 +975,7 @@ function TableDetailSheetContent({
tableCatalog: {
classification: classificationId,
},
+ notification: t("common.updated"),
});
};
diff --git a/frontend/src/routes/project/database-detail/overview/TableMetadataTable.tsx b/frontend/src/routes/project/database-detail/overview/TableMetadataTable.tsx
index 3e2b099e24..d00937faf1 100644
--- a/frontend/src/routes/project/database-detail/overview/TableMetadataTable.tsx
+++ b/frontend/src/routes/project/database-detail/overview/TableMetadataTable.tsx
@@ -188,6 +188,7 @@ export function TableMetadataTable({
tableCatalog: {
classification: classificationId,
},
+ notification: t("common.updated"),
});
}}
/>
diff --git a/frontend/src/routes/project/database-detail/panels/DatabaseCatalogPanel.test.tsx b/frontend/src/routes/project/database-detail/panels/DatabaseCatalogPanel.test.tsx
index a5f028cd90..88e188571e 100644
--- a/frontend/src/routes/project/database-detail/panels/DatabaseCatalogPanel.test.tsx
+++ b/frontend/src/routes/project/database-detail/panels/DatabaseCatalogPanel.test.tsx
@@ -259,6 +259,22 @@ const mocks = vi.hoisted(() => {
}
),
FeatureAttention: vi.fn(() => <div data-testid="feature-attention" />),
+ FeatureModal: vi.fn(
+ ({
+ open,
+ onFeatureUnlocked,
+ }: {
+ open: boolean;
+ onFeatureUnlocked?: () => void;
+ }) =>
+ open ? (
+ <div data-testid="feature-modal">
+ <button type="button" onClick={onFeatureUnlocked}>
+ unlock-feature
+ </button>
+ </div>
+ ) : null
+ ),
FeatureBadge: vi.fn(() => <div data-testid="feature-badge" />),
Button: (props: ButtonHTMLAttributes<HTMLButtonElement>) => (
<button {...props} />
@@ -379,6 +395,7 @@ const mocks = vi.hoisted(() => {
useTranslation: vi.fn(() => ({
t: (key: string) => key,
})),
+ useProductIntro: vi.fn(),
};
});
@@ -396,6 +413,11 @@ vi.mock("@/stores", () => ({
pushNotification: mocks.pushNotification,
}));
+vi.mock("@/lib/productIntro", async (importOriginal) => ({
+ ...(await importOriginal<typeof import("@/lib/productIntro")>()),
+ useProductIntro: mocks.useProductIntro,
+}));
+
vi.mock("@/hooks/useDatabaseCatalog", () => ({
useDatabaseCatalog: () => mocks.useDatabaseCatalog(),
}));
@@ -450,6 +472,10 @@ vi.mock("@/components/FeatureBadge", () => ({
FeatureBadge: mocks.FeatureBadge,
}));
+vi.mock("@/components/ui/feature-modal", () => ({
+ FeatureModal: mocks.FeatureModal,
+}));
+
vi.mock("@/components/PermissionGuard", () => ({
PermissionGuard: mocks.PermissionGuard,
}));
@@ -650,6 +676,7 @@ beforeEach(async () => {
mocks.hasProjectPermissionV2.mockReturnValue(true);
mocks.PermissionGuard.mockClear();
mocks.FeatureAttention.mockClear();
+ mocks.FeatureModal.mockClear();
mocks.FeatureBadge.mockClear();
mocks.GrantAccessDialog.mockClear();
mocks.DatabaseResourceSelector.mockClear();
@@ -693,12 +720,14 @@ describe("DatabaseCatalogPanel", () => {
render();
await flush();
- expect(
- getButton(
- container,
- "settings.sensitive-data.mark-sensitive-data"
- )
- ).toBeDefined();
+ const button = getButton(
+ container,
+ "settings.sensitive-data.mark-sensitive-data"
+ );
+ expect(button).toBeDefined();
+ expect(button?.getAttribute("data-product-intro-target")).toBe(
+ "mark-sensitive-data"
+ );
unmount();
});
@@ -749,7 +778,7 @@ describe("DatabaseCatalogPanel", () => {
unmount();
});
- test("opens the feature dialog when marking requires data masking", async () => {
+ test("opens the shared feature modal when marking requires data masking", async () => {
mocks.featureToRef.mockReturnValue({ value: false });
const { container, render, unmount } = renderIntoContainer(
@@ -769,14 +798,39 @@ describe("DatabaseCatalogPanel", () => {
);
await flush();
- expect(
- container.querySelector('[data-testid="dialog-root"]')
- ).not.toBeNull();
+ expect(container.querySelector('[data-testid="feature-modal"]')).not.toBeNull();
expect(container.querySelector('[data-testid="sheet-root"]')).toBeNull();
unmount();
});
+ test("continues to mark sensitive data after the trial unlocks masking", async () => {
+ mocks.featureToRef.mockReturnValue({ value: false });
+
+ const { container, render, unmount } = renderIntoContainer(
+ createElement(DatabaseCatalogPanel, {
+ database: makeDatabase(),
+ })
+ );
+
+ render();
+ await flush();
+ click(
+ getButton(
+ container,
+ "settings.sensitive-data.mark-sensitive-data"
+ ) as HTMLElement
+ );
+ await flush();
+
+ click(getButton(container, "unlock-feature") as HTMLElement);
+ await flush();
+
+ expect(container.querySelector('[data-testid="feature-modal"]')).toBeNull();
+ expect(container.querySelector('[data-testid="sheet-root"]')).not.toBeNull();
+ unmount();
+ });
+
test("marks a selected database column with a semantic type", async () => {
mocks.getSettingByName.mockReturnValue({
value: {
@@ -915,7 +969,7 @@ describe("DatabaseCatalogPanel", () => {
unmount();
});
- test("opens the feature dialog instead of grant access when masking feature is missing", async () => {
+ test("continues to grant access after the trial unlocks masking", async () => {
mocks.featureToRef.mockReturnValue({ value: false });
const { container, render, unmount } = renderIntoContainer(
@@ -940,10 +994,7 @@ describe("DatabaseCatalogPanel", () => {
);
await flush();
- expect(
- container.querySelector('[data-testid="dialog-root"]')
- ).not.toBeNull();
- expect(container.textContent).toContain("common.warning");
+ expect(container.querySelector('[data-testid="feature-modal"]')).not.toBeNull();
expect(mocks.GrantAccessDialog).toHaveBeenLastCalledWith(
expect.objectContaining({
open: false,
@@ -956,6 +1007,16 @@ describe("DatabaseCatalogPanel", () => {
?.getAttribute("data-open")
).toBe("false");
+ click(getButton(container, "unlock-feature") as HTMLElement);
+ await flush();
+
+ expect(container.querySelector('[data-testid="feature-modal"]')).toBeNull();
+ expect(
+ container
+ .querySelector('[data-testid="grant-access-dialog"]')
+ ?.getAttribute("data-open")
+ ).toBe("true");
+
unmount();
});
diff --git a/frontend/src/routes/project/database-detail/panels/DatabaseCatalogPanel.tsx b/frontend/src/routes/project/database-detail/panels/DatabaseCatalogPanel.tsx
index 2fb4131482..1139f1fb8c 100644
--- a/frontend/src/routes/project/database-detail/panels/DatabaseCatalogPanel.tsx
+++ b/frontend/src/routes/project/database-detail/panels/DatabaseCatalogPanel.tsx
@@ -13,10 +13,14 @@ import {
AlertDialogTitle,
} from "@/components/ui/alert-dialog";
import { Button } from "@/components/ui/button";
-import { Dialog, DialogContent, DialogTitle } from "@/components/ui/dialog";
+import { FeatureModal } from "@/components/ui/feature-modal";
import { Input } from "@/components/ui/input";
import { useDatabaseCatalog } from "@/hooks/useDatabaseCatalog";
import { useSemanticTypes } from "@/hooks/useSemanticTypes";
+import {
+ MARK_SENSITIVE_DATA_PRODUCT_INTRO,
+ useProductIntro,
+} from "@/lib/productIntro";
import type { MaskData, MaskDataTarget } from "@/lib/sensitive-data/types";
import {
getMaskDataIdentifier,
@@ -188,6 +192,14 @@ export function DatabaseCatalogPanel({ database }: { database: Database }) {
const hasGrantAccessPermission = GRANT_ACCESS_PERMISSIONS.every(
(permission) => hasProjectPermissionV2(project, permission)
);
+ useProductIntro({
+ id: MARK_SENSITIVE_DATA_PRODUCT_INTRO,
+ title: t("workspace-setup-guide.intro.mark-sensitive-data-title"),
+ description: t(
+ "workspace-setup-guide.intro.mark-sensitive-data-description"
+ ),
+ disabled: !hasUpdateCatalogPermission || isMaskingForNoSQL,
+ });
const { semanticTypes } = useSemanticTypes();
const classificationConfig = useAppStore((s) =>
@@ -199,7 +211,9 @@ export function DatabaseCatalogPanel({ database }: { database: Database }) {
const [searchText, setSearchText] = useState("");
const [checkedColumnList, setCheckedColumnList] = useState<MaskData[]>([]);
- const [showFeatureDialog, setShowFeatureDialog] = useState(false);
+ const [pendingFeatureAction, setPendingFeatureAction] = useState<
+ "mark-sensitive-data" | "grant-access"
+ >();
const [showMarkSensitiveDataSheet, setShowMarkSensitiveDataSheet] =
useState(false);
const [showGrantAccessDialog, setShowGrantAccessDialog] = useState(false);
@@ -222,7 +236,7 @@ export function DatabaseCatalogPanel({ database }: { database: Database }) {
useEffect(() => {
setSearchText("");
setCheckedColumnList([]);
- setShowFeatureDialog(false);
+ setPendingFeatureAction(undefined);
setShowMarkSensitiveDataSheet(false);
setShowGrantAccessDialog(false);
setPendingDeleteItem(null);
@@ -369,7 +383,7 @@ export function DatabaseCatalogPanel({ database }: { database: Database }) {
const handleGrantAccessClick = () => {
if (!hasSensitiveDataFeature) {
- setShowFeatureDialog(true);
+ setPendingFeatureAction("grant-access");
return;
}
setShowGrantAccessDialog(true);
@@ -377,7 +391,7 @@ export function DatabaseCatalogPanel({ database }: { database: Database }) {
const handleMarkSensitiveDataClick = () => {
if (!hasSensitiveDataFeature) {
- setShowFeatureDialog(true);
+ setPendingFeatureAction("mark-sensitive-data");
return;
}
setShowMarkSensitiveDataSheet(true);
@@ -388,6 +402,16 @@ export function DatabaseCatalogPanel({ database }: { database: Database }) {
setCheckedColumnList([]);
};
+ const handleFeatureUnlocked = () => {
+ const action = pendingFeatureAction;
+ setPendingFeatureAction(undefined);
+ if (action === "mark-sensitive-data") {
+ setShowMarkSensitiveDataSheet(true);
+ } else if (action === "grant-access") {
+ setShowGrantAccessDialog(true);
+ }
+ };
+
const handleDeleteConfirmed = async () => {
if (!pendingDeleteItem) {
return;
@@ -417,6 +441,7 @@ export function DatabaseCatalogPanel({ database }: { database: Database }) {
<Button
type="button"
className="w-full sm:w-auto"
+ data-product-intro-target={MARK_SENSITIVE_DATA_PRODUCT_INTRO}
onClick={handleMarkSensitiveDataClick}
>
{hasSensitiveDataFeature ? (
@@ -484,26 +509,15 @@ export function DatabaseCatalogPanel({ database }: { database: Database }) {
onDelete={(item) => setPendingDeleteItem(item)}
/>
- <Dialog open={showFeatureDialog} onOpenChange={setShowFeatureDialog}>
- <DialogContent className="p-6">
- <DialogTitle>{t("common.warning")}</DialogTitle>
- <div className="mt-3">
- <FeatureAttention
- feature={PlanFeature.FEATURE_DATA_MASKING}
- instance={instance}
- />
- </div>
- <div className="mt-6 flex justify-end gap-x-2">
- <Button
- type="button"
- appearance="outline"
- onClick={() => setShowFeatureDialog(false)}
- >
- {t("common.cancel")}
- </Button>
- </div>
- </DialogContent>
- </Dialog>
+ <FeatureModal
+ open={!!pendingFeatureAction}
+ feature={PlanFeature.FEATURE_DATA_MASKING}
+ instance={instance}
+ onOpenChange={(open) => {
+ if (!open) setPendingFeatureAction(undefined);
+ }}
+ onFeatureUnlocked={handleFeatureUnlocked}
+ />
<MarkSensitiveDataSheet
database={database}
diff --git a/frontend/src/routes/workspace/PurchaseSection.test.tsx b/frontend/src/routes/workspace/PurchaseSection.test.tsx
new file mode 100644
index 0000000000..77169ab317
--- /dev/null
+++ b/frontend/src/routes/workspace/PurchaseSection.test.tsx
@@ -0,0 +1,73 @@
+import { cleanup, render, screen } from "@testing-library/react";
+import { afterEach, beforeEach, expect, test, vi } from "vitest";
+import { PlanType } from "@/types/proto-es/v1/subscription_service_pb";
+import { PurchaseSection } from "./PurchaseSection";
+
+const mocks = vi.hoisted(() => ({
+ isTrialing: false,
+ isExpired: false,
+ allowManage: true,
+ fetchPaymentInfo: vi.fn(),
+ fetchPurchasePlans: vi.fn(),
+ refreshSubscription: vi.fn(),
+}));
+
+vi.mock("react-i18next", () => ({
+ useTranslation: () => ({ t: (key: string) => key }),
+}));
+vi.mock("@/hooks/useAppState", () => ({
+ useSubscriptionState: () => ({
+ currentPlan: PlanType.ENTERPRISE,
+ isFreePlan: false,
+ isExpired: mocks.isExpired,
+ isTrialing: mocks.isTrialing,
+ subscription: { seats: 20 },
+ }),
+}));
+vi.mock("@/stores/app", () => ({
+ useAppStore: Object.assign(
+ (selector: (state: unknown) => unknown) =>
+ selector({ ...mocks, paymentInfo: null, purchasePlans: [] }),
+ { getState: () => mocks }
+ ),
+}));
+vi.mock("@/stores", () => ({ pushNotification: vi.fn() }));
+vi.mock("@/utils", () => ({
+ hasWorkspacePermissionV2: () => mocks.allowManage,
+}));
+vi.mock("./CancelSubscriptionDialog", () => ({
+ CancelSubscriptionDialog: () => null,
+}));
+
+beforeEach(() => {
+ vi.clearAllMocks();
+ mocks.isTrialing = false;
+ mocks.isExpired = false;
+ mocks.allowManage = true;
+});
+afterEach(cleanup);
+
+test("does not offer cancellation or fetch payment info for a license trial", () => {
+ mocks.isTrialing = true;
+ render(<PurchaseSection onRequireEnterprise={vi.fn()} />);
+ expect(
+ screen.queryByRole("button", { name: "subscription.purchase.cancel" })
+ ).toBeNull();
+ expect(mocks.fetchPaymentInfo).not.toHaveBeenCalled();
+});
+
+test("keeps cancellation available for an active paid subscription", () => {
+ render(<PurchaseSection onRequireEnterprise={vi.fn()} />);
+ expect(
+ screen.getByRole("button", { name: "subscription.purchase.cancel" })
+ ).toBeTruthy();
+ expect(mocks.fetchPaymentInfo).toHaveBeenCalledTimes(1);
+});
+
+test("hides cancellation when the paid subscription has expired", () => {
+ mocks.isExpired = true;
+ render(<PurchaseSection onRequireEnterprise={vi.fn()} />);
+ expect(
+ screen.queryByRole("button", { name: "subscription.purchase.cancel" })
+ ).toBeNull();
+});
diff --git a/frontend/src/routes/workspace/PurchaseSection.tsx b/frontend/src/routes/workspace/PurchaseSection.tsx
index 6a5bfde29b..19edb44049 100644
--- a/frontend/src/routes/workspace/PurchaseSection.tsx
+++ b/frontend/src/routes/workspace/PurchaseSection.tsx
@@ -85,8 +85,9 @@ export function PurchaseSection({ onRequireEnterprise }: PurchaseSectionProps) {
const { t } = useTranslation();
const refreshSubscription = useAppStore((state) => state.refreshSubscription);
- const { currentPlan, isFreePlan, isExpired, subscription } =
+ const { currentPlan, isFreePlan, isExpired, isTrialing, subscription } =
useSubscriptionState();
+ const hasPaidSubscription = !isFreePlan && !isExpired && !isTrialing;
const paymentInfo = useAppStore((s) => s.paymentInfo);
const purchasePlans = useAppStore((s) => s.purchasePlans);
@@ -150,10 +151,10 @@ export function PurchaseSection({ onRequireEnterprise }: PurchaseSectionProps) {
// Fetch payment info for active subscriptions.
useEffect(() => {
- if (!isFreePlan && !isExpired) {
+ if (hasPaidSubscription) {
useAppStore.getState().fetchPaymentInfo();
}
- }, [isFreePlan, isExpired]);
+ }, [hasPaidSubscription]);
const isCurrentPlan = useCallback(
(plan: PlanType) => currentPlan === plan && !isExpired,
@@ -356,7 +357,7 @@ export function PurchaseSection({ onRequireEnterprise }: PurchaseSectionProps) {
return (
<div className="w-full">
{/* Active Subscription Management */}
- {!isFreePlan && !isExpired && (
+ {hasPaidSubscription && (
<>
{paymentInfo && (
<div className="flex flex-col gap-2">
diff --git a/frontend/src/stores/app/index.test.ts b/frontend/src/stores/app/index.test.ts
index 8e811bc627..546fbb1f2b 100644
--- a/frontend/src/stores/app/index.test.ts
+++ b/frontend/src/stores/app/index.test.ts
@@ -115,6 +115,7 @@ const mocks = vi.hoisted(() => ({
updateRole: vi.fn(),
deleteRole: vi.fn(),
getSubscription: vi.fn(),
+ startTrial: vi.fn(),
uploadLicense: vi.fn(),
getSetting: vi.fn(),
getProject: vi.fn(),
@@ -302,6 +303,7 @@ vi.mock("@/api", () => ({
},
subscriptionServiceClientConnect: {
getSubscription: mocks.getSubscription,
+ startTrial: mocks.startTrial,
uploadLicense: mocks.uploadLicense,
},
userServiceClientConnect: {
@@ -2690,6 +2692,58 @@ describe("useAppStore", () => {
expect(store.getState().userCountLimit()).toBe(12);
});
+ test("starts a trial and applies the returned subscription", async () => {
+ const trial = createProto(SubscriptionSchema, {
+ plan: PlanType.ENTERPRISE,
+ trialing: true,
+ });
+ mocks.startTrial.mockResolvedValue(trial);
+ const store = createAppStore();
+
+ const subscription = await store.getState().startTrial();
+
+ expect(mocks.startTrial).toHaveBeenCalledOnce();
+ expect(subscription).toBe(trial);
+ expect(store.getState().subscription).toBe(trial);
+ });
+
+ test("offers trial activation only to free SaaS workspaces in any mode", () => {
+ vi.stubEnv("MODE", "release-aws");
+ const store = createAppStore();
+ store.setState({
+ serverInfo: createProto(ActuatorInfoSchema, { saas: true }),
+ subscription: undefined,
+ });
+ expect(store.getState().canStartTrial()).toBe(false);
+
+ store.setState({
+ serverInfo: createProto(ActuatorInfoSchema, { saas: true }),
+ subscription: createProto(SubscriptionSchema, { plan: PlanType.FREE }),
+ });
+
+ expect(store.getState().canStartTrial()).toBe(true);
+
+ store.setState({
+ subscription: createProto(SubscriptionSchema, {
+ plan: PlanType.ENTERPRISE,
+ trialing: true,
+ }),
+ });
+ expect(store.getState().canStartTrial()).toBe(false);
+
+ store.setState({
+ serverInfo: createProto(ActuatorInfoSchema, { saas: false }),
+ subscription: createProto(SubscriptionSchema, { plan: PlanType.FREE }),
+ });
+ expect(store.getState().canStartTrial()).toBe(false);
+
+ vi.stubEnv("MODE", "development");
+ store.setState({
+ serverInfo: createProto(ActuatorInfoSchema, { saas: true }),
+ });
+ expect(store.getState().canStartTrial()).toBe(true);
+ });
+
test("loads environment settings into React state", async () => {
mocks.getSetting.mockResolvedValue(
createProto(SettingSchema, {
diff --git a/frontend/src/stores/app/types.ts b/frontend/src/stores/app/types.ts
index b545f26bba..53e4bfc2e3 100644
--- a/frontend/src/stores/app/types.ts
+++ b/frontend/src/stores/app/types.ts
@@ -277,10 +277,12 @@ export type WorkspaceSlice = {
}) => Promise<Setting>;
loadSubscription: () => Promise<Subscription | undefined>;
refreshSubscription: () => Promise<Subscription | undefined>;
+ startTrial: () => Promise<Subscription>;
uploadLicense: (license: string) => Promise<Subscription | undefined>;
currentPlan: () => PlanType;
isFreePlan: () => boolean;
isTrialing: () => boolean;
+ canStartTrial: () => boolean;
isExpired: () => boolean;
daysBeforeExpire: () => number;
trialingDays: () => number;
diff --git a/frontend/src/stores/app/workspace.ts b/frontend/src/stores/app/workspace.ts
index 34cad61a45..e25d95cad5 100644
--- a/frontend/src/stores/app/workspace.ts
+++ b/frontend/src/stores/app/workspace.ts
@@ -49,6 +49,7 @@ import {
GetSubscriptionRequestSchema,
ListPurchasePlansRequestSchema,
PlanType,
+ StartTrialRequestSchema,
UpdatePurchaseRequestSchema,
UploadLicenseRequestSchema,
VerifyCheckoutSessionRequestSchema,
@@ -517,6 +518,14 @@ export const createWorkspaceSlice: AppSliceCreator<WorkspaceSlice> = (
return request;
},
+ startTrial: async () => {
+ const subscription = await subscriptionServiceClientConnect.startTrial(
+ createProto(StartTrialRequestSchema, {})
+ );
+ set({ subscription, subscriptionRequest: undefined });
+ return subscription;
+ },
+
uploadLicense: async (license) => {
const subscription = await subscriptionServiceClientConnect.uploadLicense(
createProto(UploadLicenseRequestSchema, { license })
@@ -533,6 +542,12 @@ export const createWorkspaceSlice: AppSliceCreator<WorkspaceSlice> = (
isTrialing: () => Boolean(get().subscription?.trialing),
+ canStartTrial: () =>
+ get().isSaaSMode() &&
+ !!get().subscription &&
+ get().isFreePlan() &&
+ !get().isTrialing(),
+
isExpired: () => {
const subscription = get().subscription;
if (!subscription?.expiresTime || get().isFreePlan()) {