Skip to content

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

refactor: unified guide (#21243)

ecmadao156bd18891ea
diff --git a/frontend/scripts/ui-guideline-legacy-debt.json b/frontend/scripts/ui-guideline-legacy-debt.json
index f27b396d10..74f495f988 100644
--- a/frontend/scripts/ui-guideline-legacy-debt.json
+++ b/frontend/scripts/ui-guideline-legacy-debt.json
@@ -816,72 +816,6 @@
"token": "text-gray-700",
"count": 1
},
- {
- "path": "src/components/Quickstart.tsx",
- "rule": "no-native-control",
- "token": "button",
- "count": 1
- },
- {
- "path": "src/components/Quickstart.tsx",
- "rule": "no-raw-color",
- "token": "bg-gray-200",
- "count": 1
- },
- {
- "path": "src/components/Quickstart.tsx",
- "rule": "no-raw-color",
- "token": "bg-gray-300",
- "count": 1
- },
- {
- "path": "src/components/Quickstart.tsx",
- "rule": "no-raw-color",
- "token": "bg-indigo-400",
- "count": 1
- },
- {
- "path": "src/components/Quickstart.tsx",
- "rule": "no-raw-color",
- "token": "bg-indigo-500",
- "count": 1
- },
- {
- "path": "src/components/Quickstart.tsx",
- "rule": "no-raw-color",
- "token": "bg-indigo-600",
- "count": 1
- },
- {
- "path": "src/components/Quickstart.tsx",
- "rule": "no-raw-color",
- "token": "bg-yellow-50",
- "count": 1
- },
- {
- "path": "src/components/Quickstart.tsx",
- "rule": "no-raw-color",
- "token": "group-hover:bg-gray-400",
- "count": 1
- },
- {
- "path": "src/components/Quickstart.tsx",
- "rule": "no-raw-color",
- "token": "text-gray-600",
- "count": 1
- },
- {
- "path": "src/components/Quickstart.tsx",
- "rule": "no-raw-color",
- "token": "text-gray-900",
- "count": 1
- },
- {
- "path": "src/components/Quickstart.tsx",
- "rule": "no-raw-color",
- "token": "text-indigo-600",
- "count": 1
- },
{
"path": "src/components/release/ReleaseInfoCard.tsx",
"rule": "no-off-scale-radius",
diff --git a/frontend/src/app/analytics/RouteBehaviorRecorder.test.tsx b/frontend/src/app/analytics/RouteBehaviorRecorder.test.tsx
index f334ac2d91..e90414ada4 100644
--- a/frontend/src/app/analytics/RouteBehaviorRecorder.test.tsx
+++ b/frontend/src/app/analytics/RouteBehaviorRecorder.test.tsx
@@ -217,7 +217,7 @@ describe("RouteBehaviorRecorder", () => {
});
});
- test("emits a route-level page navigation metric on route changes", async () => {
+ test("relies on built-in pageviews instead of custom navigation metrics", async () => {
await act(async () => {
root.render(<RouteBehaviorRecorder />);
});
@@ -229,13 +229,10 @@ describe("RouteBehaviorRecorder", () => {
root.render(<RouteBehaviorRecorder />);
});
- expect(mocks.analytics.captureMetric).toHaveBeenCalledWith({
- event: "page navigated",
- properties: {
- from_route_id: "workspace.project.database",
- to_route_id: "workspace.instance.create",
- },
- });
+ expect(mocks.analytics.captureMetric).toHaveBeenCalledOnce();
+ expect(mocks.analytics.captureMetric).toHaveBeenCalledWith(
+ expect.objectContaining({ event: "page session" })
+ );
});
test("keeps the current page session when only route query changes", async () => {
diff --git a/frontend/src/app/analytics/RouteBehaviorRecorder.tsx b/frontend/src/app/analytics/RouteBehaviorRecorder.tsx
index 88742c6ac9..f6099ac4e6 100644
--- a/frontend/src/app/analytics/RouteBehaviorRecorder.tsx
+++ b/frontend/src/app/analytics/RouteBehaviorRecorder.tsx
@@ -1,5 +1,5 @@
import { useEffect, useMemo, useRef } from "react";
-import { useCurrentRoute } from "@/app/router";
+import { resolveRouteName, useCurrentRoute } from "@/app/router";
import { useAppStore } from "@/stores/app";
import type { BehaviorRecordingDecision } from "./behavior";
import {
@@ -55,6 +55,7 @@ function EnabledRouteBehaviorRecorder() {
recordingSampleRate: parseRecordingSampleRate(
import.meta.env.BB_POSTHOG_RECORDING_SAMPLE_RATE as string | undefined
),
+ resolveRouteId,
}),
[]
);
@@ -90,20 +91,6 @@ function EnabledRouteBehaviorRecorder() {
});
const previousSession = pageSessionRef.current;
endPageSession(previousSession);
- if (
- previousSession &&
- decision.recording === "allow" &&
- previousSession.decision.routeId !== decision.routeId
- ) {
- behaviorAnalytics.captureMetric(
- createBehaviorMetric("page navigated", {
- properties: {
- from_route_id: previousSession.decision.routeId,
- to_route_id: decision.routeId,
- },
- })
- );
- }
pageSessionRef.current =
decision.recording === "allow"
? {
@@ -169,3 +156,12 @@ function parseRecordingSampleRate(value: string | undefined): number {
}
return Math.min(Math.max(parsed, 0), 1);
}
+
+function resolveRouteId(url: string): string | undefined {
+ try {
+ const parsed = new URL(url, window.location.origin);
+ return resolveRouteName(parsed.pathname);
+ } catch {
+ return undefined;
+ }
+}
diff --git a/frontend/src/app/analytics/behavior.test.ts b/frontend/src/app/analytics/behavior.test.ts
index 7bcbc5c052..dda5ce130f 100644
--- a/frontend/src/app/analytics/behavior.test.ts
+++ b/frontend/src/app/analytics/behavior.test.ts
@@ -1,7 +1,5 @@
import { describe, expect, test } from "vitest";
-import type { BehaviorMetricInput } from "./behavior";
import {
- behaviorMetricDefinitions,
buildBehaviorAnalyticsConfig,
classifyBehaviorRoute,
createBehaviorMetric,
@@ -80,6 +78,10 @@ describe("behavior analytics config", () => {
posthogHost: "https://us.i.posthog.com",
recordingSampleRate: 0.25,
gitCommit: "abc123",
+ resolveRouteId: (url) =>
+ url.includes("/projects/acme/")
+ ? "workspace.project.database"
+ : undefined,
});
if (!config) {
@@ -97,12 +99,15 @@ describe("behavior analytics config", () => {
expect(
sanitizeProperties(
{
- $current_url: "https://cloud.bytebase.com/projects/acme?token=secret",
+ $current_url:
+ "https://cloud.bytebase.com/projects/acme/databases?token=secret",
+ title: "Acme production - Bytebase",
},
"$pageview"
)
).toEqual({
git_commit: "abc123",
+ route_id: "workspace.project.database",
});
});
});
@@ -205,20 +210,6 @@ describe("behavior analytics privacy helpers", () => {
});
describe("behavior analytics metrics", () => {
- test("defines metric names in one map", () => {
- expect([...behaviorMetricDefinitions.keys()]).toContain("page session");
- expect([...behaviorMetricDefinitions.keys()]).toContain("page navigated");
- expect([...behaviorMetricDefinitions.keys()]).toContain(
- "locked feature clicked"
- );
- expect([...behaviorMetricDefinitions.keys()]).not.toContain(
- "locked feature viewed"
- );
- expect([...behaviorMetricDefinitions.keys()]).not.toContain(
- "locked feature upgrade clicked"
- );
- });
-
test("creates allowlisted page session metrics with route context", () => {
expect(
createBehaviorMetric("page session", {
@@ -238,34 +229,6 @@ describe("behavior analytics metrics", () => {
});
});
- test("creates allowlisted page navigation metrics with route transition context", () => {
- expect(
- createBehaviorMetric("page navigated", {
- properties: {
- from_route_id: "workspace.landing",
- to_route_id: "workspace.instance.create",
- },
- })
- ).toEqual({
- event: "page navigated",
- properties: {
- from_route_id: "workspace.landing",
- to_route_id: "workspace.instance.create",
- },
- });
- });
-
- test("keeps route transition context out of the shared metric input fields", () => {
- const routeTransitionInput = {
- // @ts-expect-error route transitions should use event-specific properties.
- fromRouteId: "workspace.landing",
- } satisfies BehaviorMetricInput;
-
- expect(routeTransitionInput).toEqual({
- fromRouteId: "workspace.landing",
- });
- });
-
test("creates allowlisted custom action metrics and drops unsafe properties", () => {
expect(
createBehaviorMetric("setup guide action clicked", {
diff --git a/frontend/src/app/analytics/behavior.ts b/frontend/src/app/analytics/behavior.ts
index 1a3183c6dc..2ae6656bb5 100644
--- a/frontend/src/app/analytics/behavior.ts
+++ b/frontend/src/app/analytics/behavior.ts
@@ -19,25 +19,16 @@ export type BehaviorAnalyticsConfig = {
// PostHog recommends "[object] [verb]" event names.
// https://posthog.com/docs/product-analytics/capture-events
-export const behaviorMetricDefinitions = new Map([
- ["page session", {}],
- ["page navigated", {}],
- ["connect database clicked", {}],
- ["instance connection test clicked", {}],
- ["instance create clicked", {}],
- ["locked feature clicked", {}],
- ["setup guide action clicked", {}],
- ["setup guide dismissed", {}],
- ["post sync first change clicked", {}],
- ["post sync sql editor clicked", {}],
- ["trust guidance viewed", {}],
- ["sample database started", {}],
-] as const);
-
export type BehaviorMetricName =
- typeof behaviorMetricDefinitions extends ReadonlyMap<infer Name, unknown>
- ? Name
- : never;
+ | "page session"
+ | "connect database clicked"
+ | "instance connection test clicked"
+ | "instance create clicked"
+ | "locked feature clicked"
+ | "setup guide action clicked"
+ | "setup guide dismissed"
+ | "post sync first change clicked"
+ | "post sync sql editor clicked";
export type BehaviorMetric = {
event: BehaviorMetricName;
@@ -58,6 +49,7 @@ export function buildBehaviorAnalyticsConfig(params: {
posthogHost?: string;
gitCommit?: string;
recordingSampleRate: number;
+ resolveRouteId?: (url: string) => string | undefined;
}): BehaviorAnalyticsConfig | null {
const apiKey = params.posthogKey?.trim();
const apiHost = params.posthogHost?.trim();
@@ -97,10 +89,23 @@ export function buildBehaviorAnalyticsConfig(params: {
sanitize_properties: (
eventProperties: Record<string, unknown>,
eventName?: string
- ) => ({
- ...sanitizeBehaviorProperties(eventProperties, eventName),
- ...properties,
- }),
+ ) => {
+ const sanitized = sanitizeBehaviorProperties(
+ eventProperties,
+ eventName
+ );
+ const currentUrl = eventProperties.$current_url;
+ const routeId =
+ sanitized.route_id ??
+ (typeof currentUrl === "string"
+ ? params.resolveRouteId?.(currentUrl)
+ : undefined);
+ return {
+ ...sanitized,
+ ...(routeId ? { route_id: routeId } : {}),
+ ...properties,
+ };
+ },
session_recording: {
maskAllInputs: true,
blockClass: "ph-no-capture",
@@ -145,9 +150,6 @@ export function createBehaviorMetric(
event: BehaviorMetricName,
input: BehaviorMetricInput = {}
): BehaviorMetric {
- if (!behaviorMetricDefinitions.has(event)) {
- throw new Error(`Unsupported behavior metric: ${event}`);
- }
const customProperties = sanitizeBehaviorProperties(input.properties ?? {});
const standardProperties = sanitizeBehaviorProperties({
route_id: input.routeId,
@@ -172,6 +174,7 @@ function isForbiddenPropertyKey(key: string): boolean {
normalized === "$el_text" ||
normalized === "$elements" ||
normalized === "$elements_chain" ||
+ normalized === "title" ||
normalized.includes("url") ||
normalized.includes("path") ||
normalized.includes("referrer") ||
diff --git a/frontend/src/app/layouts/BodyLayout.tsx b/frontend/src/app/layouts/BodyLayout.tsx
index 7f0a641c94..b560b27417 100644
--- a/frontend/src/app/layouts/BodyLayout.tsx
+++ b/frontend/src/app/layouts/BodyLayout.tsx
@@ -10,10 +10,8 @@ import {
import { DashboardBodyShell } from "@/components/DashboardBodyShell";
import { DashboardSidebar } from "@/components/DashboardSidebar";
import { ProjectSidebar } from "@/components/ProjectSidebar";
-import { Quickstart } from "@/components/Quickstart";
import { RoutePermissionGuardShell } from "@/components/RoutePermissionGuardShell";
import { WorkspaceSetupGuide } from "@/components/WorkspaceSetupGuide";
-import { useAppStore } from "@/stores/app";
// Ported from `src/layouts/BodyLayout.vue`. Mounts the workspace
// `DashboardBodyShell` (header + sidebar slot + body slot) and portals the
@@ -38,7 +36,6 @@ export function BodyLayout() {
// Workspace "My Issues" is a standalone full-width page: header (with logo)
// but no sidebar, mirroring the Vue IssuesRouteShell (variant="issues").
const isMyIssues = currentRouteName === WORKSPACE_ROUTE_MY_ISSUES;
- const isSaaSMode = useAppStore((s) => s.isSaaSMode());
// Project-scoped routes (`workspace.project.*`) get the project sidebar; the
// bare projects list (`workspace.project`) keeps the workspace sidebar.
const isProjectRoute = Boolean(
@@ -119,10 +116,7 @@ export function BodyLayout() {
: null}
{targets.quickstart
- ? createPortal(
- isSaaSMode ? <WorkspaceSetupGuide /> : <Quickstart />,
- targets.quickstart
- )
+ ? createPortal(<WorkspaceSetupGuide />, targets.quickstart)
: null}
</>
);
diff --git a/frontend/src/app/router/currentRouteSnapshot.test.ts b/frontend/src/app/router/currentRouteSnapshot.test.ts
index 2806f1a2b4..716cf36869 100644
--- a/frontend/src/app/router/currentRouteSnapshot.test.ts
+++ b/frontend/src/app/router/currentRouteSnapshot.test.ts
@@ -3,8 +3,9 @@ import {
PROJECT_V1_ROUTE_WEBHOOK_CREATE,
PROJECT_V1_ROUTE_WEBHOOK_DETAIL,
PROJECT_V1_ROUTE_WEBHOOKS,
+ SQL_EDITOR_HOME_MODULE,
} from "./handles";
-import { router } from "./index";
+import { resolveRouteName, router } from "./index";
import { setAppRouter, setRouteNameIndex } from "./navigation";
beforeEach(() => {
@@ -64,4 +65,24 @@ describe("router named route params", () => {
}).fullPath
).toBe("/projects/project-sample/webhooks/hook-1");
});
+
+ it("resolves a pathname to the most specific registered route name", () => {
+ expect(resolveRouteName("/projects/project-sample/webhooks/new")).toBe(
+ PROJECT_V1_ROUTE_WEBHOOK_CREATE
+ );
+ expect(resolveRouteName("/projects/project-sample/webhooks/hook-1")).toBe(
+ PROJECT_V1_ROUTE_WEBHOOK_DETAIL
+ );
+ });
+
+ it("prefers the leaf route name when parent and index routes share a path", () => {
+ setRouteNameIndex(
+ new Map<string, string>([
+ ["sql-editor", "/sql-editor"],
+ [SQL_EDITOR_HOME_MODULE, "/sql-editor"],
+ ])
+ );
+
+ expect(resolveRouteName("/sql-editor")).toBe(SQL_EDITOR_HOME_MODULE);
+ });
});
diff --git a/frontend/src/app/router/index.ts b/frontend/src/app/router/index.ts
index 6fb4cf6682..e9380b2a02 100644
--- a/frontend/src/app/router/index.ts
+++ b/frontend/src/app/router/index.ts
@@ -1,4 +1,5 @@
import {
+ matchRoutes,
useLocation,
useNavigate as useReactRouterNavigate,
useMatches,
@@ -230,6 +231,20 @@ export function resolveRoute(to: RouteTarget): ReactResolvedRoute {
return { href: fullPath, fullPath };
}
+export function resolveRouteName(pathname: string): string | undefined {
+ const matches = matchRoutes(
+ // Index routes are registered after their parents and share the same path.
+ getRegisteredRoutes()
+ .reverse()
+ .map(({ name, path }) => ({
+ path,
+ handle: { name },
+ })),
+ pathname
+ );
+ return (matches?.at(-1)?.route.handle as RouteHandle | undefined)?.name;
+}
+
type PushOptions = Omit<NavigationOptions, "replace">;
function pushRoute(to: RouteTarget, options?: PushOptions): Promise<void> {
diff --git a/frontend/src/components/Quickstart.test.tsx b/frontend/src/components/Quickstart.test.tsx
deleted file mode 100644
index 703c3ed924..0000000000
--- a/frontend/src/components/Quickstart.test.tsx
+++ /dev/null
@@ -1,130 +0,0 @@
-import type { ReactElement, ReactNode } from "react";
-import { act } from "react";
-import { createRoot } from "react-dom/client";
-import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
-
-(
- globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }
-).IS_REACT_ACT_ENVIRONMENT = true;
-
-const mocks = vi.hoisted(() => ({
- getIntroStateByKey: vi.fn(
- (key: string) => key !== "hidden" && key !== "member.visit"
- ),
- getOrFetchProjectByName: vi.fn(async () => ({ name: "" })),
- hasWorkspacePermissionV2: vi.fn((_permission: string) => true),
- loadProjectIamPolicy: vi.fn(async () => undefined),
- saveIntroStateByKey: vi.fn(),
-}));
-
-vi.mock("react-i18next", () => ({
- initReactI18next: { type: "3rdParty", init: () => {} },
- useTranslation: () => ({
- t: (key: string) => key,
- }),
-}));
-
-vi.mock("@/components/RouterLink", () => ({
- RouterLink: ({
- children,
- to,
- ...props
- }: {
- children: ReactNode;
- to: { name?: string };
- }) => (
- <a data-route-name={to.name} {...props}>
- {children}
- </a>
- ),
-}));
-
-vi.mock("@/stores/app", () => {
- const state = {
- quickStartEnabled: () => true,
- getIntroStateByKey: mocks.getIntroStateByKey,
- loadProjectIamPolicy: mocks.loadProjectIamPolicy,
- };
- const useAppStore = (selector?: (s: typeof state) => unknown) =>
- selector ? selector(state) : state;
- useAppStore.getState = () => ({
- ...state,
- getOrFetchProjectByName: mocks.getOrFetchProjectByName,
- fetchIssueByName: vi.fn(),
- getOrFetchSavedQueryByName: vi.fn(),
- saveIntroStateByKey: mocks.saveIntroStateByKey,
- });
- return { useAppStore };
-});
-
-vi.mock("@/stores", () => ({
- pushNotification: vi.fn(),
-}));
-
-vi.mock("@/utils", () => ({
- extractProjectResourceName: (name: string) => name,
- hasProjectPermissionV2: () => true,
- hasWorkspacePermissionV2: mocks.hasWorkspacePermissionV2,
-}));
-
-vi.mock("@/types", () => ({
- isValidProjectName: () => false,
- UNKNOWN_PROJECT_NAME: "projects/-",
-}));
-
-import { Quickstart } from "./Quickstart";
-
-let container: HTMLDivElement;
-let root: ReturnType<typeof createRoot>;
-
-beforeEach(() => {
- vi.clearAllMocks();
- mocks.getIntroStateByKey.mockImplementation(
- (key: string) => key !== "hidden" && key !== "member.visit"
- );
- mocks.hasWorkspacePermissionV2.mockReturnValue(true);
- container = document.createElement("div");
- document.body.appendChild(container);
- root = createRoot(container);
-});
-
-afterEach(() => {
- act(() => {
- root.unmount();
- });
- document.body.removeChild(container);
-});
-
-const render = async (element: ReactElement) => {
- await act(async () => {
- root.render(element);
- await Promise.resolve();
- });
-};
-
-describe("Quickstart", () => {
- it("links the member visit item to the Members page", async () => {
- await render(<Quickstart />);
-
- const memberLink = Array.from(container.querySelectorAll("a")).find((a) =>
- a.textContent?.includes("quick-start.visit-member")
- );
-
- expect(memberLink?.getAttribute("data-route-name")).toBe(
- "workspace.members"
- );
- });
-
- it("shows the member visit item when user can access workspace IAM policy", async () => {
- mocks.hasWorkspacePermissionV2.mockImplementation(
- (permission) => permission === "bb.workspaces.getIamPolicy"
- );
-
- await render(<Quickstart />);
-
- expect(container.textContent).toContain("quick-start.visit-member");
- expect(mocks.hasWorkspacePermissionV2).not.toHaveBeenCalledWith(
- "bb.users.list"
- );
- });
-});
diff --git a/frontend/src/components/Quickstart.tsx b/frontend/src/components/Quickstart.tsx
deleted file mode 100644
index 9b59406fe5..0000000000
--- a/frontend/src/components/Quickstart.tsx
+++ /dev/null
@@ -1,357 +0,0 @@
-import { CheckCircle, X } from "lucide-react";
-import { useEffect, useMemo, useState } from "react";
-import { useTranslation } from "react-i18next";
-import type { RouteTarget } from "@/app/router";
-import {
- DATABASE_ROUTE_DASHBOARD,
- ENVIRONMENT_V1_ROUTE_DASHBOARD,
- INSTANCE_ROUTE_DASHBOARD,
- PROJECT_V1_ROUTE_DASHBOARD,
- PROJECT_V1_ROUTE_ISSUE_DETAIL,
- SQL_EDITOR_SAVED_QUERY_MODULE,
- WORKSPACE_ROUTE_MEMBERS,
-} from "@/app/router/handles";
-import { RouterLink } from "@/components/RouterLink";
-import { cn } from "@/lib/utils";
-import { pushNotification } from "@/stores";
-import { useAppStore } from "@/stores/app";
-import { projectNamePrefix } from "@/stores/modules/v1/common";
-import type { Permission } from "@/types";
-import { isValidProjectName, UNKNOWN_PROJECT_NAME } from "@/types";
-import type { Project } from "@/types/proto-es/v1/project_service_pb";
-import {
- extractProjectResourceName,
- hasProjectPermissionV2,
- hasWorkspacePermissionV2,
-} from "@/utils";
-
-const SAMPLE_PROJECT_NAME = "project-sample";
-const SAMPLE_ISSUE_ID = "101";
-const SAMPLE_SHEET_ID = "101";
-
-interface IntroItem {
- name: string;
- link: RouteTarget;
- done: boolean;
- hide?: boolean;
- requiredPermissions?: Permission[];
- needsProject?: boolean;
-}
-
-/**
- * React port of `frontend/src/components/Quickstart.vue`.
- *
- * Floating onboarding tracker pinned to the bottom of the workspace
- * shell. Renders a progress bar over a list of intro tasks (view an
- * issue, query data, visit project, visit environment / instance /
- * database, visit member). Each task is permission-gated so users only
- * see tasks they can perform; tasks that depend on the sample project
- * are filtered out when no sample project exists for this workspace.
- *
- * State sources (app store):
- * - `quickStartEnabled()` — disabled in self-hosted / enterprise builds
- * via the actuator config.
- * - `getIntroStateByKey(...)` — per-task done flags and the global
- * `hidden` flag (toggled when the user dismisses).
- *
- * Async fetches (project / sample issue / sample saved query) run on
- * mount and fall back to undefined when the sample data is missing
- * (e.g. an upgraded workspace that never bootstrapped the sample).
- */
-export function Quickstart() {
- const { t } = useTranslation();
- const loadProjectIamPolicy = useAppStore(
- (state) => state.loadProjectIamPolicy
- );
-
- const quickStartEnabled = useAppStore((s) => s.quickStartEnabled());
- const hidden = useAppStore((s) => s.getIntroStateByKey("hidden"));
-
- // Subscribe to each task's done flag so the line-through + progress
- // bar update live.
- const issueVisited = useAppStore((s) => s.getIntroStateByKey("issue.visit"));
- const dataQueried = useAppStore((s) => s.getIntroStateByKey("data.query"));
- const projectVisited = useAppStore((s) =>
- s.getIntroStateByKey("project.visit")
- );
- const environmentVisited = useAppStore((s) =>
- s.getIntroStateByKey("environment.visit")
- );
- const instanceVisited = useAppStore((s) =>
- s.getIntroStateByKey("instance.visit")
- );
- const databaseVisited = useAppStore((s) =>
- s.getIntroStateByKey("database.visit")
- );
- const memberVisited = useAppStore((s) =>
- s.getIntroStateByKey("member.visit")
- );
-
- // ---- async sample fetches --------------------------------------------
-
- const [sampleProject, setSampleProject] = useState<Project | undefined>();
- const [sampleIssueExists, setSampleIssueExists] = useState(false);
- const [sampleSheetExists, setSampleSheetExists] = useState(false);
-
- useEffect(() => {
- if (!quickStartEnabled) {
- setSampleProject(undefined);
- return;
- }
- let cancelled = false;
- void (async () => {
- const project = await useAppStore
- .getState()
- .getOrFetchProjectByName(
- `${projectNamePrefix}${SAMPLE_PROJECT_NAME}`,
- true /* silent */
- );
- if (cancelled) return;
- if (!isValidProjectName(project.name)) {
- setSampleProject(undefined);
- return;
- }
- await loadProjectIamPolicy(project.name);
- if (cancelled) return;
- setSampleProject(project);
- })();
- return () => {
- cancelled = true;
- };
- }, [quickStartEnabled, loadProjectIamPolicy]);
-
- useEffect(() => {
- if (!sampleProject) {
- setSampleIssueExists(false);
- setSampleSheetExists(false);
- return;
- }
- let cancelled = false;
- void (async () => {
- const issue = await useAppStore
- .getState()
- .fetchIssueByName(
- `${sampleProject.name}/issues/${SAMPLE_ISSUE_ID}`,
- true /* silent */
- );
- if (!cancelled) setSampleIssueExists(!!issue);
- })();
- void (async () => {
- const sheet = await useAppStore
- .getState()
- .getOrFetchSavedQueryByName(
- `${sampleProject.name}/sheets/${SAMPLE_SHEET_ID}`,
- true /* silent */
- );
- if (!cancelled) setSampleSheetExists(!!sheet);
- })();
- return () => {
- cancelled = true;
- };
- }, [sampleProject]);
-
- // ---- intro list (memoized + permission-filtered) ----------------------
-
- const introList = useMemo<IntroItem[]>(() => {
- const sampleProjectId = sampleProject
- ? extractProjectResourceName(sampleProject.name)
- : extractProjectResourceName(UNKNOWN_PROJECT_NAME);
- const all: IntroItem[] = [
- {
- name: t("quick-start.view-an-issue"),
- link: {
- name: PROJECT_V1_ROUTE_ISSUE_DETAIL,
- params: { projectId: sampleProjectId, issueId: SAMPLE_ISSUE_ID },
- },
- done: issueVisited,
- hide: !sampleIssueExists,
- requiredPermissions: ["bb.issues.get", "bb.projects.get"],
- needsProject: true,
- },
- {
- name: t("quick-start.query-data"),
- link: {
- name: SQL_EDITOR_SAVED_QUERY_MODULE,
- params: {
- project: SAMPLE_PROJECT_NAME,
- savedQuery: SAMPLE_SHEET_ID,
- },
- },
- done: dataQueried,
- hide: !sampleSheetExists,
- requiredPermissions: [
- "bb.sql.select",
- "bb.projects.get",
- "bb.savedQueries.search",
- ],
- needsProject: true,
- },
- {
- name: t("quick-start.visit-project"),
- link: { name: PROJECT_V1_ROUTE_DASHBOARD },
- done: projectVisited,
- requiredPermissions: ["bb.projects.list"],
- },
- {
- name: t("quick-start.visit-environment"),
- link: { name: ENVIRONMENT_V1_ROUTE_DASHBOARD },
- done: environmentVisited,
- requiredPermissions: ["bb.settings.getEnvironment"],
- },
- {
- name: t("quick-start.visit-instance"),
- link: { name: INSTANCE_ROUTE_DASHBOARD },
- done: instanceVisited,
- requiredPermissions: ["bb.instances.list"],
- },
- {
- name: t("quick-start.visit-database"),
- link: { name: DATABASE_ROUTE_DASHBOARD },
- done: databaseVisited,
- requiredPermissions: ["bb.databases.list"],
- },
- {
- name: t("quick-start.visit-member"),
- link: { name: WORKSPACE_ROUTE_MEMBERS },
- done: memberVisited,
- requiredPermissions: ["bb.workspaces.getIamPolicy"],
- },
- ];
- return all.filter((item) => {
- if (item.hide) return false;
- const perms = item.requiredPermissions ?? [];
- if (item.needsProject) {
- if (!sampleProject) return false;
- return perms.every((p) => hasProjectPermissionV2(sampleProject, p));
- }
- return perms.every(hasWorkspacePermissionV2);
- });
- }, [
- t,
- sampleProject,
- sampleIssueExists,
- sampleSheetExists,
- issueVisited,
- dataQueried,
- projectVisited,
- environmentVisited,
- instanceVisited,
- databaseVisited,
- memberVisited,
- ]);
-
- const showQuickstart = quickStartEnabled && !hidden;
- const currentStep = useMemo(() => {
- let i = 0;
- while (i < introList.length && introList[i].done) i++;
- return i;
- }, [introList]);
-
- const isTaskActive = (index: number) => {
- for (let i = index - 1; i >= 0; i--) {
- if (!introList[i].done) return false;
- }
- return !introList[index].done;
- };
-
- const percent = useMemo(() => {
- const total = introList.length;
- if (total === 0) return "0%";
- if (currentStep === 0) return "3rem";
- if (currentStep === total - 1) return "calc(100% - 3rem)";
- const offset = 0.5;
- const unit = 100 / total;
- return `${Math.min((currentStep + offset) * unit, 100)}%`;
- }, [currentStep, introList.length]);
-
- const handleHide = (silent = false) => {
- useAppStore
- .getState()
- .saveIntroStateByKey({ key: "hidden", newState: true });
- if (!silent) {
- pushNotification({
- module: "bytebase",
- style: "INFO",
- title: t("quick-start.notice.title"),
- description: t("quick-start.notice.desc"),
- manualHide: true,
- });
- }
- };
-
- if (!showQuickstart || introList.length === 0) {
- return null;
- }
-
- return (
- <div className="py-2 px-4 w-full shrink-0 border-t border-block-border hidden lg:block bg-yellow-50">
- <p className="text-sm font-medium text-gray-900 flex items-center justify-between">
- <span>
- 🎈 {t("quick-start.self")} - {t("quick-start.guide")}
- </span>
- <button
- type="button"
- className="rounded-xs p-1 hover:bg-control-bg cursor-pointer"
- aria-label={t("common.close")}
- onClick={() => handleHide()}
- >
- <X className="w-4 h-4" />
- </button>
- </p>
- <div className="mt-2" aria-hidden="true">
- <div className="overflow-hidden rounded-full bg-gray-200">
- <div
- className="h-2 rounded-full bg-indigo-600"
- style={{ width: percent }}
- />
- </div>
- <div
- className="mt-2 hidden text-sm font-medium text-gray-600 sm:grid"
- style={{
- gridTemplateColumns: `repeat(${introList.length}, minmax(0, 1fr))`,
- }}
- >
- {introList.map((intro, index) => {
- const active = isTaskActive(index);
- return (
- <RouterLink
- key={`${intro.name}-${index}`}
- to={intro.link}
- className={cn(
- "group cursor-pointer flex items-center gap-x-1 text-sm font-medium",
- index === 0 && "justify-start",
- index > 0 && index < introList.length - 1 && "justify-center",
- index === introList.length - 1 && "justify-end",
- active
- ? "text-indigo-600"
- : "text-control-light group-hover:text-control-light-hover",
- intro.done && "line-through"
- )}
- >
- <span className="relative h-5 w-5 inline-flex items-center justify-center">
- {intro.done ? (
- <CheckCircle className="w-4 h-auto text-success group-hover:text-success-hover" />
- ) : active ? (
- <span className="relative flex h-3 w-3">
- <span
- className="absolute inline-flex h-full w-full rounded-full bg-indigo-400 opacity-75"
- style={{
- animation:
- "ping 2s cubic-bezier(0, 0, 0.2, 1) infinite",
- }}
- />
- <span className="relative inline-flex rounded-full h-3 w-3 bg-indigo-500" />
- </span>
- ) : (
- <span className="h-2 w-2 bg-gray-300 rounded-full group-hover:bg-gray-400" />
- )}
- </span>
- <span className="inline-flex">{intro.name}</span>
- </RouterLink>
- );
- })}
- </div>
- </div>
- </div>
- );
-}
diff --git a/frontend/src/components/WorkspaceSetupGuide.test.tsx b/frontend/src/components/WorkspaceSetupGuide.test.tsx
index f87ab09fdc..f75ec81d67 100644
--- a/frontend/src/components/WorkspaceSetupGuide.test.tsx
+++ b/frontend/src/components/WorkspaceSetupGuide.test.tsx
@@ -2,6 +2,13 @@ import type { ReactElement, ReactNode } from "react";
import { act } from "react";
import { createRoot } from "react-dom/client";
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+import {
+ DATABASE_ROUTE_DASHBOARD,
+ INSTANCE_ROUTE_DATABASE_DETAIL,
+ PROJECT_V1_ROUTE_DATABASE_DETAIL,
+ SQL_EDITOR_DATABASE_MODULE,
+} from "@/app/router/handles";
+import { sqlEditorEvents } from "@/modules/sql-editor/model/events";
(
globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }
@@ -12,25 +19,29 @@ const mocks = vi.hoisted(() => ({
projectsByName: {} as Record<string, unknown>,
instancesByName: {} as Record<string, unknown>,
databasesByName: {} as Record<string, unknown>,
- fetchProjectList: vi.fn(async () => ({
+ fetchProjectList: vi.fn(async (_?: { pageToken?: string }) => ({
projects: [] as unknown[],
nextPageToken: "",
})),
- fetchInstanceList: vi.fn(async () => ({
- instances: [] as unknown[],
- nextPageToken: "",
- })),
- fetchDatabases: vi.fn(async (_?: { parent?: string }) => ({
- databases: [] as unknown[],
- nextPageToken: "",
- })),
+ fetchInstanceList: vi.fn(
+ async (_?: { parent?: string; pageToken?: string }) => ({
+ instances: [] as unknown[],
+ nextPageToken: "",
+ })
+ ),
+ fetchDatabases: vi.fn(
+ async (_?: { parent?: string; pageToken?: string }) => ({
+ databases: [] as unknown[],
+ nextPageToken: "",
+ })
+ ),
introState: {} as Record<string, boolean>,
getIntroStateByKey: vi.fn((_key: string) => false),
saveIntroStateByKey: vi.fn(
(_: { key: string; newState: boolean }) => undefined
),
introStateVersion: 0,
- searchQueryHistories: vi.fn(async () => ({
+ searchQueryHistories: vi.fn(async (_?: { pageToken?: string }) => ({
queryHistories: [] as unknown[],
nextPageToken: "",
})),
@@ -39,13 +50,23 @@ const mocks = vi.hoisted(() => ({
},
hasWorkspacePermissionV2: vi.fn(() => true),
preCreateIssue: vi.fn(),
- currentRoute: { name: "workspace.home" } as { name?: string },
+ currentRoute: { name: "workspace.home" } as {
+ name?: string;
+ params?: Record<string, string | undefined>;
+ },
routerPush: vi.fn(),
captureMetric: vi.fn(),
defaultProjectName: "projects/default",
+ sampleInstances: [] as { instance: string }[],
+ userCountInIam: 1,
+ hideQuickStart: false,
+ workspaceName: "workspaces/default",
}));
const dismissedIntroStateKey = "workspace-setup-guide.dismissed";
+const databaseExploredIntroStateKey =
+ "workspace-setup-guide.database-explored";
+const queryExecutedIntroStateKey = "workspace-setup-guide.query-executed";
vi.mock("react-i18next", () => ({
initReactI18next: { type: "3rdParty", init: () => {} },
@@ -110,10 +131,21 @@ vi.mock("@/stores/app", () => {
workspace: "workspaces/default",
},
workspace: { name: "workspaces/default" },
+ workspaceResourceName: () => mocks.workspaceName,
workspacePolicy: mocks.workspacePolicy,
- serverInfo: { defaultProject: mocks.defaultProjectName },
+ hasWorkspacePermission: mocks.hasWorkspacePermissionV2,
+ serverInfo: {
+ defaultProject: mocks.defaultProjectName,
+ sample: { instances: mocks.sampleInstances },
+ },
introStateVersion: mocks.introStateVersion,
getIntroStateByKey: mocks.getIntroStateByKey,
+ workspaceSetupGuideEnabled: () =>
+ !mocks.hideQuickStart &&
+ mocks.userCountInIam === 1 &&
+ ["bb.projects.list", "bb.instances.list", "bb.databases.list"].every(
+ mocks.hasWorkspacePermissionV2
+ ),
});
const useAppStore = (selector?: (s: ReturnType<typeof getState>) => unknown) =>
selector ? selector(getState()) : getState();
@@ -151,10 +183,13 @@ vi.mock("@/utils", () => ({
};
},
extractDatabaseResourceName: (name: string) => {
- const match = name.match(/^instances\/([^/]+)\/databases\/([^/]+)$/);
+ const match = name.match(
+ /^(?<instance>(?:projects\/[^/]+\/)?instances\/(?<instanceName>[^/]+))\/databases\/(?<databaseName>[^/]+)$/
+ );
return {
- instanceName: match?.[1] ?? "",
- databaseName: match?.[2] ?? "",
+ instance: match?.groups?.instance ?? "",
+ instanceName: match?.groups?.instanceName ?? "",
+ databaseName: match?.groups?.databaseName ?? "",
};
},
extractInstanceResourceName: (name: string) =>
@@ -210,6 +245,10 @@ beforeEach(() => {
mocks.hasWorkspacePermissionV2.mockReturnValue(true);
mocks.currentRoute = { name: "workspace.home" };
mocks.defaultProjectName = "projects/default";
+ mocks.sampleInstances = [];
+ mocks.userCountInIam = 1;
+ mocks.hideQuickStart = false;
+ mocks.workspaceName = "workspaces/default";
container = document.createElement("div");
document.body.appendChild(container);
root = createRoot(container);
@@ -267,7 +306,7 @@ describe("WorkspaceSetupGuide", () => {
container.querySelector("[data-testid='setup-step-hasInstance']")?.tagName
).toBe("BUTTON");
expect(
- container.querySelector("[data-testid='setup-step-hasProjectDatabase']")
+ container.querySelector("[data-testid='setup-step-hasExploredDatabase']")
?.tagName
).toBe("BUTTON");
expect(
@@ -330,19 +369,41 @@ describe("WorkspaceSetupGuide", () => {
});
it("hides when the workspace has more than one member", async () => {
- mocks.workspacePolicy = {
- bindings: [
- {
- role: "roles/workspaceAdmin",
- },
- ],
- };
+ mocks.userCountInIam = 2;
+
+ await render(<WorkspaceSetupGuide />);
+
+ expect(container.textContent).toBe("");
+ expect(mocks.fetchProjectList).not.toHaveBeenCalled();
+ });
+
+ it.each([0, 2])("hides when IAM user count is %s", async (count) => {
+ mocks.userCountInIam = count;
+
+ await render(<WorkspaceSetupGuide />);
+
+ expect(container.textContent).toBe("");
+ expect(mocks.fetchProjectList).not.toHaveBeenCalled();
+ });
+
+ it("hides when the quick-start feature is disabled", async () => {
+ mocks.hideQuickStart = true;
+
+ await render(<WorkspaceSetupGuide />);
+
+ expect(container.textContent).toBe("");
+ expect(mocks.fetchProjectList).not.toHaveBeenCalled();
+ });
+
+ it("hides when the user cannot list instances", async () => {
+ mocks.hasWorkspacePermissionV2.mockReturnValue(false);
await render(<WorkspaceSetupGuide />);
expect(container.textContent).toBe("");
expect(mocks.fetchProjectList).not.toHaveBeenCalled();
+ expect(mocks.fetchInstanceList).not.toHaveBeenCalled();
+ expect(mocks.fetchDatabases).not.toHaveBeenCalled();
});
it("shows setup step descriptions in tooltips", async () => {
@@ -376,7 +437,7 @@ describe("WorkspaceSetupGuide", () => {
await render(<WorkspaceSetupGuide />);
const prepareDatabaseStep = container.querySelector(
- "[data-testid='setup-step-hasProjectDatabase']"
+ "[data-testid='setup-step-hasExploredDatabase']"
) as HTMLButtonElement | null;
expect(prepareDatabaseStep).toBeDisabled();
@@ -456,7 +517,7 @@ describe("WorkspaceSetupGuide", () => {
expect(mocks.fetchProjectList).not.toHaveBeenCalled();
});
- it("advances to the project database connection step after a project exists", async () => {
+ it("connects an instance from the selected project's instance page", async () => {
mocks.fetchProjectList.mockResolvedValue({
projects: [{ name: "projects/project-a" }],
nextPageToken: "",
@@ -474,9 +535,9 @@ describe("WorkspaceSetupGuide", () => {
await Promise.resolve();
});
expect(mocks.routerPush).toHaveBeenCalledWith({
- name: "workspace.project.database",
+ name: "workspace.project.instance",
params: { projectId: "project-a" },
- query: { intro: "connect-database" },
+ query: { intro: "create-instance" },
});
expect(
container.querySelector("[data-testid='setup-step-hasFirstQuery']")
@@ -484,12 +545,45 @@ describe("WorkspaceSetupGuide", () => {
).toBe("BUTTON");
});
+ it("keeps the setup project when the first database belongs elsewhere", async () => {
+ mocks.fetchProjectList.mockResolvedValue({
+ projects: [{ name: "projects/project-a" }],
+ nextPageToken: "",
+ });
+ mocks.fetchDatabases.mockResolvedValue({
+ databases: [
+ {
+ name: "instances/sample/databases/employee",
+ project: "projects/default",
+ },
+ ],
+ nextPageToken: "",
+ });
+
+ await render(<WorkspaceSetupGuide />);
+
+ await act(async () => {
+ (
+ container.querySelector(
+ "[data-testid='setup-step-hasInstance']"
+ ) as HTMLButtonElement | null
+ )?.click();
+ await Promise.resolve();
+ });
+
+ expect(mocks.routerPush).toHaveBeenCalledWith({
+ name: "workspace.project.instance",
+ params: { projectId: "project-a" },
+ query: { intro: "create-instance" },
+ });
+ });
+
it("disables the prepare database step until a project and instance exist", async () => {
await render(<WorkspaceSetupGuide />);
expect(
container.querySelector(
- "[data-testid='setup-step-hasProjectDatabase']"
+ "[data-testid='setup-step-hasExploredDatabase']"
)
).toBeDisabled();
@@ -502,12 +596,12 @@ describe("WorkspaceSetupGuide", () => {
expect(
container.querySelector(
- "[data-testid='setup-step-hasProjectDatabase']"
+ "[data-testid='setup-step-hasExploredDatabase']"
)
).toBeDisabled();
});
- it("routes prepare database with transfer context for the database page to resolve after loading", async () => {
+ it("opens workspace databases with transfer guidance when the project has no databases", async () => {
mocks.fetchProjectList.mockResolvedValue({
projects: [{ name: "projects/project-a" }],
nextPageToken: "",
@@ -524,7 +618,7 @@ describe("WorkspaceSetupGuide", () => {
await render(<WorkspaceSetupGuide />);
const prepareStep = container.querySelector(
- "[data-testid='setup-step-hasProjectDatabase']"
+ "[data-testid='setup-step-hasExploredDatabase']"
) as HTMLButtonElement | null;
expect(prepareStep).not.toBeDisabled();
@@ -543,7 +637,7 @@ describe("WorkspaceSetupGuide", () => {
});
});
- it("routes prepare database with a transfer tip when workspace databases exist outside the project", async () => {
+ it("opens project databases with query and change guidance when the project has a database", async () => {
mocks.fetchProjectList.mockResolvedValue({
projects: [{ name: "projects/project-a" }],
nextPageToken: "",
@@ -552,18 +646,20 @@ describe("WorkspaceSetupGuide", () => {
instances: [{ name: "instances/instance-a" }],
nextPageToken: "",
});
- mocks.fetchDatabases.mockImplementation(async ({ parent } = {}) => ({
- databases:
- parent === "-"
- ? [{ name: "instances/instance-a/databases/db-a" }]
- : [],
+ mocks.fetchDatabases.mockResolvedValue({
+ databases: [
+ {
+ name: "instances/instance-a/databases/db-a",
+ project: "projects/project-a",
+ },
+ ],
nextPageToken: "",
- }));
+ });
await render(<WorkspaceSetupGuide />);
const prepareStep = container.querySelector(
- "[data-testid='setup-step-hasProjectDatabase']"
+ "[data-testid='setup-step-hasExploredDatabase']"
) as HTMLButtonElement | null;
expect(prepareStep).not.toBeDisabled();
@@ -574,14 +670,38 @@ describe("WorkspaceSetupGuide", () => {
});
expect(mocks.routerPush).toHaveBeenCalledWith({
- name: "workspace.database",
+ name: "workspace.project.database",
+ params: { projectId: "project-a" },
query: {
- intro: "prepare-database",
- tip: "transfer-databases-to-project",
+ intro: "project-instance-synced",
},
});
});
+ it("does not replay create guidance from completed steps", async () => {
+ mocks.fetchProjectList.mockResolvedValue({
+ projects: [{ name: "projects/project-a" }],
+ nextPageToken: "",
+ });
+ mocks.fetchInstanceList.mockResolvedValue({
+ instances: [{ name: "instances/instance-a" }],
+ nextPageToken: "",
+ });
+
+ await render(<WorkspaceSetupGuide />);
+
+ await act(async () => {
+ (
+ container.querySelector(
+ "[data-testid='setup-step-hasProject']"
+ ) as HTMLButtonElement | null
+ )?.click();
+ await Promise.resolve();
+ });
+
+ expect(mocks.routerPush).not.toHaveBeenCalled();
+ });
+
it("highlights the setup step matching the current route", async () => {
mocks.currentRoute = { name: "workspace.instance" };
@@ -607,7 +727,12 @@ describe("WorkspaceSetupGuide", () => {
nextPageToken: "",
});
mocks.fetchDatabases.mockResolvedValue({
- databases: [{ name: "instances/instance-a/databases/db-a" }],
+ databases: [
+ {
+ name: "instances/instance-a/databases/db-a",
+ project: "projects/default",
+ },
+ ],
nextPageToken: "",
});
@@ -621,6 +746,7 @@ describe("WorkspaceSetupGuide", () => {
});
it("does not use the default project as the setup project", async () => {
+ mocks.introState[databaseExploredIntroStateKey] = true;
mocks.fetchProjectList.mockResolvedValue({
projects: [
{ name: "projects/default" },
@@ -632,21 +758,25 @@ describe("WorkspaceSetupGuide", () => {
instances: [{ name: "instances/instance-a" }],
nextPageToken: "",
});
- mocks.fetchDatabases.mockImplementation(async ({ parent } = {}) => ({
- databases:
- parent === "projects/project-a"
- ? [{ name: "instances/instance-a/databases/db-a" }]
- : [],
+ mocks.fetchDatabases.mockResolvedValue({
+ databases: [
+ {
+ name: "instances/instance-a/databases/db-a",
+ project: "projects/project-a",
+ },
+ ],
nextPageToken: "",
- }));
+ });
await render(<WorkspaceSetupGuide />);
- expect(mocks.fetchDatabases).toHaveBeenCalledWith({
- parent: "projects/project-a",
- pageSize: 1,
- silent: true,
- });
+ expect(mocks.fetchDatabases).toHaveBeenCalledWith(
+ expect.objectContaining({
+ parent: "workspaces/default",
+ pageSize: 1,
+ filter: { project: "projects/project-a" },
+ })
+ );
const actionButton = container.querySelector(
"[data-testid='secondary-action']"
@@ -662,6 +792,286 @@ describe("WorkspaceSetupGuide", () => {
]);
});
+ it("counts self-host sample resources as project and instance readiness", async () => {
+ mocks.sampleInstances = [
+ { instance: "instances/sample-one" },
+ { instance: "instances/sample-two" },
+ ];
+ mocks.fetchProjectList.mockResolvedValue({
+ projects: [{ name: "projects/project-sample" }],
+ nextPageToken: "",
+ });
+ mocks.fetchInstanceList.mockResolvedValue({
+ instances: [
+ { name: "instances/sample-one" },
+ { name: "instances/sample-two" },
+ ],
+ nextPageToken: "",
+ });
+ mocks.fetchDatabases.mockResolvedValue({
+ databases: [
+ {
+ name: "instances/sample-one/databases/employee",
+ project: "projects/project-sample",
+ },
+ {
+ name: "instances/sample-two/databases/employee",
+ project: "projects/project-sample",
+ },
+ ],
+ nextPageToken: "",
+ });
+
+ await render(<WorkspaceSetupGuide />);
+
+ for (const key of ["hasProject", "hasInstance"]) {
+ expect(
+ container
+ .querySelector(`[data-testid='setup-step-${key}']`)
+ ?.querySelector(".lucide-circle-check-big")
+ ).not.toBeNull();
+ }
+ for (const key of ["hasExploredDatabase", "hasFirstQuery"]) {
+ expect(
+ container
+ .querySelector(`[data-testid='setup-step-${key}']`)
+ ?.querySelector(".lucide-circle-check-big")
+ ).toBeNull();
+ }
+ });
+
+ it("counts SaaS sample resources as project and instance readiness", async () => {
+ mocks.sampleInstances = [
+ { instance: "projects/app/instances/saas-sample" },
+ ];
+ mocks.fetchProjectList.mockResolvedValue({
+ projects: [{ name: "projects/app" }],
+ nextPageToken: "",
+ });
+ mocks.fetchInstanceList.mockResolvedValue({
+ instances: [{ name: "projects/app/instances/saas-sample" }],
+ nextPageToken: "",
+ });
+ mocks.fetchDatabases.mockResolvedValue({
+ databases: [
+ {
+ name: "projects/app/instances/saas-sample/databases/employee",
+ project: "projects/app",
+ },
+ ],
+ nextPageToken: "",
+ });
+
+ await render(<WorkspaceSetupGuide />);
+
+ for (const key of ["hasProject", "hasInstance"]) {
+ expect(
+ container
+ .querySelector(`[data-testid='setup-step-${key}']`)
+ ?.querySelector(".lucide-circle-check-big")
+ ).not.toBeNull();
+ }
+ for (const key of ["hasExploredDatabase", "hasFirstQuery"]) {
+ expect(
+ container
+ .querySelector(`[data-testid='setup-step-${key}']`)
+ ?.querySelector(".lucide-circle-check-big")
+ ).toBeNull();
+ }
+ });
+
+ it("uses only the first resource page", async () => {
+ mocks.introState[databaseExploredIntroStateKey] = true;
+ mocks.sampleInstances = [{ instance: "instances/sample" }];
+ mocks.fetchProjectList.mockResolvedValue({
+ projects: [{ name: "projects/project-sample" }],
+ nextPageToken: "project-page-2",
+ });
+ mocks.fetchInstanceList.mockResolvedValue({
+ instances: [{ name: "instances/sample" }],
+ nextPageToken: "instance-page-2",
+ });
+ mocks.fetchDatabases.mockResolvedValue({
+ databases: [
+ {
+ name: "instances/sample/databases/employee",
+ project: "projects/project-sample",
+ },
+ ],
+ nextPageToken: "database-page-2",
+ });
+
+ await render(<WorkspaceSetupGuide />);
+
+ expect(
+ container
+ .querySelector("[data-testid='setup-step-hasExploredDatabase']")
+ ?.querySelector(".lucide-circle-check-big")
+ ).not.toBeNull();
+ expect(
+ container.querySelector("[data-testid='active-action']")
+ ).toHaveAttribute(
+ "data-route-params",
+ JSON.stringify({
+ project: "project-sample",
+ instance: "sample",
+ database: "employee",
+ })
+ );
+ expect(mocks.fetchProjectList).toHaveBeenCalledTimes(1);
+ expect(mocks.fetchInstanceList).toHaveBeenCalledTimes(1);
+ expect(mocks.fetchDatabases).toHaveBeenCalledTimes(1);
+ expect(mocks.fetchProjectList).toHaveBeenCalledWith(
+ expect.objectContaining({ pageSize: 1 })
+ );
+ expect(mocks.fetchInstanceList).toHaveBeenCalledWith(
+ expect.objectContaining({ pageSize: 1 })
+ );
+ expect(mocks.fetchDatabases).toHaveBeenCalledWith(
+ expect.objectContaining({
+ parent: "workspaces/default",
+ pageSize: 1,
+ filter: { project: "projects/project-sample" },
+ })
+ );
+ });
+
+ it.each([
+ "fetchProjectList",
+ "fetchInstanceList",
+ "fetchDatabases",
+ ] as const)("keeps the guide available when %s fails", async (key) => {
+ if (key === "fetchDatabases") {
+ mocks.fetchProjectList.mockResolvedValue({
+ projects: [{ name: "projects/project-a" }],
+ nextPageToken: "",
+ });
+ }
+ mocks[key].mockRejectedValueOnce(new Error("permission denied"));
+
+ await render(<WorkspaceSetupGuide />);
+
+ expect(mocks[key]).toHaveBeenCalled();
+ expect(container.textContent).toContain("workspace-setup-guide.self");
+ expect(
+ container.querySelector("[data-testid='setup-step-hasProject']")
+ ).not.toBeNull();
+ });
+
+ it.each([
+ {
+ name: PROJECT_V1_ROUTE_DATABASE_DETAIL,
+ params: {
+ projectId: "project-sample",
+ instanceId: "sample-one",
+ databaseName: "employee",
+ },
+ },
+ {
+ name: INSTANCE_ROUTE_DATABASE_DETAIL,
+ params: {
+ instanceId: "sample-one",
+ databaseName: "employee",
+ },
+ },
+ {
+ name: SQL_EDITOR_DATABASE_MODULE,
+ params: {
+ project: "project-sample",
+ instance: "sample-one",
+ database: "employee",
+ },
+ },
+ ])("persists database exploration on $name", async (route) => {
+ mocks.currentRoute = route;
+ mocks.fetchProjectList.mockResolvedValue({
+ projects: [{ name: "projects/project-sample" }],
+ nextPageToken: "",
+ });
+ mocks.fetchInstanceList.mockResolvedValue({
+ instances: [{ name: "instances/sample-one" }],
+ nextPageToken: "",
+ });
+ mocks.fetchDatabases.mockResolvedValue({
+ databases: [
+ {
+ name: "instances/sample-one/databases/employee",
+ project: "projects/project-sample",
+ },
+ ],
+ nextPageToken: "",
+ });
+
+ await render(<WorkspaceSetupGuide />);
+
+ expect(mocks.saveIntroStateByKey).toHaveBeenCalledWith({
+ key: databaseExploredIntroStateKey,
+ newState: true,
+ });
+ });
+
+ it("does not count the workspace database list as exploration", async () => {
+ mocks.currentRoute = { name: DATABASE_ROUTE_DASHBOARD };
+ mocks.fetchProjectList.mockResolvedValue({
+ projects: [{ name: "projects/project-a" }],
+ nextPageToken: "",
+ });
+ mocks.fetchInstanceList.mockResolvedValue({
+ instances: [{ name: "instances/instance-a" }],
+ nextPageToken: "",
+ });
+ mocks.fetchDatabases.mockResolvedValue({
+ databases: [
+ {
+ name: "instances/instance-a/databases/db-a",
+ project: "projects/project-a",
+ },
+ ],
+ nextPageToken: "",
+ });
+
+ await render(<WorkspaceSetupGuide />);
+
+ expect(mocks.saveIntroStateByKey).not.toHaveBeenCalledWith({
+ key: databaseExploredIntroStateKey,
+ newState: true,
+ });
+ expect(
+ container
+ .querySelector("[data-testid='setup-step-hasExploredDatabase']")
+ ?.querySelector(".lucide-circle-check-big")
+ ).toBeNull();
+ });
+
+ it("keeps database exploration complete after it is persisted", async () => {
+ mocks.introState[databaseExploredIntroStateKey] = true;
+ mocks.fetchProjectList.mockResolvedValue({
+ projects: [{ name: "projects/project-a" }],
+ nextPageToken: "",
+ });
+ mocks.fetchInstanceList.mockResolvedValue({
+ instances: [{ name: "instances/instance-a" }],
+ nextPageToken: "",
+ });
+ mocks.fetchDatabases.mockResolvedValue({
+ databases: [
+ {
+ name: "instances/instance-a/databases/db-a",
+ project: "projects/project-a",
+ },
+ ],
+ nextPageToken: "",
+ });
+
+ await render(<WorkspaceSetupGuide />);
+
+ expect(
+ container
+ .querySelector("[data-testid='setup-step-hasExploredDatabase']")
+ ?.querySelector(".lucide-circle-check-big")
+ ).not.toBeNull();
+ });
+
it("does not show the active guide action when already on its route", async () => {
mocks.currentRoute = { name: "workspace.instance.create" };
mocks.fetchProjectList.mockResolvedValue({
@@ -678,7 +1088,7 @@ describe("WorkspaceSetupGuide", () => {
expect(container.querySelector("[data-testid='dismiss-guide']")).not.toBeNull();
});
- it("highlights the setup step matching the current route", async () => {
+ it("highlights the next incomplete step when the current route step is done", async () => {
mocks.currentRoute = { name: "workspace.project" };
mocks.fetchProjectList.mockResolvedValue({
projects: [{ name: "projects/project-a" }],
@@ -699,40 +1109,47 @@ describe("WorkspaceSetupGuide", () => {
container
.querySelector("[data-testid='setup-step-hasProject']")
?.getAttribute("class")
- ).toContain("bg-accent/10");
+ ).not.toContain("bg-accent/10");
expect(
container
- .querySelector("[data-testid='setup-step-hasProjectDatabase']")
+ .querySelector("[data-testid='setup-step-hasExploredDatabase']")
?.getAttribute("class")
- ).not.toContain("bg-accent/10");
+ ).toContain("bg-accent/10");
expect(container.querySelector("[data-testid='active-action']")).toBeNull();
});
it("highlights the active query step on project database pages", async () => {
- mocks.currentRoute = { name: "workspace.project.database" };
+ mocks.currentRoute = {
+ name: PROJECT_V1_ROUTE_DATABASE_DETAIL,
+ params: {
+ projectId: "project-a",
+ instanceId: "instance-a",
+ databaseName: "db-a",
+ },
+ };
mocks.fetchProjectList.mockResolvedValue({
projects: [{ name: "projects/project-a" }],
nextPageToken: "",
});
- mocks.fetchInstanceList.mockImplementation(
- async (params?: { parent?: string }) => ({
- instances:
- params?.parent === "projects/project-a"
- ? [{ name: "projects/project-a/instances/instance-a" }]
- : [],
- nextPageToken: "",
- })
- );
+ mocks.fetchInstanceList.mockResolvedValue({
+ instances: [{ name: "projects/project-a/instances/instance-a" }],
+ nextPageToken: "",
+ });
mocks.fetchDatabases.mockResolvedValue({
- databases: [{ name: "instances/instance-a/databases/db-a" }],
+ databases: [
+ {
+ name: "instances/instance-a/databases/db-a",
+ project: "projects/project-a",
+ },
+ ],
nextPageToken: "",
});
await render(<WorkspaceSetupGuide />);
expect(mocks.fetchInstanceList).toHaveBeenCalledWith(
- expect.objectContaining({ parent: "projects/project-a" })
+ expect.objectContaining({ pageSize: 1 })
);
expect(
container
@@ -766,7 +1183,7 @@ describe("WorkspaceSetupGuide", () => {
for (const key of [
"hasProject",
"hasInstance",
- "hasProjectDatabase",
+ "hasExploredDatabase",
"hasFirstQuery",
]) {
expect(
@@ -779,30 +1196,6 @@ describe("WorkspaceSetupGuide", () => {
expect(container.querySelector("[data-testid='active-action']")).toBeNull();
});
- it("scopes the query history check to the found project", async () => {
- mocks.fetchProjectList.mockResolvedValue({
- projects: [{ name: "projects/project-a" }],
- nextPageToken: "",
- });
- mocks.fetchDatabases.mockImplementation(async ({ parent } = {}) => ({
- databases:
- parent === "projects/project-a"
- ? [{ name: "instances/instance-a/databases/db-a" }]
- : [],
- nextPageToken: "",
- }));
- mocks.searchQueryHistories.mockResolvedValue({
- queryHistories: [{ name: "projects/project-a/queryHistories/h1" }],
- nextPageToken: "",
- });
-
- await render(<WorkspaceSetupGuide />);
-
- expect(mocks.searchQueryHistories).toHaveBeenCalledWith(
- expect.objectContaining({ parent: "projects/project-a" })
- );
- });
-
it("asks users to create a database when the connected instance has no databases", async () => {
mocks.fetchProjectList.mockResolvedValue({
projects: [{ name: "projects/project-a" }],
@@ -851,6 +1244,7 @@ describe("WorkspaceSetupGuide", () => {
});
it("opens SQL Editor as the primary action after a database is connected", async () => {
+ mocks.introState[databaseExploredIntroStateKey] = true;
mocks.fetchProjectList.mockResolvedValue({
projects: [{ name: "projects/project-a" }],
nextPageToken: "",
@@ -860,7 +1254,12 @@ describe("WorkspaceSetupGuide", () => {
nextPageToken: "",
});
mocks.fetchDatabases.mockResolvedValue({
- databases: [{ name: "instances/instance-a/databases/db-a" }],
+ databases: [
+ {
+ name: "instances/instance-a/databases/db-a",
+ project: "projects/project-a",
+ },
+ ],
nextPageToken: "",
});
@@ -869,13 +1268,6 @@ describe("WorkspaceSetupGuide", () => {
expect(container.textContent).toContain(
"workspace-setup-guide.steps.query"
);
- expect(mocks.searchQueryHistories).toHaveBeenCalledWith(
- expect.objectContaining({
- pageSize: 1,
- filter: 'type == "QUERY"',
- })
- );
-
const actionLink = container.querySelector(
"[data-testid='active-action']"
);
@@ -893,6 +1285,21 @@ describe("WorkspaceSetupGuide", () => {
"workspace-setup-guide.actions.query"
);
expect(actionLink?.querySelector(".lucide-square-terminal")).not.toBeNull();
+ expect(actionLink).toHaveAttribute("target", "_blank");
+ expect(actionLink).toHaveAttribute("rel", "noopener noreferrer");
+ expect(
+ container
+ .querySelector("[data-testid='setup-step-hasFirstQuery']")
+ ?.querySelector(".lucide-circle-check-big")
+ ).toBeNull();
+
+ act(() => {
+ (actionLink as HTMLAnchorElement | null)?.click();
+ });
+ expect(mocks.saveIntroStateByKey).not.toHaveBeenCalledWith({
+ key: queryExecutedIntroStateKey,
+ newState: true,
+ });
const secondaryAction = container.querySelector(
"[data-testid='secondary-action']"
@@ -905,9 +1312,218 @@ describe("WorkspaceSetupGuide", () => {
secondaryAction!.compareDocumentPosition(actionLink as Node) &
Node.DOCUMENT_POSITION_FOLLOWING
).toBe(Node.DOCUMENT_POSITION_FOLLOWING);
+
+ act(() => {
+ (secondaryAction as HTMLButtonElement).click();
+ });
+ expect(mocks.preCreateIssue).toHaveBeenCalledWith("projects/project-a", [
+ "instances/instance-a/databases/db-a",
+ ]);
+ });
+
+ it("completes Query data only after SQL execution finishes", async () => {
+ mocks.sampleInstances = [
+ { instance: "projects/app/instances/saas-sample" },
+ ];
+ mocks.fetchProjectList.mockResolvedValue({
+ projects: [{ name: "projects/project-a" }],
+ nextPageToken: "",
+ });
+ mocks.fetchInstanceList.mockResolvedValue({
+ instances: [{ name: "instances/instance-a" }],
+ nextPageToken: "",
+ });
+ mocks.fetchDatabases.mockResolvedValue({
+ databases: [
+ {
+ name: "instances/instance-a/databases/db-a",
+ project: "projects/project-a",
+ },
+ ],
+ nextPageToken: "",
+ });
+
+ await render(<WorkspaceSetupGuide />);
+
+ const queryStep = container.querySelector(
+ "[data-testid='setup-step-hasFirstQuery']"
+ );
+ expect(queryStep?.querySelector(".lucide-circle-check-big")).toBeNull();
+
+ await act(async () => {
+ await sqlEditorEvents.emit("query-executed", {
+ database: "",
+ project: "projects/project-a",
+ });
+ });
+
+ expect(queryStep?.querySelector(".lucide-circle-check-big")).toBeNull();
+ expect(mocks.saveIntroStateByKey).not.toHaveBeenCalledWith({
+ key: queryExecutedIntroStateKey,
+ newState: true,
+ });
+
+ await act(async () => {
+ await sqlEditorEvents.emit("query-executed", {
+ database: "projects/app/instances/saas-sample/databases/employee",
+ project: "projects/project-sample",
+ });
+ });
+
+ expect(mocks.saveIntroStateByKey).toHaveBeenCalledWith({
+ key: databaseExploredIntroStateKey,
+ newState: true,
+ });
+ expect(mocks.saveIntroStateByKey).toHaveBeenCalledWith({
+ key: queryExecutedIntroStateKey,
+ newState: true,
+ });
+ expect(
+ queryStep?.querySelector(".lucide-circle-check-big")
+ ).not.toBeNull();
+ });
+
+ it("keeps query progress and its event target while resource scans finish", async () => {
+ type ProjectResponse = {
+ projects: { name: string }[];
+ nextPageToken: string;
+ };
+ let resolveFirstScan: ((value: ProjectResponse) => void) | undefined;
+ let resolveSecondScan: ((value: ProjectResponse) => void) | undefined;
+ mocks.fetchProjectList
+ .mockImplementationOnce(
+ () =>
+ new Promise((resolve) => {
+ resolveFirstScan = resolve;
+ })
+ )
+ .mockImplementationOnce(
+ () =>
+ new Promise((resolve) => {
+ resolveSecondScan = resolve;
+ })
+ );
+ mocks.fetchInstanceList.mockResolvedValue({
+ instances: [{ name: "instances/discovered-instance" }],
+ nextPageToken: "",
+ });
+ mocks.fetchDatabases.mockResolvedValue({
+ databases: [
+ {
+ name: "instances/discovered-instance/databases/discovered-db",
+ project: "projects/discovered-project",
+ },
+ ],
+ nextPageToken: "",
+ });
+
+ await render(<WorkspaceSetupGuide />);
+ expect(mocks.fetchProjectList).toHaveBeenCalledTimes(1);
+
+ await act(async () => {
+ await sqlEditorEvents.emit("query-executed", {
+ database: "instances/event-instance/databases/event-db",
+ project: "projects/event-project",
+ });
+ });
+ expect(mocks.fetchProjectList).toHaveBeenCalledTimes(2);
+
+ const assertInteractionState = () => {
+ for (const key of ["hasExploredDatabase", "hasFirstQuery"]) {
+ expect(
+ container
+ .querySelector(`[data-testid='setup-step-${key}']`)
+ ?.querySelector(".lucide-circle-check-big")
+ ).not.toBeNull();
+ }
+ expect(
+ container.querySelector("[data-testid='active-action']")
+ ).toHaveAttribute(
+ "data-route-params",
+ JSON.stringify({
+ project: "event-project",
+ instance: "event-instance",
+ database: "event-db",
+ })
+ );
+ };
+
+ await act(async () => {
+ resolveFirstScan?.({
+ projects: [{ name: "projects/discovered-project" }],
+ nextPageToken: "",
+ });
+ await Promise.resolve();
+ await Promise.resolve();
+ await Promise.resolve();
+ await Promise.resolve();
+ });
+ assertInteractionState();
+
+ await act(async () => {
+ resolveSecondScan?.({
+ projects: [{ name: "projects/discovered-project" }],
+ nextPageToken: "",
+ });
+ await Promise.resolve();
+ await Promise.resolve();
+ await Promise.resolve();
+ await Promise.resolve();
+ });
+ assertInteractionState();
+ });
+
+ it("does not reconstruct query completion from query history", async () => {
+ mocks.fetchProjectList.mockResolvedValue({
+ projects: [{ name: "projects/app" }],
+ nextPageToken: "",
+ });
+ mocks.fetchDatabases.mockResolvedValue({
+ databases: [
+ {
+ name: "instances/prod/databases/main",
+ project: "projects/app",
+ },
+ ],
+ nextPageToken: "",
+ });
+ mocks.searchQueryHistories.mockResolvedValue({
+ queryHistories: [
+ { database: "instances/prod/databases/main" },
+ ],
+ nextPageToken: "",
+ });
+
+ await render(<WorkspaceSetupGuide />);
+
+ expect(
+ container
+ .querySelector("[data-testid='setup-step-hasFirstQuery']")
+ ?.querySelector(".lucide-circle-check-big")
+ ).toBeNull();
+ });
+
+ it("does not search query history for guide progress", async () => {
+ mocks.fetchProjectList.mockResolvedValue({
+ projects: [{ name: "projects/app" }],
+ nextPageToken: "",
+ });
+ mocks.fetchDatabases.mockResolvedValue({
+ databases: [
+ {
+ name: "instances/prod/databases/main",
+ project: "projects/app",
+ },
+ ],
+ nextPageToken: "",
+ });
+ await render(<WorkspaceSetupGuide />);
+
+ expect(mocks.searchQueryHistories).not.toHaveBeenCalled();
});
it("activates the query step when users click it after visiting another step", async () => {
+ mocks.introState[databaseExploredIntroStateKey] = true;
mocks.currentRoute = { name: "workspace.database" };
mocks.fetchProjectList.mockResolvedValue({
projects: [{ name: "projects/project-a" }],
@@ -918,7 +1534,12 @@ describe("WorkspaceSetupGuide", () => {
nextPageToken: "",
});
mocks.fetchDatabases.mockResolvedValue({
- databases: [{ name: "instances/instance-a/databases/db-a" }],
+ databases: [
+ {
+ name: "instances/instance-a/databases/db-a",
+ project: "projects/project-a",
+ },
+ ],
nextPageToken: "",
});
@@ -926,21 +1547,21 @@ describe("WorkspaceSetupGuide", () => {
expect(
container
- .querySelector("[data-testid='setup-step-hasProjectDatabase']")
+ .querySelector("[data-testid='setup-step-hasExploredDatabase']")
?.getAttribute("class")
- ).toContain("bg-accent/10");
+ ).not.toContain("bg-accent/10");
expect(
container
.querySelector("[data-testid='setup-step-hasFirstQuery']")
?.getAttribute("class")
- ).not.toContain("bg-accent/10");
+ ).toContain("bg-accent/10");
const queryStep = container.querySelector(
"[data-testid='setup-step-hasFirstQuery']"
);
expect(queryStep?.tagName).toBe("BUTTON");
- expect(queryStep?.getAttribute("class")).not.toContain("bg-accent/10");
+ expect(queryStep?.getAttribute("class")).toContain("bg-accent/10");
await act(async () => {
(queryStep as HTMLButtonElement | null)?.click();
@@ -958,6 +1579,7 @@ describe("WorkspaceSetupGuide", () => {
});
it("opens the first database change flow as a secondary action", async () => {
+ mocks.introState[databaseExploredIntroStateKey] = true;
mocks.fetchProjectList.mockResolvedValue({
projects: [{ name: "projects/project-a" }],
nextPageToken: "",
@@ -967,7 +1589,12 @@ describe("WorkspaceSetupGuide", () => {
nextPageToken: "",
});
mocks.fetchDatabases.mockResolvedValue({
- databases: [{ name: "instances/instance-a/databases/db-a" }],
+ databases: [
+ {
+ name: "instances/instance-a/databases/db-a",
+ project: "projects/project-a",
+ },
+ ],
nextPageToken: "",
});
@@ -1001,6 +1628,8 @@ describe("WorkspaceSetupGuide", () => {
});
it("stays visible after the first query exists", async () => {
+ mocks.introState[databaseExploredIntroStateKey] = true;
+ mocks.introState[queryExecutedIntroStateKey] = true;
mocks.fetchProjectList.mockResolvedValue({
projects: [{ name: "projects/project-a" }],
nextPageToken: "",
@@ -1010,14 +1639,14 @@ describe("WorkspaceSetupGuide", () => {
nextPageToken: "",
});
mocks.fetchDatabases.mockResolvedValue({
- databases: [{ name: "instances/instance-a/databases/db-a" }],
- nextPageToken: "",
- });
- mocks.searchQueryHistories.mockResolvedValue({
- queryHistories: [{ name: "projects/project-a/queryHistories/1" }],
+ databases: [
+ {
+ name: "instances/instance-a/databases/db-a",
+ project: "projects/project-a",
+ },
+ ],
nextPageToken: "",
});
-
await render(<WorkspaceSetupGuide />);
expect(container.textContent).toContain(
@@ -1148,6 +1777,7 @@ describe("WorkspaceSetupGuide", () => {
});
it("refreshes when a database is added to the app store", async () => {
+ mocks.introState[databaseExploredIntroStateKey] = true;
mocks.fetchProjectList.mockResolvedValue({
projects: [{ name: "projects/project-a" }],
nextPageToken: "",
@@ -1168,13 +1798,15 @@ describe("WorkspaceSetupGuide", () => {
mocks.databasesByName = {
"instances/instance-a/databases/db-a": {},
};
- mocks.fetchDatabases.mockImplementation(async ({ parent } = {}) => ({
- databases:
- parent === "projects/project-a"
- ? [{ name: "instances/instance-a/databases/db-a" }]
- : [],
+ mocks.fetchDatabases.mockResolvedValue({
+ databases: [
+ {
+ name: "instances/instance-a/databases/db-a",
+ project: "projects/project-a",
+ },
+ ],
nextPageToken: "",
- }));
+ });
await render(<WorkspaceSetupGuide />);
@@ -1184,6 +1816,7 @@ describe("WorkspaceSetupGuide", () => {
});
it("refreshes when the route changes after setup progress changes elsewhere", async () => {
+ mocks.introState[databaseExploredIntroStateKey] = true;
mocks.fetchProjectList.mockResolvedValue({
projects: [{ name: "projects/project-a" }],
nextPageToken: "",
@@ -1202,13 +1835,15 @@ describe("WorkspaceSetupGuide", () => {
expect(container.querySelector("[data-testid='active-action']")).toBeNull();
mocks.currentRoute = { name: "workspace.member" };
- mocks.fetchDatabases.mockImplementation(async ({ parent } = {}) => ({
- databases:
- parent === "projects/project-a"
- ? [{ name: "instances/instance-a/databases/db-a" }]
- : [],
+ mocks.fetchDatabases.mockResolvedValue({
+ databases: [
+ {
+ name: "instances/instance-a/databases/db-a",
+ project: "projects/project-a",
+ },
+ ],
nextPageToken: "",
- }));
+ });
await render(<WorkspaceSetupGuide />);
diff --git a/frontend/src/components/WorkspaceSetupGuide.tsx b/frontend/src/components/WorkspaceSetupGuide.tsx
index 3e913e3f5c..6d85f759a0 100644
--- a/frontend/src/components/WorkspaceSetupGuide.tsx
+++ b/frontend/src/components/WorkspaceSetupGuide.tsx
@@ -1,16 +1,17 @@
-import { create } from "@bufbuild/protobuf";
import { CheckCircle, Circle, X } from "lucide-react";
-import { useEffect, useMemo, useState } from "react";
+import { useEffect, useMemo, useRef, useState } from "react";
import { useTranslation } from "react-i18next";
-import { queryHistoryServiceClientConnect } from "@/api";
import { createBehaviorMetric } from "@/app/analytics/behavior";
import { behaviorAnalytics } from "@/app/analytics/provider";
import { type RouteTarget, router, useCurrentRoute } from "@/app/router";
import {
DATABASE_ROUTE_DASHBOARD,
INSTANCE_ROUTE_DASHBOARD,
+ INSTANCE_ROUTE_DATABASE_DETAIL,
PROJECT_V1_ROUTE_DASHBOARD,
+ PROJECT_V1_ROUTE_DATABASE_DETAIL,
PROJECT_V1_ROUTE_DATABASES,
+ PROJECT_V1_ROUTE_INSTANCES,
SQL_EDITOR_DATABASE_MODULE,
} from "@/app/router/handles";
import { SQLEditorButton } from "@/components/SQLEditorButton";
@@ -19,29 +20,30 @@ import { Tooltip } from "@/components/ui/tooltip";
import { useIntroStateByKey } from "@/hooks/useAppState";
import { preCreateIssue } from "@/lib/plan/issue";
import {
- CONNECT_DATABASE_PRODUCT_INTRO,
CREATE_INSTANCE_PRODUCT_INTRO,
CREATE_PROJECT_PRODUCT_INTRO,
PREPARE_DATABASE_PRODUCT_INTRO,
PREPARE_DATABASE_TRANSFER_TIP,
PRODUCT_INTRO_QUERY_KEY,
PRODUCT_INTRO_TIP_QUERY_KEY,
+ PROJECT_INSTANCE_SYNCED_PRODUCT_INTRO,
} from "@/lib/productIntro";
import { cn } from "@/lib/utils";
+import { sqlEditorEvents } from "@/modules/sql-editor/model/events";
import { useAppStore } from "@/stores/app";
-import { SearchQueryHistoriesRequestSchema } from "@/types/proto-es/v1/query_history_service_pb";
-import { extractProjectResourceName, hasWorkspacePermissionV2 } from "@/utils";
+import { State } from "@/types/proto-es/v1/common_pb";
+import { extractProjectResourceName } from "@/utils";
type SetupKeys = {
hasProject: boolean;
hasInstance: boolean;
- hasProjectDatabase: boolean;
+ hasExploredDatabase: boolean;
hasFirstQuery: boolean;
};
type SetupState = SetupKeys & {
- hasWorkspaceDatabase: boolean;
projectName: string;
+ databaseProjectName: string;
databaseName: string;
};
@@ -58,23 +60,63 @@ type SetupStep = {
const initialSetupState: SetupState = {
hasProject: false,
hasInstance: false,
- hasWorkspaceDatabase: false,
- hasProjectDatabase: false,
+ hasExploredDatabase: false,
hasFirstQuery: false,
projectName: "",
+ databaseProjectName: "",
databaseName: "",
};
const WORKSPACE_SETUP_GUIDE_DISMISSED_KEY = "workspace-setup-guide.dismissed";
+const WORKSPACE_SETUP_GUIDE_DATABASE_EXPLORED_KEY =
+ "workspace-setup-guide.database-explored";
+const WORKSPACE_SETUP_GUIDE_QUERY_EXECUTED_KEY =
+ "workspace-setup-guide.query-executed";
const isRouteInside = (routeName: string | undefined, parentName: string) =>
routeName === parentName || !!routeName?.startsWith(`${parentName}.`);
+const hasRouteParams = (
+ params: Record<string, string | string[] | undefined>,
+ keys: string[]
+) =>
+ keys.every((key) => {
+ const value = params[key];
+ return typeof value === "string" && value.length > 0;
+ });
+
+const isConcreteDatabaseRoute = (
+ name: string | undefined,
+ params: Record<string, string | string[] | undefined>
+) => {
+ switch (name) {
+ case PROJECT_V1_ROUTE_DATABASE_DETAIL:
+ return hasRouteParams(params, [
+ "projectId",
+ "instanceId",
+ "databaseName",
+ ]);
+ case INSTANCE_ROUTE_DATABASE_DETAIL:
+ return hasRouteParams(params, ["instanceId", "databaseName"]);
+ case SQL_EDITOR_DATABASE_MODULE:
+ return hasRouteParams(params, ["project", "instance", "database"]);
+ default:
+ return false;
+ }
+};
+
export function WorkspaceSetupGuide() {
const { t } = useTranslation();
const currentRoute = useCurrentRoute();
const dismissed = useIntroStateByKey(WORKSPACE_SETUP_GUIDE_DISMISSED_KEY);
- const defaultProject = useAppStore((s) => s.serverInfo?.defaultProject ?? "");
+ const databaseExplored = useIntroStateByKey(
+ WORKSPACE_SETUP_GUIDE_DATABASE_EXPLORED_KEY
+ );
+ const queryExecuted = useIntroStateByKey(
+ WORKSPACE_SETUP_GUIDE_QUERY_EXECUTED_KEY
+ );
+ const serverInfo = useAppStore((s) => s.serverInfo);
+ const defaultProject = serverInfo?.defaultProject ?? "";
const projectCacheSize = useAppStore(
(s) => Object.keys(s.projectsByName).length
);
@@ -84,16 +126,79 @@ export function WorkspaceSetupGuide() {
const databaseCacheSize = useAppStore(
(s) => Object.keys(s.databasesByName).length
);
- const workspaceMemberCount = useAppStore((s) =>
- (s.workspacePolicy?.bindings ?? []).reduce(
- (count, binding) => count + binding.members.length,
- 0
- )
- );
- const hasSingleWorkspaceMember = workspaceMemberCount === 1;
+ const workspaceResourceName = useAppStore((s) => s.workspaceResourceName());
+ const guideEnabled = useAppStore((s) => s.workspaceSetupGuideEnabled());
const [loading, setLoading] = useState(true);
const [selectedStepKey, setSelectedStepKey] = useState<keyof SetupKeys>();
const [setupState, setSetupState] = useState<SetupState>(initialSetupState);
+ const queryTargetRef = useRef<
+ { projectName: string; databaseName: string } | undefined
+ >(undefined);
+
+ useEffect(() => {
+ const off = sqlEditorEvents.on(
+ "query-executed",
+ ({ data: { database, project } }) => {
+ if (!database) {
+ return;
+ }
+
+ queryTargetRef.current = {
+ projectName: project,
+ databaseName: database,
+ };
+ const store = useAppStore.getState();
+ if (!databaseExplored) {
+ store.saveIntroStateByKey({
+ key: WORKSPACE_SETUP_GUIDE_DATABASE_EXPLORED_KEY,
+ newState: true,
+ });
+ }
+ if (!queryExecuted) {
+ store.saveIntroStateByKey({
+ key: WORKSPACE_SETUP_GUIDE_QUERY_EXECUTED_KEY,
+ newState: true,
+ });
+ }
+ setSetupState((state) => ({
+ ...state,
+ hasExploredDatabase: true,
+ hasFirstQuery: true,
+ databaseProjectName: project,
+ databaseName: database,
+ }));
+ }
+ );
+ return () => {
+ off();
+ };
+ }, [databaseExplored, queryExecuted]);
+
+ useEffect(() => {
+ if (
+ dismissed ||
+ !guideEnabled ||
+ databaseExplored ||
+ !isConcreteDatabaseRoute(currentRoute.name, currentRoute.params ?? {})
+ ) {
+ return;
+ }
+
+ useAppStore.getState().saveIntroStateByKey({
+ key: WORKSPACE_SETUP_GUIDE_DATABASE_EXPLORED_KEY,
+ newState: true,
+ });
+ setSetupState((state) => ({
+ ...state,
+ hasExploredDatabase: true,
+ }));
+ }, [
+ currentRoute.name,
+ currentRoute.params,
+ databaseExplored,
+ dismissed,
+ guideEnabled,
+ ]);
useEffect(() => {
setSelectedStepKey(undefined);
@@ -114,7 +219,7 @@ export function WorkspaceSetupGuide() {
};
useEffect(() => {
- if (dismissed || !hasSingleWorkspaceMember) {
+ if (dismissed || !guideEnabled) {
setSetupState(initialSetupState);
setLoading(false);
return;
@@ -122,130 +227,86 @@ export function WorkspaceSetupGuide() {
void (async () => {
const store = useAppStore.getState();
- const [projectResult, instanceResult] = await Promise.allSettled([
- useAppStore.getState().fetchProjectList({
- pageSize: 1,
- silent: true,
- filter: {
- excludeDefault: true,
- },
- }),
- hasWorkspacePermissionV2("bb.instances.list")
- ? useAppStore.getState().fetchInstanceList({
- pageSize: 1,
- silent: true,
- })
- : Promise.resolve({ instances: [] }),
- ]);
-
- const projectName =
- projectResult.status === "fulfilled"
- ? (projectResult.value.projects.find(
- (project) => project.name !== defaultProject
- )?.name ?? "")
- : "";
- const hasProject = !!projectName;
- let hasInstance =
- instanceCacheSize > 0 ||
- (instanceResult.status === "fulfilled" &&
- instanceResult.value.instances.length > 0);
- if (
- !hasInstance &&
- projectName &&
- hasWorkspacePermissionV2("bb.instances.list")
- ) {
- try {
- const projectInstanceResult = await store.fetchInstanceList({
- parent: projectName,
+ try {
+ const [projectResponse, instanceResponse] = await Promise.all([
+ store.fetchProjectList({
pageSize: 1,
silent: true,
- });
- hasInstance = projectInstanceResult.instances.length > 0;
- } catch {
- hasInstance = false;
- }
- }
- let databaseName = "";
- let hasWorkspaceDatabase = databaseCacheSize > 0;
- let hasFirstQuery = false;
-
- if (projectName || hasInstance) {
- const [projectDatabaseResult, workspaceDatabaseResult] =
- await Promise.allSettled([
- projectName
- ? store.fetchDatabases({
- parent: projectName,
- pageSize: 1,
- silent: true,
- })
- : Promise.resolve({ databases: [] }),
- hasInstance
- ? store.fetchDatabases({
- parent: "-",
- pageSize: 1,
- silent: true,
- })
- : Promise.resolve({ databases: [] }),
- ]);
- if (projectDatabaseResult.status === "fulfilled") {
- databaseName = projectDatabaseResult.value.databases[0]?.name ?? "";
- }
- if (workspaceDatabaseResult.status === "fulfilled") {
- hasWorkspaceDatabase =
- hasWorkspaceDatabase ||
- workspaceDatabaseResult.value.databases.length > 0;
- }
- }
-
- if (databaseName) {
- // databaseName is only set from the project database lookup, so
- // projectName is always concrete here — which SearchQueryHistories
- // requires (it has no cross-project wildcard).
- try {
- const queryHistoryResult =
- await queryHistoryServiceClientConnect.searchQueryHistories(
- create(SearchQueryHistoriesRequestSchema, {
- parent: projectName,
+ filter: {
+ excludeDefault: true,
+ state: State.ACTIVE,
+ },
+ }),
+ store.fetchInstanceList({
+ pageSize: 1,
+ filter: { state: State.ACTIVE },
+ silent: true,
+ }),
+ ]);
+ const project = projectResponse.projects.find(
+ ({ name }) => !!name && name !== defaultProject
+ );
+ const instance = instanceResponse.instances[0];
+ const databaseResponse =
+ project && workspaceResourceName
+ ? await store.fetchDatabases({
+ parent: workspaceResourceName,
pageSize: 1,
- filter: 'type == "QUERY"',
+ filter: { project: project.name },
+ silent: true,
})
- );
- hasFirstQuery = queryHistoryResult.queryHistories.length > 0;
- } catch {
- hasFirstQuery = false;
- }
- }
+ : undefined;
+ const database = databaseResponse?.databases.find(
+ ({ name, project }) => !!name && !!project
+ );
- setSetupState({
- hasProject,
- hasInstance,
- hasWorkspaceDatabase,
- hasProjectDatabase: !!databaseName,
- hasFirstQuery,
- projectName,
- databaseName,
- });
+ const latestDatabaseExplored = store.getIntroStateByKey(
+ WORKSPACE_SETUP_GUIDE_DATABASE_EXPLORED_KEY
+ );
+ const latestQueryExecuted = store.getIntroStateByKey(
+ WORKSPACE_SETUP_GUIDE_QUERY_EXECUTED_KEY
+ );
+ const queryTarget = latestQueryExecuted
+ ? queryTargetRef.current
+ : undefined;
+
+ setSetupState({
+ hasProject: !!project,
+ hasInstance: !!instance,
+ hasExploredDatabase: latestDatabaseExplored,
+ hasFirstQuery: latestQueryExecuted,
+ projectName: project?.name ?? "",
+ databaseProjectName:
+ queryTarget?.projectName ?? database?.project ?? "",
+ databaseName: queryTarget?.databaseName ?? database?.name ?? "",
+ });
+ } catch {
+ // Keep the current progress when resource discovery is unavailable.
+ }
setLoading(false);
})();
}, [
databaseCacheSize,
+ databaseExplored,
defaultProject,
dismissed,
- hasSingleWorkspaceMember,
+ guideEnabled,
instanceCacheSize,
projectCacheSize,
+ queryExecuted,
currentRoute.name,
+ workspaceResourceName,
]);
const sqlEditorDatabase = useMemo(() => {
- if (!setupState.databaseName || !setupState.projectName) {
+ if (!setupState.databaseName || !setupState.databaseProjectName) {
return undefined;
}
return {
name: setupState.databaseName,
- project: setupState.projectName,
+ project: setupState.databaseProjectName,
};
- }, [setupState.databaseName, setupState.projectName]);
+ }, [setupState.databaseName, setupState.databaseProjectName]);
const steps = useMemo<SetupStep[]>(
() => [
@@ -253,10 +314,14 @@ export function WorkspaceSetupGuide() {
key: "hasProject",
label: t("workspace-setup-guide.steps.project"),
description: t("workspace-setup-guide.descriptions.project"),
- link: {
- name: PROJECT_V1_ROUTE_DASHBOARD,
- query: { [PRODUCT_INTRO_QUERY_KEY]: CREATE_PROJECT_PRODUCT_INTRO },
- },
+ link: setupState.hasProject
+ ? undefined
+ : {
+ name: PROJECT_V1_ROUTE_DASHBOARD,
+ query: {
+ [PRODUCT_INTRO_QUERY_KEY]: CREATE_PROJECT_PRODUCT_INTRO,
+ },
+ },
done: setupState.hasProject,
matchesRoute: (routeName) => routeName === PROJECT_V1_ROUTE_DASHBOARD,
},
@@ -264,15 +329,16 @@ export function WorkspaceSetupGuide() {
key: "hasInstance",
label: t("workspace-setup-guide.steps.instance"),
description: t("workspace-setup-guide.descriptions.instance"),
- link:
- !setupState.hasInstance && setupState.projectName
+ link: setupState.hasInstance
+ ? undefined
+ : setupState.projectName
? {
- name: PROJECT_V1_ROUTE_DATABASES,
+ name: PROJECT_V1_ROUTE_INSTANCES,
params: {
projectId: extractProjectResourceName(setupState.projectName),
},
query: {
- [PRODUCT_INTRO_QUERY_KEY]: CONNECT_DATABASE_PRODUCT_INTRO,
+ [PRODUCT_INTRO_QUERY_KEY]: CREATE_INSTANCE_PRODUCT_INTRO,
},
}
: {
@@ -283,39 +349,51 @@ export function WorkspaceSetupGuide() {
},
done: setupState.hasInstance,
matchesRoute: (routeName) =>
- isRouteInside(routeName, INSTANCE_ROUTE_DASHBOARD),
+ isRouteInside(routeName, INSTANCE_ROUTE_DASHBOARD) ||
+ isRouteInside(routeName, PROJECT_V1_ROUTE_INSTANCES),
},
{
- key: "hasProjectDatabase",
+ key: "hasExploredDatabase",
label: t("workspace-setup-guide.steps.database"),
description: t("workspace-setup-guide.descriptions.database"),
- link: {
- name: DATABASE_ROUTE_DASHBOARD,
- query: !setupState.hasProjectDatabase
- ? {
+ link: sqlEditorDatabase
+ ? {
+ name: PROJECT_V1_ROUTE_DATABASES,
+ params: {
+ projectId: extractProjectResourceName(
+ setupState.databaseProjectName
+ ),
+ },
+ query: {
+ [PRODUCT_INTRO_QUERY_KEY]:
+ PROJECT_INSTANCE_SYNCED_PRODUCT_INTRO,
+ },
+ }
+ : {
+ name: DATABASE_ROUTE_DASHBOARD,
+ query: {
[PRODUCT_INTRO_QUERY_KEY]: PREPARE_DATABASE_PRODUCT_INTRO,
[PRODUCT_INTRO_TIP_QUERY_KEY]: PREPARE_DATABASE_TRANSFER_TIP,
- }
- : {
- [PRODUCT_INTRO_QUERY_KEY]: PREPARE_DATABASE_PRODUCT_INTRO,
},
- },
- done: setupState.hasProjectDatabase,
+ },
+ done: setupState.hasExploredDatabase,
disabled: !setupState.hasProject || !setupState.hasInstance,
matchesRoute: (routeName) =>
- isRouteInside(routeName, DATABASE_ROUTE_DASHBOARD),
+ isRouteInside(routeName, DATABASE_ROUTE_DASHBOARD) ||
+ isRouteInside(routeName, PROJECT_V1_ROUTE_DATABASES) ||
+ routeName === INSTANCE_ROUTE_DATABASE_DETAIL,
},
{
key: "hasFirstQuery",
label: t("workspace-setup-guide.steps.query"),
description: t("workspace-setup-guide.descriptions.sql-editor"),
done: setupState.hasFirstQuery,
- disabled: !setupState.hasProjectDatabase,
+ disabled: !setupState.hasExploredDatabase,
matchesRoute: (routeName) =>
isRouteInside(routeName, SQL_EDITOR_DATABASE_MODULE),
},
],
- [setupState, t]
+ [setupState, sqlEditorDatabase, t]
);
const activeStep = steps.find((step) => !step.done) ?? steps.at(-1)!;
@@ -324,11 +402,7 @@ export function WorkspaceSetupGuide() {
(step) => step.matchesRoute?.(currentRoute.name) ?? false
);
const highlightedStep =
- selectedStep ??
- routeMatchedStep ??
- (isRouteInside(currentRoute.name, PROJECT_V1_ROUTE_DATABASES)
- ? activeStep
- : undefined);
+ selectedStep ?? (routeMatchedStep?.done ? activeStep : routeMatchedStep);
const actionStep =
highlightedStep && !highlightedStep.done ? highlightedStep : activeStep;
@@ -340,7 +414,9 @@ export function WorkspaceSetupGuide() {
},
})
);
- void preCreateIssue(setupState.projectName, [setupState.databaseName]);
+ void preCreateIssue(setupState.databaseProjectName, [
+ setupState.databaseName,
+ ]);
};
const handleDismiss = () => {
@@ -357,7 +433,7 @@ export function WorkspaceSetupGuide() {
});
};
- if (dismissed || !hasSingleWorkspaceMember || loading) {
+ if (dismissed || !guideEnabled || loading) {
return null;
}
@@ -421,7 +497,7 @@ export function WorkspaceSetupGuide() {
</div>
<div className="ml-auto flex shrink-0 items-center gap-x-2">
{actionStep.key === "hasFirstQuery" &&
- setupState.projectName &&
+ setupState.databaseProjectName &&
setupState.databaseName && (
<Button
type="button"
@@ -438,6 +514,7 @@ export function WorkspaceSetupGuide() {
<SQLEditorButton
data-testid="active-action"
database={sqlEditorDatabase}
+ openInNewTab
size="sm"
className="2xl:h-9 2xl:gap-1.5 2xl:px-3 2xl:text-sm 2xl:leading-5"
label={t("workspace-setup-guide.actions.query")}
diff --git a/frontend/src/components/header/ProfileMenuTrigger.test.tsx b/frontend/src/components/header/ProfileMenuTrigger.test.tsx
index 9a05f65668..7e73199393 100644
--- a/frontend/src/components/header/ProfileMenuTrigger.test.tsx
+++ b/frontend/src/components/header/ProfileMenuTrigger.test.tsx
@@ -26,6 +26,9 @@ const mocks = vi.hoisted(() => ({
},
resetQuickstart: vi.fn(),
hideQuickStart: false,
+ canReadSetupResources: true,
+ userCountInIam: 1,
+ sampleAvailable: true,
isDev: false,
}));
@@ -42,7 +45,7 @@ vi.mock("react-i18next", () => ({
({
"common.language": "Language",
"common.license": "License",
- "quick-start.self": "Quick Start",
+ "workspace-setup-guide.getting-started": "Getting started",
"common.logout": "Logout",
"settings.general.workspace.default-landing-page.go-to-workspace":
"Go to workspace",
@@ -134,8 +137,8 @@ vi.mock("@/hooks/useAppState", () => ({
}),
useServerInfo: () => ({
- sample: { available: true },
- userCountInIam: 1,
+ sample: { available: mocks.sampleAvailable },
+ userCountInIam: mocks.userCountInIam,
}),
useSubscription: () => ({
subscription: { plan: PlanType.FREE },
@@ -145,15 +148,24 @@ vi.mock("@/hooks/useAppState", () => ({
logo: "",
}),
useAppFeature: () => mocks.hideQuickStart,
- useQuickstartReset: () => mocks.resetQuickstart,
+ useWorkspaceSetupGuideReset: () => mocks.resetQuickstart,
}));
vi.mock("@/stores/app", () => ({
- useAppStore: {
- getState: () => ({
- logout: mocks.logout,
- }),
- },
+ useAppStore: Object.assign(
+ (selector: (state: unknown) => unknown) =>
+ selector({
+ workspaceSetupGuideEnabled: () =>
+ !mocks.hideQuickStart &&
+ mocks.canReadSetupResources &&
+ mocks.userCountInIam === 1,
+ }),
+ {
+ getState: () => ({
+ logout: mocks.logout,
+ }),
+ }
+ ),
}));
vi.mock("@/utils/util", () => ({
@@ -184,6 +196,9 @@ const renderIntoContainer = (element: ReactElement) => {
beforeEach(async () => {
vi.clearAllMocks();
mocks.hideQuickStart = false;
+ mocks.canReadSetupResources = true;
+ mocks.userCountInIam = 1;
+ mocks.sampleAvailable = true;
mocks.isDev = false;
mocks.currentRoute.name = "sql-editor.home";
window.open = vi.fn();
@@ -262,7 +277,7 @@ describe("ProfileMenuTrigger", () => {
unmount();
});
- test("hides quick start when the app feature disables it", () => {
+ test("hides getting started when the app feature disables it", () => {
mocks.hideQuickStart = true;
const { container, render, unmount } = renderIntoContainer(
<ProfileMenuTrigger size="medium" link />
@@ -270,7 +285,48 @@ describe("ProfileMenuTrigger", () => {
render();
- expect(container.textContent).not.toContain("Quick Start");
+ expect(container.textContent).not.toContain("Getting started");
+ unmount();
+ });
+
+ test("restores the unified guide even when no sample is available", () => {
+ mocks.sampleAvailable = false;
+ const { container, render, unmount } = renderIntoContainer(
+ <ProfileMenuTrigger size="medium" link />
+ );
+
+ render();
+
+ const gettingStartedButton = Array.from(
+ container.querySelectorAll("button")
+ ).find((button) => button.textContent === "Getting started");
+ expect(gettingStartedButton).not.toBeUndefined();
+ act(() => gettingStartedButton?.click());
+ expect(mocks.resetQuickstart).toHaveBeenCalledTimes(1);
+ unmount();
+ });
+
+ test.each([0, 2])("hides getting started for IAM user count %s", (count) => {
+ mocks.userCountInIam = count;
+ const { container, render, unmount } = renderIntoContainer(
+ <ProfileMenuTrigger size="medium" link />
+ );
+
+ render();
+
+ expect(container.textContent).not.toContain("Getting started");
+ unmount();
+ });
+
+ test("hides getting started without setup resource permissions", () => {
+ mocks.canReadSetupResources = false;
+ const { container, render, unmount } = renderIntoContainer(
+ <ProfileMenuTrigger size="medium" link />
+ );
+
+ render();
+
+ expect(container.textContent).not.toContain("Getting started");
unmount();
});
diff --git a/frontend/src/components/header/ProfileMenuTrigger.tsx b/frontend/src/components/header/ProfileMenuTrigger.tsx
index b7a1110382..a47e8d8f12 100644
--- a/frontend/src/components/header/ProfileMenuTrigger.tsx
+++ b/frontend/src/components/header/ProfileMenuTrigger.tsx
@@ -22,12 +22,10 @@ import {
} from "@/components/ui/dropdown-menu";
import { RadioGroup, RadioGroupItem } from "@/components/ui/radio-group";
import {
- useAppFeature,
useOptionalCurrentUser,
- useQuickstartReset,
- useServerInfo,
useSubscription,
useWorkspace,
+ useWorkspaceSetupGuideReset,
} from "@/hooks/useAppState";
import { useAppStore } from "@/stores/app";
import { PlanType } from "@/types/proto-es/v1/subscription_service_pb";
@@ -46,13 +44,14 @@ export function ProfileMenuTrigger({
}: ProfileMenuProps) {
const { t, i18n } = useTranslation();
const currentUser = useOptionalCurrentUser();
- const serverInfo = useServerInfo();
const { subscription, uploadLicense } = useSubscription();
const workspace = useWorkspace();
const route = useCurrentRoute();
const navigate = useNavigate();
- const resetQuickstartProgress = useQuickstartReset();
- const hideQuickStart = useAppFeature("bb.feature.hide-quick-start");
+ const resetWorkspaceSetupGuide = useWorkspaceSetupGuideReset();
+ const workspaceSetupGuideEnabled = useAppStore((state) =>
+ state.workspaceSetupGuideEnabled()
+ );
const currentPlan = subscription?.plan ?? PlanType.FREE;
const devLicenseOptions = [
{
@@ -71,10 +70,6 @@ export function ProfileMenuTrigger({
plan: PlanType.ENTERPRISE,
},
];
- const quickStartEnabled =
- !hideQuickStart &&
- Boolean(serverInfo?.sample?.available) &&
- (serverInfo?.userCountInIam ?? 0) <= 1;
const customLogo = workspace?.logo ?? "";
const [open, setOpen] = useState(false);
@@ -226,14 +221,14 @@ export function ProfileMenuTrigger({
</DropdownMenuSubmenu>
) : null}
- {quickStartEnabled ? (
+ {workspaceSetupGuideEnabled ? (
<DropdownMenuItem
onClick={() => {
- resetQuickstartProgress();
+ resetWorkspaceSetupGuide();
setOpen(false);
}}
>
- {t("quick-start.self")}
+ {t("workspace-setup-guide.getting-started")}
</DropdownMenuItem>
) : null}
diff --git a/frontend/src/components/instance/InstanceDashboard.test.ts b/frontend/src/components/instance/InstanceDashboard.test.ts
index 449d333f75..e0366ebb69 100644
--- a/frontend/src/components/instance/InstanceDashboard.test.ts
+++ b/frontend/src/components/instance/InstanceDashboard.test.ts
@@ -30,4 +30,16 @@ describe("InstanceDashboard", () => {
expect(source).toContain("setSelectedNames(new Set());");
expect(source).toContain("}, [parent]);");
});
+
+ test("allows the connect-instance intro on project instance pages", () => {
+ const source = readFileSync(
+ join(process.cwd(), "src/components/instance/InstanceDashboard.tsx"),
+ "utf-8"
+ );
+
+ expect(source).toContain("disabled: !canCreate,");
+ expect(source).not.toContain(
+ 'disabled: layout === "project" || !canCreate,'
+ );
+ });
});
diff --git a/frontend/src/components/instance/InstanceDashboard.tsx b/frontend/src/components/instance/InstanceDashboard.tsx
index bb5caaaa8a..e16cb415d3 100644
--- a/frontend/src/components/instance/InstanceDashboard.tsx
+++ b/frontend/src/components/instance/InstanceDashboard.tsx
@@ -599,17 +599,6 @@ export function InstanceDashboard({
[searchParams]
);
- // Mark instance visit on mount
- useEffect(() => {
- const store = useAppStore.getState();
- if (!store.getIntroStateByKey("instance.visit")) {
- store.saveIntroStateByKey({
- key: "instance.visit",
- newState: true,
- });
- }
- }, []);
-
// Instance count warning
const instanceCountLimit = useAppStore((s) => s.instanceCountLimit());
const totalInstanceCount = useAppStore((s) => s.totalInstanceCount());
@@ -906,7 +895,7 @@ export function InstanceDashboard({
id: CREATE_INSTANCE_PRODUCT_INTRO,
title: t("workspace-setup-guide.intro.instance-title"),
description: t("workspace-setup-guide.intro.instance-description"),
- disabled: layout === "project" || !canCreate,
+ disabled: !canCreate,
});
const allSelected =
instances.length > 0 && selectedNames.size === instances.length;
diff --git a/frontend/src/hooks/useAppState.ts b/frontend/src/hooks/useAppState.ts
index 3f76302b31..8c34c83bd1 100644
--- a/frontend/src/hooks/useAppState.ts
+++ b/frontend/src/hooks/useAppState.ts
@@ -484,8 +484,8 @@ export function useNotify() {
return useAppStore((state) => state.notify);
}
-export function useQuickstartReset() {
- return useAppStore((state) => state.resetQuickstartProgress);
+export function useWorkspaceSetupGuideReset() {
+ return useAppStore((state) => state.resetWorkspaceSetupGuide);
}
export function useIntroStateByKey(key: string) {
diff --git a/frontend/src/hooks/useExecuteSQL.ts b/frontend/src/hooks/useExecuteSQL.ts
index 5059b00dff..8cbc3a0aac 100644
--- a/frontend/src/hooks/useExecuteSQL.ts
+++ b/frontend/src/hooks/useExecuteSQL.ts
@@ -381,7 +381,10 @@ export const useExecuteSQL = () => {
/* nothing */
})
.finally(() => {
- void sqlEditorEvents.emit("query-executed");
+ void sqlEditorEvents.emit("query-executed", {
+ database: database.name,
+ project: database.project,
+ });
});
if (isDisallowChangeDatabaseError(resultSet)) {
diff --git a/frontend/src/locales/en-US.json b/frontend/src/locales/en-US.json
index a380463ba0..8934cbaa17 100644
--- a/frontend/src/locales/en-US.json
+++ b/frontend/src/locales/en-US.json
@@ -2036,21 +2036,6 @@
"create-project": "Create project",
"new-project": "New Project"
},
- "quick-start": {
- "guide": "click on the step to try it out",
- "notice": {
- "desc": "You can still bring it back later from the top right menu",
- "title": "Quickstart guide dismissed"
- },
- "query-data": "Query data",
- "self": "Quick Start",
- "view-an-issue": "View an issue",
- "visit-database": "Visit Databases",
- "visit-environment": "Visit Environments",
- "visit-instance": "Visit Instances",
- "visit-member": "Visit Members",
- "visit-project": "Visit Projects"
- },
"refresh-remind": {},
"release": {
"and-n-more-files": "and {{count}} more files",
@@ -3470,12 +3455,13 @@
"query": "Go to SQL Editor"
},
"descriptions": {
- "database": "View an existing database in your project or a sample database, or create or transfer one when needed.",
+ "database": "Open a database to explore its schemas and tables, or create one when needed.",
"instance": "Connect an instance so Bytebase can sync your databases.",
"project": "Create a project to organize databases and changes.",
"sql-editor": "Query data in SQL Editor, or create a governed database change."
},
"dismiss": "Dismiss guide",
+ "getting-started": "Getting started",
"intro": {
"database-description": "Create a database in your connected instance.",
"database-title": "Create a database",
diff --git a/frontend/src/locales/es-ES.json b/frontend/src/locales/es-ES.json
index 1e788f8a02..2ed85e524c 100644
--- a/frontend/src/locales/es-ES.json
+++ b/frontend/src/locales/es-ES.json
@@ -2036,21 +2036,6 @@
"create-project": "Crear proyecto",
"new-project": "Nuevo Proyecto"
},
- "quick-start": {
- "guide": "haga clic en el paso para probarlo",
- "notice": {
- "desc": "Todavía puede volver a abrirla más tarde desde el menú en la parte superior derecha",
- "title": "Guía de inicio rápido omitida"
- },
- "query-data": "Consultar datos",
- "self": "Inicio rápido",
- "view-an-issue": "Ver una incidencia",
- "visit-database": "Visitar Bases de datos",
- "visit-environment": "Visitar Entornos",
- "visit-instance": "Visitar Instancias",
- "visit-member": "Visitar Miembros",
- "visit-project": "Visitar Proyectos"
- },
"refresh-remind": {},
"release": {
"and-n-more-files": "y {{count}} archivos más",
@@ -3470,12 +3455,13 @@
"query": "Ir a SQL Editor"
},
"descriptions": {
- "database": "Consulta una base de datos existente en tu proyecto o una base de datos de ejemplo, o crea o transfiere una cuando sea necesario.",
+ "database": "Consulta una base de datos de tu instancia conectada, o crea o transfiere una cuando sea necesario.",
"instance": "Conecta una instancia para que Bytebase pueda sincronizar tus bases de datos.",
"project": "Crea un proyecto para organizar bases de datos y cambios.",
"sql-editor": "Consulta datos en SQL Editor o crea un cambio de base de datos gobernado."
},
"dismiss": "Cerrar guía",
+ "getting-started": "Primeros pasos",
"intro": {
"database-description": "Crea una base de datos en tu instancia conectada.",
"database-title": "Crear base de datos",
diff --git a/frontend/src/locales/ja-JP.json b/frontend/src/locales/ja-JP.json
index 6b31427721..a4aa237531 100644
--- a/frontend/src/locales/ja-JP.json
+++ b/frontend/src/locales/ja-JP.json
@@ -2036,21 +2036,6 @@
"create-project": "プロジェクトを作成",
"new-project": "作成するプロジェクト"
},
- "quick-start": {
- "guide": "クリックしてステップを試してみましょう",
- "notice": {
- "desc": "後から右上のメニューから元に戻すことができます",
- "title": "クイックスタートガイドを終了しました"
- },
- "query-data": "クエリデータ",
- "self": "クイックスタート",
- "view-an-issue": "イシューを表示する",
- "visit-database": "データベースにアクセスする",
- "visit-environment": "環境にアクセスする",
- "visit-instance": "インスタンスにアクセスする",
- "visit-member": "メンバーにアクセスする",
- "visit-project": "プロジェクトにアクセスする"
- },
"refresh-remind": {},
"release": {
"and-n-more-files": "他 {{count}} 件のファイル",
@@ -3470,12 +3455,13 @@
"query": "SQL Editor に移動"
},
"descriptions": {
- "database": "プロジェクト内またはサンプルの既存データベースを確認できます。必要に応じて、データベースを作成または転送してください。",
+ "database": "接続したインスタンスのデータベースを確認し、必要に応じて作成または転送します。",
"instance": "インスタンスを接続して、Bytebase がデータベースを同期できるようにします。",
"project": "データベースと変更を整理するプロジェクトを作成します。",
"sql-editor": "SQL Editor でデータをクエリするか、ガバナンス付きデータベース変更を作成します。"
},
"dismiss": "ガイドを閉じる",
+ "getting-started": "はじめに",
"intro": {
"database-description": "接続済みインスタンスにデータベースを作成します。",
"database-title": "データベースを作成",
diff --git a/frontend/src/locales/vi-VN.json b/frontend/src/locales/vi-VN.json
index 319b43dd04..d6a9a8f28e 100644
--- a/frontend/src/locales/vi-VN.json
+++ b/frontend/src/locales/vi-VN.json
@@ -2036,21 +2036,6 @@
"create-project": "Tạo dự án",
"new-project": "Mới Dự án"
},
- "quick-start": {
- "guide": "nhấp vào bước để thử",
- "notice": {
- "desc": "Bạn vẫn có thể mang nó trở lại sau từ menu trên cùng bên phải",
- "title": "Đã bỏ qua hướng dẫn bắt đầu nhanh"
- },
- "query-data": "Truy vấn dữ liệu",
- "self": "Bắt đầu nhanh",
- "view-an-issue": "Xem một vấn đề",
- "visit-database": "Truy cập Cơ sở dữ liệu",
- "visit-environment": "Truy cập Môi trường",
- "visit-instance": "Truy cập Phiên bản",
- "visit-member": "Truy cập Thành viên",
- "visit-project": "Truy cập Dự án"
- },
"refresh-remind": {},
"release": {
"and-n-more-files": "và {{count}} tệp khác",
@@ -3470,12 +3455,13 @@
"query": "Đi tới SQL Editor"
},
"descriptions": {
- "database": "Xem cơ sở dữ liệu hiện có trong dự án hoặc cơ sở dữ liệu mẫu, hoặc tạo hay chuyển một cơ sở dữ liệu khi cần.",
+ "database": "Xem cơ sở dữ liệu từ instance đã kết nối, hoặc tạo hay chuyển một cơ sở dữ liệu khi cần.",
"instance": "Kết nối instance để Bytebase có thể đồng bộ cơ sở dữ liệu của bạn.",
"project": "Tạo dự án để quản lý cơ sở dữ liệu và thay đổi.",
"sql-editor": "Truy vấn dữ liệu trong SQL Editor hoặc tạo thay đổi cơ sở dữ liệu được quản trị."
},
"dismiss": "Đóng hướng dẫn",
+ "getting-started": "Bắt đầu",
"intro": {
"database-description": "Tạo cơ sở dữ liệu trong instance đã kết nối.",
"database-title": "Tạo cơ sở dữ liệu",
diff --git a/frontend/src/locales/zh-CN.json b/frontend/src/locales/zh-CN.json
index 1756d8eb08..7befeeba5f 100644
--- a/frontend/src/locales/zh-CN.json
+++ b/frontend/src/locales/zh-CN.json
@@ -2036,21 +2036,6 @@
"create-project": "创建项目",
"new-project": "创建项目"
},
- "quick-start": {
- "guide": "可点击步骤进行尝试",
- "notice": {
- "desc": "您稍后仍可以从右上角的菜单中再次打开新手任务",
- "title": "新手任务已关闭"
- },
- "query-data": "查询数据",
- "self": "快速开始",
- "view-an-issue": "查看工单",
- "visit-database": "访问数据库",
- "visit-environment": "访问环境",
- "visit-instance": "访问实例",
- "visit-member": "访问成员",
- "visit-project": "访问项目"
- },
"refresh-remind": {},
"release": {
"and-n-more-files": "以及另外 {{count}} 个文件",
@@ -3470,12 +3455,13 @@
"query": "前往 SQL Editor"
},
"descriptions": {
- "database": "查看项目中现有的数据库或示例数据库;如有需要,可创建或转移数据库。",
+ "database": "查看已连接实例中的数据库;如有需要,可创建或转移数据库。",
"instance": "连接实例,让 Bytebase 可以同步你的数据库。",
"project": "创建项目来管理数据库和变更。",
"sql-editor": "在 SQL Editor 中查询数据,或创建受管数据库变更。"
},
"dismiss": "关闭指南",
+ "getting-started": "入门指南",
"intro": {
"database-description": "在已连接的实例中创建数据库。",
"database-title": "创建数据库",
diff --git a/frontend/src/modules/sql-editor/components/EditorAction.tsx b/frontend/src/modules/sql-editor/components/EditorAction.tsx
index 958e82e93f..d2dbb42af6 100644
--- a/frontend/src/modules/sql-editor/components/EditorAction.tsx
+++ b/frontend/src/modules/sql-editor/components/EditorAction.tsx
@@ -133,10 +133,6 @@ export function EditorAction({ onExecute }: Props) {
explain: false,
selection: currentTab.editorState.selection,
});
- useAppStore.getState().saveIntroStateByKey({
- key: "data.query",
- newState: true,
- });
};
const exitAdminMode = () => {
diff --git a/frontend/src/modules/sql-editor/components/SQLEditorHomePage.test.tsx b/frontend/src/modules/sql-editor/components/SQLEditorHomePage.test.tsx
new file mode 100644
index 0000000000..74d225b85a
--- /dev/null
+++ b/frontend/src/modules/sql-editor/components/SQLEditorHomePage.test.tsx
@@ -0,0 +1,149 @@
+import type { ReactElement } from "react";
+import { act } from "react";
+import { createRoot } from "react-dom/client";
+import { afterEach, beforeEach, describe, expect, test, vi } from "vitest";
+
+(globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }).IS_REACT_ACT_ENVIRONMENT =
+ true;
+
+const mocks = vi.hoisted(() => ({
+ setPendingInsertAtCaret: vi.fn(),
+}));
+
+vi.mock("react-i18next", () => ({
+ initReactI18next: { type: "3rdParty", init: vi.fn() },
+ useTranslation: () => ({ t: (key: string) => key }),
+}));
+
+vi.mock("react-resizable-panels", () => ({
+ Group: ({ children }: { children: ReactElement | ReactElement[] }) => (
+ <div>{children}</div>
+ ),
+ Panel: ({ children }: { children: ReactElement | ReactElement[] }) => (
+ <div>{children}</div>
+ ),
+ Separator: () => <div />,
+}));
+
+vi.mock("@/app/router", () => ({
+ useNavigate: () => ({
+ resolve: vi.fn(() => ({ fullPath: "/plans/create" })),
+ }),
+}));
+
+vi.mock("@/components/IAMRemindDialog", () => ({
+ IAMRemindDialog: () => <div />,
+}));
+
+vi.mock("@/components/WorkspaceSetupGuide", () => ({
+ WorkspaceSetupGuide: () => <div>unified-guide</div>,
+}));
+
+vi.mock("@/components/ui/layer", () => ({
+ getLayerRoot: () => document.body,
+ LAYER_BACKDROP_CLASS: "layer-backdrop",
+ LAYER_SURFACE_CLASS: "layer-surface",
+}));
+
+vi.mock("@/hooks/useAppProject", () => ({
+ useAppProject: () => ({ name: "" }),
+}));
+
+vi.mock("@/lib/plan/issue", () => ({ preCreateIssue: vi.fn() }));
+vi.mock("@/lib/plan/title", () => ({ applyPlanTitleToQuery: vi.fn() }));
+vi.mock("@/lib/utils", () => ({
+ cn: (...classes: Array<string | false | undefined>) =>
+ classes.filter(Boolean).join(" "),
+}));
+vi.mock("@/modules/schema-editor/resize", () => ({
+ resizeHandleClass: () => "resize-handle",
+}));
+
+vi.mock("@/modules/sql-editor/components/AsidePanel", () => ({
+ AsidePanel: () => <div />,
+}));
+
+vi.mock("@/modules/sql-editor/components/ConnectionPanel", () => ({
+ ConnectionPanel: () => <div />,
+}));
+
+vi.mock("@/modules/sql-editor/components/SQLEditorHeader", () => ({
+ SQLEditorHeader: () => <div />,
+}));
+
+vi.mock("@/modules/sql-editor/components/TabList", () => ({
+ TabList: () => <div />,
+}));
+
+vi.mock("@/modules/sql-editor/components/Panels/Panels", () => ({
+ Panels: () => <div />,
+}));
+
+vi.mock(
+ "@/modules/sql-editor/components/theme/SQLEditorThemeScope",
+ () => ({
+ SQLEditorThemeScope: ({ children }: { children: ReactElement }) => children,
+ useSQLEditorTheme: () => ({}),
+ })
+);
+
+vi.mock("@/modules/sql-editor/model/events", () => ({
+ sqlEditorEvents: { on: () => () => {} },
+}));
+
+vi.mock("@/modules/sql-editor/store", () => ({
+ useSQLEditorStore: (selector: (state: unknown) => unknown) =>
+ selector({ setPendingInsertAtCaret: mocks.setPendingInsertAtCaret }),
+}));
+
+vi.mock("@/modules/sql-editor/store/editor", () => ({
+ useSQLEditorEditorState: (selector: (state: unknown) => unknown) =>
+ selector({ projectContextReady: false, project: "" }),
+}));
+
+vi.mock("@/modules/sql-editor/store/tab", () => ({
+ getSQLEditorTabsState: vi.fn(),
+ useCurrentSQLEditorTab: () => undefined,
+ useIsDisconnected: () => true,
+}));
+
+vi.mock("@/stores/app", () => ({
+ useAppStore: Object.assign(
+ (selector: (state: unknown) => unknown) => selector({}),
+ { getState: vi.fn() }
+ ),
+}));
+
+vi.mock("@/types", () => ({ unknownProject: () => ({ name: "" }) }));
+vi.mock("@/utils", () => ({
+ extractDatabaseResourceName: vi.fn(),
+ extractProjectResourceName: vi.fn(),
+}));
+
+import { SQLEditorHomePage } from "./SQLEditorHomePage";
+
+let container: HTMLDivElement;
+let root: ReturnType<typeof createRoot>;
+
+beforeEach(() => {
+ container = document.createElement("div");
+ document.body.appendChild(container);
+ root = createRoot(container);
+});
+
+afterEach(() => {
+ act(() => root.unmount());
+ container.remove();
+});
+
+const render = () => {
+ act(() => root.render(<SQLEditorHomePage />));
+};
+
+describe("SQLEditorHomePage guide", () => {
+ test("renders the unified guide", () => {
+ render();
+
+ expect(container.textContent).toContain("unified-guide");
+ });
+});
diff --git a/frontend/src/modules/sql-editor/components/SQLEditorHomePage.tsx b/frontend/src/modules/sql-editor/components/SQLEditorHomePage.tsx
index 8037e5c08d..d499f4b11c 100644
--- a/frontend/src/modules/sql-editor/components/SQLEditorHomePage.tsx
+++ b/frontend/src/modules/sql-editor/components/SQLEditorHomePage.tsx
@@ -10,12 +10,12 @@ import {
import { useNavigate } from "@/app/router";
import { buildPlanCreateRoute } from "@/app/router/routeHelpers";
import { IAMRemindDialog } from "@/components/IAMRemindDialog";
-import { Quickstart } from "@/components/Quickstart";
import {
getLayerRoot,
LAYER_BACKDROP_CLASS,
LAYER_SURFACE_CLASS,
} from "@/components/ui/layer";
+import { WorkspaceSetupGuide } from "@/components/WorkspaceSetupGuide";
import { useAppProject } from "@/hooks/useAppProject";
import { applyPlanTitleToQuery } from "@/lib/plan/title";
import { cn } from "@/lib/utils";
@@ -245,7 +245,7 @@ export function SQLEditorHomePage() {
</Panel>
</PanelGroup>
- <Quickstart />
+ <WorkspaceSetupGuide />
{projectContextReady && project && <IAMRemindDialog project={project} />}
<ConnectionPanel />
diff --git a/frontend/src/modules/sql-editor/components/SQLEditorRouteShell.test.tsx b/frontend/src/modules/sql-editor/components/SQLEditorRouteShell.test.tsx
index 25cd209fcb..b1a3860aa4 100644
--- a/frontend/src/modules/sql-editor/components/SQLEditorRouteShell.test.tsx
+++ b/frontend/src/modules/sql-editor/components/SQLEditorRouteShell.test.tsx
@@ -610,7 +610,7 @@ describe("SQLEditorRouteShell", () => {
test("restores the sidebar tab from project-scoped localStorage", async () => {
localStorage.setItem(
"bb.sql-editor.sidebar.last-visited-tab.projects/proj1",
- JSON.stringify("SCHEMA")
+ JSON.stringify("SAVED_QUERY")
);
const { unmount } = renderShell();
@@ -622,7 +622,52 @@ describe("SQLEditorRouteShell", () => {
await new Promise((resolve) => requestAnimationFrame(resolve));
});
- expect(mocks.setAsidePanelTab).toHaveBeenCalledWith("SCHEMA");
+ expect(mocks.setAsidePanelTab).toHaveBeenCalledWith("SAVED_QUERY");
+
+ unmount();
+ });
+
+ test("defaults the sidebar to schema for a database route", async () => {
+ const { unmount } = renderShell();
+
+ mocks.setAsidePanelTab.mockClear();
+ await act(async () => {
+ await sqlEditorEvents.emit("project-context-ready", {
+ project: "projects/proj1",
+ });
+ await new Promise((resolve) => requestAnimationFrame(resolve));
+ });
+
+ expect(mocks.setAsidePanelTab).toHaveBeenLastCalledWith("SCHEMA");
+
+ unmount();
+ });
+
+ test("defaults the sidebar to saved queries for a project route", async () => {
+ mocks.renderRoute = {
+ ...mocks.renderRoute,
+ name: "sql-editor.project",
+ params: { project: "proj1" },
+ query: {},
+ };
+ mocks.currentRoute = {
+ ...mocks.currentRoute,
+ name: "sql-editor.project",
+ params: { project: "proj1" },
+ query: {},
+ };
+
+ const { unmount } = renderShell();
+
+ mocks.setAsidePanelTab.mockClear();
+ await act(async () => {
+ await sqlEditorEvents.emit("project-context-ready", {
+ project: "projects/proj1",
+ });
+ await new Promise((resolve) => requestAnimationFrame(resolve));
+ });
+
+ expect(mocks.setAsidePanelTab).toHaveBeenLastCalledWith("SAVED_QUERY");
unmount();
});
diff --git a/frontend/src/modules/sql-editor/components/SQLEditorRouteShell.tsx b/frontend/src/modules/sql-editor/components/SQLEditorRouteShell.tsx
index 427103b799..79c05c52e8 100644
--- a/frontend/src/modules/sql-editor/components/SQLEditorRouteShell.tsx
+++ b/frontend/src/modules/sql-editor/components/SQLEditorRouteShell.tsx
@@ -639,7 +639,7 @@ export function SQLEditorRouteShell() {
return;
}
- let stored: AsidePanelTab = "SAVED_QUERY";
+ let stored: AsidePanelTab | undefined;
try {
const raw = window.localStorage.getItem(
storageKeySqlEditorSidebarTab(project)
@@ -657,14 +657,20 @@ export function SQLEditorRouteShell() {
// ignore — fall back to default
}
+ const defaultTab =
+ router.currentRoute.value.name === SQL_EDITOR_DATABASE_MODULE
+ ? "SCHEMA"
+ : "SAVED_QUERY";
+ const fallbackTab = stored ?? defaultTab;
+
const panelQuery = router.currentRoute.value.query.panel;
if (typeof panelQuery === "string" && panelQuery) {
const raw = panelQuery.toUpperCase();
// Pre-rename links used ?panel=worksheet.
const tab = (raw === "WORKSHEET" ? "SAVED_QUERY" : raw) as AsidePanelTab;
- setAsidePanelTab(ASIDE_PANEL_TABS.includes(tab) ? tab : stored);
+ setAsidePanelTab(ASIDE_PANEL_TABS.includes(tab) ? tab : fallbackTab);
} else {
- setAsidePanelTab(stored);
+ setAsidePanelTab(fallbackTab);
}
sidebarRestoredProjectRef.current = project;
};
diff --git a/frontend/src/modules/sql-editor/components/StandardPanel/SQLEditor.tsx b/frontend/src/modules/sql-editor/components/StandardPanel/SQLEditor.tsx
index 0d8978bb30..c3c6734b7b 100644
--- a/frontend/src/modules/sql-editor/components/StandardPanel/SQLEditor.tsx
+++ b/frontend/src/modules/sql-editor/components/StandardPanel/SQLEditor.tsx
@@ -23,7 +23,6 @@ import {
getSQLEditorTabsState,
useSQLEditorTabState,
} from "@/modules/sql-editor/store/tab";
-import { useAppStore } from "@/stores/app";
import {
dialectOfEngineV1,
isValidDatabaseName,
@@ -210,10 +209,6 @@ export function SQLEditor({ onExecute }: SQLEditorProps) {
selection: newTab ? null : tab.editorState.selection,
};
onExecuteRef.current(params, newTab);
- useAppStore.getState().saveIntroStateByKey({
- key: "data.query",
- newState: true,
- });
},
[getActiveStatement]
);
diff --git a/frontend/src/modules/sql-editor/model/events.ts b/frontend/src/modules/sql-editor/model/events.ts
index 301897ca37..023acbf780 100644
--- a/frontend/src/modules/sql-editor/model/events.ts
+++ b/frontend/src/modules/sql-editor/model/events.ts
@@ -25,7 +25,7 @@ export type SQLEditorEvents = {
// paths. `HistoryPane` listens and refetches. Bypasses store
// reactivity that doesn't reliably propagate the post-exec
// mutations into React selector subscribers.
- "query-executed": undefined;
+ "query-executed": { database: string; project: string };
};
export const sqlEditorEvents: Emittery<SQLEditorEvents> =
diff --git a/frontend/src/modules/sql-editor/store/webTerminal-service.ts b/frontend/src/modules/sql-editor/store/webTerminal-service.ts
index 1df0862d2a..2b3bbfe541 100644
--- a/frontend/src/modules/sql-editor/store/webTerminal-service.ts
+++ b/frontend/src/modules/sql-editor/store/webTerminal-service.ts
@@ -274,21 +274,25 @@ const bindStreamingLogic = (session: WebTerminalQuerySession) => {
// post-exec history refresh here. `mergeLatest` prepends the
// just-run statement without resetting the user's pagination.
const database = tail?.params?.connection.database;
+ const project = getSQLEditorEditorState().project;
if (database) {
useSQLEditorReactStore
.getState()
.mergeLatest({
- project: getSQLEditorEditorState().project,
+ project,
database,
})
.catch(() => {
/* nothing */
})
.finally(() => {
- void sqlEditorEvents.emit("query-executed");
+ void sqlEditorEvents.emit("query-executed", { database, project });
});
} else {
- void sqlEditorEvents.emit("query-executed");
+ void sqlEditorEvents.emit("query-executed", {
+ database: "",
+ project,
+ });
}
// Finish the current item and append a fresh one for the next prompt.
const finishedTail = activeItem();
diff --git a/frontend/src/routes/auth/SetupPage.test.tsx b/frontend/src/routes/auth/SetupPage.test.tsx
index 01ea5f167c..e0230c8158 100644
--- a/frontend/src/routes/auth/SetupPage.test.tsx
+++ b/frontend/src/routes/auth/SetupPage.test.tsx
@@ -20,7 +20,7 @@ const mocks = vi.hoisted(() => ({
createProject: vi.fn(),
setupSample: vi.fn(),
updateWorkspaceProfile: vi.fn(),
- resetQuickstartProgress: vi.fn(),
+ resetWorkspaceSetupGuide: vi.fn(),
}));
vi.mock("@/app/router", async (importOriginal) => ({
@@ -43,7 +43,7 @@ vi.mock("@/stores/app", () => {
createProject: mocks.createProject,
setupSample: mocks.setupSample,
updateWorkspaceProfile: mocks.updateWorkspaceProfile,
- resetQuickstartProgress: mocks.resetQuickstartProgress,
+ resetWorkspaceSetupGuide: mocks.resetWorkspaceSetupGuide,
};
return {
useAppStore: Object.assign(
@@ -185,7 +185,7 @@ describe("SetupPage", () => {
expect(mocks.routerPush).toHaveBeenLastCalledWith({
name: "workspace.landing",
});
- expect(mocks.resetQuickstartProgress).toHaveBeenCalledTimes(1);
+ expect(mocks.resetWorkspaceSetupGuide).toHaveBeenCalledTimes(1);
unmount();
});
diff --git a/frontend/src/routes/auth/SetupPage.tsx b/frontend/src/routes/auth/SetupPage.tsx
index 4366e363e2..500baf4527 100644
--- a/frontend/src/routes/auth/SetupPage.tsx
+++ b/frontend/src/routes/auth/SetupPage.tsx
@@ -153,7 +153,7 @@ function SetupWizard() {
paths: ["value.workspace_profile.database_change_mode"],
}),
});
- useAppStore.getState().resetQuickstartProgress();
+ useAppStore.getState().resetWorkspaceSetupGuide();
router.push(homePath(mode));
} finally {
setLoading(false);
diff --git a/frontend/src/routes/project/ProjectDatabasesPage.test.tsx b/frontend/src/routes/project/ProjectDatabasesPage.test.tsx
index a210927a60..3de09b8cc0 100644
--- a/frontend/src/routes/project/ProjectDatabasesPage.test.tsx
+++ b/frontend/src/routes/project/ProjectDatabasesPage.test.tsx
@@ -605,6 +605,38 @@ describe("ProjectDatabasesPage", () => {
});
});
+ test("shows database next actions when requested by the setup guide", async () => {
+ 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
+ .querySelector("[role='alert']")
+ ?.getAttribute("data-product-intro-target")
+ ).toBe("project-instance-synced");
+ expect(mocks.useProductIntro).toHaveBeenCalledWith({
+ id: "project-instance-synced",
+ title: "db.project-instance-synced-title",
+ description: "db.project-instance-synced-description",
+ disabled: false,
+ });
+
+ act(() => {
+ root.unmount();
+ });
+ });
+
test("hides post-sync guidance when the workspace has multiple instances", async () => {
mocks.routerCurrentQuery = { syncingInstance: "prod" };
mocks.fetchInstanceList.mockResolvedValueOnce({
diff --git a/frontend/src/routes/project/ProjectDatabasesPage.tsx b/frontend/src/routes/project/ProjectDatabasesPage.tsx
index 14cf720456..00a5b9e21c 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,
+ PRODUCT_INTRO_QUERY_KEY,
PROJECT_INSTANCE_SYNCED_PRODUCT_INTRO,
useProductIntro,
} from "@/lib/productIntro";
@@ -505,8 +506,11 @@ export function ProjectDatabasesPage({ projectId }: { projectId: string }) {
const hasVisibleDatabase = visibleDatabases.length > 0;
const showSyncingInstanceHint =
!!syncingInstanceId && !hasVisibleDatabase && !syncingRefreshExhausted;
- const showPostSyncNextAction =
- workspaceInstanceCount === 1 && !!syncingInstanceId && hasVisibleDatabase;
+ const showDatabaseNextAction =
+ hasVisibleDatabase &&
+ ((workspaceInstanceCount === 1 && !!syncingInstanceId) ||
+ currentRoute.query[PRODUCT_INTRO_QUERY_KEY] ===
+ PROJECT_INSTANCE_SYNCED_PRODUCT_INTRO);
const checkingWorkspaceInstance =
!hasVisibleDatabase &&
!showSyncingInstanceHint &&
@@ -557,7 +561,7 @@ export function ProjectDatabasesPage({ projectId }: { projectId: string }) {
id: PROJECT_INSTANCE_SYNCED_PRODUCT_INTRO,
title: t("db.project-instance-synced-title"),
description: t("db.project-instance-synced-description"),
- disabled: !showPostSyncNextAction,
+ disabled: !showDatabaseNextAction,
});
const handleCreateDatabaseAction = useCallback(() => {
@@ -664,7 +668,7 @@ export function ProjectDatabasesPage({ projectId }: { projectId: string }) {
/>
)}
- {showPostSyncNextAction && (
+ {showDatabaseNextAction && (
<Alert
variant="info"
data-product-intro-target={PROJECT_INSTANCE_SYNCED_PRODUCT_INTRO}
diff --git a/frontend/src/routes/project/ProjectMaskingExemptionCreatePage.test.tsx b/frontend/src/routes/project/ProjectMaskingExemptionCreatePage.test.tsx
index 9a22240b00..dcb336ecbf 100644
--- a/frontend/src/routes/project/ProjectMaskingExemptionCreatePage.test.tsx
+++ b/frontend/src/routes/project/ProjectMaskingExemptionCreatePage.test.tsx
@@ -106,7 +106,9 @@ vi.mock("@/components/FeatureAttention", () => ({
}));
vi.mock("@/components/FeatureBadge", () => ({
- FeatureBadge: () => <div data-testid="feature-badge" />,
+ FeatureBadge: ({ clickable }: { clickable?: boolean }) => (
+ <div data-clickable={String(clickable)} data-testid="feature-badge" />
+ ),
}));
vi.mock("@/components/ui/feature-modal", () => ({
@@ -288,6 +290,18 @@ describe("ProjectMaskingExemptionCreatePage builder (BYT-9788)", () => {
mocks.getExpressionsForDatabaseResource.mockReset();
});
+ test("keeps badges inside modal-opening radio controls non-clickable", () => {
+ const { container, unmount } = render();
+
+ const badges = container.querySelectorAll('[data-testid="feature-badge"]');
+ expect(badges).toHaveLength(2);
+ for (const badge of badges) {
+ expect(badge.getAttribute("data-clickable")).toBe("false");
+ }
+
+ unmount();
+ });
+
test("SELECT mode: wraps the OR-group so the expiration binds to every resource", async () => {
const { container, unmount } = render();
await flush();
diff --git a/frontend/src/routes/project/ProjectMaskingExemptionCreatePage.tsx b/frontend/src/routes/project/ProjectMaskingExemptionCreatePage.tsx
index 527f67e2bd..d97acebb29 100644
--- a/frontend/src/routes/project/ProjectMaskingExemptionCreatePage.tsx
+++ b/frontend/src/routes/project/ProjectMaskingExemptionCreatePage.tsx
@@ -227,14 +227,20 @@ export function ProjectMaskingExemptionCreatePage({
<RadioGroupItem value="EXPRESSION" disabled={!project}>
<div className="flex items-center gap-x-1">
- <FeatureBadge feature={PlanFeature.FEATURE_DATA_MASKING} />
+ <FeatureBadge
+ feature={PlanFeature.FEATURE_DATA_MASKING}
+ clickable={false}
+ />
<span>{t("issue.role-grant.use-cel")}</span>
</div>
</RadioGroupItem>
<RadioGroupItem value="SELECT" disabled={!project}>
<div className="flex items-center gap-x-1">
- <FeatureBadge feature={PlanFeature.FEATURE_DATA_MASKING} />
+ <FeatureBadge
+ feature={PlanFeature.FEATURE_DATA_MASKING}
+ clickable={false}
+ />
<span>{t("issue.role-grant.manually-select")}</span>
</div>
</RadioGroupItem>
diff --git a/frontend/src/routes/project/database-detail/catalog/GrantAccessDialog.test.tsx b/frontend/src/routes/project/database-detail/catalog/GrantAccessDialog.test.tsx
index 0b209d6a91..3edab938e7 100644
--- a/frontend/src/routes/project/database-detail/catalog/GrantAccessDialog.test.tsx
+++ b/frontend/src/routes/project/database-detail/catalog/GrantAccessDialog.test.tsx
@@ -176,7 +176,9 @@ vi.mock("@/components/FeatureAttention", () => ({
}));
vi.mock("@/components/FeatureBadge", () => ({
- FeatureBadge: () => <div data-testid="feature-badge" />,
+ FeatureBadge: ({ clickable }: { clickable?: boolean }) => (
+ <div data-clickable={String(clickable)} data-testid="feature-badge" />
+ ),
}));
vi.mock("@/components/ui/feature-modal", () => ({
@@ -377,6 +379,19 @@ describe("GrantAccessDialog", () => {
mocks.stringifyConditionExpression.mockClear();
});
+ test("keeps badges inside modal-opening radio controls non-clickable", async () => {
+ const { container, unmount } = renderGrantAccessDialog();
+ await flush();
+
+ const badges = container.querySelectorAll('[data-testid="feature-badge"]');
+ expect(badges).toHaveLength(2);
+ for (const badge of badges) {
+ expect(badge.getAttribute("data-clickable")).toBe("false");
+ }
+
+ unmount();
+ });
+
test("preserves selected scope when switching from select to expression mode", async () => {
const { container, unmount } = renderGrantAccessDialog();
await flush();
diff --git a/frontend/src/routes/project/database-detail/catalog/GrantAccessDialog.tsx b/frontend/src/routes/project/database-detail/catalog/GrantAccessDialog.tsx
index c0be1315ed..5aa0979ffc 100644
--- a/frontend/src/routes/project/database-detail/catalog/GrantAccessDialog.tsx
+++ b/frontend/src/routes/project/database-detail/catalog/GrantAccessDialog.tsx
@@ -432,6 +432,7 @@ export function GrantAccessDialog({
<FeatureBadge
feature={PlanFeature.FEATURE_DATA_MASKING}
instance={instance}
+ clickable={false}
/>
<span>{t("issue.role-grant.use-cel")}</span>
</div>
@@ -445,6 +446,7 @@ export function GrantAccessDialog({
<FeatureBadge
feature={PlanFeature.FEATURE_DATA_MASKING}
instance={instance}
+ clickable={false}
/>
<span>{t("issue.role-grant.manually-select")}</span>
</div>
diff --git a/frontend/src/routes/workspace/DatabasesPage.tsx b/frontend/src/routes/workspace/DatabasesPage.tsx
index 1796a26ec4..3b7ad455e3 100644
--- a/frontend/src/routes/workspace/DatabasesPage.tsx
+++ b/frontend/src/routes/workspace/DatabasesPage.tsx
@@ -1,7 +1,7 @@
import { create } from "@bufbuild/protobuf";
import { FieldMaskSchema } from "@bufbuild/protobuf/wkt";
import { Plus } from "lucide-react";
-import { useCallback, useEffect, useMemo, useRef, useState } from "react";
+import { useCallback, useMemo, useRef, useState } from "react";
import { useTranslation } from "react-i18next";
import { useCurrentRoute } from "@/app/router";
import { markListScrollRestorationEntry } from "@/app/router/NavigationScrollRestoration";
@@ -288,17 +288,6 @@ export function DatabasesPage() {
]
);
- // Mark database visit on mount
- useEffect(() => {
- const store = useAppStore.getState();
- if (!store.getIntroStateByKey("database.visit")) {
- store.saveIntroStateByKey({
- key: "database.visit",
- newState: true,
- });
- }
- }, []);
-
const showPrepareDatabaseTip =
currentRoute.query[PRODUCT_INTRO_TIP_QUERY_KEY] ===
PREPARE_DATABASE_TRANSFER_TIP;
diff --git a/frontend/src/routes/workspace/EnvironmentsPage.tsx b/frontend/src/routes/workspace/EnvironmentsPage.tsx
index 26a68906fa..6975123a79 100644
--- a/frontend/src/routes/workspace/EnvironmentsPage.tsx
+++ b/frontend/src/routes/workspace/EnvironmentsPage.tsx
@@ -1357,17 +1357,6 @@ export function EnvironmentsPage() {
void useAppStore.getState().fetchEnvironments();
}, []);
- // Initialize selected tab and intro state
- useEffect(() => {
- const store = useAppStore.getState();
- if (!store.getIntroStateByKey("environment.visit")) {
- store.saveIntroStateByKey({
- key: "environment.visit",
- newState: true,
- });
- }
- }, []);
-
// Select from hash or default to first
useEffect(() => {
const hash = window.location.hash.slice(1);
diff --git a/frontend/src/routes/workspace/MembersPage.test.tsx b/frontend/src/routes/workspace/MembersPage.test.tsx
index 125b79643d..d715ca7605 100644
--- a/frontend/src/routes/workspace/MembersPage.test.tsx
+++ b/frontend/src/routes/workspace/MembersPage.test.tsx
@@ -12,16 +12,12 @@ import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
).IS_REACT_ACT_ENVIRONMENT = true;
const {
- mockGetIntroStateByKey,
mockPushNotification,
- mockSaveIntroStateByKey,
mockUpdateProjectIamPolicy,
maximumRoleExpirationSeconds,
maximumRequestExpirationSeconds,
} = vi.hoisted(() => ({
- mockGetIntroStateByKey: vi.fn(),
mockPushNotification: vi.fn(),
- mockSaveIntroStateByKey: vi.fn(),
mockUpdateProjectIamPolicy: vi.fn(),
maximumRoleExpirationSeconds: { value: undefined as number | undefined },
maximumRequestExpirationSeconds: { value: undefined as number | undefined },
@@ -333,8 +329,6 @@ vi.mock("@/stores/app", () => {
? undefined
: { seconds: BigInt(maximumRequestExpirationSeconds.value) },
}),
- getIntroStateByKey: mockGetIntroStateByKey,
- saveIntroStateByKey: mockSaveIntroStateByKey,
});
const useAppStore = (selector?: (state: unknown) => unknown) =>
selector ? selector(buildState()) : buildState();
@@ -365,7 +359,6 @@ beforeEach(() => {
vi.clearAllMocks();
maximumRoleExpirationSeconds.value = undefined;
maximumRequestExpirationSeconds.value = undefined;
- mockGetIntroStateByKey.mockReturnValue(false);
projectIamPolicy.bindings = [];
container = document.createElement("div");
document.body.appendChild(container);
@@ -394,16 +387,6 @@ async function flush(): Promise<void> {
}
describe("MembersPage project role grant drawer", () => {
- it("marks the member quick-start item visited on mount", async () => {
- await renderPage();
-
- expect(mockGetIntroStateByKey).toHaveBeenCalledWith("member.visit");
- expect(mockSaveIntroStateByKey).toHaveBeenCalledWith({
- key: "member.visit",
- newState: true,
- });
- });
-
it("uses maximum role expiration instead of request expiration for direct role grants", async () => {
maximumRequestExpirationSeconds.value = 30 * 24 * 60 * 60;
diff --git a/frontend/src/routes/workspace/MembersPage.tsx b/frontend/src/routes/workspace/MembersPage.tsx
index 73dbaa150a..54b82c8214 100644
--- a/frontend/src/routes/workspace/MembersPage.tsx
+++ b/frontend/src/routes/workspace/MembersPage.tsx
@@ -2047,16 +2047,6 @@ export function MembersPage({ projectId }: { projectId?: string }) {
>();
const [showRequestRoleDialog, setShowRequestRoleDialog] = useState(false);
- useEffect(() => {
- const store = useAppStore.getState();
- if (!store.getIntroStateByKey("member.visit")) {
- store.saveIntroStateByKey({
- key: "member.visit",
- newState: true,
- });
- }
- }, []);
-
const hasRequestRoleFeature = useAppStore((s) =>
s.hasFeature(PlanFeature.FEATURE_REQUEST_ROLE_WORKFLOW)
);
diff --git a/frontend/src/routes/workspace/ProjectsPage.tsx b/frontend/src/routes/workspace/ProjectsPage.tsx
index c3ba1b84d0..0beda16c52 100644
--- a/frontend/src/routes/workspace/ProjectsPage.tsx
+++ b/frontend/src/routes/workspace/ProjectsPage.tsx
@@ -319,17 +319,6 @@ export function ProjectsPage() {
[searchParams]
);
- // Mark project visit on mount
- useEffect(() => {
- const store = useAppStore.getState();
- if (!store.getIntroStateByKey("project.visit")) {
- store.saveIntroStateByKey({
- key: "project.visit",
- newState: true,
- });
- }
- }, []);
-
// Data fetching state
const [projects, setProjects] = useState<Project[]>([]);
const [loading, setLoading] = useState(true);
diff --git a/frontend/src/stores/app/index.test.ts b/frontend/src/stores/app/index.test.ts
index c56f4aceaa..f8cf8b92f5 100644
--- a/frontend/src/stores/app/index.test.ts
+++ b/frontend/src/stores/app/index.test.ts
@@ -1978,6 +1978,40 @@ describe("useAppStore", () => {
expect(store.getState().appFeatures["bb.feature.hide-trial"]).toBe(false);
});
+ test("enables the workspace setup guide only for an eligible sole IAM user", () => {
+ const store = createAppStore();
+ store.setState({ hasWorkspacePermission: () => true });
+
+ for (const [userCountInIam, expected] of [
+ [0, false],
+ [1, true],
+ [2, false],
+ ] as const) {
+ store.setState({
+ serverInfo: createProto(ActuatorInfoSchema, { userCountInIam }),
+ });
+ expect(store.getState().workspaceSetupGuideEnabled()).toBe(expected);
+ }
+
+ store.setState((state) => ({
+ appFeatures: {
+ ...state.appFeatures,
+ "bb.feature.hide-quick-start": true,
+ },
+ }));
+ expect(store.getState().workspaceSetupGuideEnabled()).toBe(false);
+
+ store.setState((state) => ({
+ appFeatures: {
+ ...state.appFeatures,
+ "bb.feature.hide-quick-start": false,
+ },
+ serverInfo: createProto(ActuatorInfoSchema, { userCountInIam: 1 }),
+ hasWorkspacePermission: () => false,
+ }));
+ expect(store.getState().workspaceSetupGuideEnabled()).toBe(false);
+ });
+
test("derives actuator state for React consumers", () => {
const store = createAppStore();
store.setState({
@@ -2432,9 +2466,12 @@ describe("useAppStore", () => {
store.getState().recordRecentVisit("/projects/a?tab=1");
store.getState().recordRecentVisit("/projects/a?tab=2");
store.getState().removeRecentVisit("/missing");
- store.getState().resetQuickstartProgress();
+ store.getState().saveIntroStateByKey({
+ key: "workspace-setup-guide.dismissed",
+ newState: true,
+ });
+ store.getState().resetWorkspaceSetupGuide();
- // Not SaaS in this test, so keys are workspace-agnostic (scope "").
expect(
JSON.parse(
localStorage.getItem(storageKeyRecentProjects("", user.email))!
@@ -2444,12 +2481,50 @@ describe("useAppStore", () => {
JSON.parse(localStorage.getItem(storageKeyRecentVisit("", user.email))!)
).toEqual(["/projects/a?tab=2"]);
expect(
- JSON.parse(localStorage.getItem(storageKeyIntroState("", user.email))!)
- ).toMatchObject({
- hidden: false,
- "project.visit": false,
- "data.query": false,
+ JSON.parse(
+ localStorage.getItem(
+ storageKeyIntroState("workspaces/default", user.email)
+ )!
+ )
+ ).toEqual({ "workspace-setup-guide.dismissed": false });
+ });
+
+ test("resets all workspace setup guide progress", () => {
+ const store = createAppStore();
+ store.setState({ currentUser: user });
+
+ store.getState().saveIntroStateByKey({
+ key: "workspace-setup-guide.dismissed",
+ newState: true,
+ });
+ store.getState().saveIntroStateByKey({
+ key: "workspace-setup-guide.database-explored",
+ newState: true,
});
+ store.getState().saveIntroStateByKey({
+ key: "workspace-setup-guide.query-executed",
+ newState: true,
+ });
+ store
+ .getState()
+ .saveIntroStateByKey({ key: "unrelated.intro", newState: true });
+
+ store.getState().resetWorkspaceSetupGuide();
+
+ expect(
+ store.getState().getIntroStateByKey("workspace-setup-guide.dismissed")
+ ).toBe(false);
+ expect(
+ store
+ .getState()
+ .getIntroStateByKey("workspace-setup-guide.database-explored")
+ ).toBe(false);
+ expect(
+ store
+ .getState()
+ .getIntroStateByKey("workspace-setup-guide.query-executed")
+ ).toBe(false);
+ expect(store.getState().getIntroStateByKey("unrelated.intro")).toBe(true);
});
test("scopes recent projects by workspace in SaaS mode", () => {
@@ -2524,50 +2599,57 @@ describe("useAppStore", () => {
serverInfo: createProto(ActuatorInfoSchema, { saas: true }),
});
store.setState({ currentUser: { ...user, workspace: "workspaces/a" } });
- store
- .getState()
- .saveIntroStateByKey({ key: "project.visit", newState: true });
+ store.getState().saveIntroStateByKey({ key: "some.intro", newState: true });
store.setState({ currentUser: { ...user, workspace: "workspaces/b" } });
- expect(store.getState().getIntroStateByKey("project.visit")).toBe(false);
+ expect(store.getState().getIntroStateByKey("some.intro")).toBe(false);
store
.getState()
- .saveIntroStateByKey({ key: "database.visit", newState: true });
+ .saveIntroStateByKey({ key: "another.intro", newState: true });
expect(
JSON.parse(
localStorage.getItem(storageKeyIntroState("workspaces/a", user.email))!
)
- ).toEqual({ "project.visit": true });
+ ).toEqual({ "some.intro": true });
expect(
JSON.parse(
localStorage.getItem(storageKeyIntroState("workspaces/b", user.email))!
)
- ).toEqual({ "database.visit": true });
+ ).toEqual({ "another.intro": true });
});
- test("keeps intro state workspace-agnostic in self-host mode", () => {
+ test("scopes intro state by workspace in self-host mode", () => {
const store = createAppStore();
store.setState({
serverInfo: createProto(ActuatorInfoSchema, {
saas: false,
- workspace: "workspaces/default",
}),
});
- store.setState({ currentUser: user });
+ store.setState({ currentUser: { ...user, workspace: "workspaces/a" } });
localStorage.setItem(
storageKeyIntroState("", user.email),
- JSON.stringify({ "project.visit": true })
+ JSON.stringify({ "stale.intro": true })
);
+ store.getState().saveIntroStateByKey({ key: "some.intro", newState: true });
- expect(store.getState().getIntroStateByKey("project.visit")).toBe(true);
+ store.setState({ currentUser: { ...user, workspace: "workspaces/b" } });
+ expect(store.getState().getIntroStateByKey("some.intro")).toBe(false);
+ expect(store.getState().getIntroStateByKey("stale.intro")).toBe(false);
store
.getState()
- .saveIntroStateByKey({ key: "database.visit", newState: true });
+ .saveIntroStateByKey({ key: "another.intro", newState: true });
expect(
- JSON.parse(localStorage.getItem(storageKeyIntroState("", user.email))!)
- ).toEqual({ "project.visit": true, "database.visit": true });
+ JSON.parse(
+ localStorage.getItem(storageKeyIntroState("workspaces/a", user.email))!
+ )
+ ).toEqual({ "some.intro": true });
+ expect(
+ JSON.parse(
+ localStorage.getItem(storageKeyIntroState("workspaces/b", user.email))!
+ )
+ ).toEqual({ "another.intro": true });
});
test("caches database metadata and reuses inflight request", async () => {
diff --git a/frontend/src/stores/app/preferences.ts b/frontend/src/stores/app/preferences.ts
index 01e558e5e9..22755e4d14 100644
--- a/frontend/src/stores/app/preferences.ts
+++ b/frontend/src/stores/app/preferences.ts
@@ -7,23 +7,13 @@ import type { AppSliceCreator, PreferencesSlice } from "./types";
import {
getCurrentUserEmail,
getWorkspaceCacheScope,
+ getWorkspaceResourceScope,
MAX_RECENT_PROJECT,
MAX_RECENT_VISIT,
readJson,
writeJson,
} from "./utils";
-const QUICKSTART_RESET_KEYS = [
- "hidden",
- "issue.visit",
- "project.visit",
- "environment.visit",
- "instance.visit",
- "database.visit",
- "member.visit",
- "data.query",
-];
-
export const createPreferencesSlice: AppSliceCreator<PreferencesSlice> = (
set,
get
@@ -70,15 +60,20 @@ export const createPreferencesSlice: AppSliceCreator<PreferencesSlice> = (
);
},
- resetQuickstartProgress: () => {
+ resetWorkspaceSetupGuide: () => {
const email = getCurrentUserEmail(get);
if (!email) return;
- const key = storageKeyIntroState(getWorkspaceCacheScope(get), email);
+ const key = storageKeyIntroState(getWorkspaceResourceScope(get), email);
const previous = readJson<Record<string, boolean>>(key, {});
- const next = {
+ const next: Record<string, boolean> = {
...previous,
- ...Object.fromEntries(QUICKSTART_RESET_KEYS.map((key) => [key, false])),
+ "workspace-setup-guide.dismissed": false,
};
+ for (const introStateKey of Object.keys(next)) {
+ if (introStateKey.startsWith("workspace-setup-guide.")) {
+ next[introStateKey] = false;
+ }
+ }
writeJson(key, next);
set((state) => ({ introStateVersion: state.introStateVersion + 1 }));
},
@@ -90,18 +85,21 @@ export const createPreferencesSlice: AppSliceCreator<PreferencesSlice> = (
const email = getCurrentUserEmail(get);
if (!email) return false;
const map = readJson<Record<string, boolean>>(
- storageKeyIntroState(getWorkspaceCacheScope(get), email),
+ storageKeyIntroState(getWorkspaceResourceScope(get), email),
{}
);
return map[key] ?? false;
},
// Mirrors the Pinia `useUIStateStore.saveIntroStateByKey`: persists a
- // single intro flag (e.g. `data.query`) to the per-user localStorage map.
+ // single intro flag to the per-user localStorage map.
saveIntroStateByKey: ({ key, newState }) => {
const email = getCurrentUserEmail(get);
if (!email) return;
- const storageKey = storageKeyIntroState(getWorkspaceCacheScope(get), email);
+ const storageKey = storageKeyIntroState(
+ getWorkspaceResourceScope(get),
+ email
+ );
const previous = readJson<Record<string, boolean>>(storageKey, {});
writeJson(storageKey, { ...previous, [key]: newState });
set((state) => ({ introStateVersion: state.introStateVersion + 1 }));
diff --git a/frontend/src/stores/app/types.ts b/frontend/src/stores/app/types.ts
index 278a3dc600..8fbf302d78 100644
--- a/frontend/src/stores/app/types.ts
+++ b/frontend/src/stores/app/types.ts
@@ -308,7 +308,7 @@ export type WorkspaceSlice = {
userCountInIam: () => number;
activeVcsUserCount: () => number;
enableOnboarding: () => boolean;
- quickStartEnabled: () => boolean;
+ workspaceSetupGuideEnabled: () => boolean;
setupSample: () => Promise<void>;
// Always returns a profile (never undefined), mirroring the Pinia
// `workspaceProfile` getter so consumers read fields without null checks.
@@ -952,7 +952,7 @@ export type PreferencesSlice = {
setRecentProject: (name: string) => void;
recordRecentVisit: (path: string, workspaceName?: string) => void;
removeRecentVisit: (path: string) => void;
- resetQuickstartProgress: () => void;
+ resetWorkspaceSetupGuide: () => void;
getIntroStateByKey: (key: string) => boolean;
saveIntroStateByKey: (params: { key: string; newState: boolean }) => void;
};
diff --git a/frontend/src/stores/app/utils.ts b/frontend/src/stores/app/utils.ts
index 9a55924d99..53c999593e 100644
--- a/frontend/src/stores/app/utils.ts
+++ b/frontend/src/stores/app/utils.ts
@@ -30,6 +30,18 @@ export function getCurrentUserEmail(get: () => AppStoreState): string {
return get().currentUser?.email ?? "";
}
+export function getWorkspaceResourceScope(
+ get: () => AppStoreState,
+ workspaceName?: string
+): string {
+ return (
+ workspaceName ||
+ get().currentUser?.workspace ||
+ get().serverInfo?.workspace ||
+ ""
+ );
+}
+
// Workspace segment for localStorage cache keys — "" for self-host (keys stay
// shared/unchanged), the workspace name for SaaS (keys are workspace-isolated).
// Fall back to serverInfo while the current user is still hydrating.
@@ -37,11 +49,7 @@ export function getWorkspaceCacheScope(
get: () => AppStoreState,
workspaceName?: string
): string {
- const scope =
- workspaceName ||
- get().currentUser?.workspace ||
- get().serverInfo?.workspace ||
- "";
+ const scope = getWorkspaceResourceScope(get, workspaceName);
return workspaceCacheScope(get().isSaaSMode(), scope);
}
diff --git a/frontend/src/stores/app/workspace.ts b/frontend/src/stores/app/workspace.ts
index b8ee1c3b3c..3fb2a3ae95 100644
--- a/frontend/src/stores/app/workspace.ts
+++ b/frontend/src/stores/app/workspace.ts
@@ -688,15 +688,12 @@ export const createWorkspaceSlice: AppSliceCreator<WorkspaceSlice> = (
enableOnboarding: () => get().userCountInIam() === 1 && !get().isSaaSMode(),
- quickStartEnabled: () => {
- if (get().appFeatures["bb.feature.hide-quick-start"]) {
- return false;
- }
- if (!get().serverInfo?.sample?.available) {
- return false;
- }
- return get().userCountInIam() <= 1;
- },
+ workspaceSetupGuideEnabled: () =>
+ !get().appFeatures["bb.feature.hide-quick-start"] &&
+ get().userCountInIam() === 1 &&
+ get().hasWorkspacePermission("bb.projects.list") &&
+ get().hasWorkspacePermission("bb.instances.list") &&
+ get().hasWorkspacePermission("bb.databases.list"),
setupSample: async () => {
await actuatorServiceClientConnect.setupSample({});
diff --git a/frontend/src/utils/storage-keys.ts b/frontend/src/utils/storage-keys.ts
index c908d3da43..65d3c618fe 100644
--- a/frontend/src/utils/storage-keys.ts
+++ b/frontend/src/utils/storage-keys.ts
@@ -57,6 +57,8 @@ export const storageKeyLastActivity = (email: string) =>
`bb.last-activity.${email}`;
export const storageKeyCollapseState = (email: string) =>
`bb.collapse-state.${email}`;
+// Always workspace-scoped, including self-host, because browser storage can
+// outlive the server data associated with a workspace id.
export const storageKeyIntroState = (scope: string, email: string) =>
withScope("bb.intro-state", scope, email);
// Workspace-scoped: value keys embed project resource names.