Skip to content

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

chore: ga4 and optimization (#21007)

ecmadao3e0b3b24a60e
diff --git a/backend/server/echo_routes.go b/backend/server/echo_routes.go
index 9447534c57..8ad1e6bbf3 100644
--- a/backend/server/echo_routes.go
+++ b/backend/server/echo_routes.go
@@ -35,7 +35,7 @@ func configureEchoRouters(
profile *config.Profile,
) {
e.Use(recoverMiddleware)
- e.Use(securityHeadersMiddleware)
+ e.Use(securityHeadersMiddleware(profile.SaaS))
if profile.Mode == common.ReleaseModeDev {
e.Use(middleware.CORSWithConfig(middleware.CORSConfig{
@@ -145,7 +145,7 @@ func recoverMiddleware(next echo.HandlerFunc) echo.HandlerFunc {
}
}
-func securityHeadersMiddleware(next echo.HandlerFunc) echo.HandlerFunc {
+func securityHeadersMiddleware(saas bool) echo.MiddlewareFunc {
// Content Security Policy
// Note: style-src allows 'unsafe-inline' temporarily due to inline styles in Vue components
// TODO: Migrate inline styles to CSS classes and remove 'unsafe-inline'
@@ -155,30 +155,40 @@ func securityHeadersMiddleware(next echo.HandlerFunc) echo.HandlerFunc {
// Monaco's TextMate service embeds WASM that requires runtime compilation
// Note: connect-src allows 'data:' for Monaco Editor language definitions
scriptHashes := loadCSPHashes()
+ scriptSrc := "script-src 'self' " + strings.Join(scriptHashes, " ") + " 'wasm-unsafe-eval'"
+ imgSrc := "img-src 'self' data: blob: discordapp.com"
+ connectSrc := "connect-src 'self' data: ws: wss: https://api.github.com https://hub.bytebase.com"
+ if saas {
+ scriptSrc += " https://www.googletagmanager.com"
+ imgSrc += " https://*.google-analytics.com https://*.googletagmanager.com"
+ connectSrc += " https://*.google-analytics.com https://*.analytics.google.com https://*.googletagmanager.com"
+ }
csp := "default-src 'self'; " +
- "script-src 'self' " + strings.Join(scriptHashes, " ") + " 'wasm-unsafe-eval'; " +
+ scriptSrc + "; " +
"style-src 'self' 'unsafe-inline'; " +
- "img-src 'self' data: blob: discordapp.com; " +
- "connect-src 'self' data: ws: wss: https://api.github.com https://hub.bytebase.com; " +
+ imgSrc + "; " +
+ connectSrc + "; " +
"font-src 'self'; " +
"object-src 'none'; " +
"base-uri 'self'; " +
"form-action 'self'; " +
"frame-ancestors 'self'"
- return func(c *echo.Context) error {
- // Allow popups to maintain window.opener for OAuth flows
- c.Response().Header().Set("Cross-Origin-Opener-Policy", "same-origin-allow-popups")
- // Prevent being embedded in iframes from different origins
- c.Response().Header().Set("X-Frame-Options", "SAMEORIGIN")
- // Prevent MIME-type sniffing
- c.Response().Header().Set("X-Content-Type-Options", "nosniff")
- // Force HTTPS in production (only if request is already HTTPS)
- if c.Request().TLS != nil || c.Request().Header.Get("X-Forwarded-Proto") == "https" {
- // max-age=31536000 (1 year), includeSubDomains for all subdomains
- c.Response().Header().Set("Strict-Transport-Security", "max-age=31536000; includeSubDomains")
+ return func(next echo.HandlerFunc) echo.HandlerFunc {
+ return func(c *echo.Context) error {
+ // Allow popups to maintain window.opener for OAuth flows
+ c.Response().Header().Set("Cross-Origin-Opener-Policy", "same-origin-allow-popups")
+ // Prevent being embedded in iframes from different origins
+ c.Response().Header().Set("X-Frame-Options", "SAMEORIGIN")
+ // Prevent MIME-type sniffing
+ c.Response().Header().Set("X-Content-Type-Options", "nosniff")
+ // Force HTTPS in production (only if request is already HTTPS)
+ if c.Request().TLS != nil || c.Request().Header.Get("X-Forwarded-Proto") == "https" {
+ // max-age=31536000 (1 year), includeSubDomains for all subdomains
+ c.Response().Header().Set("Strict-Transport-Security", "max-age=31536000; includeSubDomains")
+ }
+ c.Response().Header().Set("Content-Security-Policy", csp)
+ return next(c)
}
- c.Response().Header().Set("Content-Security-Policy", csp)
- return next(c)
}
}
diff --git a/backend/server/echo_routes_test.go b/backend/server/echo_routes_test.go
new file mode 100644
index 0000000000..8ba433270e
--- /dev/null
+++ b/backend/server/echo_routes_test.go
@@ -0,0 +1,78 @@
+package server
+
+import (
+ "net/http"
+ "net/http/httptest"
+ "strings"
+ "testing"
+
+ "github.com/labstack/echo/v5"
+)
+
+func TestSecurityHeadersMiddleware_GA4Sources(t *testing.T) {
+ tests := []struct {
+ name string
+ saas bool
+ wantGoogleGA4 bool
+ wantBaseSource []string
+ }{
+ {
+ name: "self-host does not allow GA4 sources",
+ saas: false,
+ wantGoogleGA4: false,
+ wantBaseSource: []string{
+ "script-src 'self'",
+ "connect-src 'self'",
+ "img-src 'self'",
+ },
+ },
+ {
+ name: "SaaS allows GA4 sources",
+ saas: true,
+ wantGoogleGA4: true,
+ wantBaseSource: []string{
+ "script-src 'self'",
+ "connect-src 'self'",
+ "img-src 'self'",
+ },
+ },
+ }
+
+ for _, tt := range tests {
+ t.Run(tt.name, func(t *testing.T) {
+ csp := testSecurityHeadersCSP(t, tt.saas)
+ for _, want := range tt.wantBaseSource {
+ if !strings.Contains(csp, want) {
+ t.Errorf("Content-Security-Policy = %q, want to contain %q", csp, want)
+ }
+ }
+ for _, googleSource := range []string{
+ "https://www.googletagmanager.com",
+ "https://*.google-analytics.com",
+ "https://*.analytics.google.com",
+ "https://*.googletagmanager.com",
+ } {
+ if got := strings.Contains(csp, googleSource); got != tt.wantGoogleGA4 {
+ t.Errorf("Content-Security-Policy contains %q = %t, want %t; csp=%q", googleSource, got, tt.wantGoogleGA4, csp)
+ }
+ }
+ })
+ }
+}
+
+func testSecurityHeadersCSP(t *testing.T, saas bool) string {
+ t.Helper()
+
+ e := echo.New()
+ req := httptest.NewRequest(http.MethodGet, "/", nil)
+ rec := httptest.NewRecorder()
+ c := e.NewContext(req, rec)
+
+ err := securityHeadersMiddleware(saas)(func(c *echo.Context) error {
+ return c.NoContent(http.StatusOK)
+ })(c)
+ if err != nil {
+ t.Fatal(err)
+ }
+ return rec.Header().Get("Content-Security-Policy")
+}
diff --git a/frontend/src/components/BytebaseLogo.test.tsx b/frontend/src/components/BytebaseLogo.test.tsx
index e9a6da43e4..6e171be35e 100644
--- a/frontend/src/components/BytebaseLogo.test.tsx
+++ b/frontend/src/components/BytebaseLogo.test.tsx
@@ -86,6 +86,10 @@ describe("BytebaseLogo", () => {
expect(img).not.toBeNull();
expect(img?.getAttribute("src")).toBe("https://example.com/logo.png");
expect(img?.getAttribute("alt")).toBe("Logo");
+ expect(img?.className).toContain("max-h-full");
+ expect(img?.className).toContain("max-w-full");
+ expect(img?.className).toContain("object-contain");
+ expect(container.firstElementChild?.className).toContain("h-10");
unmount();
});
@@ -99,6 +103,9 @@ describe("BytebaseLogo", () => {
expect(img).not.toBeNull();
expect(img?.getAttribute("src")).toBe("/assets/logo-full.svg");
expect(img?.getAttribute("alt")).toBe("Bytebase");
+ expect(img?.className).toContain("max-h-full");
+ expect(img?.className).toContain("max-w-full");
+ expect(img?.className).toContain("object-contain");
unmount();
});
diff --git a/frontend/src/components/BytebaseLogo.tsx b/frontend/src/components/BytebaseLogo.tsx
index 54edf94246..aecfc31606 100644
--- a/frontend/src/components/BytebaseLogo.tsx
+++ b/frontend/src/components/BytebaseLogo.tsx
@@ -36,13 +36,13 @@ export function BytebaseLogo({
<img
src={customLogo}
alt={t("settings.general.workspace.logo")}
- className="h-full object-contain"
+ className="max-h-full max-w-full object-contain"
/>
) : (
<img
src={builtinLogo}
alt="Bytebase"
- className="h-8 md:h-10 w-auto object-contain"
+ className="max-h-full max-w-full object-contain"
/>
)}
</span>
@@ -51,7 +51,7 @@ export function BytebaseLogo({
return (
<div
className={cn(
- "shrink-0 max-w-44 flex items-center overflow-hidden",
+ "h-10 shrink-0 max-w-44 flex items-center overflow-hidden",
className
)}
>
diff --git a/frontend/src/components/DashboardSidebar.test.tsx b/frontend/src/components/DashboardSidebar.test.tsx
index 3fe55faeee..d51a3d1c74 100644
--- a/frontend/src/components/DashboardSidebar.test.tsx
+++ b/frontend/src/components/DashboardSidebar.test.tsx
@@ -254,9 +254,17 @@ describe("DashboardSidebar", () => {
const logoLink = container.querySelector<HTMLAnchorElement>("nav > a");
expect(logoLink?.getAttribute("href")).toBe("/sql-editor");
+ expect(logoLink?.className).toContain("h-20");
+ expect(logoLink?.className).toContain("w-full");
expect(logoLink?.querySelector("img")?.getAttribute("src")).toBe(
"https://example.com/logo.png"
);
+ expect(logoLink?.querySelector("img")?.className).toContain("h-full");
+ expect(logoLink?.querySelector("img")?.className).toContain("w-full");
+ expect(logoLink?.querySelector("img")?.className).toContain("max-w-44");
+ expect(logoLink?.querySelector("img")?.className).toContain(
+ "object-contain"
+ );
act(() => {
logoLink?.dispatchEvent(
diff --git a/frontend/src/components/DashboardSidebar.tsx b/frontend/src/components/DashboardSidebar.tsx
index 025c86be58..784dd691be 100644
--- a/frontend/src/components/DashboardSidebar.tsx
+++ b/frontend/src/components/DashboardSidebar.tsx
@@ -499,10 +499,14 @@ export function DashboardSidebar() {
<nav className="flex-1 flex flex-col overflow-y-hidden border-r border-block-border">
<RouterLink
to={homeRoute}
- className="p-2 shrink-0 m-auto cursor-pointer"
+ className="h-20 w-full shrink-0 cursor-pointer flex items-center justify-center px-4"
onClick={handleHomeClick}
>
- <img src={logoSrc} alt="Bytebase" className="max-w-44" />
+ <img
+ src={logoSrc}
+ alt="Bytebase"
+ className="h-full w-full max-w-44 object-contain"
+ />
</RouterLink>
<MobileSidebarSwitchers />
<div className="flex-1 overflow-y-auto px-2.5 pb-4 flex flex-col gap-y-1">
diff --git a/frontend/src/components/EnvironmentLabel.test.tsx b/frontend/src/components/EnvironmentLabel.test.tsx
index 2d4a3dfe2f..3227e5a296 100644
--- a/frontend/src/components/EnvironmentLabel.test.tsx
+++ b/frontend/src/components/EnvironmentLabel.test.tsx
@@ -54,6 +54,11 @@ const environment = {
tags: {},
} as Environment;
+const defaultColorEnvironment = {
+ ...environment,
+ color: "",
+} as Environment;
+
describe("EnvironmentBadge", () => {
let root: Root | undefined;
@@ -78,4 +83,21 @@ describe("EnvironmentBadge", () => {
expect(link?.className).toBe("hover:underline");
expect(link?.textContent).toBe("Production");
});
+
+ test("uses readable default color with dark style options", async () => {
+ const rendered = await render(
+ <EnvironmentBadge
+ environment={defaultColorEnvironment}
+ hasEnvTierFeature={false}
+ styleOptions={{
+ defaultColorTextColor: "#818cf8",
+ backgroundAlpha: 0.18,
+ }}
+ />
+ );
+ root = rendered.root;
+
+ const badge = rendered.container.querySelector("span");
+ expect(badge?.style.color).toBe("rgb(129, 140, 248)");
+ });
});
diff --git a/frontend/src/components/EnvironmentLabel.tsx b/frontend/src/components/EnvironmentLabel.tsx
index 35cd24997f..9181cdc857 100644
--- a/frontend/src/components/EnvironmentLabel.tsx
+++ b/frontend/src/components/EnvironmentLabel.tsx
@@ -14,6 +14,8 @@ import {
import { PlanFeature } from "@/types/proto-es/v1/subscription_service_pb";
import { hexToRgb } from "@/utils";
+const LIGHT_BADGE_BACKGROUND_ALPHA = 0.1;
+
/**
* Pure-presentational environment badge — no hooks, no store reads.
*
@@ -28,11 +30,16 @@ export const EnvironmentBadge = memo(function EnvironmentBadge({
hasEnvTierFeature,
className,
link,
+ styleOptions,
}: {
environment: Environment;
hasEnvTierFeature: boolean;
className?: string;
link?: boolean;
+ styleOptions?: {
+ defaultColorTextColor?: string;
+ backgroundAlpha?: number;
+ };
}) {
const { t } = useTranslation();
@@ -41,9 +48,21 @@ export const EnvironmentBadge = memo(function EnvironmentBadge({
environment.name === NULL_ENVIRONMENT_NAME;
const isProtected =
hasEnvTierFeature && environment.tags?.protected === "protected";
- const bgColorRgb = isUnset
- ? null
- : hexToRgb(environment.color || DEFAULT_ENVIRONMENT_COLOR);
+ const color = environment.color || DEFAULT_ENVIRONMENT_COLOR;
+ const baseRgb = !isUnset ? hexToRgb(color) : [];
+ const displayRgb =
+ color.toLowerCase() === DEFAULT_ENVIRONMENT_COLOR.toLowerCase() &&
+ styleOptions?.defaultColorTextColor
+ ? hexToRgb(styleOptions.defaultColorTextColor)
+ : baseRgb;
+ const badgeStyle = !isUnset
+ ? {
+ backgroundColor: `rgba(${baseRgb.join(", ")}, ${
+ styleOptions?.backgroundAlpha ?? LIGHT_BADGE_BACKGROUND_ALPHA
+ })`,
+ color: `rgb(${displayRgb.join(", ")})`,
+ }
+ : undefined;
const badge = (
<span
@@ -51,14 +70,7 @@ export const EnvironmentBadge = memo(function EnvironmentBadge({
"inline-flex items-center gap-x-1 px-1.5 rounded-xs truncate",
className
)}
- style={
- bgColorRgb && !isUnset
- ? {
- backgroundColor: `rgba(${bgColorRgb.join(", ")}, 0.1)`,
- color: `rgb(${bgColorRgb.join(", ")})`,
- }
- : undefined
- }
+ style={badgeStyle}
>
<span className="truncate">
{isUnset ? (
@@ -108,11 +120,16 @@ export function EnvironmentLabel({
environmentName,
className,
link,
+ styleOptions,
}: {
environment?: Environment;
environmentName?: string;
className?: string;
link?: boolean;
+ styleOptions?: {
+ defaultColorTextColor?: string;
+ backgroundAlpha?: number;
+ };
}) {
// Always called (rules of hooks); result ignored when envProp is provided.
const envFromStore = useEnvironment(environmentName || NULL_ENVIRONMENT_NAME);
@@ -126,6 +143,7 @@ export function EnvironmentLabel({
hasEnvTierFeature={hasEnvTierFeature}
className={className}
link={link}
+ styleOptions={styleOptions}
/>
);
}
diff --git a/frontend/src/components/ProjectSidebar.test.tsx b/frontend/src/components/ProjectSidebar.test.tsx
index d76ffc41f2..6e062167b8 100644
--- a/frontend/src/components/ProjectSidebar.test.tsx
+++ b/frontend/src/components/ProjectSidebar.test.tsx
@@ -138,6 +138,7 @@ beforeEach(async () => {
projectId: "sample",
};
mocks.defaultProject = "";
+ mocks.workspace.logo = "";
({ ProjectSidebar } = await import("./ProjectSidebar"));
});
@@ -171,4 +172,24 @@ describe("ProjectSidebar", () => {
unmount();
});
+
+ test("gives the custom logo an explicit rendered size", () => {
+ mocks.workspace.logo = "https://example.com/logo.png";
+ const { container, render, unmount } = renderIntoContainer(
+ <ProjectSidebar />
+ );
+ render();
+
+ const logoLink = container.querySelector("nav > a");
+ const logo = container.querySelector("nav > a img");
+ expect(logoLink?.className).toContain("h-20");
+ expect(logoLink?.className).toContain("w-full");
+ expect(logo?.getAttribute("src")).toBe("https://example.com/logo.png");
+ expect(logo?.className).toContain("h-full");
+ expect(logo?.className).toContain("w-full");
+ expect(logo?.className).toContain("max-w-44");
+ expect(logo?.className).toContain("object-contain");
+
+ unmount();
+ });
});
diff --git a/frontend/src/components/ProjectSidebar.tsx b/frontend/src/components/ProjectSidebar.tsx
index 945bd345d5..b6d3a2506e 100644
--- a/frontend/src/components/ProjectSidebar.tsx
+++ b/frontend/src/components/ProjectSidebar.tsx
@@ -433,10 +433,14 @@ export function ProjectSidebar() {
<nav className="flex-1 flex flex-col overflow-y-hidden border-r border-block-border">
<RouterLink
to={homeRoute}
- className="p-2 shrink-0 m-auto cursor-pointer"
+ className="h-20 w-full shrink-0 cursor-pointer flex items-center justify-center px-4"
onClick={handleHomeClick}
>
- <img src={logoSrc} alt="Bytebase" className="max-w-44" />
+ <img
+ src={logoSrc}
+ alt="Bytebase"
+ className="h-full w-full max-w-44 object-contain"
+ />
</RouterLink>
<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))}
diff --git a/frontend/src/components/header/HeaderBreadcrumb.test.tsx b/frontend/src/components/header/HeaderBreadcrumb.test.tsx
index 2f3f468e62..a5c6f2824d 100644
--- a/frontend/src/components/header/HeaderBreadcrumb.test.tsx
+++ b/frontend/src/components/header/HeaderBreadcrumb.test.tsx
@@ -25,6 +25,7 @@ const mocks = vi.hoisted(() => ({
projectSwitchPanelProps: undefined as
| { excludeDefaultProject?: boolean }
| undefined,
+ onSelectWorkspace: vi.fn(),
switchWorkspace: vi.fn(),
workspaceList: [
{
@@ -216,6 +217,108 @@ describe("HeaderBreadcrumb", () => {
unmount();
});
+ test("uses custom project selection when clicking the project title", () => {
+ const onSelectProject = vi.fn();
+ const { container, render, unmount } = renderIntoContainer(
+ <HeaderBreadcrumb onSelectProject={onSelectProject} />
+ );
+
+ render();
+
+ expect(
+ container.querySelector(`a[data-route-name="${PROJECT_V1_ROUTE_ISSUES}"]`)
+ ).toBeNull();
+ const projectButton = Array.from(container.querySelectorAll("button")).find(
+ (button) => button.textContent?.includes("Recent Project")
+ );
+ expect(projectButton).not.toBeUndefined();
+
+ act(() => {
+ projectButton?.click();
+ });
+
+ expect(onSelectProject).toHaveBeenCalledTimes(1);
+ expect(onSelectProject).toHaveBeenCalledWith(
+ { name: "projects/recent-project", title: "Recent Project" },
+ expect.objectContaining({ ctrlKey: false, metaKey: false })
+ );
+ expect(mocks.record).not.toHaveBeenCalled();
+
+ unmount();
+ });
+
+ test("uses custom workspace selection when clicking the workspace title", () => {
+ const { container, render, unmount } = renderIntoContainer(
+ <HeaderBreadcrumb onSelectWorkspace={mocks.onSelectWorkspace} />
+ );
+
+ render();
+
+ expect(
+ container.querySelector('a[data-route-name="workspace.landing"]')
+ ).toBeNull();
+ const workspaceButton = Array.from(
+ container.querySelectorAll("button")
+ ).find((button) => button.textContent?.includes("Default Workspace"));
+ expect(workspaceButton).not.toBeUndefined();
+
+ act(() => {
+ workspaceButton?.click();
+ });
+
+ expect(mocks.onSelectWorkspace).toHaveBeenCalledWith(
+ "workspaces/default",
+ expect.objectContaining({ ctrlKey: false, metaKey: false })
+ );
+ expect(mocks.record).not.toHaveBeenCalled();
+
+ unmount();
+ });
+
+ test("uses custom workspace selection when switching workspace", () => {
+ mocks.workspaceList = [
+ {
+ name: "workspaces/default",
+ title: "Default Workspace",
+ },
+ {
+ name: "workspaces/other",
+ title: "Other Workspace",
+ },
+ ];
+ const onBeforeSwitchWorkspace = vi.fn(() => true);
+ const { container, render, unmount } = renderIntoContainer(
+ <HeaderBreadcrumb
+ onBeforeSwitchWorkspace={onBeforeSwitchWorkspace}
+ onSelectWorkspace={mocks.onSelectWorkspace}
+ />
+ );
+
+ render();
+
+ const workspaceSwitchButton = Array.from(
+ container.querySelectorAll("button")
+ ).find((button) => button.textContent === "");
+ act(() => {
+ workspaceSwitchButton?.click();
+ });
+ const otherWorkspaceButton = Array.from(
+ container.querySelectorAll("button")
+ ).find((button) => button.textContent?.includes("Other Workspace"));
+ act(() => {
+ otherWorkspaceButton?.click();
+ });
+
+ expect(onBeforeSwitchWorkspace).toHaveBeenCalledTimes(1);
+ expect(mocks.onSelectWorkspace).toHaveBeenCalledWith(
+ "workspaces/other",
+ expect.objectContaining({ ctrlKey: false, metaKey: false })
+ );
+ expect(mocks.switchWorkspace).not.toHaveBeenCalled();
+
+ unmount();
+ });
+
test("checks before switching workspace", () => {
mocks.workspaceList = [
{
diff --git a/frontend/src/components/header/HeaderBreadcrumb.tsx b/frontend/src/components/header/HeaderBreadcrumb.tsx
index c1012aa2ef..39b3832218 100644
--- a/frontend/src/components/header/HeaderBreadcrumb.tsx
+++ b/frontend/src/components/header/HeaderBreadcrumb.tsx
@@ -1,5 +1,10 @@
import { Building2, Check, ChevronDown, FolderKanban } from "lucide-react";
-import { useCallback, useEffect, useState } from "react";
+import {
+ type MouseEvent as ReactMouseEvent,
+ useCallback,
+ useEffect,
+ useState,
+} from "react";
import { useTranslation } from "react-i18next";
import {
useCurrentRoute,
@@ -41,6 +46,10 @@ export type HeaderBreadcrumbProps = {
currentProjectName?: string;
projectSwitchExcludeDefaultProject?: boolean;
onBeforeSwitchWorkspace?: () => boolean;
+ onSelectWorkspace?: (
+ workspaceName: string,
+ event: ReactMouseEvent<HTMLElement>
+ ) => void;
onSelectProject?: NonNullable<ProjectSwitchPanelProps["onSelectProject"]>;
};
@@ -78,7 +87,11 @@ function planVariant(
// ---------------------------------------------------------------------------
export function WorkspaceSegment({
onBeforeSwitchWorkspace,
-}: Pick<HeaderBreadcrumbProps, "onBeforeSwitchWorkspace"> = {}) {
+ onSelectWorkspace,
+}: Pick<
+ HeaderBreadcrumbProps,
+ "onBeforeSwitchWorkspace" | "onSelectWorkspace"
+> = {}) {
const { t } = useTranslation();
const workspace = useWorkspace();
const workspaceList = useWorkspaceList();
@@ -93,36 +106,66 @@ export function WorkspaceSegment({
const navigate = useNavigate();
const onSwitch = useCallback(
- (workspaceName: string) => {
+ (workspaceName: string, event: ReactMouseEvent<HTMLElement>) => {
if (workspaceName === currentWorkspaceName) return;
if (onBeforeSwitchWorkspace && !onBeforeSwitchWorkspace()) return;
setOpen(false);
+ if (onSelectWorkspace) {
+ onSelectWorkspace(workspaceName, event);
+ return;
+ }
void switchWorkspace(workspaceName);
},
- [currentWorkspaceName, onBeforeSwitchWorkspace, switchWorkspace]
+ [
+ currentWorkspaceName,
+ onBeforeSwitchWorkspace,
+ onSelectWorkspace,
+ switchWorkspace,
+ ]
);
return (
<div className="inline-flex items-center">
- <RouterLink
- to={{ 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" />
- <span className="truncate max-w-40">{workspace?.title}</span>
- {label && (
- <Badge
- variant={planVariant(currentPlan)}
- className="text-[10px] px-1.5 py-0 hidden lg:block"
- >
- {label}
- </Badge>
- )}
- </RouterLink>
+ {onSelectWorkspace ? (
+ <Button
+ type="button"
+ appearance="secondary"
+ size="sm"
+ onClick={(event) => onSelectWorkspace(currentWorkspaceName, event)}
+ className="h-auto px-2 py-1 text-sm gap-x-1.5"
+ >
+ <Building2 className="size-4 text-control-light shrink-0" />
+ <span className="truncate max-w-40">{workspace?.title}</span>
+ {label && (
+ <Badge
+ variant={planVariant(currentPlan)}
+ className="text-[10px] px-1.5 py-0 hidden lg:block"
+ >
+ {label}
+ </Badge>
+ )}
+ </Button>
+ ) : (
+ <RouterLink
+ to={{ 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" />
+ <span className="truncate max-w-40">{workspace?.title}</span>
+ {label && (
+ <Badge
+ variant={planVariant(currentPlan)}
+ className="text-[10px] px-1.5 py-0 hidden lg:block"
+ >
+ {label}
+ </Badge>
+ )}
+ </RouterLink>
+ )}
{hasMultiple && (
<Popover open={open} onOpenChange={setOpen}>
<PopoverTrigger
@@ -154,7 +197,7 @@ export function WorkspaceSegment({
? "bg-control-bg font-medium text-accent"
: "text-control hover:bg-control-bg"
)}
- onClick={() => onSwitch(ws.name)}
+ onClick={(event) => onSwitch(ws.name, event)}
>
<span className="flex flex-col items-start min-w-0">
<span className="truncate w-full text-left">
@@ -217,23 +260,36 @@ export function ProjectSegment({
<>
<div className="inline-flex items-center">
{hasProject && projectId ? (
- <RouterLink
- to={{
- name: PROJECT_V1_ROUTE_ISSUES,
- params: { projectId },
- }}
- onClick={() => {
- const resolvedRoute = navigate.resolve({
+ onSelectProject ? (
+ <Button
+ type="button"
+ appearance="secondary"
+ size="sm"
+ onClick={(event) => onSelectProject(currentProject, event)}
+ className="h-auto px-2 py-1 text-sm gap-x-1.5"
+ >
+ <FolderKanban className="size-4 text-control-light shrink-0" />
+ <span className="truncate max-w-48">{currentProject.title}</span>
+ </Button>
+ ) : (
+ <RouterLink
+ to={{
name: PROJECT_V1_ROUTE_ISSUES,
params: { projectId },
- });
- record(resolvedRoute.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"
- >
- <FolderKanban className="size-4 text-control-light shrink-0" />
- <span className="truncate max-w-48">{currentProject.title}</span>
- </RouterLink>
+ }}
+ onClick={() => {
+ const resolvedRoute = navigate.resolve({
+ name: PROJECT_V1_ROUTE_ISSUES,
+ params: { projectId },
+ });
+ record(resolvedRoute.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"
+ >
+ <FolderKanban className="size-4 text-control-light shrink-0" />
+ <span className="truncate max-w-48">{currentProject.title}</span>
+ </RouterLink>
+ )
) : (
<div className="inline-flex items-center gap-x-1.5 rounded-xs px-2 py-1 text-sm font-medium text-control">
<FolderKanban className="size-4 text-control-light shrink-0" />
@@ -291,12 +347,16 @@ export function HeaderBreadcrumb({
currentProjectName,
projectSwitchExcludeDefaultProject,
onBeforeSwitchWorkspace,
+ onSelectWorkspace,
onSelectProject,
}: HeaderBreadcrumbProps = {}) {
return (
<div className="flex items-center gap-x-1">
<div className="hidden md:flex items-center gap-x-1">
- <WorkspaceSegment onBeforeSwitchWorkspace={onBeforeSwitchWorkspace} />
+ <WorkspaceSegment
+ onBeforeSwitchWorkspace={onBeforeSwitchWorkspace}
+ onSelectWorkspace={onSelectWorkspace}
+ />
<span className="text-control-placeholder select-none">/</span>
</div>
<ProjectSegment
diff --git a/frontend/src/components/instance/CredentialSourceForm.test.tsx b/frontend/src/components/instance/CredentialSourceForm.test.tsx
index 77f7bf698d..a7dbc2d81e 100644
--- a/frontend/src/components/instance/CredentialSourceForm.test.tsx
+++ b/frontend/src/components/instance/CredentialSourceForm.test.tsx
@@ -1,12 +1,13 @@
import { create } from "@bufbuild/protobuf";
-import type { ReactElement } from "react";
+import { type ReactElement, useState } from "react";
import { act } from "react";
import { createRoot } from "react-dom/client";
-import { describe, expect, test, vi } from "vitest";
+import { beforeEach, describe, expect, test, vi } from "vitest";
import { Engine } from "@/types/proto-es/v1/common_pb";
import {
DataSource_AuthenticationType,
DataSource_CloudSQLIPType,
+ DataSource_GCPCredentialSchema,
DataSourceSchema,
} from "@/types/proto-es/v1/instance_service_pb";
import {
@@ -27,9 +28,11 @@ vi.mock("react-i18next", () => ({
}),
}));
+const serverState = vi.hoisted(() => ({ isSaaSMode: false }));
+
vi.mock("@/hooks/useAppState", () => ({
useServerState: () => ({
- isSaaSMode: false,
+ isSaaSMode: serverState.isSaaSMode,
}),
}));
@@ -67,6 +70,10 @@ function render(element: ReactElement) {
}
describe("CredentialSourceForm", () => {
+ beforeEach(() => {
+ serverState.isSaaSMode = false;
+ });
+
test.each([
[
DataSource_AuthenticationType.AZURE_IAM,
@@ -80,20 +87,23 @@ describe("CredentialSourceForm", () => {
DataSource_AuthenticationType.GOOGLE_CLOUD_SQL_IAM,
"instance.iam-extension.default-credential.gcp",
],
- ])("renders default credential help through i18n for authentication type %s", (authenticationType, expectedKey) => {
- const { container, unmount } = render(
- <CredentialSourceForm
- dataSource={makeDataSource(authenticationType)}
- engine={Engine.POSTGRES}
- allowEdit={true}
- onDataSourceChange={vi.fn()}
- />
- );
+ ])(
+ "renders default credential help through i18n for authentication type %s",
+ (authenticationType, expectedKey) => {
+ const { container, unmount } = render(
+ <CredentialSourceForm
+ dataSource={makeDataSource(authenticationType)}
+ engine={Engine.POSTGRES}
+ allowEdit={true}
+ onDataSourceChange={vi.fn()}
+ />
+ );
- expect(container.textContent).toContain(expectedKey);
+ expect(container.textContent).toContain(expectedKey);
- unmount();
- });
+ unmount();
+ }
+ );
test("shows the Cloud SQL IP selector only for Cloud SQL MySQL/Postgres IAM", () => {
const { GOOGLE_CLOUD_SQL_IAM, PASSWORD } = DataSource_AuthenticationType;
@@ -153,4 +163,104 @@ describe("CredentialSourceForm", () => {
expect(offeredCloudSQLIPTypes(PRIVATE)).toEqual([PUBLIC, PRIVATE]);
expect(offeredCloudSQLIPTypes(PSC)).toEqual([PUBLIC, PRIVATE, PSC]);
});
+
+ test("keeps the specific credential source selected after changing from default", () => {
+ function StatefulCredentialSourceForm() {
+ const [dataSource, setDataSource] = useState<EditDataSource>(() =>
+ makeDataSource(DataSource_AuthenticationType.GOOGLE_CLOUD_SQL_IAM)
+ );
+ return (
+ <CredentialSourceForm
+ dataSource={dataSource}
+ engine={Engine.POSTGRES}
+ allowEdit={true}
+ onDataSourceChange={(updates) =>
+ setDataSource((prev) => ({ ...prev, ...updates }))
+ }
+ />
+ );
+ }
+
+ const { container, unmount } = render(<StatefulCredentialSourceForm />);
+
+ const radios = container.querySelectorAll('[role="radio"]');
+ const specificCredential = radios[1] as HTMLElement;
+ act(() => {
+ specificCredential.click();
+ });
+
+ expect(specificCredential.getAttribute("aria-checked")).toBe("true");
+ expect(
+ container.querySelector("textarea")?.getAttribute("placeholder")
+ ).toBe("instance.type-or-paste-credentials-write-only");
+
+ unmount();
+ });
+
+ test("keeps the SaaS-forced specific credential source stable", () => {
+ serverState.isSaaSMode = true;
+
+ function StatefulCredentialSourceForm() {
+ const [dataSource, setDataSource] = useState<EditDataSource>(() =>
+ makeDataSource(DataSource_AuthenticationType.GOOGLE_CLOUD_SQL_IAM)
+ );
+ return (
+ <CredentialSourceForm
+ dataSource={dataSource}
+ engine={Engine.POSTGRES}
+ allowEdit={true}
+ onDataSourceChange={(updates) =>
+ setDataSource((prev) => ({ ...prev, ...updates }))
+ }
+ />
+ );
+ }
+
+ const { container, unmount } = render(<StatefulCredentialSourceForm />);
+
+ const radios = container.querySelectorAll('[role="radio"]');
+ const defaultCredential = radios[0] as HTMLElement;
+ const specificCredential = radios[1] as HTMLElement;
+
+ expect(defaultCredential.getAttribute("aria-checked")).toBe("false");
+ expect(specificCredential.getAttribute("aria-checked")).toBe("true");
+ expect(
+ container.querySelector("textarea")?.getAttribute("placeholder")
+ ).toBe("instance.type-or-paste-credentials-write-only");
+
+ unmount();
+ });
+
+ test("does not rewrite a credential that is already specific", () => {
+ const onDataSourceChange = vi.fn();
+ const dataSource = makeDataSource(
+ DataSource_AuthenticationType.GOOGLE_CLOUD_SQL_IAM
+ );
+ dataSource.iamExtension = {
+ case: "gcpCredential",
+ value: create(DataSource_GCPCredentialSchema, {
+ content: "{}",
+ }),
+ };
+
+ const { container, unmount } = render(
+ <CredentialSourceForm
+ dataSource={dataSource}
+ engine={Engine.POSTGRES}
+ allowEdit={true}
+ onDataSourceChange={onDataSourceChange}
+ />
+ );
+
+ const radios = container.querySelectorAll('[role="radio"]');
+ const specificCredential = radios[1] as HTMLElement;
+ act(() => {
+ specificCredential.click();
+ });
+
+ expect(specificCredential.getAttribute("aria-checked")).toBe("true");
+ expect(onDataSourceChange).not.toHaveBeenCalled();
+
+ unmount();
+ });
});
diff --git a/frontend/src/components/instance/CredentialSourceForm.tsx b/frontend/src/components/instance/CredentialSourceForm.tsx
index bcc6910d06..07ef9bae50 100644
--- a/frontend/src/components/instance/CredentialSourceForm.tsx
+++ b/frontend/src/components/instance/CredentialSourceForm.tsx
@@ -48,47 +48,34 @@ function CredentialSourceForm({
const isDefaultCredentialDisabled = isSaaSMode && isIAMAuthentication;
- const deriveCredentialSource = useCallback((): CredentialSource => {
- const ext = dataSource.iamExtension;
- if (
- ext?.case === "azureCredential" ||
- ext?.case === "awsCredential" ||
- ext?.case === "gcpCredential"
- ) {
- return "specific-credential";
- }
- return "default";
- }, [dataSource.iamExtension]);
-
- const [credentialSource, setCredentialSource] = useState<CredentialSource>(
- () => {
- const derived = deriveCredentialSource();
- if (isDefaultCredentialDisabled && derived === "default") {
- return "specific-credential";
- }
- return derived;
- }
- );
-
- // Sync credentialSource when iamExtension changes externally
- useEffect(() => {
- setCredentialSource(deriveCredentialSource());
- }, [deriveCredentialSource]);
-
- // Force specific credential in SaaS mode for IAM authentication
- useEffect(() => {
- if (isDefaultCredentialDisabled && credentialSource === "default") {
- setCredentialSource("specific-credential");
+ const expectedCredentialCase = useMemo(() => {
+ switch (dataSource.authenticationType) {
+ case DataSource_AuthenticationType.AWS_RDS_IAM:
+ return "awsCredential";
+ case DataSource_AuthenticationType.GOOGLE_CLOUD_SQL_IAM:
+ return "gcpCredential";
+ case DataSource_AuthenticationType.AZURE_IAM:
+ return "azureCredential";
+ default:
+ return undefined;
}
- }, [isDefaultCredentialDisabled, credentialSource]);
-
- // When credential source changes, update the iamExtension on the dataSource
- useEffect(() => {
- const authType = dataSource.authenticationType;
- if (credentialSource === "default") {
- onDataSourceChange({ iamExtension: { case: undefined } });
+ }, [dataSource.authenticationType]);
+ const hasCredentialForAuthenticationType =
+ dataSource.iamExtension?.case === expectedCredentialCase;
+ const credentialSource: CredentialSource =
+ hasCredentialForAuthenticationType || isDefaultCredentialDisabled
+ ? "specific-credential"
+ : "default";
+
+ const clearCredential = useCallback(() => {
+ onDataSourceChange({ iamExtension: { case: undefined } });
+ }, [onDataSourceChange]);
+
+ const applySpecificCredential = useCallback(() => {
+ if (dataSource.iamExtension?.case === expectedCredentialCase) {
return;
}
+ const authType = dataSource.authenticationType;
switch (authType) {
case DataSource_AuthenticationType.AWS_RDS_IAM:
onDataSourceChange({
@@ -130,16 +117,32 @@ function CredentialSourceForm({
});
break;
}
- }, [credentialSource]);
+ }, [
+ dataSource.authenticationType,
+ dataSource.iamExtension,
+ expectedCredentialCase,
+ onDataSourceChange,
+ ]);
- // Reset to default when authentication type changes
- const [prevAuthType, setPrevAuthType] = useState(
- dataSource.authenticationType
- );
- if (dataSource.authenticationType !== prevAuthType) {
- setPrevAuthType(dataSource.authenticationType);
- setCredentialSource("default");
- }
+ useEffect(() => {
+ if (
+ dataSource.iamExtension?.case &&
+ dataSource.iamExtension.case !== expectedCredentialCase
+ ) {
+ clearCredential();
+ return;
+ }
+ if (isDefaultCredentialDisabled && !hasCredentialForAuthenticationType) {
+ applySpecificCredential();
+ }
+ }, [
+ applySpecificCredential,
+ clearCredential,
+ dataSource.iamExtension?.case,
+ expectedCredentialCase,
+ hasCredentialForAuthenticationType,
+ isDefaultCredentialDisabled,
+ ]);
const options = useMemo(
() => [
@@ -158,7 +161,11 @@ function CredentialSourceForm({
const handleCredentialSourceChange = (value: CredentialSource) => {
if (!allowEdit) return;
- setCredentialSource(value);
+ if (value === "default") {
+ clearCredential();
+ return;
+ }
+ applySpecificCredential();
};
const updateAzureField = (
diff --git a/frontend/src/components/ui/checkbox.tsx b/frontend/src/components/ui/checkbox.tsx
index 171bc51a7a..400927d67b 100644
--- a/frontend/src/components/ui/checkbox.tsx
+++ b/frontend/src/components/ui/checkbox.tsx
@@ -44,7 +44,7 @@ function Checkbox({
indeterminate={indeterminate}
onCheckedChange={(value) => onCheckedChange?.(value)}
className={cn(
- "inline-flex shrink-0 items-center justify-center align-middle rounded-sm border bg-background transition-colors",
+ "inline-flex shrink-0 items-center justify-center align-middle rounded-sm border-2 bg-background transition-colors",
ROOT_SIZE[size],
"border-control-border hover:border-accent/60",
"data-[checked]:bg-accent data-[checked]:border-accent",
diff --git a/frontend/src/lib/ga4.test.ts b/frontend/src/lib/ga4.test.ts
new file mode 100644
index 0000000000..492d928c84
--- /dev/null
+++ b/frontend/src/lib/ga4.test.ts
@@ -0,0 +1,67 @@
+import { afterEach, describe, expect, test } from "vitest";
+import { initializeGA4 } from "./ga4";
+
+const ga4ScriptSelector = "script#bytebase-ga4-tag";
+
+declare global {
+ interface Window {
+ dataLayer?: unknown[][];
+ gtag?: (...args: unknown[]) => void;
+ }
+}
+
+afterEach(() => {
+ document.querySelector(ga4ScriptSelector)?.remove();
+ delete window.dataLayer;
+ delete window.gtag;
+ window.history.replaceState(null, "", "/");
+});
+
+describe("initializeGA4", () => {
+ test("does not load GA4 outside SaaS mode", () => {
+ initializeGA4(false);
+
+ expect(document.querySelector(ga4ScriptSelector)).toBeNull();
+ expect(window.dataLayer).toBeUndefined();
+ expect(window.gtag).toBeUndefined();
+ });
+
+ test("loads the shared GA4 property in SaaS mode", () => {
+ initializeGA4(true);
+
+ const script = document.querySelector<HTMLScriptElement>(ga4ScriptSelector);
+ expect(script?.async).toBe(true);
+ expect(script?.src).toBe(
+ "https://www.googletagmanager.com/gtag/js?id=G-4BZ4JH7449"
+ );
+ expect(window.dataLayer).toHaveLength(2);
+ expect(window.dataLayer?.[0][0]).toBe("js");
+ expect(window.dataLayer?.[1]).toEqual([
+ "config",
+ "G-4BZ4JH7449",
+ {
+ page_location: `${window.location.origin}/`,
+ page_path: "/",
+ },
+ ]);
+ });
+
+ test("sanitizes the initial page view URL", () => {
+ window.history.replaceState(
+ null,
+ "",
+ "/oauth/callback?code=secret&state=token#fragment"
+ );
+
+ initializeGA4(true);
+
+ expect(window.dataLayer?.[1]).toEqual([
+ "config",
+ "G-4BZ4JH7449",
+ {
+ page_location: `${window.location.origin}/oauth/callback`,
+ page_path: "/oauth/callback",
+ },
+ ]);
+ });
+});
diff --git a/frontend/src/lib/ga4.ts b/frontend/src/lib/ga4.ts
new file mode 100644
index 0000000000..46a74c6a7e
--- /dev/null
+++ b/frontend/src/lib/ga4.ts
@@ -0,0 +1,30 @@
+const GA4_MEASUREMENT_ID = "G-4BZ4JH7449";
+const GA4_SCRIPT_ID = "bytebase-ga4-tag";
+
+type GAWindow = Window & {
+ dataLayer?: unknown[][];
+ gtag?: (...args: unknown[]) => void;
+};
+
+export function initializeGA4(isSaaSMode: boolean): void {
+ if (!isSaaSMode || document.getElementById(GA4_SCRIPT_ID)) {
+ return;
+ }
+
+ const script = document.createElement("script");
+ script.id = GA4_SCRIPT_ID;
+ script.async = true;
+ script.src = `https://www.googletagmanager.com/gtag/js?id=${GA4_MEASUREMENT_ID}`;
+ document.head.appendChild(script);
+
+ const gaWindow = window as GAWindow;
+ gaWindow.dataLayer = gaWindow.dataLayer || [];
+ gaWindow.gtag = (...args: unknown[]) => {
+ gaWindow.dataLayer?.push(args);
+ };
+ gaWindow.gtag("js", new Date());
+ gaWindow.gtag("config", GA4_MEASUREMENT_ID, {
+ page_location: `${window.location.origin}${window.location.pathname}`,
+ page_path: window.location.pathname,
+ });
+}
diff --git a/frontend/src/main.ts b/frontend/src/main.ts
index e31ddbcc6d..18e7d1a78d 100644
--- a/frontend/src/main.ts
+++ b/frontend/src/main.ts
@@ -8,6 +8,7 @@ import "./stylex-dev-css";
// registers the SQL highlight.js language + theme used across the app.
import "./lib/dayjs";
import "./lib/highlight";
+import { initializeGA4 } from "./lib/ga4";
import { useAppStore } from "./stores/app";
import { isDev, isRelease, migrateStorageKeys } from "./utils";
@@ -31,6 +32,7 @@ migrateStorageKeys();
initPromises.push(store.loadWorkspaceProfile());
}
await Promise.all(initPromises);
+ initializeGA4(store.isSaaSMode());
const { mountReactRouterApp } = await import("./app/mountApp");
await mountReactRouterApp("#app");
diff --git a/frontend/src/modules/sql-editor/components/ConnectionPane/TreeNode/Label.test.tsx b/frontend/src/modules/sql-editor/components/ConnectionPane/TreeNode/Label.test.tsx
index 2391ce295a..83376e3e90 100644
--- a/frontend/src/modules/sql-editor/components/ConnectionPane/TreeNode/Label.test.tsx
+++ b/frontend/src/modules/sql-editor/components/ConnectionPane/TreeNode/Label.test.tsx
@@ -8,6 +8,14 @@ import type { SQLEditorTreeNode } from "@/types";
globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }
).IS_REACT_ACT_ENVIRONMENT = true;
+const mocks = vi.hoisted(() => ({
+ EnvironmentLabel: vi.fn(
+ ({ environment }: { environment: { title: string } }) => (
+ <span data-testid="SharedEnvironmentLabel">{environment.title}</span>
+ )
+ ),
+}));
+
vi.mock("./InstanceNode", () => ({
InstanceNode: () => <div data-testid="InstanceNode" />,
}));
@@ -17,19 +25,19 @@ vi.mock("./DatabaseNode", () => ({
vi.mock("./LabelNode", () => ({
LabelNode: () => <div data-testid="LabelNode" />,
}));
-vi.mock("@/modules/sql-editor/hooks/useSQLEditorState", () => ({
- useSQLEditorFeature: () => false,
+vi.mock("@/components/EnvironmentLabel", () => ({
+ EnvironmentLabel: mocks.EnvironmentLabel,
}));
-vi.mock("@/types/proto-es/v1/subscription_service_pb", () => ({
- PlanFeature: { FEATURE_ENVIRONMENT_TIERS: "FEATURE_ENVIRONMENT_TIERS" },
-}));
-vi.mock("@/types", () => ({
- NULL_ENVIRONMENT_NAME: "environments/-",
- UNKNOWN_ENVIRONMENT_NAME: "environments/-1",
- DEFAULT_ENVIRONMENT_COLOR: "#4f46e5",
+vi.mock("@/modules/sql-editor/components/theme/SQLEditorThemeScope", () => ({
+ useSQLEditorTheme: () => ({
+ tokens: {
+ "--color-background": "#1e1e1e",
+ "--color-accent-hover": "#818cf8",
+ },
+ }),
}));
-vi.mock("@/utils", () => ({
- hexToRgb: () => [128, 128, 128],
+vi.mock("@/modules/sql-editor/components/theme/derive", () => ({
+ isDarkTheme: () => true,
}));
let Label: typeof import("./Label").Label;
@@ -70,6 +78,7 @@ const makeNode = (
}) as unknown as SQLEditorTreeNode;
beforeEach(async () => {
+ vi.clearAllMocks();
({ Label } = await import("./Label"));
});
@@ -113,4 +122,29 @@ describe("Label", () => {
expect(container.textContent).toContain("Dev");
unmount();
});
+
+ test("uses shared EnvironmentLabel for type=environment", () => {
+ const { container, render, unmount } = renderIntoContainer(
+ <Label node={makeNode("environment")} keyword="Dev" checked={false} />
+ );
+ render();
+ expect(
+ container.querySelector("[data-testid='SharedEnvironmentLabel']")
+ ).not.toBeNull();
+ expect(mocks.EnvironmentLabel).toHaveBeenCalledWith(
+ expect.objectContaining({
+ environment: expect.objectContaining({ title: "Dev" }),
+ link: false,
+ styleOptions: {
+ defaultColorTextColor: "#818cf8",
+ backgroundAlpha: 0.18,
+ },
+ }),
+ undefined
+ );
+ expect(mocks.EnvironmentLabel.mock.calls[0][0]).not.toHaveProperty(
+ "keyword"
+ );
+ unmount();
+ });
});
diff --git a/frontend/src/modules/sql-editor/components/ConnectionPane/TreeNode/Label.tsx b/frontend/src/modules/sql-editor/components/ConnectionPane/TreeNode/Label.tsx
index ce6de8fab5..044bda55ac 100644
--- a/frontend/src/modules/sql-editor/components/ConnectionPane/TreeNode/Label.tsx
+++ b/frontend/src/modules/sql-editor/components/ConnectionPane/TreeNode/Label.tsx
@@ -1,16 +1,7 @@
-import { ShieldAlert } from "lucide-react";
-import { useTranslation } from "react-i18next";
-import { HighlightLabelText } from "@/components/HighlightLabelText";
-import { cn } from "@/lib/utils";
-import { useSQLEditorFeature } from "@/modules/sql-editor/hooks/useSQLEditorState";
+import { EnvironmentLabel } from "@/components/EnvironmentLabel";
+import { isDarkTheme } from "@/modules/sql-editor/components/theme/derive";
+import { useSQLEditorTheme } from "@/modules/sql-editor/components/theme/SQLEditorThemeScope";
import type { SQLEditorTreeNode } from "@/types";
-import {
- DEFAULT_ENVIRONMENT_COLOR,
- NULL_ENVIRONMENT_NAME,
- UNKNOWN_ENVIRONMENT_NAME,
-} from "@/types";
-import { PlanFeature } from "@/types/proto-es/v1/subscription_service_pb";
-import { hexToRgb } from "@/utils";
import { DatabaseNode } from "./DatabaseNode";
import { InstanceNode } from "./InstanceNode";
import { LabelNode } from "./LabelNode";
@@ -37,7 +28,7 @@ export function Label(props: Props) {
return <InstanceNode node={node} keyword={keyword} />;
}
if (type === "environment") {
- return <EnvironmentLabel node={node} keyword={keyword} />;
+ return <EnvironmentNodeLabel node={node} />;
}
if (type === "database") {
return (
@@ -57,61 +48,23 @@ export function Label(props: Props) {
return null;
}
-/**
- * Inline environment-name renderer — mirrors the subset of
- * `EnvironmentV1Name` props the tree uses (link=false, keyword highlight,
- * optional color tint, production shield).
- */
-function EnvironmentLabel({
- node,
- keyword,
-}: {
- node: SQLEditorTreeNode;
- keyword: string;
-}) {
- const { t } = useTranslation();
+function EnvironmentNodeLabel({ node }: Readonly<{ node: SQLEditorTreeNode }>) {
const environment = (node as SQLEditorTreeNode<"environment">).meta.target;
- const isUnset =
- environment.name === UNKNOWN_ENVIRONMENT_NAME ||
- environment.name === NULL_ENVIRONMENT_NAME;
- const hasEnvTierFeature = useSQLEditorFeature(
- PlanFeature.FEATURE_ENVIRONMENT_TIERS
- );
- const isProtected =
- hasEnvTierFeature && environment.tags?.protected === "protected";
- const bgColorRgb = isUnset
- ? null
- : hexToRgb(environment.color || DEFAULT_ENVIRONMENT_COLOR);
+ const theme = useSQLEditorTheme();
+ const darkTheme = isDarkTheme(theme);
return (
- <span
- className={cn(
- "inline-flex items-center gap-x-1 select-none truncate",
- bgColorRgb && "px-1.5 rounded-xs"
- )}
- style={
- bgColorRgb
+ <EnvironmentLabel
+ environment={environment}
+ link={false}
+ styleOptions={
+ darkTheme
? {
- backgroundColor: `rgba(${bgColorRgb.join(", ")}, 0.1)`,
- color: `rgb(${bgColorRgb.join(", ")})`,
+ defaultColorTextColor: theme.tokens["--color-accent-hover"],
+ backgroundAlpha: 0.18,
}
: undefined
}
- >
- {isUnset ? (
- // Matches the shared <EnvironmentLabel> treatment: the store's
- // getEnvironmentByName fallback sets `title = id` for unknown envs,
- // so rendering `environment.title` would surface raw "-1" in the
- // tree. Show a localized italic placeholder instead.
- <span className="text-control-light italic">
- {t("common.unassigned")}
- </span>
- ) : (
- <HighlightLabelText text={environment.title} keyword={keyword} />
- )}
- {isProtected && !isUnset && (
- <ShieldAlert className="size-3.5 shrink-0 text-current" />
- )}
- </span>
+ />
);
}
diff --git a/frontend/src/modules/sql-editor/components/FolderForm.test.tsx b/frontend/src/modules/sql-editor/components/FolderForm.test.tsx
index e5982ee162..6e2777b1de 100644
--- a/frontend/src/modules/sql-editor/components/FolderForm.test.tsx
+++ b/frontend/src/modules/sql-editor/components/FolderForm.test.tsx
@@ -121,11 +121,13 @@ vi.mock("@/components/ui/input", () => ({
placeholder,
onFocus,
onChange,
+ autoComplete,
}: {
value?: string;
placeholder?: string;
onFocus?: () => void;
onChange?: (e: React.ChangeEvent<HTMLInputElement>) => void;
+ autoComplete?: string;
}) => (
<input
data-testid="folder-input"
@@ -133,6 +135,7 @@ vi.mock("@/components/ui/input", () => ({
placeholder={placeholder}
onFocus={onFocus}
onChange={onChange}
+ autoComplete={autoComplete}
readOnly={!onChange}
/>
),
@@ -233,6 +236,21 @@ describe("FolderForm", () => {
unmount();
});
+ test("folder input disables browser autocomplete", () => {
+ const { container, render, unmount } = renderIntoContainer(
+ <FolderForm folder="/my/foo" onFolderChange={vi.fn()} />
+ );
+ render();
+
+ const input = container.querySelector(
+ "[data-testid='folder-input']"
+ ) as HTMLInputElement;
+ expect(input).not.toBeNull();
+ expect(input.autocomplete).toBe("off");
+
+ unmount();
+ });
+
test("focusing the input opens the popover", () => {
const { container, render, unmount } = renderIntoContainer(
<FolderForm folder="/my" onFolderChange={vi.fn()} />
diff --git a/frontend/src/modules/sql-editor/components/FolderForm.tsx b/frontend/src/modules/sql-editor/components/FolderForm.tsx
index e8d2c289c7..9cf3af5357 100644
--- a/frontend/src/modules/sql-editor/components/FolderForm.tsx
+++ b/frontend/src/modules/sql-editor/components/FolderForm.tsx
@@ -118,6 +118,7 @@ export function FolderForm({ folder, onFolderChange }: Props) {
data-testid="folder-input"
value={formattedFolderPath}
placeholder={t("sql-editor.choose-folder")}
+ autoComplete="off"
onFocus={() => setShowPopover(true)}
onClick={() => setShowPopover(true)}
onChange={(e) => handleInput(e.target.value)}
diff --git a/frontend/src/modules/sql-editor/components/SQLEditorHeader.test.tsx b/frontend/src/modules/sql-editor/components/SQLEditorHeader.test.tsx
index f5d9caad65..555ffc3c02 100644
--- a/frontend/src/modules/sql-editor/components/SQLEditorHeader.test.tsx
+++ b/frontend/src/modules/sql-editor/components/SQLEditorHeader.test.tsx
@@ -2,7 +2,6 @@ import type { ReactElement, ReactNode } from "react";
import { act } from "react";
import { createRoot } from "react-dom/client";
import { beforeEach, describe, expect, test, vi } from "vitest";
-import { WORKSPACE_ROUTE_LANDING } from "@/app/router";
(
globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }
@@ -15,6 +14,10 @@ const mocks = vi.hoisted(() => ({
currentProjectName?: string;
projectSwitchExcludeDefaultProject?: boolean;
onBeforeSwitchWorkspace?: () => boolean;
+ onSelectWorkspace?: (
+ workspaceName: string,
+ event: { ctrlKey?: boolean; metaKey?: boolean }
+ ) => void;
onSelectProject?: (
project: { name: string },
event: { ctrlKey?: boolean; metaKey?: boolean }
@@ -23,6 +26,9 @@ const mocks = vi.hoisted(() => ({
| undefined,
maybeSwitchProject: vi.fn().mockResolvedValue(undefined),
record: vi.fn(),
+ switchWorkspace: vi.fn().mockResolvedValue(undefined),
+ assignLocation: vi.fn(),
+ push: vi.fn(),
setRecentProject: vi.fn(),
loadWorkspacePermissionState: vi.fn().mockResolvedValue(undefined),
hasProjectPermission: vi.fn(),
@@ -57,9 +63,11 @@ vi.mock("react-i18next", () => ({
}));
vi.mock("@/app/router", () => ({
+ SQL_EDITOR_HOME_MODULE: "sql-editor.home",
SQL_EDITOR_PROJECT_MODULE: "sql-editor.project",
WORKSPACE_ROUTE_LANDING: "workspace.landing",
useNavigate: () => ({
+ push: mocks.push,
resolve: mocks.resolve,
}),
}));
@@ -68,6 +76,10 @@ vi.mock("@/hooks/useAppState", () => ({
useRecentVisit: () => ({
record: mocks.record,
}),
+ useSwitchWorkspace: () => mocks.switchWorkspace,
+ useWorkspace: () => ({
+ name: "workspaces/default",
+ }),
}));
vi.mock("@/stores/app", () => ({
@@ -200,10 +212,17 @@ beforeEach(async () => {
mocks.hasProjectPermission.mockImplementation(
() => mocks.allowAccessDefaultProject
);
+ mocks.maybeSwitchProject.mockImplementation(async (projectName: string) => {
+ return projectName;
+ });
mocks.loadWorkspacePermissionState.mockResolvedValue(undefined);
mocks.themeDark = true;
window.alert = vi.fn();
window.open = vi.fn();
+ Object.defineProperty(globalThis, "location", {
+ writable: true,
+ value: { ...globalThis.location, assign: mocks.assignLocation },
+ });
({ SQLEditorHeader } = await import("./SQLEditorHeader"));
});
@@ -215,7 +234,7 @@ describe("SQLEditorHeader", () => {
render();
const logo = container.querySelector("[data-testid='sql-editor-logo']");
- expect(logo?.getAttribute("data-redirect")).toBe(WORKSPACE_ROUTE_LANDING);
+ expect(logo?.getAttribute("data-redirect")).toBeNull();
expect(logo?.getAttribute("data-builtin-theme")).toBe("dark");
expect(
container.querySelector("[data-testid='sql-editor-breadcrumb']")
@@ -232,6 +251,7 @@ describe("SQLEditorHeader", () => {
);
expect(mocks.loadWorkspacePermissionState).toHaveBeenCalled();
expect(mocks.breadcrumbProps?.onBeforeSwitchWorkspace?.()).toBe(true);
+ expect(mocks.breadcrumbProps?.onSelectWorkspace).toEqual(expect.any(Function));
expect(window.alert).not.toHaveBeenCalled();
unmount();
@@ -259,11 +279,11 @@ describe("SQLEditorHeader", () => {
unmount();
});
- test("switches the SQL Editor project from the breadcrumb switcher", () => {
+ test("switches the SQL Editor project from the breadcrumb switcher", async () => {
const { render, unmount } = renderIntoContainer(<SQLEditorHeader />);
render();
- act(() => {
+ await act(async () => {
mocks.breadcrumbProps?.onSelectProject?.(
{ name: "projects/other-project" },
{ ctrlKey: false, metaKey: false }
@@ -283,11 +303,87 @@ describe("SQLEditorHeader", () => {
expect(mocks.maybeSwitchProject).toHaveBeenCalledWith(
"projects/other-project"
);
+ expect(mocks.push).toHaveBeenCalledWith({
+ fullPath: "/sql-editor/projects/other-project",
+ });
+ expect(window.open).not.toHaveBeenCalled();
+
+ unmount();
+ });
+
+ test("navigates to the SQL Editor project route when clicking the current project", async () => {
+ const { render, unmount } = renderIntoContainer(<SQLEditorHeader />);
+ render();
+
+ await act(async () => {
+ mocks.breadcrumbProps?.onSelectProject?.(
+ { name: "projects/recent-project" },
+ { ctrlKey: false, metaKey: false }
+ );
+ });
+
+ expect(mocks.record).toHaveBeenCalledWith(
+ "/sql-editor/projects/recent-project"
+ );
+ expect(mocks.maybeSwitchProject).toHaveBeenCalledWith(
+ "projects/recent-project"
+ );
+ expect(mocks.push).toHaveBeenCalledWith({
+ fullPath: "/sql-editor/projects/recent-project",
+ });
expect(window.open).not.toHaveBeenCalled();
unmount();
});
+ test("keeps SQL Editor when clicking the current workspace", () => {
+ const { render, unmount } = renderIntoContainer(<SQLEditorHeader />);
+ render();
+
+ act(() => {
+ mocks.breadcrumbProps?.onSelectWorkspace?.("workspaces/default", {
+ ctrlKey: false,
+ metaKey: false,
+ });
+ });
+
+ expect(mocks.resolve).toHaveBeenCalledWith({
+ name: "sql-editor.home",
+ });
+ expect(mocks.record).not.toHaveBeenCalled();
+ expect(mocks.push).toHaveBeenCalledWith({ name: "sql-editor.home" });
+ expect(mocks.switchWorkspace).not.toHaveBeenCalled();
+ expect(mocks.assignLocation).not.toHaveBeenCalled();
+
+ unmount();
+ });
+
+ test("keeps SQL Editor when switching workspace", async () => {
+ const { render, unmount } = renderIntoContainer(<SQLEditorHeader />);
+ render();
+
+ await act(async () => {
+ mocks.breadcrumbProps?.onSelectWorkspace?.("workspaces/other", {
+ ctrlKey: false,
+ metaKey: false,
+ });
+ });
+
+ expect(mocks.resolve).toHaveBeenCalledWith({
+ name: "sql-editor.home",
+ });
+ expect(mocks.record).not.toHaveBeenCalled();
+ expect(mocks.switchWorkspace).toHaveBeenCalledWith(
+ "workspaces/other",
+ false,
+ true
+ );
+ expect(mocks.assignLocation).toHaveBeenCalledWith("/sql-editor");
+ expect(mocks.push).not.toHaveBeenCalled();
+
+ unmount();
+ });
+
test("records recent project when opening the SQL Editor project in a new tab", () => {
const { render, unmount } = renderIntoContainer(<SQLEditorHeader />);
render();
diff --git a/frontend/src/modules/sql-editor/components/SQLEditorHeader.tsx b/frontend/src/modules/sql-editor/components/SQLEditorHeader.tsx
index a0252db8ce..a5d75054c5 100644
--- a/frontend/src/modules/sql-editor/components/SQLEditorHeader.tsx
+++ b/frontend/src/modules/sql-editor/components/SQLEditorHeader.tsx
@@ -1,14 +1,18 @@
import { useCallback, useEffect } from "react";
import { useTranslation } from "react-i18next";
import {
+ SQL_EDITOR_HOME_MODULE,
SQL_EDITOR_PROJECT_MODULE,
useNavigate,
- WORKSPACE_ROUTE_LANDING,
} from "@/app/router";
import { BytebaseLogo } from "@/components/BytebaseLogo";
import { HeaderBreadcrumb } from "@/components/header/HeaderBreadcrumb";
import { ProfileMenuTrigger } from "@/components/header/ProfileMenuTrigger";
-import { useRecentVisit } from "@/hooks/useAppState";
+import {
+ useRecentVisit,
+ useSwitchWorkspace,
+ useWorkspace,
+} from "@/hooks/useAppState";
import { getProjectName, isValidProjectName } from "@/lib/resourceName";
import { useSQLEditorStore } from "@/modules/sql-editor/store";
import { useSQLEditorEditorState } from "@/modules/sql-editor/store/editor";
@@ -23,6 +27,8 @@ export function SQLEditorHeader() {
const { t } = useTranslation();
const navigate = useNavigate();
const { record } = useRecentVisit();
+ const workspace = useWorkspace();
+ const switchWorkspace = useSwitchWorkspace();
const theme = useSQLEditorTheme();
const projectName = useSQLEditorEditorState((s) => s.project);
const maybeSwitchProject = useSQLEditorStore((s) => s.maybeSwitchProject);
@@ -63,7 +69,11 @@ export function SQLEditorHeader() {
if (event.ctrlKey || event.metaKey) {
window.open(route.fullPath, "_blank");
} else {
- void maybeSwitchProject(project.name);
+ void maybeSwitchProject(project.name).then((switchedProject) => {
+ if (switchedProject) {
+ void navigate.push(route);
+ }
+ });
}
},
[maybeSwitchProject, navigate, record, setRecentProject]
@@ -81,11 +91,32 @@ export function SQLEditorHeader() {
return true;
}, [t]);
+ const handleSelectWorkspace = useCallback(
+ (workspaceName: string, event: React.MouseEvent<HTMLElement>) => {
+ const route = navigate.resolve({
+ name: SQL_EDITOR_HOME_MODULE,
+ });
+
+ if (workspaceName === workspace?.name) {
+ if (event.ctrlKey || event.metaKey) {
+ window.open(route.fullPath, "_blank");
+ } else {
+ void navigate.push({ name: SQL_EDITOR_HOME_MODULE });
+ }
+ return;
+ }
+
+ void switchWorkspace(workspaceName, false, true).then(() => {
+ globalThis.location.assign(route.fullPath);
+ });
+ },
+ [navigate, switchWorkspace, workspace?.name]
+ );
+
return (
<header className="h-12 shrink-0 border-b border-block-border bg-background px-3 flex items-center justify-between gap-x-4">
<div className="min-w-0 flex items-center gap-x-4">
<BytebaseLogo
- redirect={WORKSPACE_ROUTE_LANDING}
builtinTheme={isDarkTheme(theme) ? "dark" : "light"}
className="h-9 md:h-10"
/>
@@ -94,6 +125,7 @@ export function SQLEditorHeader() {
currentProjectName={projectName}
projectSwitchExcludeDefaultProject={!allowAccessDefaultProject}
onBeforeSwitchWorkspace={handleBeforeSwitchWorkspace}
+ onSelectWorkspace={handleSelectWorkspace}
onSelectProject={handleSelectProject}
/>
</div>
diff --git a/frontend/src/modules/sql-editor/components/SaveSheetModal.test.tsx b/frontend/src/modules/sql-editor/components/SaveSheetModal.test.tsx
index e4a45bddaf..727d66a3bc 100644
--- a/frontend/src/modules/sql-editor/components/SaveSheetModal.test.tsx
+++ b/frontend/src/modules/sql-editor/components/SaveSheetModal.test.tsx
@@ -126,11 +126,13 @@ vi.mock("@/components/ui/input", () => ({
onChange,
placeholder,
maxLength,
+ autoComplete,
}: {
value: string;
onChange?: (e: React.ChangeEvent<HTMLInputElement>) => void;
placeholder?: string;
maxLength?: number;
+ autoComplete?: string;
}) => (
<input
data-testid="title-input"
@@ -138,6 +140,7 @@ vi.mock("@/components/ui/input", () => ({
onChange={onChange}
placeholder={placeholder}
maxLength={maxLength}
+ autoComplete={autoComplete}
/>
),
}));
@@ -235,6 +238,23 @@ describe("SaveSheetModal", () => {
unmount();
});
+ test("title input disables browser autocomplete", () => {
+ const { container, render, unmount } = renderIntoContainer(
+ <SaveSheetModal />
+ );
+ render();
+
+ emitSaveSheet({ tab: tabWithoutWorksheet });
+
+ const input = container.querySelector(
+ "[data-testid='title-input']"
+ ) as HTMLInputElement;
+ expect(input).not.toBeNull();
+ expect(input.autocomplete).toBe("off");
+
+ unmount();
+ });
+
test("2. Saved tab without editTitle saves silently — no modal, maybeUpdateWorksheet called", async () => {
const { container, render, unmount } = renderIntoContainer(
<SaveSheetModal />
diff --git a/frontend/src/modules/sql-editor/components/SaveSheetModal.tsx b/frontend/src/modules/sql-editor/components/SaveSheetModal.tsx
index d05af61c4d..2713c39e9f 100644
--- a/frontend/src/modules/sql-editor/components/SaveSheetModal.tsx
+++ b/frontend/src/modules/sql-editor/components/SaveSheetModal.tsx
@@ -115,6 +115,7 @@ export function SaveSheetModal() {
onChange={(e) => setTitle(e.target.value)}
placeholder={t("common.untitled")}
maxLength={200}
+ autoComplete="off"
/>
</div>
<FolderForm folder={folder} onFolderChange={setFolder} />
diff --git a/frontend/src/modules/sql-editor/components/Welcome.test.tsx b/frontend/src/modules/sql-editor/components/Welcome.test.tsx
index 314c47300f..6861a9751e 100644
--- a/frontend/src/modules/sql-editor/components/Welcome.test.tsx
+++ b/frontend/src/modules/sql-editor/components/Welcome.test.tsx
@@ -18,6 +18,7 @@ const mocks = vi.hoisted(() => ({
>(),
routerPush: vi.fn(),
projectData: { name: "projects/test" } as { name: string },
+ themeDark: false,
}));
vi.mock("react-i18next", () => ({
@@ -30,7 +31,19 @@ vi.mock("@/components/PermissionGuard", () => ({
}));
vi.mock("@/components/BytebaseLogo", () => ({
- BytebaseLogo: () => null,
+ BytebaseLogo: ({
+ builtinTheme,
+ className,
+ }: {
+ builtinTheme?: string;
+ className?: string;
+ }) => (
+ <div
+ data-testid="welcome-logo"
+ data-builtin-theme={builtinTheme}
+ className={className}
+ />
+ ),
}));
vi.mock("@/hooks/useAppProject", () => ({
@@ -54,6 +67,16 @@ vi.mock("@/assets/logo-full.svg", () => ({
default: "/assets/logo-full.svg",
}));
+vi.mock("@/modules/sql-editor/components/theme/SQLEditorThemeScope", () => ({
+ useSQLEditorTheme: () => ({
+ id: mocks.themeDark ? "dark" : "light",
+ }),
+}));
+
+vi.mock("@/modules/sql-editor/components/theme/derive", () => ({
+ isDarkTheme: () => mocks.themeDark,
+}));
+
let Welcome: typeof import("./Welcome").Welcome;
const renderIntoContainer = (element: ReactElement) => {
@@ -78,6 +101,7 @@ const renderIntoContainer = (element: ReactElement) => {
beforeEach(async () => {
vi.clearAllMocks();
+ mocks.themeDark = false;
// Default: both permissions granted.
mocks.usePermissionCheck.mockReturnValue([true, undefined]);
({ Welcome } = await import("./Welcome"));
@@ -89,11 +113,32 @@ describe("Welcome", () => {
<Welcome onChangeConnection={() => {}} />
);
render();
+ expect(container.firstElementChild?.className).toContain("gap-y-10");
+ expect(
+ container.querySelector('[data-testid="welcome-logo"]')?.className
+ ).toContain("h-20");
+ expect(
+ container.querySelector('[data-testid="welcome-logo"]')?.className
+ ).toContain("w-44");
expect(container.textContent).toContain("sql-editor.add-a-new-instance");
expect(container.textContent).toContain("sql-editor.connect-to-a-database");
unmount();
});
+ test("passes dark SQL Editor theme to the logo", () => {
+ mocks.themeDark = true;
+ const { container, render, unmount } = renderIntoContainer(
+ <Welcome onChangeConnection={() => {}} />
+ );
+ render();
+ expect(
+ container.querySelector('[data-testid="welcome-logo"]')?.getAttribute(
+ "data-builtin-theme"
+ )
+ ).toBe("dark");
+ unmount();
+ });
+
test("hides Add-Instance when missing bb.instances.create", () => {
mocks.usePermissionCheck.mockImplementation((perms) => {
if (perms.includes("bb.instances.create")) return [false, "missing"];
diff --git a/frontend/src/modules/sql-editor/components/Welcome.tsx b/frontend/src/modules/sql-editor/components/Welcome.tsx
index 7f438e718b..44c72a04f1 100644
--- a/frontend/src/modules/sql-editor/components/Welcome.tsx
+++ b/frontend/src/modules/sql-editor/components/Welcome.tsx
@@ -6,6 +6,8 @@ import { BytebaseLogo } from "@/components/BytebaseLogo";
import { usePermissionCheck } from "@/components/PermissionGuard";
import { useAppProject } from "@/hooks/useAppProject";
import { useSQLEditorEditorState } from "@/modules/sql-editor/store/editor";
+import { isDarkTheme } from "./theme/derive";
+import { useSQLEditorTheme } from "./theme/SQLEditorThemeScope";
import { WelcomeButton } from "./WelcomeButton";
export type WelcomeProps = {
@@ -19,6 +21,7 @@ export type WelcomeProps = {
export function Welcome({ onChangeConnection }: WelcomeProps) {
const { t } = useTranslation();
+ const theme = useSQLEditorTheme();
const projectName = useSQLEditorEditorState((s) => s.project);
const resolvedProject = useAppProject(projectName);
@@ -37,8 +40,11 @@ export function Welcome({ onChangeConnection }: WelcomeProps) {
};
return (
- <div className="w-full h-full flex flex-col items-center justify-center gap-y-4">
- <BytebaseLogo />
+ <div className="w-full h-full flex flex-col items-center justify-center gap-y-10">
+ <BytebaseLogo
+ builtinTheme={isDarkTheme(theme) ? "dark" : "light"}
+ className="h-20 w-44"
+ />
<div className="flex items-center flex-wrap gap-4">
{showCreateInstanceButton && (
<WelcomeButton
diff --git a/frontend/src/stores/app/types.ts b/frontend/src/stores/app/types.ts
index dd3c53dd79..88e929ca36 100644
--- a/frontend/src/stores/app/types.ts
+++ b/frontend/src/stores/app/types.ts
@@ -236,7 +236,11 @@ export type WorkspaceSlice = {
workspace: Workspace,
updateMask: string[]
) => Promise<Workspace>;
- switchWorkspace: (workspaceName: string, redirect?: boolean) => Promise<void>;
+ switchWorkspace: (
+ workspaceName: string,
+ redirect?: boolean,
+ recordVisit?: boolean
+ ) => Promise<void>;
loadWorkspaceProfile: (
force?: boolean
) => Promise<WorkspaceProfileSetting | undefined>;
diff --git a/frontend/src/stores/app/workspace.ts b/frontend/src/stores/app/workspace.ts
index 7ed7a347b2..163a4aaa03 100644
--- a/frontend/src/stores/app/workspace.ts
+++ b/frontend/src/stores/app/workspace.ts
@@ -289,17 +289,23 @@ export const createWorkspaceSlice: AppSliceCreator<WorkspaceSlice> = (
return updated;
},
- switchWorkspace: async (workspaceName: string, redirect = true) => {
+ switchWorkspace: async (
+ workspaceName: string,
+ redirect = true,
+ recordVisit = true
+ ) => {
await authServiceClientConnect.switchWorkspace(
createProto(SwitchWorkspaceRequestSchema, {
workspace: workspaceName,
web: true,
})
);
- get().recordRecentVisit(
- resolvePath(WORKSPACE_ROUTE_LANDING),
- workspaceName
- );
+ if (recordVisit) {
+ get().recordRecentVisit(
+ resolvePath(WORKSPACE_ROUTE_LANDING),
+ workspaceName
+ );
+ }
// Notify other tabs to reload with the new workspace.
broadcastWorkspaceSwitch(workspaceName);
if (redirect) {