Skip to content

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

chore: some optimize and fix for instance form (#21445)

ecmadao2e340b4de0f3
diff --git a/docs/agents/frontend-ux.md b/docs/agents/frontend-ux.md
index 2581d8000f..1e8a355aa4 100644
--- a/docs/agents/frontend-ux.md
+++ b/docs/agents/frontend-ux.md
@@ -205,8 +205,11 @@ third column for section titles.
- Stack labels based on available form width, independently of the navigation
sidebar breakpoint. Compound controls MAY wrap within the control column
before the field itself stacks.
-- Keep descriptions and validation beside the control they explain. Associate
- labels and radio groups with accessible names in both layouts.
+- Keep concise descriptions and validation beside the control they explain.
+ Long secondary guidance that would make a dense form harder to scan MAY use
+ a focusable info tooltip beside the field title; validation and essential
+ status remain visible beside the control. Associate labels and radio groups
+ with accessible names in both layouts.
- Put choices that determine subsequent fields first. Use one `Select` dropdown
combining authentication methods and password sources. Do not add a separate
password-source selector. Keep synchronization choices visible in a
@@ -217,9 +220,9 @@ third column for section titles.
TLS, SSH, IAM, and external-source configuration below its controlling
choice, using nested flow rather than a framed surface inside another frame.
- Keep security modes visible; reveal their dependent fields when selected.
- Switches and segmented controls align to the start of their control column.
- Keep ordinary connection rows on the 16px rhythm. Use explicit choices for
- modes such as syncing all or selected databases.
+ Switches, segmented controls, and radio groups align to the start of their
+ control column. Keep ordinary connection rows on the 16px rhythm. Use
+ explicit choices for modes such as syncing all or selected databases.
- Empty optional collections MAY start as an add action. Existing entries and
validation errors MUST remain discoverable.
- A connection-creation footer MAY place Test Connection beside Create, with
diff --git a/frontend/src/components/instance/InstanceFormBody.test.tsx b/frontend/src/components/instance/InstanceFormBody.test.tsx
index f6a768e77e..0c49d2bf4f 100644
--- a/frontend/src/components/instance/InstanceFormBody.test.tsx
+++ b/frontend/src/components/instance/InstanceFormBody.test.tsx
@@ -1,5 +1,12 @@
import { create } from "@bufbuild/protobuf";
-import { cleanup, fireEvent, render, screen } from "@testing-library/react";
+import {
+ act,
+ cleanup,
+ fireEvent,
+ render,
+ screen,
+ waitFor,
+} from "@testing-library/react";
import { afterEach, expect, test, vi } from "vitest";
import { Engine, State } from "@/types/proto-es/v1/common_pb";
import {
@@ -7,6 +14,7 @@ import {
DataSource_RedisType,
DataSourceType,
InstanceSchema,
+ SyncDatabasesSchema,
} from "@/types/proto-es/v1/instance_service_pb";
import type { EditDataSource } from "./common";
import {
@@ -29,11 +37,13 @@ const mocks = vi.hoisted(() => ({
vi.mock("@/components/EngineIcon", () => ({ EngineIcon: () => null }));
vi.mock("@/components/EnvironmentSelect", () => ({
- EnvironmentSelect: () => null,
+ EnvironmentSelect: ({ className }: { className?: string }) => (
+ <div data-testid="environment-select" className={className} />
+ ),
}));
vi.mock("@/components/FeatureBadge", () => ({ FeatureBadge: () => null }));
vi.mock("@/components/LabelListEditor", () => ({
- LabelListEditor: () => null,
+ LabelListEditor: () => <div data-testid="label-list-editor" />,
}));
vi.mock("@/components/LearnMoreLink", () => ({ LearnMoreLink: () => null }));
vi.mock("@/components/ResourceIdField", () => ({
@@ -157,6 +167,7 @@ vi.mock("@/utils", () => ({
hasWorkspacePermissionV2: () => true,
isValidEnvironmentName: () => false,
engineNameV1: () => "Engine",
+ supportedEngineV1List: () => [],
extractInstanceResourceName: () => "prod",
onlyAllowNumber: (value: string) => /^\d+$/.test(value),
RE_GCP_PROJECT_ID: /^[a-z-]+$/,
@@ -205,7 +216,7 @@ vi.mock("@/components/ui/feature-modal", () => ({
globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }
).IS_REACT_ACT_ENVIRONMENT = true;
-import { InstanceFormBody } from "./InstanceFormBody";
+import { InstanceFormBody, SyncDatabases } from "./InstanceFormBody";
let context: ReturnType<typeof useInstanceFormContext>;
function Editor() {
@@ -254,6 +265,251 @@ afterEach(cleanup);
const input = (container: HTMLElement, id: string) =>
container.querySelector<HTMLInputElement>(`#${id}`)!;
+test("uses a compact segmented synchronization selector", () => {
+ const { container } = render(
+ <InstanceFormProvider>
+ <SyncDatabases
+ isCreating
+ showLabel
+ allowEdit
+ onSyncDatabasesChange={() => undefined}
+ />
+ </InstanceFormProvider>
+ );
+
+ const group = container.querySelector('[role="radiogroup"]');
+ expect(group?.classList.contains("inline-flex")).toBe(true);
+ expect(group?.classList.contains("rounded-xs")).toBe(true);
+ expect(group?.classList.contains("flex-col")).toBe(false);
+ expect(group?.querySelectorAll('[role="radio"]')).toHaveLength(2);
+});
+
+test("keeps newly loaded selections in the database preview", async () => {
+ mocks.listInstanceDatabases.mockResolvedValue({ databases: ["analytics"] });
+ const instance = create(InstanceSchema, {
+ name: "instances/production",
+ engine: Engine.POSTGRES,
+ });
+ const { rerender } = render(
+ <InstanceFormProvider instance={instance}>
+ <SyncDatabases
+ isCreating={false}
+ showLabel={false}
+ allowEdit
+ syncDatabases={create(SyncDatabasesSchema, {
+ databases: ["analytics"],
+ })}
+ onSyncDatabasesChange={() => undefined}
+ />
+ </InstanceFormProvider>
+ );
+
+ try {
+ await waitFor(() => {
+ expect(screen.getByText("analytics")).toBeInTheDocument();
+ });
+
+ rerender(
+ <InstanceFormProvider instance={instance}>
+ <SyncDatabases
+ isCreating={false}
+ showLabel={false}
+ allowEdit
+ syncDatabases={create(SyncDatabasesSchema, {
+ databases: ["app"],
+ })}
+ onSyncDatabasesChange={() => undefined}
+ />
+ </InstanceFormProvider>
+ );
+
+ await waitFor(() => {
+ expect(screen.getByText("app")).toBeInTheDocument();
+ });
+ expect(
+ screen
+ .getByText("app")
+ .closest("label")
+ ?.querySelector('[role="checkbox"]')
+ ).toHaveAttribute("data-checked");
+ } finally {
+ mocks.listInstanceDatabases.mockResolvedValue({
+ databases: ["app", "analytics"],
+ });
+ }
+});
+
+test("keeps selections added while the database preview request is pending", async () => {
+ const requestCount = mocks.listInstanceDatabases.mock.calls.length;
+ let resolvePreview:
+ | ((value: { databases: string[] }) => void)
+ | undefined;
+ mocks.listInstanceDatabases.mockImplementationOnce(
+ () =>
+ new Promise((resolve) => {
+ resolvePreview = resolve;
+ })
+ );
+ const instance = create(InstanceSchema, {
+ name: "instances/production",
+ engine: Engine.POSTGRES,
+ });
+ const { rerender } = render(
+ <InstanceFormProvider instance={instance}>
+ <SyncDatabases
+ isCreating={false}
+ showLabel={false}
+ allowEdit
+ syncDatabases={create(SyncDatabasesSchema, {
+ databases: ["analytics"],
+ })}
+ onSyncDatabasesChange={() => undefined}
+ />
+ </InstanceFormProvider>
+ );
+
+ try {
+ await waitFor(() => {
+ expect(mocks.listInstanceDatabases).toHaveBeenCalledTimes(requestCount + 1);
+ });
+
+ rerender(
+ <InstanceFormProvider instance={instance}>
+ <SyncDatabases
+ isCreating={false}
+ showLabel={false}
+ allowEdit
+ syncDatabases={create(SyncDatabasesSchema, {
+ databases: ["app"],
+ })}
+ onSyncDatabasesChange={() => undefined}
+ />
+ </InstanceFormProvider>
+ );
+
+ await act(async () => {
+ resolvePreview?.({ databases: ["analytics"] });
+ });
+ await waitFor(() => {
+ expect(screen.getByText("app")).toBeInTheDocument();
+ });
+ } finally {
+ mocks.listInstanceDatabases.mockResolvedValue({
+ databases: ["app", "analytics"],
+ });
+ }
+});
+
+test("keeps labels in their own form field", () => {
+ const { container } = render(
+ <InstanceFormProvider>
+ <InstanceFormBody />
+ </InstanceFormProvider>
+ );
+
+ const environmentField = Array.from(
+ container.querySelectorAll('[data-slot="form-field"]')
+ ).find((field) =>
+ field
+ .querySelector('[data-slot="form-field-title"]')
+ ?.textContent?.includes("common.environment")
+ );
+ const labelsField = Array.from(
+ container.querySelectorAll('[data-slot="form-field"]')
+ ).find((field) =>
+ field
+ .querySelector('[data-slot="form-field-title"]')
+ ?.textContent?.includes("common.labels")
+ );
+
+ expect(environmentField?.textContent).not.toContain("instance.add-labels");
+ expect(labelsField).toContainElement(
+ container.querySelector('[data-testid="label-list-editor"]')
+ );
+});
+
+test("uses the shared form width for basic info controls", () => {
+ const { container } = render(
+ <InstanceFormProvider>
+ <InstanceFormBody />
+ </InstanceFormProvider>
+ );
+
+ expect(container.querySelector("#name")).toHaveClass("w-full");
+ expect(container.querySelector("#name")).not.toHaveClass("max-w-[40rem]");
+ expect(
+ container.querySelector('[data-testid="environment-select"]')
+ ).toHaveClass("w-full");
+ expect(
+ container.querySelector('[data-testid="environment-select"]')
+ ).not.toHaveClass("max-w-[40rem]");
+});
+
+test("names the external link info button distinctly", async () => {
+ const { container } = render(
+ <InstanceFormProvider
+ instance={create(InstanceSchema, {
+ name: "instances/production",
+ engine: Engine.POSTGRES,
+ externalLink: "https://example.com",
+ })}
+ >
+ <InstanceFormBody />
+ </InstanceFormProvider>
+ );
+ vi.useFakeTimers();
+
+ try {
+ const externalLinkInput = container.querySelector("#external-link");
+ const field = externalLinkInput?.closest('[data-slot="form-field"]');
+ const infoButton = field?.querySelector<HTMLButtonElement>(
+ 'button[aria-label="instance.external-link common.info"]'
+ );
+ const openLinkButton = field?.querySelector<HTMLButtonElement>(
+ 'button[aria-label="instance.external-link"]'
+ );
+
+ expect(infoButton).toBeDefined();
+ expect(openLinkButton).toBeDefined();
+
+ fireEvent.focus(infoButton!);
+ await act(async () => {
+ vi.advanceTimersByTime(100);
+ });
+
+ expect(
+ document.getElementById("bb-react-layer-overlay")?.textContent
+ ).toContain("instance.sentence.console.snowflake");
+
+ const scanIntervalField = Array.from(
+ container.querySelectorAll('[data-slot="form-field"]')
+ ).find((candidate) =>
+ candidate
+ .querySelector('[data-slot="form-field-title"]')
+ ?.textContent?.includes("instance.scan-interval.self")
+ );
+ const scanIntervalInfoButton =
+ scanIntervalField?.querySelector<HTMLButtonElement>(
+ 'button[aria-label="instance.scan-interval.self"]'
+ );
+
+ expect(
+ scanIntervalField?.querySelector('[data-slot="form-field-description"]')
+ ).toBeNull();
+ expect(scanIntervalInfoButton).toBeDefined();
+
+ fireEvent.focus(scanIntervalInfoButton!);
+ await act(async () => {
+ vi.advanceTimersByTime(100);
+ });
+ expect(
+ document.getElementById("bb-react-layer-overlay")?.textContent
+ ).toContain("instance.scan-interval.description");
+ } finally {
+ vi.useRealTimers();
+ }
+});
+
test("each connection tab edits its own endpoint and authentication", () => {
const { container } = mount(Engine.POSTGRES);
expect(input(container, "host").value).toBe("primary.example.com");
diff --git a/frontend/src/components/instance/InstanceFormBody.tsx b/frontend/src/components/instance/InstanceFormBody.tsx
index ac9e69041e..9e86c60388 100644
--- a/frontend/src/components/instance/InstanceFormBody.tsx
+++ b/frontend/src/components/instance/InstanceFormBody.tsx
@@ -1,6 +1,7 @@
import { create } from "@bufbuild/protobuf";
import type { Duration } from "@bufbuild/protobuf/wkt";
import { DurationSchema } from "@bufbuild/protobuf/wkt";
+import { isEqual, omit } from "lodash-es";
import {
ChevronDown,
ChevronRight,
@@ -37,6 +38,7 @@ import {
import { RadioGroup, RadioGroupItem } from "@/components/ui/radio-group";
import { SegmentedControl } from "@/components/ui/segmented-control";
import { Switch } from "@/components/ui/switch";
+import { Tooltip } from "@/components/ui/tooltip";
import { cn } from "@/lib/utils";
import { pushNotification } from "@/stores";
import { useAppStore } from "@/stores/app";
@@ -447,14 +449,27 @@ function ScanIntervalInput({
return (
<FormField
title={
- <span className="flex items-center gap-x-2">
+ <span className="inline-flex items-center gap-x-2">
{t("instance.scan-interval.self")}
<FeatureBadge
feature={PlanFeature.FEATURE_CUSTOM_INSTANCE_SYNC_TIME}
/>
+ <Tooltip
+ content={t("instance.scan-interval.description")}
+ popupClassName="max-w-96"
+ >
+ <Button
+ type="button"
+ appearance="link"
+ size="xs"
+ className="-ml-1 w-6 p-0"
+ aria-label={t("instance.scan-interval.self")}
+ >
+ <Info className="size-3.5" />
+ </Button>
+ </Tooltip>
</span>
}
- description={t("instance.scan-interval.description")}
>
<RadioGroup
className="gap-x-6"
@@ -523,6 +538,8 @@ export function SyncDatabases({
const [selectedSet, setSelectedSet] = useState<Set<string>>(
() => new Set(syncDatabases?.databases ?? [])
);
+ const selectedSetRef = useRef(selectedSet);
+ selectedSetRef.current = selectedSet;
const [databaseList, setDatabaseList] = useState<Set<string>>(new Set());
const [loading, setLoading] = useState(false);
const [searchText, setSearchText] = useState("");
@@ -532,12 +549,44 @@ export function SyncDatabases({
);
const pendingScrollDatabaseRef = useRef<string | null>(null);
const firstNewDatabaseRef = useRef<HTMLLabelElement | null>(null);
+ const databaseListInstance = isCreatingProp
+ ? pendingCreateInstance
+ : instance;
+ const previousDatabaseListInstanceRef =
+ useRef<typeof databaseListInstance>(undefined);
+ const activeDatabaseListRequestRef = useRef(0);
+ const isMountedRef = useRef(false);
+
+ useEffect(() => {
+ isMountedRef.current = true;
+ return () => {
+ isMountedRef.current = false;
+ };
+ }, []);
// Notify parent only when selection actually changes.
const onSyncDatabasesChangeRef = useRef(onSyncDatabasesChange);
onSyncDatabasesChangeRef.current = onSyncDatabasesChange;
const prevNotifiedRef = useRef<string | null>(null);
+ useEffect(() => {
+ const selectedDatabases = syncDatabases?.databases ?? [];
+ const nextSyncAll = syncDatabases === undefined;
+
+ setSyncAll((current) => (current === nextSyncAll ? current : nextSyncAll));
+ setSelectedSet((current) =>
+ current.size === selectedDatabases.length &&
+ selectedDatabases.every((database) => current.has(database))
+ ? current
+ : new Set(selectedDatabases)
+ );
+ setDatabaseList((current) =>
+ selectedDatabases.every((database) => current.has(database))
+ ? current
+ : new Set([...current, ...selectedDatabases])
+ );
+ }, [syncDatabases]);
+
useEffect(() => {
const key = [
syncAll ? "all" : "selected",
@@ -548,32 +597,54 @@ export function SyncDatabases({
onSyncDatabasesChangeRef.current(syncAll ? [] : [...selectedSet], syncAll);
}, [syncAll, selectedSet]);
- const databaseListInstance = isCreatingProp
- ? pendingCreateInstance
- : instance;
-
useEffect(() => {
- if (syncAll) return;
- let cancelled = false;
+ if (syncAll) {
+ previousDatabaseListInstanceRef.current = undefined;
+ activeDatabaseListRequestRef.current += 1;
+ setLoading(false);
+ return;
+ }
const fetchDatabases = async () => {
const inst = databaseListInstance;
- if (!inst) return;
+ if (!inst) {
+ activeDatabaseListRequestRef.current += 1;
+ setLoading(false);
+ return;
+ }
+ if (
+ isEqual(
+ omit(previousDatabaseListInstanceRef.current, "syncDatabases"),
+ omit(inst, "syncDatabases")
+ )
+ ) {
+ return;
+ }
+ previousDatabaseListInstanceRef.current = inst;
+ const requestId = activeDatabaseListRequestRef.current + 1;
+ activeDatabaseListRequestRef.current = requestId;
setLoading(true);
try {
const resp = await useAppStore
.getState()
.listInstanceDatabases(inst.name, isCreatingProp ? inst : undefined);
- if (!cancelled) {
- setDatabaseList(new Set([...resp.databases, ...selectedSet]));
+ if (
+ isMountedRef.current &&
+ requestId === activeDatabaseListRequestRef.current
+ ) {
+ setDatabaseList(
+ new Set([...selectedSetRef.current, ...resp.databases])
+ );
}
} finally {
- if (!cancelled) setLoading(false);
+ if (
+ isMountedRef.current &&
+ requestId === activeDatabaseListRequestRef.current
+ ) {
+ setLoading(false);
+ }
}
};
- fetchDatabases();
- return () => {
- cancelled = true;
- };
+ void fetchDatabases();
}, [syncAll, isCreatingProp, databaseListInstance]);
useEffect(() => {
@@ -886,7 +957,6 @@ export function InstanceFormBody({ onOpenInfoPanel }: InstanceFormBodyProps) {
const [isEngineSelectorCollapsed, setIsEngineSelectorCollapsed] =
useState(false);
- const [showLabels, setShowLabels] = useState(false);
// --- Computed values ---
@@ -1299,7 +1369,7 @@ export function InstanceFormBody({ onOpenInfoPanel }: InstanceFormBodyProps) {
id="name"
value={basicInfo.title}
required
- className="w-full max-w-[40rem]"
+ className="w-full"
disabled={!allowEdit}
maxLength={200}
onChange={(e) => updateBasicInfo({ title: e.target.value })}
@@ -1348,36 +1418,25 @@ export function InstanceFormBody({ onOpenInfoPanel }: InstanceFormBodyProps) {
{/* Environment */}
<FormField title={t("common.environment")}>
- <div className="flex items-center gap-4">
- <EnvironmentSelect
- portal
- className="w-full max-w-[40rem]"
- value={
- isValidEnvironmentName(
- `${environmentNamePrefix}${environment.id}`
- )
- ? `${environmentNamePrefix}${environment.id}`
- : ""
- }
- disabled={!allowEdit}
- onChange={(value) =>
- handleSelectEnvironment(value || undefined)
- }
- />
- {!showLabels && labelKVList.length === 0 && allowEdit && (
- <Button
- size="sm"
- appearance="link"
- onClick={() => setShowLabels(true)}
- >
- {t("instance.add-labels")}
- </Button>
- )}
- </div>
+ <EnvironmentSelect
+ portal
+ className="w-full"
+ value={
+ isValidEnvironmentName(
+ `${environmentNamePrefix}${environment.id}`
+ )
+ ? `${environmentNamePrefix}${environment.id}`
+ : ""
+ }
+ disabled={!allowEdit}
+ onChange={(value) =>
+ handleSelectEnvironment(value || undefined)
+ }
+ />
</FormField>
{/* Labels */}
- {(showLabels || labelKVList.length > 0) && (
+ {(allowEdit || labelKVList.length > 0) && (
<FormField title={t("common.labels")}>
<LabelListEditor
kvList={labelKVList}
@@ -1393,12 +1452,30 @@ export function InstanceFormBody({ onOpenInfoPanel }: InstanceFormBodyProps) {
{!isCreating && (
<FormField
title={
- <div className="inline-flex items-center">
+ <div className="inline-flex items-center gap-x-1">
<FormLabel htmlFor="external-link">
{basicInfo.engine === Engine.SNOWFLAKE
? t("instance.snowflake-web-console")
: t("instance.external-link")}
</FormLabel>
+ {basicInfo.engine !== Engine.SNOWFLAKE && (
+ <Tooltip
+ content={t("instance.sentence.console.snowflake")}
+ popupClassName="max-w-96"
+ >
+ <Button
+ type="button"
+ appearance="link"
+ size="xs"
+ className="-ml-1 w-6 p-0"
+ aria-label={`${t("instance.external-link")} ${t(
+ "common.info"
+ )}`}
+ >
+ <Info className="size-3.5" />
+ </Button>
+ </Tooltip>
+ )}
{(basicInfo.externalLink ?? "").trim().length > 0 && (
<Button
type="button"
@@ -1429,22 +1506,17 @@ export function InstanceFormBody({ onOpenInfoPanel }: InstanceFormBodyProps) {
value={instanceLink}
/>
) : (
- <>
- <p className="text-xs leading-4 text-control-light">
- {t("instance.sentence.console.snowflake")}
- </p>
- <Input
- id="external-link"
- value={basicInfo.externalLink ?? ""}
- required
- className="w-full"
- disabled={!allowEdit}
- placeholder={SnowflakeExtraLinkPlaceHolder}
- onChange={(e) =>
- updateBasicInfo({ externalLink: e.target.value })
- }
- />
- </>
+ <Input
+ id="external-link"
+ value={basicInfo.externalLink ?? ""}
+ required
+ className="w-full"
+ disabled={!allowEdit}
+ placeholder={SnowflakeExtraLinkPlaceHolder}
+ onChange={(e) =>
+ updateBasicInfo({ externalLink: e.target.value })
+ }
+ />
)}
</FormField>
)}
diff --git a/frontend/src/components/instance/InstanceFormContext.test.tsx b/frontend/src/components/instance/InstanceFormContext.test.tsx
index 932d03532d..05e9e02239 100644
--- a/frontend/src/components/instance/InstanceFormContext.test.tsx
+++ b/frontend/src/components/instance/InstanceFormContext.test.tsx
@@ -41,11 +41,13 @@ const mocks = vi.hoisted(() => ({
vi.mock("@/components/EngineIcon", () => ({ EngineIcon: () => null }));
vi.mock("@/components/EnvironmentSelect", () => ({
- EnvironmentSelect: () => null,
+ EnvironmentSelect: ({ className }: { className?: string }) => (
+ <div data-testid="environment-select" className={className} />
+ ),
}));
vi.mock("@/components/FeatureBadge", () => ({ FeatureBadge: () => null }));
vi.mock("@/components/LabelListEditor", () => ({
- LabelListEditor: () => null,
+ LabelListEditor: () => <div data-testid="label-list-editor" />,
}));
vi.mock("@/components/LearnMoreLink", () => ({ LearnMoreLink: () => null }));
vi.mock("@/components/ResourceIdField", () => ({
@@ -83,7 +85,9 @@ vi.mock(
vi.mock("@/types", () => ({
DATASOURCE_ADMIN_USER_NAME: "bytebase",
+ UNKNOWN_ID: "-",
UNKNOWN_INSTANCE_NAME: "instances/-",
+ isValidEnvironmentName: () => true,
unknownDataSource: () => ({
id: "admin",
type: 1,
@@ -109,6 +113,7 @@ vi.mock("@/stores/app", () => {
createInstance: mocks.createInstance,
listInstanceDatabases: mocks.listInstanceDatabases,
updateDataSource: vi.fn(),
+ hasUnifiedInstanceLicense: () => false,
getEnvironmentByName: (name: string) => ({ name }),
hasInstanceFeature: () => false,
instanceLicenseCount: () => 1,
@@ -132,6 +137,8 @@ vi.mock("@/utils", () => ({
Object.fromEntries(list.map(({ key, value }) => [key, value])),
convertLabelsToKVList: (labels: Record<string, string>) =>
Object.entries(labels).map(([key, value]) => ({ key, value })),
+ engineNameV1: () => "PostgreSQL",
+ extractInstanceResourceName: () => "instance",
hasWorkspacePermissionV2: () => true,
instanceV1HasExtraParameters: () => mocks.hasExtraParameters,
instanceV1HasSSH: () => false,
@@ -140,6 +147,11 @@ vi.mock("@/utils", () => ({
ds.projectId !== "" && ds.instanceId !== "",
isValidBigQueryDataSource: (ds: { projectId: string }) =>
ds.projectId !== "",
+ onlyAllowNumber: (value: string) => value,
+ RE_GCP_INSTANCE_ID: /^[a-z]+$/,
+ RE_GCP_PROJECT_ID: /^[a-z]+$/,
+ supportedEngineV1List: () => [],
+ urlfy: (value: string) => value,
}));
vi.mock("@/utils/connect", () => ({
@@ -351,6 +363,209 @@ describe("InstanceFormProvider", () => {
}
);
+ test("updates the sync database selection after the instance loads", async () => {
+ const { SyncDatabases } = await import("./InstanceFormBody");
+ const instance = create(InstanceSchema, {
+ name: "instances/production",
+ engine: Engine.POSTGRES,
+ });
+ const selectedDatabases = create(SyncDatabasesSchema, {
+ databases: ["app"],
+ });
+ const harness = renderIntoContainer();
+
+ try {
+ await harness.render(
+ <InstanceFormProvider instance={instance}>
+ <SyncDatabases
+ isCreating={false}
+ showLabel={false}
+ allowEdit
+ syncDatabases={undefined}
+ onSyncDatabasesChange={() => undefined}
+ />
+ </InstanceFormProvider>
+ );
+
+ await harness.render(
+ <InstanceFormProvider instance={instance}>
+ <SyncDatabases
+ isCreating={false}
+ showLabel={false}
+ allowEdit
+ syncDatabases={selectedDatabases}
+ onSyncDatabasesChange={() => undefined}
+ />
+ </InstanceFormProvider>
+ );
+
+ expect(
+ harness.container.querySelector('input[type="radio"][value="selected"]')
+ ).toBeChecked();
+ } finally {
+ harness.unmount();
+ }
+ });
+
+ test("lists selected databases before unselected databases", async () => {
+ const { SyncDatabases } = await import("./InstanceFormBody");
+ mocks.listInstanceDatabases.mockResolvedValue({
+ databases: ["analytics", "app", "warehouse"],
+ });
+ const instance = create(InstanceSchema, {
+ name: "instances/production",
+ engine: Engine.POSTGRES,
+ syncDatabases: { databases: ["app"] },
+ });
+ const harness = renderIntoContainer();
+
+ try {
+ await harness.render(
+ <InstanceFormProvider instance={instance}>
+ <SyncDatabases
+ isCreating={false}
+ showLabel={false}
+ allowEdit
+ syncDatabases={instance.syncDatabases}
+ onSyncDatabasesChange={() => undefined}
+ />
+ </InstanceFormProvider>
+ );
+ await act(async () => {
+ await Promise.resolve();
+ });
+
+ expect(
+ Array.from(harness.container.querySelectorAll('[role="checkbox"]')).map(
+ (checkbox) => checkbox.parentElement?.textContent
+ )
+ ).toEqual(["app", "analytics", "warehouse"]);
+ } finally {
+ harness.unmount();
+ }
+ });
+
+ test("finishes loading after an equivalent instance refresh", async () => {
+ const { SyncDatabases } = await import("./InstanceFormBody");
+ let resolveDatabases: (value: { databases: string[] }) => void;
+ mocks.listInstanceDatabases.mockImplementation(
+ () =>
+ new Promise<{ databases: string[] }>((resolve) => {
+ resolveDatabases = resolve;
+ })
+ );
+ const instance = create(InstanceSchema, {
+ name: "instances/production",
+ engine: Engine.POSTGRES,
+ syncDatabases: { databases: ["app"] },
+ });
+ const harness = renderIntoContainer();
+
+ try {
+ await harness.render(
+ <InstanceFormProvider instance={instance}>
+ <SyncDatabases
+ isCreating={false}
+ showLabel={false}
+ allowEdit
+ syncDatabases={instance.syncDatabases}
+ onSyncDatabasesChange={() => undefined}
+ />
+ </InstanceFormProvider>
+ );
+ expect(harness.container.textContent).toContain("common.loading");
+
+ const refreshedInstance = create(InstanceSchema, {
+ name: instance.name,
+ engine: instance.engine,
+ syncDatabases: instance.syncDatabases,
+ });
+ expect(refreshedInstance).not.toBe(instance);
+ await harness.render(
+ <InstanceFormProvider instance={refreshedInstance}>
+ <SyncDatabases
+ isCreating={false}
+ showLabel={false}
+ allowEdit
+ syncDatabases={refreshedInstance.syncDatabases}
+ onSyncDatabasesChange={() => undefined}
+ />
+ </InstanceFormProvider>
+ );
+ await act(async () => {
+ resolveDatabases!({ databases: ["app"] });
+ });
+
+ expect(harness.container.textContent).not.toContain("common.loading");
+ } finally {
+ harness.unmount();
+ mocks.listInstanceDatabases.mockResolvedValue({
+ databases: ["app", "analytics"],
+ });
+ }
+ });
+
+ test("does not reload the database preview when selection changes during creation", async () => {
+ const { SyncDatabases } = await import("./InstanceFormBody");
+ const CreateSelector = () => {
+ const { basicInfo, setBasicInfo } = useInstanceFormContext();
+ return (
+ <SyncDatabases
+ isCreating
+ showLabel={false}
+ allowEdit
+ syncDatabases={basicInfo.syncDatabases}
+ onSyncDatabasesChange={(databases, syncAll) => {
+ setBasicInfo((prev) => ({
+ ...prev,
+ syncDatabases: syncAll
+ ? undefined
+ : create(SyncDatabasesSchema, { databases }),
+ }));
+ }}
+ />
+ );
+ };
+ vi.useFakeTimers();
+ const harness = renderIntoContainer();
+ try {
+ await harness.render(
+ <InstanceFormProvider>
+ <CreateSelector />
+ </InstanceFormProvider>
+ );
+ await act(async () => {
+ harness.container
+ .querySelector<HTMLElement>('[role="radio"][value="selected"]')
+ ?.click();
+ await vi.advanceTimersByTimeAsync(600);
+ });
+
+ const checkbox = harness.container.querySelector<HTMLElement>(
+ '[role="checkbox"]'
+ );
+ expect(checkbox).toBeDefined();
+ mocks.listInstanceDatabases.mockClear();
+ mocks.listInstanceDatabases.mockImplementation(
+ () => new Promise(() => {})
+ );
+
+ await act(async () => {
+ checkbox?.click();
+ await vi.advanceTimersByTimeAsync(300);
+ });
+
+ expect(mocks.listInstanceDatabases).not.toHaveBeenCalled();
+ expect(harness.container.textContent).not.toContain("common.loading");
+ } finally {
+ harness.unmount();
+ vi.useRealTimers();
+ mocks.listInstanceDatabases.mockResolvedValue({
+ databases: ["app", "analytics"],
+ });
+ }
+ });
+
test("refreshes database previews when the create connection changes", async () => {
const { SyncDatabases } = await import("./InstanceFormBody");
const CreateSelector = () => {
diff --git a/frontend/src/components/instance/SshConnectionForm.test.tsx b/frontend/src/components/instance/SshConnectionForm.test.tsx
index e520e536e0..96b4ded593 100644
--- a/frontend/src/components/instance/SshConnectionForm.test.tsx
+++ b/frontend/src/components/instance/SshConnectionForm.test.tsx
@@ -63,6 +63,24 @@ describe("SshConnectionForm", () => {
document.body.innerHTML = "";
});
+ test("renders a compact segmented SSH selector", () => {
+ const { container, root } = mount(<ControlledSshConnectionForm />);
+ expect(
+ container
+ .querySelector('[role="radiogroup"]')
+ ?.classList.contains("inline-flex")
+ ).toBe(true);
+ expect(
+ container
+ .querySelector('[role="radiogroup"]')
+ ?.classList.contains("rounded-xs")
+ ).toBe(true);
+
+ act(() => {
+ root.unmount();
+ });
+ });
+
test("keeps tunnel selected after editing SSH fields before port is entered", () => {
const { container, root } = mount(<ControlledSshConnectionForm />);
const tunnelRadio = container.querySelector(
diff --git a/frontend/src/components/ui/styles.stylex.ts b/frontend/src/components/ui/styles.stylex.ts
index 30c55fd40b..396adb8253 100644
--- a/frontend/src/components/ui/styles.stylex.ts
+++ b/frontend/src/components/ui/styles.stylex.ts
@@ -216,7 +216,7 @@ const formStyles = stylex.create({
alignItems: "start",
columnGap: 16,
display: "grid",
- gridTemplateColumns: "160px minmax(0, 1fr)",
+ gridTemplateColumns: "224px minmax(0, 1fr)",
rowGap: 0,
},
fieldControl: {
diff --git a/frontend/src/locales/en-US.json b/frontend/src/locales/en-US.json
index 6fd284cd90..7c3cccae27 100644
--- a/frontend/src/locales/en-US.json
+++ b/frontend/src/locales/en-US.json
@@ -968,7 +968,6 @@
},
"instance": {
"account-locator": "Account Locator",
- "add-labels": "Add labels",
"add-parameter": "Add parameter",
"advanced-search": {
"scope": {
diff --git a/frontend/src/locales/es-ES.json b/frontend/src/locales/es-ES.json
index 5bcbf31f1e..a59995e85d 100644
--- a/frontend/src/locales/es-ES.json
+++ b/frontend/src/locales/es-ES.json
@@ -968,7 +968,6 @@
},
"instance": {
"account-locator": "Localizadora de cuentas",
- "add-labels": "Añadir etiquetas",
"add-parameter": "Añadir parámetro",
"advanced-search": {
"scope": {
diff --git a/frontend/src/locales/ja-JP.json b/frontend/src/locales/ja-JP.json
index e29641ef06..dcab92736e 100644
--- a/frontend/src/locales/ja-JP.json
+++ b/frontend/src/locales/ja-JP.json
@@ -968,7 +968,6 @@
},
"instance": {
"account-locator": "アカウントロケーター",
- "add-labels": "ラベルを追加",
"add-parameter": "パラメータを追加",
"advanced-search": {
"scope": {
diff --git a/frontend/src/locales/vi-VN.json b/frontend/src/locales/vi-VN.json
index b4a214495c..554ceed4fe 100644
--- a/frontend/src/locales/vi-VN.json
+++ b/frontend/src/locales/vi-VN.json
@@ -968,7 +968,6 @@
},
"instance": {
"account-locator": "Định vị tài khoản",
- "add-labels": "Thêm nhãn",
"add-parameter": "Thêm tham số",
"advanced-search": {
"scope": {
diff --git a/frontend/src/locales/zh-CN.json b/frontend/src/locales/zh-CN.json
index c8df7c22d0..545923c7b0 100644
--- a/frontend/src/locales/zh-CN.json
+++ b/frontend/src/locales/zh-CN.json
@@ -968,7 +968,6 @@
},
"instance": {
"account-locator": "账户定位符",
- "add-labels": "添加标签",
"add-parameter": "添加参数",
"advanced-search": {
"scope": {