Database governance built for humans and agents — controlling changes and access across every major database.
Go cicddata-governancedata-maskingdata-securitydatabase-accessdatabase-governancedevopsdevsecopsflywaygitopsliquibasemongodbmysqloraclepostgresqlschema-migrationssecuritysql-clientsqlservertidb
chore: record workspace switch (#20680)
ecmadao069898a74578
diff --git a/frontend/src/react/components/BannersWrapper.test.tsx b/frontend/src/react/components/BannersWrapper.test.tsxindex 45f44f9144..8eea5f4f57 100644--- a/frontend/src/react/components/BannersWrapper.test.tsx+++ b/frontend/src/react/components/BannersWrapper.test.tsx@@ -260,4 +260,32 @@ describe("BannersWrapper", () => {expect(container.textContent).toContain("Upgrade");unmount();});++ test("allows the upgrade banner to grow when the message wraps", () => {+ mocks.useServerState.mockReturnValue({+ needConfigureExternalUrl: false,+ serverInfo: { unlicensedFeatures: ["FEATURE_BATCH_QUERY"] },+ });+ mocks.getMinimumRequiredPlan.mockReturnValue(PlanType.TEAM);+ const { container, unmount } = renderIntoContainer(<BannersWrapper />);++ const banner = container.querySelector(".bb-banner-scroll");+ const classes = banner?.className.split(/\s+/) ?? [];+ expect(classes).toContain("min-h-10");+ expect(classes).not.toContain("h-10");+ const content = banner?.firstElementChild;+ const contentClasses = content?.className.split(/\s+/) ?? [];+ expect(contentClasses).toContain("flex-row");+ expect(contentClasses).toContain("flex-wrap");+ expect(contentClasses).not.toContain("flex-col");+ const messageContainer = container.querySelector(+ '[data-label="bb-upgrade-banner-message"]'+ )?.parentElement;+ expect(messageContainer?.className).toContain("flex-[0_1_auto]");+ expect(+ container.querySelector('[data-label="bb-upgrade-banner-message"]')+ ).not.toBeNull();++ unmount();+ });});diff --git a/frontend/src/react/components/BannersWrapper.tsx b/frontend/src/react/components/BannersWrapper.tsxindex b80e21cbfe..d14ee32eaf 100644--- a/frontend/src/react/components/BannersWrapper.tsx+++ b/frontend/src/react/components/BannersWrapper.tsx@@ -228,31 +228,33 @@ function BannerUpgradeSubscription() {return (<><div className="overflow-clip bg-gray-200">- <div className="bb-banner-scroll h-10 w-full">- <div className="mx-auto flex w-full flex-row flex-wrap items-center justify-center px-3 py-1">- <div className="flex flex-row items-center">- <AlertCircle className="mr-1 h-auto w-5 text-gray-800" />- <Trans- t={t}- i18nKey="subscription.overuse-warning"- values={{- currentPlan: currentPlanTitle,- neededPlan: neededPlanFeatures,- }}- components={{- neededPlan: (- <button- type="button"- className="mr-1 cursor-pointer underline hover:opacity-60"- onClick={() => setShowModal(true)}- >- {neededPlanFeatures}- </button>- ),- }}- />+ <div className="bb-banner-scroll min-h-10 w-full">+ <div className="mx-auto flex min-h-10 w-full flex-row flex-wrap items-center justify-start gap-x-2 gap-y-1 px-3 py-2 text-sm leading-5 sm:justify-center sm:py-1">+ <div className="flex min-w-0 max-w-full flex-[0_1_auto] flex-row items-start sm:items-center">+ <AlertCircle className="mt-0.5 mr-1 h-auto w-5 shrink-0 text-gray-800 sm:mt-0" />+ <span data-label="bb-upgrade-banner-message" className="min-w-0">+ <Trans+ t={t}+ i18nKey="subscription.overuse-warning"+ values={{+ currentPlan: currentPlanTitle,+ neededPlan: neededPlanFeatures,+ }}+ components={{+ neededPlan: (+ <button+ type="button"+ className="mr-1 cursor-pointer whitespace-nowrap underline hover:opacity-60"+ onClick={() => setShowModal(true)}+ >+ {neededPlanFeatures}+ </button>+ ),+ }}+ />+ </span></div>- <div className="ml-2">+ <div className="shrink-0"><RouterLinkto={{ name: SETTING_ROUTE_WORKSPACE_SUBSCRIPTION }}className={buttonVariants({ size: "sm" })}diff --git a/frontend/src/react/components/DashboardSidebar.test.tsx b/frontend/src/react/components/DashboardSidebar.test.tsxindex 78fa9ec1a2..1c68576b47 100644--- a/frontend/src/react/components/DashboardSidebar.test.tsx+++ b/frontend/src/react/components/DashboardSidebar.test.tsx@@ -24,6 +24,21 @@ const mocks = vi.hoisted(() => ({databaseChangeMode: 1,isSaaSMode: false,workspaceLogo: "",+ project: undefined as { name: string; title: string } | undefined,+ workspace: {+ name: "workspaces/default",+ title: "Default Workspace",+ logo: "",+ },+ workspaceList: [+ {+ name: "workspaces/default",+ title: "Default Workspace",+ },+ ],+ subscription: {+ plan: 0,+ },record: vi.fn(),push: vi.fn(),resolve: vi.fn((target: string | { name?: string; path?: string }) => {@@ -59,6 +74,10 @@ const t = vi.hoisted("common.environments": "Environments","common.users": "Users","common.settings": "Settings",+ "project.select": "Select project",+ "subscription.plan.free.title": "Free",+ "subscription.plan.team.title": "Team",+ "subscription.plan.enterprise.title": "Enterprise","settings.sidebar.iam-and-admin": "IAM & Admin","settings.members.service-accounts": "Service Accounts","settings.members.workload-identities": "Workload Identities",@@ -91,12 +110,19 @@ vi.mock("react-i18next", () => ({vi.mock("@/react/hooks/useAppState", () => ({useAppFeature: () => mocks.databaseChangeMode,useIsSaaSMode: () => mocks.isSaaSMode,- useWorkspace: () => ({- logo: mocks.workspaceLogo,- }),+ useProject: () => mocks.project,useRecentVisit: () => ({record: mocks.record,}),+ useSubscription: () => ({+ subscription: mocks.subscription,+ }),+ useSwitchWorkspace: () => vi.fn(),+ useWorkspace: () => ({+ ...mocks.workspace,+ logo: mocks.workspaceLogo,+ }),+ useWorkspaceList: () => mocks.workspaceList,}));vi.mock("@/react/router", () => ({@@ -140,8 +166,12 @@ vi.mock("@/assets/logo-full.svg", () => ({default: "/assets/logo-full.svg",}));-vi.mock("./WorkspaceSwitcher", () => ({- WorkspaceSwitcher: () => <div data-testid="workspace-switcher" />,+vi.mock("@/react/components/header/ProjectCreateDialog", () => ({+ ProjectCreateDialog: () => null,+}));++vi.mock("@/react/components/header/ProjectSwitchPanel", () => ({+ ProjectSwitchPanel: () => <div data-testid="project-switch-panel" />,}));let DashboardSidebar: typeof import("./DashboardSidebar").DashboardSidebar;@@ -169,9 +199,22 @@ beforeEach(async () => {vi.clearAllMocks();mocks.currentRoute.name = WORKSPACE_ROUTE_LANDING;mocks.currentRoute.fullPath = "/";+ mocks.currentRoute.params = {};mocks.databaseChangeMode = DatabaseChangeMode.PIPELINE;mocks.isSaaSMode = false;mocks.workspaceLogo = "";+ mocks.project = undefined;+ mocks.workspace = {+ name: "workspaces/default",+ title: "Default Workspace",+ logo: "",+ };+ mocks.workspaceList = [+ {+ name: "workspaces/default",+ title: "Default Workspace",+ },+ ];({ DashboardSidebar } = await import("./DashboardSidebar"));});@@ -227,6 +270,27 @@ describe("DashboardSidebar", () => {unmount();});+ test("places workspace and project switchers in a mobile-only sidebar block", () => {+ const { container, render, unmount } = renderIntoContainer(+ <DashboardSidebar />+ );+ render();++ const switcherBlock = container.querySelector(+ '[data-label="bb-mobile-sidebar-switchers"]'+ );+ expect(switcherBlock).not.toBeNull();+ expect(switcherBlock?.className).toContain("md:hidden");+ expect(switcherBlock?.textContent).toContain("Default Workspace");+ expect(switcherBlock?.textContent).toContain("Select project");+ expect(switcherBlock?.previousElementSibling?.tagName).toBe("A");+ expect(+ switcherBlock?.previousElementSibling?.querySelector("img")+ ).not.toBeNull();++ unmount();+ });+test("highlights the active route", () => {mocks.currentRoute.name = DATABASE_ROUTE_DASHBOARD;const { container, render, unmount } = renderIntoContainer(diff --git a/frontend/src/react/components/DashboardSidebar.tsx b/frontend/src/react/components/DashboardSidebar.tsxindex 1669c07bcd..f46fe908f8 100644--- a/frontend/src/react/components/DashboardSidebar.tsx+++ b/frontend/src/react/components/DashboardSidebar.tsx@@ -16,6 +16,7 @@ import type { ElementType } from "react";import { useCallback, useEffect, useMemo, useRef, useState } from "react";import { useTranslation } from "react-i18next";import logoFull from "@/assets/logo-full.svg";+import { MobileSidebarSwitchers } from "@/react/components/header/HeaderBreadcrumb";import { RouterLink } from "@/react/components/RouterLink";import {useAppFeature,@@ -503,6 +504,7 @@ export function DashboardSidebar() {><img src={logoSrc} alt="Bytebase" className="max-w-44" /></RouterLink>+ <MobileSidebarSwitchers /><div className="flex-1 overflow-y-auto px-2.5 pb-4 flex flex-col gap-y-1">{filteredItems.map((item, i) => renderItem(item, i))}</div>diff --git a/frontend/src/react/components/WorkspaceSwitcher.tsx b/frontend/src/react/components/WorkspaceSwitcher.tsxdeleted file mode 100644index 0cf8228a4b..0000000000--- a/frontend/src/react/components/WorkspaceSwitcher.tsx+++ /dev/null@@ -1,61 +0,0 @@-import { Building2, ChevronsUpDown } from "lucide-react";-import { useState } from "react";-import {- DropdownMenu,- DropdownMenuContent,- DropdownMenuItem,- DropdownMenuTrigger,-} from "@/react/components/ui/dropdown-menu";-import { useWorkspace, useWorkspaceList } from "@/react/hooks/useAppState";-import { useAppStore } from "@/react/stores/app";--export function WorkspaceSwitcher() {- const workspaceList = useWorkspaceList();- const currentWorkspace = useWorkspace();- const switchWorkspace = useAppStore((state) => state.switchWorkspace);- const currentWorkspaceName = currentWorkspace?.name ?? "";-- const [open, setOpen] = useState(false);-- if (workspaceList.length <= 1) {- return null;- }-- const onSwitch = (workspaceName: string) => {- if (workspaceName === currentWorkspaceName) return;- setOpen(false);- switchWorkspace(workspaceName);- };-- return (- <div className="px-2.5 pb-2">- <DropdownMenu open={open} onOpenChange={setOpen}>- <DropdownMenuTrigger className="w-full flex items-center gap-x-2 px-2 py-1.5 rounded-xs text-sm font-medium text-control hover:bg-control-bg cursor-pointer outline-hidden focus-visible:ring-2 focus-visible:ring-accent">- <Building2 className="size-4 text-control-light shrink-0" />- <span className="truncate flex-1 text-left">- {currentWorkspace?.title}- </span>- <ChevronsUpDown className="size-3.5 text-control-placeholder shrink-0" />- </DropdownMenuTrigger>- <DropdownMenuContent- align="start"- className="w-[var(--anchor-width)] py-1"- >- {workspaceList.map((ws) => (- <DropdownMenuItem- key={ws.name}- className={`px-3 py-1.5 ${- ws.name === currentWorkspaceName- ? "font-medium text-accent"- : "text-control"- }`}- onClick={() => onSwitch(ws.name)}- >- {ws.title}- </DropdownMenuItem>- ))}- </DropdownMenuContent>- </DropdownMenu>- </div>- );-}diff --git a/frontend/src/react/components/header/DashboardHeader.test.tsx b/frontend/src/react/components/header/DashboardHeader.test.tsxindex 3811279602..50822a4005 100644--- a/frontend/src/react/components/header/DashboardHeader.test.tsx+++ b/frontend/src/react/components/header/DashboardHeader.test.tsx@@ -160,6 +160,10 @@ describe("DashboardHeader", () => {expect(container.querySelector('[data-testid="header-breadcrumb"]')).not.toBeNull();+ expect(+ container.querySelector('[data-label="bb-header-breadcrumb-slot"]')+ ?.className+ ).toContain("hidden md:flex");expect(container.querySelector('[data-testid="profile-menu-trigger"]')).not.toBeNull();diff --git a/frontend/src/react/components/header/DashboardHeader.tsx b/frontend/src/react/components/header/DashboardHeader.tsxindex 56c1fee7e1..db04454170 100644--- a/frontend/src/react/components/header/DashboardHeader.tsx+++ b/frontend/src/react/components/header/DashboardHeader.tsx@@ -11,6 +11,7 @@ import { v4 as uuidv4 } from "uuid";import { BytebaseLogo } from "@/react/components/BytebaseLogo";import { Button } from "@/react/components/ui/button";import { useRecentVisit, useSubscription } from "@/react/hooks/useAppState";+import { cn } from "@/react/lib/utils";import {SQL_EDITOR_DATABASE_MODULE,SQL_EDITOR_HOME_MODULE,@@ -117,7 +118,12 @@ export function DashboardHeader({</button>) : null}- <HeaderBreadcrumb />+ <div+ data-label="bb-header-breadcrumb-slot"+ className={cn(showMobileSidebarToggle ? "hidden md:flex" : "flex")}+ >+ <HeaderBreadcrumb />+ </div><div className="flex flex-1 items-center justify-end gap-x-2"><Buttondiff --git a/frontend/src/react/components/header/HeaderBreadcrumb.tsx b/frontend/src/react/components/header/HeaderBreadcrumb.tsxindex 005bffdbcc..331ef9a83d 100644--- a/frontend/src/react/components/header/HeaderBreadcrumb.tsx+++ b/frontend/src/react/components/header/HeaderBreadcrumb.tsx@@ -10,6 +10,7 @@ import {} from "@/react/components/ui/popover";import {useProject,+ useRecentVisit,useSubscription,useSwitchWorkspace,useWorkspace,@@ -21,7 +22,11 @@ import {workspaceNamePrefix,} from "@/react/lib/resourceName";import { cn } from "@/react/lib/utils";-import { useCurrentRoute, WORKSPACE_ROUTE_LANDING } from "@/react/router";+import {+ useCurrentRoute,+ useNavigate,+ WORKSPACE_ROUTE_LANDING,+} from "@/react/router";import { PlanType } from "@/types/proto-es/v1/subscription_service_pb";import { ProjectCreateDialog } from "./ProjectCreateDialog";import { ProjectSwitchPanel } from "./ProjectSwitchPanel";@@ -58,7 +63,7 @@ function planVariant(// ---------------------------------------------------------------------------// WorkspaceSegment — shows workspace name + plan badge + optional dropdown// ----------------------------------------------------------------------------function WorkspaceSegment() {+export function WorkspaceSegment() {const { t } = useTranslation();const workspace = useWorkspace();const workspaceList = useWorkspaceList();@@ -69,6 +74,8 @@ function WorkspaceSegment() {const hasMultiple = workspaceList.length > 1;const switchWorkspace = useSwitchWorkspace();const [open, setOpen] = useState(false);+ const { record } = useRecentVisit();+ const navigate = useNavigate();const onSwitch = useCallback((workspaceName: string) => {@@ -83,6 +90,10 @@ function WorkspaceSegment() {<div className="inline-flex items-center"><RouterLinkto={{ name: WORKSPACE_ROUTE_LANDING }}+ onClick={() => {+ const route = navigate.resolve({ name: WORKSPACE_ROUTE_LANDING });+ record(route.fullPath);+ }}className="inline-flex items-center gap-x-1.5 rounded-xs px-2 py-1 text-sm font-medium text-control hover:bg-control-bg cursor-pointer no-underline"><Building2 className="size-4 text-control-light shrink-0" />@@ -156,7 +167,7 @@ function WorkspaceSegment() {// ---------------------------------------------------------------------------// ProjectSegment — shows project name + dropdown, only when inside a project// ----------------------------------------------------------------------------function ProjectSegment() {+export function ProjectSegment() {const { t } = useTranslation();const route = useCurrentRoute();const [open, setOpen] = useState(false);@@ -230,3 +241,17 @@ export function HeaderBreadcrumb() {</div>);}++export function MobileSidebarSwitchers() {+ return (+ <div+ data-label="bb-mobile-sidebar-switchers"+ className="md:hidden border-b border-block-border px-2.5 py-2"+ >+ <div className="flex flex-col gap-y-1">+ <WorkspaceSegment />+ <ProjectSegment />+ </div>+ </div>+ );+}diff --git a/frontend/src/react/components/header/ProjectSwitchPanel.tsx b/frontend/src/react/components/header/ProjectSwitchPanel.tsxindex d9dcf46b39..7248c46440 100644--- a/frontend/src/react/components/header/ProjectSwitchPanel.tsx+++ b/frontend/src/react/components/header/ProjectSwitchPanel.tsx@@ -171,12 +171,7 @@ export function ProjectSwitchPanel({if (event.ctrlKey || event.metaKey) {window.open(route.fullPath, "_blank");} else {- void navigate.push({- name: PROJECT_V1_ROUTE_DETAIL,- params: {- projectId: getProjectName(project.name),- },- });+ void navigate.push(route);}onClose();diff --git a/frontend/src/react/stores/app/preferences.ts b/frontend/src/react/stores/app/preferences.tsindex 4426b26207..ee40cfbf0a 100644--- a/frontend/src/react/stores/app/preferences.ts+++ b/frontend/src/react/stores/app/preferences.ts@@ -44,10 +44,13 @@ export const createPreferencesSlice: AppSliceCreator<PreferencesSlice> = ();},- recordRecentVisit: (path) => {+ recordRecentVisit: (path, workspaceName) => {const email = getCurrentUserEmail(get);if (!email) return;- const key = storageKeyRecentVisit(getWorkspaceCacheScope(get), email);+ const key = storageKeyRecentVisit(+ getWorkspaceCacheScope(get, workspaceName),+ );const previous = readJson<string[]>(key, []);const pathOnly = path.replace(/[?#].*$/, "");const next = [diff --git a/frontend/src/react/stores/app/types.ts b/frontend/src/react/stores/app/types.tsindex b1508b7576..1846928788 100644--- a/frontend/src/react/stores/app/types.ts+++ b/frontend/src/react/stores/app/types.ts@@ -866,7 +866,7 @@ export type PreferencesSlice = {// re-run (the flags live in localStorage, not Zustand state).introStateVersion: number;setRecentProject: (name: string) => void;- recordRecentVisit: (path: string) => void;+ recordRecentVisit: (path: string, workspaceName?: string) => void;removeRecentVisit: (path: string) => void;resetQuickstartProgress: () => void;getIntroStateByKey: (key: string) => boolean;diff --git a/frontend/src/react/stores/app/utils.ts b/frontend/src/react/stores/app/utils.tsindex c7bc54eaba..1bd02192ea 100644--- a/frontend/src/react/stores/app/utils.ts+++ b/frontend/src/react/stores/app/utils.ts@@ -30,11 +30,11 @@ export function getCurrentUserEmail(get: () => AppStoreState): string {// Workspace segment for localStorage cache keys — "" for self-host (keys stay// shared/unchanged), the workspace name for SaaS (keys are workspace-isolated).-export function getWorkspaceCacheScope(get: () => AppStoreState): string {- return workspaceCacheScope(- get().isSaaSMode(),- get().currentUser?.workspace ?? ""- );+export function getWorkspaceCacheScope(+ get: () => AppStoreState,+ workspaceName = get().currentUser?.workspace ?? ""+): string {+ return workspaceCacheScope(get().isSaaSMode(), workspaceName);}export function readJson<T>(key: string, fallback: T): T {diff --git a/frontend/src/react/stores/app/workspace.ts b/frontend/src/react/stores/app/workspace.tsindex 9bf78d83eb..2c69b1966b 100644--- a/frontend/src/react/stores/app/workspace.ts+++ b/frontend/src/react/stores/app/workspace.ts@@ -15,6 +15,8 @@ import {settingNamePrefix,workspaceNamePrefix,} from "@/react/lib/resourceName";+import { WORKSPACE_ROUTE_LANDING } from "@/react/router";+import { resolvePath } from "@/react/router/navigation";import { getEnvironmentId } from "@/store/modules/v1/common";import {broadcastWorkspaceSwitch,@@ -71,14 +73,7 @@ import {import { formatAbsoluteDateTime } from "@/utils/datetime";import type { AppSliceCreator, WorkspaceSlice } from "./types";-// Listen on the shared cross-tab channel (see store/workspaceSwitchChannel.ts).-// Using `addEventListener` rather than `onmessage = ...` allows the Vue-side-// store to register its own handler on the same object, and source-object-// exclusion correctly suppresses both handlers when a post originates from-// this tab (e.g. the OAuth2 consent page's in-place switch).-workspaceSwitchChannel.addEventListener("message", () => {- window.location.href = "/";-});+let workspaceSwitchListenerRegistered = false;const workspaceProfileSettingName = `${settingNamePrefix}${Setting_SettingName[Setting_SettingName.WORKSPACE_PROFILE]@@ -151,6 +146,22 @@ export const createWorkspaceSlice: AppSliceCreator<WorkspaceSlice> = (set,get) => {+ // Listen on the shared cross-tab channel (see store/workspaceSwitchChannel.ts).+ // Using `addEventListener` rather than `onmessage = ...` allows the Vue-side+ // store to register its own handler on the same object, and source-object+ // exclusion correctly suppresses both handlers when a post originates from+ // this tab (e.g. the OAuth2 consent page's in-place switch).+ if (!workspaceSwitchListenerRegistered) {+ workspaceSwitchListenerRegistered = true;+ workspaceSwitchChannel.addEventListener("message", (event) => {+ get().recordRecentVisit(+ resolvePath(WORKSPACE_ROUTE_LANDING),+ typeof event.data === "string" ? event.data : undefined+ );+ window.location.href = "/";+ });+ }+const unknownEnvironment = createUnknownEnvironment();const nullEnvironment = createNullEnvironment();const environmentFallbacksByName = new Map<string, Environment>();@@ -287,6 +298,10 @@ export const createWorkspaceSlice: AppSliceCreator<WorkspaceSlice> = (web: true,}));+ get().recordRecentVisit(+ resolvePath(WORKSPACE_ROUTE_LANDING),+ workspaceName+ );// Notify other tabs to reload with the new workspace.broadcastWorkspaceSwitch(workspaceName);if (redirect) {