Database governance built for humans and agents — controlling changes and access across every major database.
Go cicddata-governancedata-maskingdata-securitydatabase-accessdatabase-governancedevopsdevsecopsflywaygitopsliquibasemongodbmysqloraclepostgresqlschema-migrationssecuritysql-clientsqlservertidb
chore:optimize perf
ecmadaob7214e8e01b1
diff --git a/frontend/src/components/AccountMultiSelect.test.tsx b/frontend/src/components/AccountMultiSelect.test.tsxnew file mode 100644index 0000000000..8aac5763d5--- /dev/null+++ b/frontend/src/components/AccountMultiSelect.test.tsx@@ -0,0 +1,140 @@+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(() => ({+ listUsers: vi.fn(),+ listGroups: vi.fn(),+}));++vi.mock("react-i18next", () => ({+ initReactI18next: { type: "3rdParty", init: () => {} },+ useTranslation: () => ({ t: (key: string) => key }),+}));++vi.mock("@/hooks/useAppState", () => ({+ useCurrentUser: () => ({ email: "[email protected]" }),+}));++vi.mock("@/hooks/useClickOutside", () => ({+ useClickOutside: () => {},+}));++vi.mock("@/stores/app", () => {+ const state = () => ({+ listUsers: mocks.listUsers,+ listGroups: mocks.listGroups,+ });+ return {+ useAppStore: (selector: (s: ReturnType<typeof state>) => unknown) =>+ selector(state()),+ };+});++vi.mock("@/types", () => ({+ AccountType: {+ USER: 0,+ SERVICE_ACCOUNT: 1,+ WORKLOAD_IDENTITY: 2,+ },+ ALL_USERS_USER_EMAIL: "allUsers",+ getAccountTypeByEmail: () => 0,+ serviceAccountBindingPrefix: "serviceAccount:",+ userBindingPrefix: "user:",+ workloadIdentityBindingPrefix: "workloadIdentity:",+}));++vi.mock("@/utils", () => ({+ getDefaultPagination: () => 50,+ isValidEmail: (value: string) => value.includes("@"),+}));++vi.mock("@/components/ui/search-input", () => ({+ SearchInput: ({+ onChange,+ value,+ }: {+ onChange: (event: React.ChangeEvent<HTMLInputElement>) => void;+ value: string;+ }) => <input data-testid="search" value={value} onChange={onChange} />,+}));++vi.mock("@/components/HighlightLabelText", () => ({+ HighlightLabelText: ({+ keyword,+ text,+ }: {+ keyword?: string;+ text: string;+ }) => <b data-keyword={keyword}>{text}</b>,+}));++vi.mock("./UserAvatar", () => ({+ getAvatarColor: () => "#000000",+ getInitials: () => "A",+}));++let AccountMultiSelect: typeof import("./AccountMultiSelect").AccountMultiSelect;++beforeEach(async () => {+ vi.useFakeTimers();+ mocks.listUsers.mockResolvedValue({+ users: [+ {+ name: "users/[email protected]",+ email: "[email protected]",+ title: "Alice",+ },+ ],+ nextPageToken: "",+ });+ mocks.listGroups.mockResolvedValue({ groups: [], nextPageToken: "" });+ ({ AccountMultiSelect } = await import("./AccountMultiSelect"));+});++afterEach(() => {+ vi.useRealTimers();+ document.body.innerHTML = "";+});++describe("AccountMultiSelect", () => {+ test("highlights the search query in account results", async () => {+ const container = document.createElement("div");+ document.body.appendChild(container);+ const root = createRoot(container);+ act(() => {+ root.render(<AccountMultiSelect value={[]} onChange={() => {}} />);+ });+ act(() => {+ container.firstElementChild?.firstElementChild?.dispatchEvent(+ new MouseEvent("click", { bubbles: true })+ );+ });++ const input = container.querySelector(+ '[data-testid="search"]'+ ) as HTMLInputElement;+ await act(async () => {+ const valueSetter = Object.getOwnPropertyDescriptor(+ HTMLInputElement.prototype,+ "value"+ )?.set;+ valueSetter?.call(input, "ali");+ input.dispatchEvent(new Event("input", { bubbles: true }));+ vi.advanceTimersByTime(300);+ await Promise.resolve();+ await Promise.resolve();+ });++ const title = Array.from(container.querySelectorAll("b")).find(+ (element) => element.textContent === "Alice"+ );+ expect(title?.dataset.keyword).toBe("ali");++ act(() => root.unmount());+ });+});diff --git a/frontend/src/components/AccountMultiSelect.tsx b/frontend/src/components/AccountMultiSelect.tsxindex 88dcf6d0d2..c4b0be1572 100644--- a/frontend/src/components/AccountMultiSelect.tsx+++ b/frontend/src/components/AccountMultiSelect.tsx@@ -1,6 +1,7 @@import { Check, ChevronDown, KeyRound, Shield, Users, X } from "lucide-react";import { useCallback, useEffect, useMemo, useRef, useState } from "react";import { useTranslation } from "react-i18next";+import { HighlightLabelText } from "@/components/HighlightLabelText";import { LAYER_SURFACE_CLASS } from "@/components/ui/layer";import { SearchInput } from "@/components/ui/search-input";import { useCurrentUser } from "@/hooks/useAppState";@@ -130,10 +131,12 @@ function SelectionCheckbox({ selected }: { selected: boolean }) {}function SpecialAccountOption({+ keyword,match,selected,onToggle,}: {+ keyword: string;match: { type: SpecialAccountType; email: string };selected: boolean;onToggle: () => void;@@ -162,16 +165,20 @@ function SpecialAccountOption({</div><div className="flex flex-col min-w-0"><div className="flex items-center gap-x-1">- <span className="text-sm font-medium truncate">- {match.email.split("@")[0]}- </span>+ <HighlightLabelText+ text={match.email.split("@")[0]}+ keyword={keyword}+ className="text-sm font-medium truncate"+ /><span className="text-xs text-control-light bg-control-bg rounded-xs px-1">{label}</span></div>- <span className="text-xs text-control-light truncate">- {match.email}- </span>+ <HighlightLabelText+ text={match.email}+ keyword={keyword}+ className="text-xs text-control-light truncate"+ /></div></div>);@@ -393,9 +400,11 @@ export function AccountMultiSelect({><Users className="h-4 w-4" /></div>- <span className="text-sm font-medium">- {t("settings.members.all-users")}- </span>+ <HighlightLabelText+ text={t("settings.members.all-users")}+ keyword={search}+ className="text-sm font-medium"+ /></div>)}@@ -431,9 +440,11 @@ export function AccountMultiSelect({</div><div className="flex flex-col min-w-0"><div className="flex items-center gap-x-1">- <span className="text-sm font-medium truncate">- {displayName}- </span>+ <HighlightLabelText+ text={displayName}+ keyword={search}+ className="text-sm font-medium truncate"+ />{isCurrentUser && (<span className="text-xs text-control-light bg-control-bg rounded-xs px-1">{t("common.you")}@@ -441,9 +452,11 @@ export function AccountMultiSelect({)}</div>{user.title && (- <span className="text-xs text-control-light truncate">- {user.email}- </span>+ <HighlightLabelText+ text={user.email}+ keyword={search}+ className="text-xs text-control-light truncate"+ />)}</div></div>@@ -475,9 +488,11 @@ export function AccountMultiSelect({</div><div className="flex flex-col min-w-0"><div className="flex items-center gap-x-1.5">- <span className="text-sm font-medium truncate">- {group.title || group.email}- </span>+ <HighlightLabelText+ text={group.title || group.email}+ keyword={search}+ className="text-sm font-medium truncate"+ /><span className="text-xs text-control-light">({group.members.length}{" "}{t("common.members", {@@ -486,9 +501,11 @@ export function AccountMultiSelect({)</span></div>- <span className="text-xs text-control-light truncate">- {group.email}- </span>+ <HighlightLabelText+ text={group.email}+ keyword={search}+ className="text-xs text-control-light truncate"+ /></div></div>);@@ -499,6 +516,7 @@ export function AccountMultiSelect({{/* Service account / workload identity match */}{specialAccountMatch && (<SpecialAccountOption+ keyword={search}match={specialAccountMatch}selected={selectedFullnames.has(specialAccountMatch.fullname)}onToggle={() => toggle(specialAccountMatch.fullname)}@@ -529,9 +547,11 @@ export function AccountMultiSelect({{getInitials(arbitraryEmailMatch.split("@")[0])}</div><div className="flex flex-col min-w-0">- <span className="text-sm font-medium truncate">- {arbitraryEmailMatch}- </span>+ <HighlightLabelText+ text={arbitraryEmailMatch}+ keyword={search}+ className="text-sm font-medium truncate"+ /></div></div>)}diff --git a/frontend/src/components/DatabaseResourceSelector.test.tsx b/frontend/src/components/DatabaseResourceSelector.test.tsxindex 65a1375752..aa6acdb88d 100644--- a/frontend/src/components/DatabaseResourceSelector.test.tsx+++ b/frontend/src/components/DatabaseResourceSelector.test.tsx@@ -98,13 +98,19 @@ vi.mock("@/components/EnvironmentLabel", () => ({vi.mock("@/components/DatabaseTargetDisplay", () => ({DatabaseTargetDisplay: ({database,+ keyword,target,}: {database?: { name: string };+ keyword?: string;target?: string;}) => {const name = database?.name ?? target ?? "";- return <span>{name.split("/databases/").at(-1) ?? name}</span>;+ return (+ <span data-keyword={keyword}>+ {name.split("/databases/").at(-1) ?? name}+ </span>+ );},}));@@ -296,6 +302,21 @@ describe("DatabaseResourceSelector", () => {unmount();});+ test("passes the free-text query to database result highlighting", async () => {+ const { container, unmount } = renderIntoContainer(<Harness />);+ await flushPromises();+ await waitForText(container, "advanced-search:");++ clickFirstButtonInRow(container, "advanced-search:");+ await flushPromises();++ const databaseLabel = Array.from(+ container.querySelectorAll("[data-keyword]")+ ).find((element) => element.textContent === "hr") as HTMLElement;+ expect(databaseLabel.dataset.keyword).toBe("salary");+ unmount();+ });+test("does not expose column rows unless explicitly enabled", async () => {const { container, unmount } = renderIntoContainer(<Harness />);await flushPromises();diff --git a/frontend/src/components/DatabaseResourceSelector.tsx b/frontend/src/components/DatabaseResourceSelector.tsxindex 675f070a32..af1df761fc 100644--- a/frontend/src/components/DatabaseResourceSelector.tsx+++ b/frontend/src/components/DatabaseResourceSelector.tsx@@ -918,6 +918,7 @@ export function DatabaseResourceSelector({/><DatabaseTargetDisplaydatabase={db}+ keyword={searchParams.query}showEnvironmentclassName="min-w-0"/>diff --git a/frontend/src/components/DatabaseSelect.test.tsx b/frontend/src/components/DatabaseSelect.test.tsxindex 1cb29f0bc7..ef28871e35 100644--- a/frontend/src/components/DatabaseSelect.test.tsx+++ b/frontend/src/components/DatabaseSelect.test.tsx@@ -1,4 +1,4 @@-import { act, type ReactElement } from "react";+import { act, type ReactElement, type ReactNode } from "react";import { createRoot } from "react-dom/client";import { afterEach, beforeEach, describe, expect, test, vi } from "vitest";import type { Database } from "@/types/proto-es/v1/database_service_pb";@@ -12,8 +12,15 @@ type ComboProps = {multiple?: boolean;value: string | string[];onChange: (v: string | string[]) => void;- onSearch?: (q: string) => void;- options: { value: string; label: string }[];+ onSearch?: (q: string) => void | Promise<void>;+ hasMore?: boolean;+ loadingMore?: boolean;+ onLoadMore?: () => void | Promise<void>;+ options: {+ value: string;+ label: string;+ render?: (keyword: string) => ReactNode;+ }[];renderValue?: (opt: { value: string; label: string }) => unknown;};const combo: { props?: ComboProps } = {};@@ -63,9 +70,11 @@ vi.mock("@/components/ui/combobox", () => ({vi.mock("@/components/DatabaseTargetDisplay", () => ({DatabaseTargetDisplay: ({database,+ keyword,target,}: {database?: { name: string };+ keyword?: string;target?: string;}) => {const name = database?.name ?? target ?? "";@@ -73,10 +82,29 @@ vi.mock("@/components/DatabaseTargetDisplay", () => ({/(?:^|\/)instances\/(?<instanceName>[^/]+)\/databases\/(?<databaseName>[^/]+)(?:$|\/)/);const { instanceName = "", databaseName = name } = matches?.groups ?? {};- return <span>{`${instanceName} / ${databaseName}`}</span>;+ return (+ <span>{`${instanceName} / ${databaseName}${keyword ? ` [${keyword}]` : ""}`}</span>+ );},}));+vi.mock("@/components/HighlightLabelText", () => ({+ HighlightLabelText: ({+ className,+ keyword,+ text,+ }: {+ className?: string;+ keyword?: string;+ text: string;+ }) => (+ <span className={className}>+ {text}+ {keyword ? ` [${keyword}]` : ""}+ </span>+ ),+}));+vi.mock("@/utils", () => ({extractDatabaseResourceName: (name: string) => {const parts = name.split("/");@@ -196,7 +224,9 @@ describe("DatabaseSelect — multi mode", () => {await flush();expect(combo.props?.onSearch).toBeTypeOf("function");- act(() => combo.props?.onSearch?.("orders"));+ await act(async () => {+ await combo.props?.onSearch?.("orders");+ });expect(mocks.fetchDatabases).toHaveBeenCalledWith(expect.objectContaining({parent: "projects/p",@@ -206,6 +236,66 @@ describe("DatabaseSelect — multi mode", () => {unmount();});+ test("loads and appends the next database page", async () => {+ mocks.fetchDatabases+ .mockResolvedValueOnce({+ databases: [db("instances/i/databases/one")],+ nextPageToken: "page-2",+ })+ .mockResolvedValueOnce({+ databases: [db("instances/i/databases/two")],+ nextPageToken: "",+ });+ const { unmount } = render(+ <DatabaseSelect+ multiple+ value={[]}+ onChange={vi.fn()}+ projectName="projects/p"+ />+ );+ await flush();++ expect(combo.props?.hasMore).toBe(true);+ await act(async () => {+ await combo.props?.onLoadMore?.();+ });++ expect(mocks.fetchDatabases).toHaveBeenLastCalledWith(+ expect.objectContaining({ pageToken: "page-2" })+ );+ expect(combo.props?.options.map((option) => option.value)).toEqual([+ "instances/i/databases/one",+ "instances/i/databases/two",+ ]);+ expect(combo.props?.hasMore).toBe(false);+ unmount();+ });++ test("forwards the active search query to the database row renderer", async () => {+ mocks.fetchDatabases.mockResolvedValue({+ databases: [db("instances/i/databases/bytebase")],+ nextPageToken: "",+ });+ const { unmount } = render(+ <DatabaseSelect+ multiple+ value={[]}+ onChange={vi.fn()}+ projectName="projects/p"+ />+ );+ await flush();++ const option = combo.props?.options.find(+ (item) => item.value === "instances/i/databases/bytebase"+ );+ const rendered = render(option?.render?.("byte") as ReactElement);+ expect(rendered.container.textContent).toContain("[byte]");+ rendered.unmount();+ unmount();+ });+test("a selected value absent from current results still renders as an option (chip preservation)", async () => {// Server never returns the pre-selected db (it's past page 1).mocks.fetchDatabases.mockResolvedValue({@@ -278,7 +368,9 @@ describe("DatabaseSelect — multi mode", () => {/>);// Mount fetch (call 1) is in flight; fire a search (call 2).- act(() => combo.props?.onSearch?.("q"));+ act(() => {+ void combo.props?.onSearch?.("q");+ });// Resolve the NEWER search first, then the OLDER mount fetch.await act(async () => {@@ -346,8 +438,9 @@ describe("DatabaseSelect — single mode (regression guard for Sync Schema)", ()databases: [db("instances/i/databases/zzz")],nextPageToken: "",});- act(() => combo.props?.onSearch?.("zzz"));- await flush();+ await act(async () => {+ await combo.props?.onSearch?.("zzz");+ });// The selected value must still be resolvable as an option/label.const opt = combo.props?.options.find(diff --git a/frontend/src/components/DatabaseSelect.tsx b/frontend/src/components/DatabaseSelect.tsxindex 3a52f1a9e7..d9fc358a78 100644--- a/frontend/src/components/DatabaseSelect.tsx+++ b/frontend/src/components/DatabaseSelect.tsx@@ -1,7 +1,9 @@-import { useCallback, useEffect, useMemo, useRef, useState } from "react";+import { useCallback, useEffect, useMemo, useRef } from "react";import { useTranslation } from "react-i18next";import { DatabaseTargetDisplay } from "@/components/DatabaseTargetDisplay";+import { HighlightLabelText } from "@/components/HighlightLabelText";import { Combobox, type ComboboxOption } from "@/components/ui/combobox";+import { usePaginatedSelect } from "@/components/usePaginatedSelect";import { useAppStore } from "@/stores/app";import type { Engine } from "@/types/proto-es/v1/common_pb";import type { Database } from "@/types/proto-es/v1/database_service_pb";@@ -58,13 +60,6 @@ export function DatabaseSelect(props: DatabaseSelectProps) {// synthesized label in practice.const getDatabaseByName = useAppStore((s) => s.getDatabaseByName);- // Current page / latest search results (drives the dropdown rows).- const [databases, setDatabases] = useState<Database[]>([]);- // Monotonic fetch id: only the latest in-flight fetch may apply its result,- // so an out-of-order (slow mount / stale search) response can't clobber newer- // results. Mirrors DatabaseResourceSelector / the plan-detail DatabaseSelector.- const fetchIdRef = useRef(0);-// Stabilize engines array to avoid re-fetching on every render.const enginesRef = useRef(allowedEngineTypeList);const stableEngines = useMemo(() => {@@ -81,37 +76,37 @@ export function DatabaseSelect(props: DatabaseSelectProps) {return allowedEngineTypeList;}, [allowedEngineTypeList]);- const fetchDatabases = useCallback(- (query: string) => {- const fetchId = ++fetchIdRef.current;- useAppStore- .getState()- .fetchDatabases({- parent: projectName ?? workspaceResourceName,- filter: {- environment: environmentName,- engines: stableEngines,- query,- },- pageSize: getDefaultPagination(),- silent: true,- })- .then((result) => {- // Drop stale responses so a slower earlier fetch can't overwrite the- // results of a newer query.- if (fetchId !== fetchIdRef.current) return;- setDatabases(result.databases);- })- .catch(() => {- /* keep existing options on error — never wipe the selection */- });+ const fetchPage = useCallback(+ async (query: string, pageToken: string) => {+ const result = await useAppStore.getState().fetchDatabases({+ parent: projectName ?? workspaceResourceName,+ filter: {+ environment: environmentName,+ engines: stableEngines,+ query,+ },+ pageSize: getDefaultPagination(),+ pageToken,+ silent: true,+ });+ return {+ items: result.databases,+ nextPageToken: result.nextPageToken,+ };},[projectName, environmentName, stableEngines, workspaceResourceName]);+ const {+ items: databases,+ search,+ hasMore,+ loadingMore,+ loadMore,+ } = usePaginatedSelect({ fetchPage });useEffect(() => {- fetchDatabases("");- }, [fetchDatabases]);+ search("");+ }, [search]);const selectedValues: string[] = useMemo(() => {if (props.multiple === true) return props.value;@@ -141,12 +136,18 @@ export function DatabaseSelect(props: DatabaseSelectProps) {value: database.name,label: databaseName,description: instance,- render: () => (+ render: (keyword) => (<div className="flex flex-col gap-0.5">- <DatabaseTargetDisplay database={database} showEnvironment />- <span className="text-xs text-control-placeholder">- {database.name}- </span>+ <DatabaseTargetDisplay+ database={database}+ keyword={keyword}+ showEnvironment+ />+ <HighlightLabelText+ text={database.name}+ keyword={keyword}+ className="text-xs text-control-placeholder"+ /></div>),};@@ -176,7 +177,10 @@ export function DatabaseSelect(props: DatabaseSelectProps) {const commonProps = {placeholder: placeholder ?? t("database.select"),noResultsText: t("common.no-data"),- onSearch: fetchDatabases,+ onSearch: search,+ hasMore,+ loadingMore,+ onLoadMore: loadMore,disabled,className,portal,diff --git a/frontend/src/components/DatabaseTargetDisplay.test.tsx b/frontend/src/components/DatabaseTargetDisplay.test.tsxindex e26f0151ca..c3ded9ce47 100644--- a/frontend/src/components/DatabaseTargetDisplay.test.tsx+++ b/frontend/src/components/DatabaseTargetDisplay.test.tsx@@ -175,6 +175,29 @@ describe("DatabaseTargetDisplay", () => {).toBeTruthy();});+ it("highlights the search keyword in the database name", () => {+ act(() => {+ root.render(+ <DatabaseTargetDisplay+ database={{+ name: "projects/p/instances/bbdev/databases/bytebase",+ instanceResource: {+ engine: Engine.POSTGRES,+ title: "bbdev",+ },+ } as Database}+ keyword="byte"+ />+ );+ });++ const highlight = container.querySelector(+ '[data-testid="ellipsis-bytebase"] b'+ );+ expect(highlight?.textContent).toBe("byte");+ expect(highlight?.className).toContain("text-accent");+ });+it("falls back to target path context while the database cache is missing", () => {mocks.databasesByName = {};diff --git a/frontend/src/components/DatabaseTargetDisplay.tsx b/frontend/src/components/DatabaseTargetDisplay.tsxindex a060b003fc..5293b0ca20 100644--- a/frontend/src/components/DatabaseTargetDisplay.tsx+++ b/frontend/src/components/DatabaseTargetDisplay.tsx@@ -1,6 +1,7 @@import { useMemo } from "react";import { EngineIcon } from "@/components/EngineIcon";import { EnvironmentLabel } from "@/components/EnvironmentLabel";+import { HighlightLabelText } from "@/components/HighlightLabelText";import { EllipsisText } from "@/components/ui/ellipsis-text";import { cn } from "@/lib/utils";import { useAppStore } from "@/stores/app";@@ -42,6 +43,7 @@ type DatabaseTargetDisplayProps = {showEnvironment?: boolean;showInstance?: boolean;size?: DatabaseTargetDisplaySize;+ keyword?: string | readonly string[];} & (| {database?: Database;@@ -56,6 +58,7 @@ type DatabaseTargetDisplayProps = {export function DatabaseTargetDisplay({className,database: databaseProp,+ keyword,showEngine = true,showEnvironment = false,showInstance = true,@@ -88,7 +91,9 @@ export function DatabaseTargetDisplay({classes.root,className)}- />+ >+ <HighlightLabelText text={targetName} keyword={keyword} />+ </EllipsisText>);}@@ -137,7 +142,9 @@ export function DatabaseTargetDisplay({<EllipsisTexttext={databaseName}className={cn("flex-1 truncate text-control", classes.database)}- />+ >+ <HighlightLabelText text={databaseName} keyword={keyword} />+ </EllipsisText></div>);}diff --git a/frontend/src/components/EnvironmentLabel.test.tsx b/frontend/src/components/EnvironmentLabel.test.tsxindex 3227e5a296..3b4164d47c 100644--- a/frontend/src/components/EnvironmentLabel.test.tsx+++ b/frontend/src/components/EnvironmentLabel.test.tsx@@ -100,4 +100,19 @@ describe("EnvironmentBadge", () => {const badge = rendered.container.querySelector("span");expect(badge?.style.color).toBe("rgb(129, 140, 248)");});++ test("highlights the environment title", async () => {+ const rendered = await render(+ <EnvironmentBadge+ environment={environment}+ hasEnvTierFeature={false}+ keyword="duct"+ />+ );+ root = rendered.root;++ const highlight = rendered.container.querySelector("b");+ expect(highlight?.textContent).toBe("duct");+ expect(highlight?.className).toContain("text-accent");+ });});diff --git a/frontend/src/components/EnvironmentLabel.tsx b/frontend/src/components/EnvironmentLabel.tsxindex 9181cdc857..badf80f4e3 100644--- a/frontend/src/components/EnvironmentLabel.tsx+++ b/frontend/src/components/EnvironmentLabel.tsx@@ -1,6 +1,7 @@import { ShieldAlert } from "lucide-react";import { memo } from "react";import { useTranslation } from "react-i18next";+import { HighlightLabelText } from "@/components/HighlightLabelText";import { RouterLink } from "@/components/RouterLink";import { useEnvironment, usePlanFeature } from "@/hooks/useAppState";import { cn } from "@/lib/utils";@@ -29,12 +30,14 @@ export const EnvironmentBadge = memo(function EnvironmentBadge({environment,hasEnvTierFeature,className,+ keyword,link,styleOptions,}: {environment: Environment;hasEnvTierFeature: boolean;className?: string;+ keyword?: string | readonly string[];link?: boolean;styleOptions?: {defaultColorTextColor?: string;@@ -78,7 +81,7 @@ export const EnvironmentBadge = memo(function EnvironmentBadge({{t("common.unassigned")}</span>) : (- environment.title+ <HighlightLabelText text={environment.title} keyword={keyword} />)}</span>{isProtected && !isUnset && (@@ -119,12 +122,14 @@ export function EnvironmentLabel({environment: envProp,environmentName,className,+ keyword,link,styleOptions,}: {environment?: Environment;environmentName?: string;className?: string;+ keyword?: string | readonly string[];link?: boolean;styleOptions?: {defaultColorTextColor?: string;@@ -142,6 +147,7 @@ export function EnvironmentLabel({environment={environment}hasEnvTierFeature={hasEnvTierFeature}className={className}+ keyword={keyword}link={link}styleOptions={styleOptions}/>diff --git a/frontend/src/components/EnvironmentSelect.tsx b/frontend/src/components/EnvironmentSelect.tsxindex ac7bcec0fa..60ffa78867 100644--- a/frontend/src/components/EnvironmentSelect.tsx+++ b/frontend/src/components/EnvironmentSelect.tsx@@ -1,6 +1,7 @@import { useMemo } from "react";import { useTranslation } from "react-i18next";import { EnvironmentLabel } from "@/components/EnvironmentLabel";+import { HighlightLabelText } from "@/components/HighlightLabelText";import { Combobox } from "@/components/ui/combobox";import { useEnvironmentList } from "@/hooks/useAppState";import { formatEnvironmentName } from "@/types";@@ -38,15 +39,17 @@ export function EnvironmentSelect(props: EnvironmentSelectProps) {environments.map((env) => ({value: formatEnvironmentName(env.id),label: env.title,- render: () => (+ render: (keyword: string) => (<div className="flex flex-col gap-0.5"><div className="flex items-center gap-x-1">- <EnvironmentLabel environment={env} />+ <EnvironmentLabel environment={env} keyword={keyword} />{renderSuffix?.(env)}</div>- <span className="text-xs text-control-placeholder">- {formatEnvironmentName(env.id)}- </span>+ <HighlightLabelText+ text={formatEnvironmentName(env.id)}+ keyword={keyword}+ className="text-xs text-control-placeholder"+ /></div>),})),diff --git a/frontend/src/components/InstanceSelect.tsx b/frontend/src/components/InstanceSelect.tsxindex 7f23caa071..827cc7be08 100644--- a/frontend/src/components/InstanceSelect.tsx+++ b/frontend/src/components/InstanceSelect.tsx@@ -1,8 +1,10 @@-import { useCallback, useEffect, useMemo, useRef, useState } from "react";+import { useCallback, useEffect, useMemo, useRef } from "react";import { useTranslation } from "react-i18next";import { EngineIcon } from "@/components/EngineIcon";import { EnvironmentLabel } from "@/components/EnvironmentLabel";+import { HighlightLabelText } from "@/components/HighlightLabelText";import { Combobox } from "@/components/ui/combobox";+import { usePaginatedSelect } from "@/components/usePaginatedSelect";import { useAppStore } from "@/stores/app";import type { Engine } from "@/types/proto-es/v1/common_pb";import type { Instance } from "@/types/proto-es/v1/instance_service_pb";@@ -29,8 +31,6 @@ export function InstanceSelect({engines,}: InstanceSelectProps) {const { t } = useTranslation();- const [instances, setInstances] = useState<Instance[]>([]);-// Stabilize engines array to avoid re-fetching on every renderconst enginesRef = useRef(engines);const stableEngines = useMemo(() => {@@ -47,22 +47,31 @@ export function InstanceSelect({return engines;}, [engines]);- const fetchInstances = useCallback(- (query: string) => {- useAppStore- .getState()- .fetchInstanceList({- pageSize: getDefaultPagination(),- filter: { query, engines: stableEngines },- })- .then((result) => setInstances(result.instances));+ const fetchPage = useCallback(+ async (query: string, pageToken: string) => {+ const result = await useAppStore.getState().fetchInstanceList({+ pageSize: getDefaultPagination(),+ pageToken,+ filter: { query, engines: stableEngines },+ });+ return {+ items: result.instances,+ nextPageToken: result.nextPageToken,+ };},[stableEngines]);+ const {+ items: instances,+ search,+ hasMore,+ loadingMore,+ loadMore,+ } = usePaginatedSelect({ fetchPage });useEffect(() => {- fetchInstances("");- }, [fetchInstances]);+ search("");+ }, [search]);const handleChange = useCallback((name: string) => {@@ -78,7 +87,10 @@ export function InstanceSelect({onChange={handleChange}placeholder={placeholder ?? t("common.instance")}noResultsText={t("common.no-data")}- onSearch={fetchInstances}+ onSearch={search}+ hasMore={hasMore}+ loadingMore={loadingMore}+ onLoadMore={loadMore}disabled={disabled}className={className}portal={portal}@@ -96,18 +108,20 @@ export function InstanceSelect({value: inst.name,label: inst.title,description: extractInstanceResourceName(inst.name),- render: () => (+ render: (keyword) => (<div className="flex flex-col gap-0.5"><div className="flex items-center gap-1.5">{inst.environment && (<EnvironmentLabel environmentName={inst.environment} />)}<EngineIcon engine={inst.engine} className="h-4 w-4" />- <span>{inst.title}</span>+ <HighlightLabelText text={inst.title} keyword={keyword} /></div>- <span className="text-xs text-control-placeholder">- {extractInstanceResourceName(inst.name)}- </span>+ <HighlightLabelText+ text={extractInstanceResourceName(inst.name)}+ keyword={keyword}+ className="text-xs text-control-placeholder"+ /></div>),}))}diff --git a/frontend/src/components/ProjectSelect.tsx b/frontend/src/components/ProjectSelect.tsxindex 1d6380ed76..61645a5d29 100644--- a/frontend/src/components/ProjectSelect.tsx+++ b/frontend/src/components/ProjectSelect.tsx@@ -2,6 +2,7 @@ import type { ReactNode } from "react";import { useCallback, useEffect, useMemo, useRef, useState } from "react";import { useTranslation } from "react-i18next";import { Combobox } from "@/components/ui/combobox";+import { usePaginatedSelect } from "@/components/usePaginatedSelect";import { useAppStore } from "@/stores/app";import { isValidProjectName } from "@/types";import type { Project } from "@/types/proto-es/v1/project_service_pb";@@ -37,7 +38,6 @@ export function ProjectSelect({portal,}: ProjectSelectProps) {const { t } = useTranslation();- const [projects, setProjects] = useState<Project[]>([]);// Projects referenced by `value` that aren't in the paged fetch.// Mirrors Vue's `additionalOptions` so deep-linked URLs (e.g.// `/sql-editor/projects/foo/...`) show the correct project label@@ -56,23 +56,32 @@ export function ProjectSelect({const excludeDefaultRef = useRef(excludeDefault);excludeDefaultRef.current = excludeDefault;- const fetchProjects = useCallback((query: string) => {- useAppStore- .getState()- .fetchProjectList({- filter: { query, excludeDefault: excludeDefaultRef.current },- pageSize: getDefaultPagination(),- })- .then(({ projects: result }) => setProjects(result));+ const fetchPage = useCallback(async (query: string, pageToken: string) => {+ const result = await useAppStore.getState().fetchProjectList({+ filter: { query, excludeDefault: excludeDefaultRef.current },+ pageSize: getDefaultPagination(),+ pageToken,+ });+ return {+ items: result.projects,+ nextPageToken: result.nextPageToken,+ };}, []);+ const {+ items: projects,+ search,+ hasMore,+ loadingMore,+ loadMore,+ } = usePaginatedSelect({ fetchPage });// Fetch the first page on mount, and re-fetch only when// `excludeDefault` actually flips (rare — typically once after- // permissions hydrate). `fetchProjects` is stable so this effect+ // permissions hydrate). `search` is stable so this effect// never re-fires from parent re-renders alone.useEffect(() => {- fetchProjects("");- }, [excludeDefault, fetchProjects]);+ search("");+ }, [excludeDefault, search]);// Hydrate the selected project so the trigger always renders its// label, even before the paged list loads or when the project is@@ -123,7 +132,10 @@ export function ProjectSelect({placeholder={placeholder ?? t("common.project")}noResultsText={t("common.no-data")}noResultsContent={emptyContent}- onSearch={fetchProjects}+ onSearch={search}+ hasMore={hasMore}+ loadingMore={loadingMore}+ onLoadMore={loadMore}disabled={disabled}className={className}portal={portal}diff --git a/frontend/src/components/RoleSelect.tsx b/frontend/src/components/RoleSelect.tsxindex 3400d770c4..f7a0849b3b 100644--- a/frontend/src/components/RoleSelect.tsx+++ b/frontend/src/components/RoleSelect.tsx@@ -1,6 +1,7 @@import { useMemo } from "react";import { useTranslation } from "react-i18next";import { FeatureBadge } from "@/components/FeatureBadge";+import { HighlightLabelText } from "@/components/HighlightLabelText";import { Combobox, type ComboboxGroup } from "@/components/ui/combobox";import {displayRoleDescriptionFromList,@@ -73,9 +74,12 @@ export function RoleSelect({label: displayRoleTitleFromList(r.name, roleList),description: displayRoleDescriptionFromList(r.name, roleList),disabled: !hasCustomRoleFeature,- render: () => (+ render: (keyword: string) => (<div className="flex items-center gap-x-1">- <span>{displayRoleTitleFromList(r.name, roleList)}</span>+ <HighlightLabelText+ text={displayRoleTitleFromList(r.name, roleList)}+ keyword={keyword}+ />{isCustomRole(r.name) && !hasCustomRoleFeature && (<FeatureBadgefeature={PlanFeature.FEATURE_CUSTOM_ROLES}diff --git a/frontend/src/components/UserSelect.tsx b/frontend/src/components/UserSelect.tsxindex 825ba8036c..9af134c007 100644--- a/frontend/src/components/UserSelect.tsx+++ b/frontend/src/components/UserSelect.tsx@@ -1,5 +1,6 @@-import { useCallback, useEffect, useMemo, useRef, useState } from "react";+import { useCallback, useEffect, useMemo, useState } from "react";import { Combobox, type ComboboxOption } from "@/components/ui/combobox";+import { usePaginatedSelect } from "@/components/usePaginatedSelect";import { useAppStore } from "@/stores/app";import { userNamePrefix } from "@/stores/modules/v1/common";import { ALL_USERS_USER_EMAIL } from "@/types";@@ -38,12 +39,8 @@ export function UserSelect({const getOrFetchUserByIdentifier = useAppStore((state) => state.getOrFetchUserByIdentifier);- const [users, setUsers] = useState<User[]>([]);const [selectedUser, setSelectedUser] = useState<User | undefined>(undefined);const [search, setSearch] = useState("");- // Track the latest in-flight request to ignore stale responses when the- // user types quickly (a slow A can arrive after a fast B).- const searchSeqRef = useRef(0);// Hydrate the selected user so its label renders even when it isn't in// the current search results.@@ -61,19 +58,34 @@ export function UserSelect({};}, [value, getOrFetchUserByIdentifier]);- const handleSearch = useCallback(- (query: string) => {- setSearch(query);- const seq = ++searchSeqRef.current;- listUsers({+ const fetchPage = useCallback(+ async (query: string, pageToken: string) => {+ const response = await listUsers({pageSize: getDefaultPagination(),- filter: { query: query.trim() },- }).then(({ users: fetched }) => {- if (seq === searchSeqRef.current) setUsers(fetched);+ pageToken,+ filter: { query },});+ return {+ items: response.users,+ nextPageToken: response.nextPageToken,+ };},[listUsers]);+ const {+ items: users,+ search: searchUsers,+ hasMore,+ loadingMore,+ loadMore,+ } = usePaginatedSelect({ fetchPage });+ const handleSearch = useCallback(+ (query: string) => {+ setSearch(query);+ void searchUsers(query.trim());+ },+ [searchUsers]+ );const options: ComboboxOption[] = useMemo(() => {const list: ComboboxOption[] = [];@@ -113,6 +125,9 @@ export function UserSelect({onChange={onChange}options={options}onSearch={handleSearch}+ hasMore={hasMore}+ loadingMore={loadingMore}+ onLoadMore={loadMore}placeholder={placeholder}disabled={disabled}className={className}diff --git a/frontend/src/components/WorkloadIdentitySelect.test.tsx b/frontend/src/components/WorkloadIdentitySelect.test.tsxnew file mode 100644index 0000000000..106e9bad9d--- /dev/null+++ b/frontend/src/components/WorkloadIdentitySelect.test.tsx@@ -0,0 +1,259 @@+import { act, type ReactElement } from "react";+import { createRoot } from "react-dom/client";+import { afterEach, beforeEach, describe, expect, test, vi } from "vitest";+import type { WorkloadIdentity } from "@/types/proto-es/v1/workload_identity_service_pb";++(+ globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }+).IS_REACT_ACT_ENVIRONMENT = true;++type ComboProps = {+ value: string;+ onChange: (value: string) => void;+ className?: string;+ onSearch?: (query: string) => void | Promise<void>;+ hasMore?: boolean;+ loadingMore?: boolean;+ onLoadMore?: () => void | Promise<void>;+ options: { value: string; label: string; description?: string }[];+};++const combo: { props?: ComboProps } = {};++const mocks = vi.hoisted(() => ({+ listWorkloadIdentities: vi.fn(),+ getWorkloadIdentity: vi.fn(),+}));++vi.mock("react-i18next", () => ({+ useTranslation: () => ({ t: (key: string) => key }),+}));++vi.mock("@/stores/app", () => {+ const state = () => ({+ listWorkloadIdentities: mocks.listWorkloadIdentities,+ getWorkloadIdentity: mocks.getWorkloadIdentity,+ });+ return {+ useAppStore: Object.assign(+ (selector: (s: ReturnType<typeof state>) => unknown) => selector(state()),+ { getState: state }+ ),+ };+});++vi.mock("@/components/ui/combobox", () => ({+ Combobox: (props: ComboProps) => {+ combo.props = props;+ return null;+ },+}));++vi.mock("@/utils", () => ({+ getDefaultPagination: () => 50,+}));++let WorkloadIdentitySelect: typeof import("./WorkloadIdentitySelect").WorkloadIdentitySelect;++const workloadIdentity = (+ name: string,+ title: string,+ email = `${title.toLowerCase()}@example.com`+): WorkloadIdentity => ({ name, title, email }) as WorkloadIdentity;++const render = (element: ReactElement) => {+ const container = document.createElement("div");+ const root = createRoot(container);+ document.body.appendChild(container);+ act(() => root.render(element));+ return {+ container,+ unmount: () => {+ act(() => root.unmount());+ container.remove();+ },+ };+};++const flush = async () => {+ await act(async () => {+ await Promise.resolve();+ await Promise.resolve();+ });+};++beforeEach(async () => {+ vi.clearAllMocks();+ combo.props = undefined;+ mocks.listWorkloadIdentities.mockResolvedValue({+ workloadIdentities: [],+ nextPageToken: "",+ });+ mocks.getWorkloadIdentity.mockImplementation((name: string) =>+ workloadIdentity(name, name)+ );+ ({ WorkloadIdentitySelect } = await import("./WorkloadIdentitySelect"));+});++afterEach(() => {+ document.body.innerHTML = "";+});++describe("WorkloadIdentitySelect", () => {+ test("fills the available width while preserving the caller width cap", async () => {+ const { unmount } = render(+ <WorkloadIdentitySelect+ projectName="projects/p"+ value=""+ onChange={() => {}}+ className="max-w-lg"+ />+ );+ await flush();++ expect(combo.props?.className).toContain("w-full");+ expect(combo.props?.className).toContain("max-w-lg");+ unmount();+ });++ test("fetches only the first page on mount", async () => {+ mocks.listWorkloadIdentities.mockResolvedValue({+ workloadIdentities: [workloadIdentity("workloadIdentities/one", "One")],+ nextPageToken: "page-2",+ });++ const { unmount } = render(+ <WorkloadIdentitySelect+ projectName="projects/p"+ value=""+ onChange={() => {}}+ />+ );+ await flush();++ expect(mocks.listWorkloadIdentities).toHaveBeenCalledTimes(1);+ expect(mocks.listWorkloadIdentities).toHaveBeenCalledWith({+ parent: "projects/p",+ filter: { query: "" },+ pageSize: 50,+ pageToken: "",+ showDeleted: false,+ });+ expect(combo.props?.options).toEqual([+ expect.objectContaining({+ value: "workloadIdentities/one",+ label: "One",+ }),+ ]);+ expect(combo.props?.hasMore).toBe(true);+ unmount();+ });++ test("loads and appends the next page", async () => {+ mocks.listWorkloadIdentities+ .mockResolvedValueOnce({+ workloadIdentities: [+ workloadIdentity("workloadIdentities/one", "One"),+ ],+ nextPageToken: "page-2",+ })+ .mockResolvedValueOnce({+ workloadIdentities: [+ workloadIdentity("workloadIdentities/two", "Two"),+ ],+ nextPageToken: "",+ });++ const { unmount } = render(+ <WorkloadIdentitySelect+ projectName="projects/p"+ value=""+ onChange={() => {}}+ />+ );+ await flush();++ await act(async () => {+ await combo.props?.onLoadMore?.();+ });++ expect(mocks.listWorkloadIdentities).toHaveBeenLastCalledWith(+ expect.objectContaining({+ filter: { query: "" },+ pageToken: "page-2",+ })+ );+ expect(combo.props?.options.map((option) => option.value)).toEqual([+ "workloadIdentities/one",+ "workloadIdentities/two",+ ]);+ expect(combo.props?.hasMore).toBe(false);+ unmount();+ });++ test("starts a new paginated request for backend search", async () => {+ mocks.listWorkloadIdentities+ .mockResolvedValueOnce({+ workloadIdentities: [+ workloadIdentity("workloadIdentities/one", "One"),+ ],+ nextPageToken: "page-2",+ })+ .mockResolvedValueOnce({+ workloadIdentities: [+ workloadIdentity("workloadIdentities/search", "Search result"),+ ],+ nextPageToken: "search-page-2",+ });++ const { unmount } = render(+ <WorkloadIdentitySelect+ projectName="projects/p"+ value=""+ onChange={() => {}}+ />+ );+ await flush();++ await act(async () => {+ await combo.props?.onSearch?.("search");+ });++ expect(mocks.listWorkloadIdentities).toHaveBeenLastCalledWith(+ expect.objectContaining({+ filter: { query: "search" },+ pageToken: "",+ })+ );+ expect(combo.props?.options.map((option) => option.value)).toEqual([+ "workloadIdentities/search",+ ]);+ expect(combo.props?.hasMore).toBe(true);+ unmount();+ });++ test("keeps the selected identity available when it is not on the page", async () => {+ const selected = workloadIdentity(+ "workloadIdentities/selected",+ "Selected identity"+ );+ mocks.getWorkloadIdentity.mockReturnValue(selected);++ const { unmount } = render(+ <WorkloadIdentitySelect+ projectName="projects/p"+ value={selected.name}+ onChange={() => {}}+ />+ );+ await flush();++ expect(combo.props?.options).toContainEqual(+ expect.objectContaining({+ value: selected.name,+ label: selected.title,+ })+ );+ unmount();+ });+});diff --git a/frontend/src/components/WorkloadIdentitySelect.tsx b/frontend/src/components/WorkloadIdentitySelect.tsxnew file mode 100644index 0000000000..f6f805e088--- /dev/null+++ b/frontend/src/components/WorkloadIdentitySelect.tsx@@ -0,0 +1,105 @@+import { useCallback, useEffect, useMemo } from "react";+import { useTranslation } from "react-i18next";+import { Combobox, type ComboboxOption } from "@/components/ui/combobox";+import { usePaginatedSelect } from "@/components/usePaginatedSelect";+import { cn } from "@/lib/utils";+import { useAppStore } from "@/stores/app";+import type { WorkloadIdentity } from "@/types/proto-es/v1/workload_identity_service_pb";+import { getDefaultPagination } from "@/utils";++interface WorkloadIdentitySelectProps {+ projectName: string;+ value: string;+ onChange: (+ value: string,+ workloadIdentity: WorkloadIdentity | undefined+ ) => void;+ placeholder?: string;+ disabled?: boolean;+ className?: string;+ portal?: boolean;+}++export function WorkloadIdentitySelect({+ projectName,+ value,+ onChange,+ placeholder,+ disabled,+ className,+ portal,+}: WorkloadIdentitySelectProps) {+ const { t } = useTranslation();+ const listWorkloadIdentities = useAppStore(+ (state) => state.listWorkloadIdentities+ );+ const getWorkloadIdentity = useAppStore((state) => state.getWorkloadIdentity);+ const selectedWorkloadIdentity = useAppStore((state) =>+ value ? state.getWorkloadIdentity(value) : undefined+ );++ const listPage = useCallback(+ async (query: string, pageToken: string) => {+ const response = await listWorkloadIdentities({+ parent: projectName,+ filter: { query },+ pageSize: getDefaultPagination(),+ pageToken,+ showDeleted: false,+ });+ return {+ items: response.workloadIdentities,+ nextPageToken: response.nextPageToken,+ };+ },+ [listWorkloadIdentities, projectName]+ );+ const {+ items: workloadIdentities,+ search,+ hasMore,+ loadingMore,+ loadMore,+ } = usePaginatedSelect({ fetchPage: listPage });++ useEffect(() => {+ search("");+ }, [search]);++ const options = useMemo(() => {+ const toOption = (identity: WorkloadIdentity): ComboboxOption => ({+ value: identity.name,+ label: identity.title || identity.email,+ description: identity.email,+ });+ const options = workloadIdentities.map(toOption);+ if (+ selectedWorkloadIdentity &&+ !workloadIdentities.some(+ (identity) => identity.name === selectedWorkloadIdentity.name+ )+ ) {+ options.push(toOption(selectedWorkloadIdentity));+ }+ return options;+ }, [selectedWorkloadIdentity, workloadIdentities]);++ return (+ <Combobox+ value={value}+ options={options}+ placeholder={placeholder}+ noResultsText={t("common.no-data")}+ onChange={(name) =>+ onChange(name, name ? getWorkloadIdentity(name) : undefined)+ }+ onSearch={search}+ hasMore={hasMore}+ loadingMore={loadingMore}+ onLoadMore={loadMore}+ disabled={disabled}+ className={cn("w-full", className)}+ portal={portal}+ />+ );+}diff --git a/frontend/src/components/database/CreateDatabaseSheet.tsx b/frontend/src/components/database/CreateDatabaseSheet.tsxindex 6172718ef3..80641cb30c 100644--- a/frontend/src/components/database/CreateDatabaseSheet.tsx+++ b/frontend/src/components/database/CreateDatabaseSheet.tsx@@ -635,7 +635,12 @@ function CreateDatabaseForm({options={environments.map((env) => ({value: env.name,label: env.title,- render: () => <EnvironmentLabel environmentName={env.name} />,+ render: (keyword) => (+ <EnvironmentLabel+ environmentName={env.name}+ keyword={keyword}+ />+ ),}))}portal/>diff --git a/frontend/src/components/ui/combobox.test.tsx b/frontend/src/components/ui/combobox.test.tsxindex 1e7de6c936..06fc5023d2 100644--- a/frontend/src/components/ui/combobox.test.tsx+++ b/frontend/src/components/ui/combobox.test.tsx@@ -1,6 +1,6 @@import { act } from "react";import { createRoot } from "react-dom/client";-import { afterEach, describe, expect, test } from "vitest";+import { afterEach, describe, expect, test, vi } from "vitest";import { Combobox } from "./combobox";import { Dialog, DialogContent } from "./dialog";import { LAYER_BACKDROP_CLASS, LAYER_SURFACE_CLASS } from "./layer";@@ -78,4 +78,85 @@ describe("Combobox", () => {root.unmount();});});++ test("renders and invokes the load-more action", () => {+ const container = document.createElement("div");+ document.body.appendChild(container);+ const root = createRoot(container);+ const onLoadMore = vi.fn();++ act(() => {+ root.render(+ <Combobox+ value=""+ onChange={() => {}}+ options={[{ value: "alpha", label: "Alpha" }]}+ hasMore+ onLoadMore={onLoadMore}+ />+ );+ });++ act(() => {+ container.firstElementChild?.firstElementChild+ ?.dispatchEvent(new MouseEvent("click", { bubbles: true }));+ });++ expect(container.textContent).toContain("Load more");++ const loadMoreButton = Array.from(container.querySelectorAll("button")).find(+ (button) => button.textContent === "Load more"+ );+ act(() => loadMoreButton?.click());+ expect(onLoadMore).toHaveBeenCalledOnce();++ act(() => {+ root.unmount();+ });+ });++ test("passes the search query to custom option renderers", () => {+ const container = document.createElement("div");+ document.body.appendChild(container);+ const root = createRoot(container);++ act(() => {+ root.render(+ <Combobox+ value=""+ onChange={() => {}}+ options={[+ {+ value: "bytebase",+ label: "bytebase",+ render: (keyword) => (+ <span data-testid="custom-option">{keyword}</span>+ ),+ },+ ]}+ />+ );+ });++ act(() => {+ container.firstElementChild?.firstElementChild+ ?.dispatchEvent(new MouseEvent("click", { bubbles: true }));+ });+ const input = container.querySelector("input");+ act(() => {+ if (!input) return;+ const valueSetter = Object.getOwnPropertyDescriptor(+ HTMLInputElement.prototype,+ "value"+ )?.set;+ valueSetter?.call(input, "byte");+ input.dispatchEvent(new Event("input", { bubbles: true }));+ });++ expect(+ container.querySelector('[data-testid="custom-option"]')?.textContent+ ).toBe("byte");++ act(() => root.unmount());+ });});diff --git a/frontend/src/components/ui/combobox.tsx b/frontend/src/components/ui/combobox.tsxindex 5c2f885a50..d69a4e3e91 100644--- a/frontend/src/components/ui/combobox.tsx+++ b/frontend/src/components/ui/combobox.tsx@@ -9,8 +9,10 @@ import {useState,} from "react";import { createPortal } from "react-dom";+import { useTranslation } from "react-i18next";import { cn } from "@/lib/utils";import { HighlightLabelText } from "../HighlightLabelText";+import { Button } from "./button";import {getPortalDropdownStyle,isPortalDropdownStyleEqual,@@ -32,7 +34,7 @@ export interface ComboboxOption {/** Secondary text shown below the label */description?: string;/** Custom render for the option row */- render?: () => React.ReactNode;+ render?: (keyword: string) => React.ReactNode;/** Whether this option is disabled (shown but not selectable) */disabled?: boolean;}@@ -69,7 +71,11 @@ type ComboboxBaseProps = {* the empty state needs links or conditional copy beyond a flat string. */noResultsContent?: React.ReactNode;/** Server-side search callback. When provided, filters via this instead of client-side. */- onSearch?: (query: string) => void;+ onSearch?: (query: string) => void | Promise<void>;+ /** Whether another page of server-side options is available. */+ hasMore?: boolean;+ loadingMore?: boolean;+ onLoadMore?: () => void | Promise<void>;className?: string;disabled?: boolean;clearable?: boolean;@@ -105,12 +111,16 @@ export function Combobox(props: ComboboxProps) {noResultsText,noResultsContent,onSearch,+ hasMore,+ loadingMore,+ onLoadMore,className,disabled,clearable = true,size = "md",portal,} = props;+ const { t } = useTranslation();const multiple = props.multiple === true;const [open, setOpen] = useState(false);@@ -356,7 +366,7 @@ export function Combobox(props: ComboboxProps) {)}<div className="flex flex-col min-w-0 flex-1">{option.render ? (- option.render()+ option.render(search)) : (<><HighlightLabelText@@ -425,6 +435,18 @@ export function Combobox(props: ComboboxProps) {</div>)))}+ {hasMore && onLoadMore && (+ <Button+ type="button"+ appearance="secondary"+ size="sm"+ className="w-full mt-1"+ disabled={loadingMore}+ onClick={onLoadMore}+ >+ {loadingMore ? t("common.loading") : t("common.load-more")}+ </Button>+ )}</div></div>);diff --git a/frontend/src/components/usePaginatedSelect.test.tsx b/frontend/src/components/usePaginatedSelect.test.tsxnew file mode 100644index 0000000000..215cdefd92--- /dev/null+++ b/frontend/src/components/usePaginatedSelect.test.tsx@@ -0,0 +1,71 @@+import { act, renderHook } from "@testing-library/react";+import { describe, expect, test, vi } from "vitest";+import { usePaginatedSelect } from "./usePaginatedSelect";++describe("usePaginatedSelect", () => {+ test("resets on search and appends the next page", async () => {+ const fetchPage = vi+ .fn()+ .mockResolvedValueOnce({+ items: [{ name: "one" }],+ nextPageToken: "page-2",+ })+ .mockResolvedValueOnce({+ items: [{ name: "two" }],+ nextPageToken: "",+ })+ .mockResolvedValueOnce({+ items: [{ name: "search" }],+ nextPageToken: "search-page-2",+ });+ const { result } = renderHook(() => usePaginatedSelect({ fetchPage }));++ await act(() => result.current.search(""));+ expect(result.current.items.map((item) => item.name)).toEqual(["one"]);+ expect(result.current.hasMore).toBe(true);++ await act(() => result.current.loadMore());+ expect(fetchPage).toHaveBeenLastCalledWith("", "page-2");+ expect(result.current.items.map((item) => item.name)).toEqual([+ "one",+ "two",+ ]);++ await act(() => result.current.search("search"));+ expect(fetchPage).toHaveBeenLastCalledWith("search", "");+ expect(result.current.items.map((item) => item.name)).toEqual(["search"]);+ expect(result.current.hasMore).toBe(true);+ });++ test("ignores stale first-page responses", async () => {+ let resolveOld: (value: {+ items: { name: string }[];+ nextPageToken: string;+ }) => void = () => {};+ const fetchPage = vi+ .fn()+ .mockImplementationOnce(+ () =>+ new Promise((resolve) => {+ resolveOld = resolve;+ })+ )+ .mockResolvedValueOnce({+ items: [{ name: "new" }],+ nextPageToken: "",+ });+ const { result } = renderHook(() => usePaginatedSelect({ fetchPage }));++ let oldRequest: Promise<void>;+ act(() => {+ oldRequest = result.current.search("old");+ });+ await act(() => result.current.search("new"));+ await act(async () => {+ resolveOld({ items: [{ name: "old" }], nextPageToken: "" });+ await oldRequest;+ });++ expect(result.current.items.map((item) => item.name)).toEqual(["new"]);+ });+});diff --git a/frontend/src/components/usePaginatedSelect.ts b/frontend/src/components/usePaginatedSelect.tsnew file mode 100644index 0000000000..ac7ae30f2f--- /dev/null+++ b/frontend/src/components/usePaginatedSelect.ts@@ -0,0 +1,70 @@+import { useCallback, useRef, useState } from "react";++interface Page<T> {+ items: T[];+ nextPageToken?: string;+}++interface UsePaginatedSelectOptions<T> {+ fetchPage: (query: string, pageToken: string) => Promise<Page<T>>;+}++export function usePaginatedSelect<T extends { name: string }>({+ fetchPage,+}: UsePaginatedSelectOptions<T>) {+ const [items, setItems] = useState<T[]>([]);+ const [nextPageToken, setNextPageToken] = useState("");+ const [loadingMore, setLoadingMore] = useState(false);+ const queryRef = useRef("");+ const requestGenerationRef = useRef(0);++ const search = useCallback(+ async (query: string) => {+ const generation = ++requestGenerationRef.current;+ queryRef.current = query;+ setNextPageToken("");+ setLoadingMore(false);+ try {+ const response = await fetchPage(query, "");+ if (generation !== requestGenerationRef.current) return;+ setItems(response.items);+ setNextPageToken(response.nextPageToken ?? "");+ } catch {+ // Keep the current options when a search request fails.+ }+ },+ [fetchPage]+ );++ const loadMore = useCallback(async () => {+ if (!nextPageToken || loadingMore) return;+ const generation = requestGenerationRef.current;+ setLoadingMore(true);+ try {+ const response = await fetchPage(queryRef.current, nextPageToken);+ if (generation !== requestGenerationRef.current) return;+ setItems((previous) => {+ const names = new Set(previous.map((item) => item.name));+ return [+ ...previous,+ ...response.items.filter((item) => !names.has(item.name)),+ ];+ });+ setNextPageToken(response.nextPageToken ?? "");+ } catch {+ // Keep the current page and token so the request can be retried.+ } finally {+ if (generation === requestGenerationRef.current) {+ setLoadingMore(false);+ }+ }+ }, [fetchPage, loadingMore, nextPageToken]);++ return {+ items,+ search,+ hasMore: Boolean(nextPageToken),+ loadingMore,+ loadMore,+ };+}diff --git a/frontend/src/modules/sql-editor/components/ConnectChooser.test.tsx b/frontend/src/modules/sql-editor/components/ConnectChooser.test.tsxindex eea054caf0..e2cae43046 100644--- a/frontend/src/modules/sql-editor/components/ConnectChooser.test.tsx+++ b/frontend/src/modules/sql-editor/components/ConnectChooser.test.tsx@@ -38,6 +38,16 @@ vi.mock("@/components/ui/search-input", () => ({}) => <input data-testid="search" value={value} onChange={onChange} />,}));+vi.mock("@/components/HighlightLabelText", () => ({+ HighlightLabelText: ({+ keyword,+ text,+ }: {+ keyword?: string;+ text: string;+ }) => <b data-keyword={keyword}>{text}</b>,+}));+let ConnectChooser: typeof import("./ConnectChooser").ConnectChooser;const renderIntoContainer = (element: ReactElement) => {@@ -235,6 +245,38 @@ describe("ConnectChooser", () => {unmount();});+ test("highlights matching option text", () => {+ const { container, render, unmount } = renderIntoContainer(+ <ConnectChooser+ value=""+ onChange={vi.fn()}+ options={defaultOptions}+ isChosen={false}+ placeholder="Select schema"+ />+ );+ render();+ act(() => container.querySelector("button")?.click());++ const input = document.body.querySelector(+ '[data-testid="search"]'+ ) as HTMLInputElement;+ act(() => {+ const valueSetter = Object.getOwnPropertyDescriptor(+ HTMLInputElement.prototype,+ "value"+ )?.set;+ valueSetter?.call(input, "pub");+ input.dispatchEvent(new Event("input", { bubbles: true }));+ });++ const highlight = Array.from(document.body.querySelectorAll("b")).find(+ (element) => element.textContent === "public"+ );+ expect(highlight?.dataset.keyword).toBe("pub");+ unmount();+ });+test("opens the dropdown when the external open signal changes", () => {const container = document.createElement("div");const root = createRoot(container);diff --git a/frontend/src/modules/sql-editor/components/ConnectChooser.tsx b/frontend/src/modules/sql-editor/components/ConnectChooser.tsxindex 824fb243a3..2bc8034e97 100644--- a/frontend/src/modules/sql-editor/components/ConnectChooser.tsx+++ b/frontend/src/modules/sql-editor/components/ConnectChooser.tsx@@ -9,6 +9,7 @@ import {} from "react";import { createPortal } from "react-dom";import { useTranslation } from "react-i18next";+import { HighlightLabelText } from "@/components/HighlightLabelText";import { Button } from "@/components/ui/button";import type { ComboboxOption } from "@/components/ui/combobox";import {@@ -209,7 +210,7 @@ export function ConnectChooser({isSelected && "text-accent font-medium")}>- {option.label}+ <HighlightLabelText text={option.label} keyword={search} /></span>{isSelected && (<Check className="size-4 text-accent shrink-0" />diff --git a/frontend/src/routes/project/ProjectGitOpsPage.tsx b/frontend/src/routes/project/ProjectGitOpsPage.tsxindex 9f586415c2..0eb95be173 100644--- a/frontend/src/routes/project/ProjectGitOpsPage.tsx+++ b/frontend/src/routes/project/ProjectGitOpsPage.tsx@@ -1,8 +1,9 @@import { Check, ChevronDown, ChevronRight, XCircle } from "lucide-react";-import { useCallback, useEffect, useMemo, useState } from "react";+import { useEffect, useMemo, useState } from "react";import { useTranslation } from "react-i18next";import gitopsWorkflowImage from "@/assets/gitops-workflow.svg";import { CreateWorkloadIdentitySheet } from "@/components/CreateWorkloadIdentitySheet";+import { DatabaseSelect } from "@/components/DatabaseSelect";import { ExternalUrlAlert } from "@/components/ExternalUrlAlert";import { PermissionGuard } from "@/components/PermissionGuard";import { ProjectPageLayout } from "@/components/ProjectPageLayout";@@ -12,6 +13,7 @@ import { Combobox, type ComboboxOption } from "@/components/ui/combobox";import { CopyButton } from "@/components/ui/copy-button";import { Switch } from "@/components/ui/switch";import { Tabs, TabsList, TabsPanel, TabsTrigger } from "@/components/ui/tabs";+import { WorkloadIdentitySelect } from "@/components/WorkloadIdentitySelect";import { useProjectByName } from "@/hooks/useProjectByName";import { cn } from "@/lib/utils";import { useAppStore } from "@/stores/app";@@ -21,8 +23,6 @@ import { DatabaseGroupView } from "@/types/proto-es/v1/database_group_service_pbimport type { WorkloadIdentity } from "@/types/proto-es/v1/workload_identity_service_pb";import { WorkloadIdentityConfig_ProviderType } from "@/types/proto-es/v1/workload_identity_service_pb";import {- extractDatabaseResourceName,- getDefaultPagination,getWorkloadIdentityProviderText,hasProjectPermissionV2,parseWorkloadIdentitySubjectPattern,@@ -32,9 +32,6 @@ export function ProjectGitOpsPage({ projectId }: { projectId: string }) {const { t } = useTranslation();const serverInfo = useAppStore((s) => s.serverInfo);const projectsByName = useAppStore((s) => s.projectsByName);- const listWorkloadIdentities = useAppStore(- (state) => state.listWorkloadIdentities- );const fetchWorkloadIdentity = useAppStore((state) => state.fetchWorkloadIdentity);@@ -58,46 +55,12 @@ export function ProjectGitOpsPage({ projectId }: { projectId: string }) {const [showReleaseYaml, setShowReleaseYaml] = useState(true);const [showGitlabCiYaml, setShowGitlabCiYaml] = useState(true);- // Workload identity options- const [wiOptions, setWiOptions] = useState<ComboboxOption[]>([]);- const [wiSearch, setWiSearch] = useState("");const selectedIdentity = useAppStore((state) =>selectedIdentityName? state.getWorkloadIdentity(selectedIdentityName): undefined);- const fetchWorkloadIdentities = useCallback(- async (search: string) => {- const all: ComboboxOption[] = [];- let pageToken: string | undefined;- // Fetch all pages so every identity is discoverable.- do {- const resp = await listWorkloadIdentities({- parent: projectName,- filter: { query: search },- pageToken,- pageSize: getDefaultPagination(),- showDeleted: false,- });- for (const wi of resp.workloadIdentities) {- all.push({- value: wi.name,- label: wi.title || wi.email,- description: wi.email,- });- }- pageToken = resp.nextPageToken || undefined;- } while (pageToken);- setWiOptions(all);- },- [projectName, listWorkloadIdentities]- );-- useEffect(() => {- fetchWorkloadIdentities(wiSearch).catch(() => {});- }, [wiSearch, fetchWorkloadIdentities]);-// Database group optionsconst [dbGroupOptions, setDbGroupOptions] = useState<ComboboxOption[]>([]);useEffect(() => {@@ -115,34 +78,6 @@ export function ProjectGitOpsPage({ projectId }: { projectId: string }) {.catch(() => {});}, [projectName]);- // Database options for individual selection- const [dbOptions, setDbOptions] = useState<ComboboxOption[]>([]);- const [dbSearch, setDbSearch] = useState("");- useEffect(() => {- const fetchAllDatabases = async () => {- const all: ComboboxOption[] = [];- let pageToken: string | undefined;- do {- const resp = await useAppStore.getState().fetchDatabases({- parent: projectName,- filter: dbSearch ? { query: dbSearch } : {},- pageSize: getDefaultPagination(),- pageToken,- });- for (const db of resp.databases) {- all.push({- value: db.name,- label: extractDatabaseResourceName(db.name).databaseName,- description: db.name,- });- }- pageToken = resp.nextPageToken || undefined;- } while (pageToken);- setDbOptions(all);- };- fetchAllDatabases().catch(() => {});- }, [projectName, dbSearch]);-// Fetch the selected identity into the store cache so getWorkloadIdentity// returns the real object (with workloadIdentityConfig) instead of a stub.useEffect(() => {@@ -227,7 +162,6 @@ export function ProjectGitOpsPage({ projectId }: { projectId: string }) {const handleWorkloadIdentityCreated = (wi: WorkloadIdentity) => {setSelectedIdentityName(wi.name);- fetchWorkloadIdentities("");};const canCreateWorkloadIdentity = project@@ -380,12 +314,11 @@ export function ProjectGitOpsPage({ projectId }: { projectId: string }) {{t("gitops.checklist.workload-identity")}</span><div className="flex items-center gap-x-3">- <Combobox+ <WorkloadIdentitySelect+ projectName={projectName}value={selectedIdentityName}- options={wiOptions}placeholder={t("gitops.workload-identity.select-placeholder")}- onChange={setSelectedIdentityName}- onSearch={setWiSearch}+ onChange={(name) => setSelectedIdentityName(name)}className="max-w-lg"/><PermissionGuard@@ -453,11 +386,11 @@ export function ProjectGitOpsPage({ projectId }: { projectId: string }) {</p></>) : (- <MultiDatabaseSelect+ <DatabaseSelect+ multiplevalue={selectedDatabaseNames}- options={dbOptions}- onChange={setSelectedDatabaseNames}- onSearch={setDbSearch}+ onChange={(names) => setSelectedDatabaseNames(names)}+ projectName={projectName}/>)}</div>@@ -724,59 +657,6 @@ function StepItem({);}-function MultiDatabaseSelect({- value,- options,- onChange,- onSearch,-}: {- value: string[];- options: ComboboxOption[];- onChange: (value: string[]) => void;- onSearch: (query: string) => void;-}) {- const { t } = useTranslation();-- const handleToggle = (dbName: string) => {- if (value.includes(dbName)) {- onChange(value.filter((n) => n !== dbName));- } else {- onChange([...value, dbName]);- }- };-- return (- <div className="flex flex-col gap-y-2">- <Combobox- value=""- options={options.filter((o) => !value.includes(o.value))}- placeholder={t("database.select")}- onChange={handleToggle}- onSearch={onSearch}- />- {value.length > 0 && (- <div className="flex flex-wrap gap-1">- {value.map((name) => (- <span- key={name}- className="inline-flex items-center gap-x-1 px-2 py-0.5 text-xs bg-gray-100 rounded-xs"- >- {extractDatabaseResourceName(name).databaseName}- <button- type="button"- className="hover:text-error"- onClick={() => onChange(value.filter((n) => n !== name))}- >- <XCircle className="w-3 h-3" />- </button>- </span>- ))}- </div>- )}- </div>- );-}-// --- YAML generators ---const SAMPLE_FILE_PATH = "migrations/20240101000000_create_sample_table.sql";