Database governance built for humans and agents — controlling changes and access across every major database.
Go cicddata-governancedata-maskingdata-securitydatabase-accessdatabase-governancedevopsdevsecopsflywaygitopsliquibasemongodbmysqloraclepostgresqlschema-migrationssecuritysql-clientsqlservertidb
feat(instance): streamline connection form layout (#21396)
p0ny45a9dfbb1f68
diff --git a/docs/agents/frontend-ux.md b/docs/agents/frontend-ux.mdindex 68946bf58e..980dbca946 100644--- a/docs/agents/frontend-ux.md+++ b/docs/agents/frontend-ux.md@@ -194,6 +194,37 @@ behavior:- Required fields, disabled state, pending state, and server errors MUST remainunderstandable without color alone.+### Dense Horizontal Forms++Multi-option connection forms MAY use horizontal fields through shared form+primitives. Keep section headings above their fields rather than adding a+third column for section titles.++- Use a consistent label column and a flexible control column. Keep ordinary+ controls at `md`; recover space through layout and progressive disclosure.+- 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.+- Put choices that determine subsequent fields first. Keep authentication,+ password-source, and synchronization choices visible in a+ `SegmentedControl`. Longer provider labels MAY wrap within the control when+ every segment remains distinct and usable.+- A password source selector MAY share a row with direct password entry.+ External sources reveal their configuration below. Preserve separate drafts+ while switching sources, and submit only the active source. Reveal dependent+ 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.+- 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+ Cancel on the left. Test feedback MUST remain visible and reachable.+### Page FormsUse a page form when settings have multiple sections, need a stable URL, or arediff --git a/frontend/scripts/ui-guideline-legacy-debt.json b/frontend/scripts/ui-guideline-legacy-debt.jsonindex 979574abe7..41a11c637e 100644--- a/frontend/scripts/ui-guideline-legacy-debt.json+++ b/frontend/scripts/ui-guideline-legacy-debt.json@@ -462,18 +462,6 @@"token": "text-gray-500","count": 1},- {- "path": "src/components/instance/CredentialSourceForm.tsx",- "rule": "no-raw-color",- "token": "bg-gray-100",- "count": 1- },- {- "path": "src/components/instance/CredentialSourceForm.tsx",- "rule": "no-raw-color",- "token": "text-gray-500",- "count": 2- },{"path": "src/components/instance/DataSourceForm.tsx","rule": "no-native-control",@@ -498,18 +486,6 @@"token": "gap-x-0.5","count": 3},- {- "path": "src/components/instance/DataSourceForm.tsx",- "rule": "no-raw-color",- "token": "bg-indigo-100",- "count": 1- },- {- "path": "src/components/instance/DataSourceForm.tsx",- "rule": "no-raw-color",- "token": "text-indigo-800",- "count": 1- },{"path": "src/components/instance/DataSourceSection.tsx","rule": "no-native-control",@@ -558,35 +534,11 @@"token": "text-white","count": 1},- {- "path": "src/components/instance/InstanceFormBody.tsx",- "rule": "no-arbitrary-type",- "token": "text-[11px]",- "count": 1- },{"path": "src/components/instance/InstanceFormBody.tsx","rule": "no-native-control","token": "button",- "count": 8- },- {- "path": "src/components/instance/InstanceFormBody.tsx",- "rule": "no-native-control",- "token": "input",- "count": 1- },- {- "path": "src/components/instance/InstanceFormBody.tsx",- "rule": "no-off-scale-gap",- "token": "gap-x-0.5",- "count": 1- },- {- "path": "src/components/instance/SshConnectionForm.tsx",- "rule": "no-native-control",- "token": "textarea",- "count": 1+ "count": 4},{"path": "src/components/instance/SslCertificateForm.tsx",diff --git a/frontend/src/components/instance/CreateInstanceView.tsx b/frontend/src/components/instance/CreateInstanceView.tsxindex 73195a55a5..aaeee825cd 100644--- a/frontend/src/components/instance/CreateInstanceView.tsx+++ b/frontend/src/components/instance/CreateInstanceView.tsx@@ -13,6 +13,7 @@ import {import type { InfoSection } from "@/components/instance/info-content";import { Alert } from "@/components/ui/alert";import { Button } from "@/components/ui/button";+import { ResponsiveFormLayout } from "@/components/ui/form";import { useUnsavedChangesGuard } from "@/hooks/useUnsavedChangesGuard";import { pushNotification } from "@/stores";import { useAppStore } from "@/stores/app";@@ -150,7 +151,7 @@ function CreateInstanceFormInner({const infoPanelTitle = useMemo(() => {if (!activeInfoSection) return "";const titleMap: Record<InfoSection, string> = {- host: t("instance.host-or-socket"),+ host: t("instance.hostname"),port: t("instance.port"),authentication: t("instance.connection-info"),ssl: t("data-source.ssl-connection"),@@ -220,7 +221,7 @@ function CreateInstanceFormInner({<div className="min-w-0 min-h-0 flex-1 flex flex-col">{/* Body */}<div className="flex-1 min-h-0 overflow-auto">- <div className="px-4 py-4 sm:px-6 gap-y-4 flex flex-col">+ <ResponsiveFormLayout className="px-4 py-4 sm:px-6 gap-y-4 flex flex-col">{canPrepareSampleProjectInstance && (<Alerttitle={t("instance.sample-project-instance-title")}@@ -248,7 +249,7 @@ function CreateInstanceFormInner({</Alert>)}<InstanceFormBody onOpenInfoPanel={handleOpenInfoPanel} />- </div>+ </ResponsiveFormLayout></div><InstanceFormButtons onCreated={onCreated} />diff --git a/frontend/src/components/instance/CredentialSourceForm.tsx b/frontend/src/components/instance/CredentialSourceForm.tsxindex 07ef9bae50..d1c4b9048c 100644--- a/frontend/src/components/instance/CredentialSourceForm.tsx+++ b/frontend/src/components/instance/CredentialSourceForm.tsx@@ -7,8 +7,9 @@ import {useState,} from "react";import { Trans, useTranslation } from "react-i18next";+import { FormField } from "@/components/ui/form";import { Input } from "@/components/ui/input";-import { RadioGroup, RadioGroupItem } from "@/components/ui/radio-group";+import { SegmentedControl } from "@/components/ui/segmented-control";import { Textarea } from "@/components/ui/textarea";import { useServerState } from "@/hooks/useAppState";import { Engine } from "@/types/proto-es/v1/common_pb";@@ -217,34 +218,30 @@ function CredentialSourceForm({};return (- <div className="sm:col-span-3 sm:col-start-1">- <label htmlFor="credential-source" className="textlabel block">- {t("instance.iam-extension.credential-source")}- </label>- <RadioGroup- className="textlabel mt-2 gap-x-4"- value={credentialSource}- onValueChange={(value) =>- handleCredentialSourceChange(value as CredentialSource)- }- >- {options.map((option) => (- <RadioGroupItem- key={option.value}- value={option.value}- disabled={!allowEdit || option.disabled}- title={- option.disabled- ? t(- "instance.iam-extension.saas-default-credential-restriction"- )- : undefined- }- >- {option.label}- </RadioGroupItem>- ))}- </RadioGroup>+ <div className="flex flex-col gap-4 sm:col-span-3 sm:col-start-1">+ <FormField title={t("instance.iam-extension.credential-source")}>+ <SegmentedControl+ value={credentialSource}+ onValueChange={(value) =>+ handleCredentialSourceChange(value as CredentialSource)+ }+ ariaLabel={t("instance.iam-extension.credential-source")}+ options={options.map((option) => ({+ ...option,+ tooltip: option.disabled+ ? t("instance.iam-extension.saas-default-credential-restriction")+ : undefined,+ }))}+ disabled={!allowEdit}+ size="sm"+ />++ {credentialSource === "default" && (+ <DefaultCredentialInfo+ authenticationType={dataSource.authenticationType}+ />+ )}+ </FormField>{credentialSource === "specific-credential" && (<>@@ -278,12 +275,6 @@ function CredentialSourceForm({</>)}- {credentialSource === "default" && (- <DefaultCredentialInfo- authenticationType={dataSource.authenticationType}- />- )}-{showsCloudSQLIPType(engine, dataSource.authenticationType) && (<CloudSQLIPTypeFieldvalue={dataSource.cloudSqlIpType}@@ -356,29 +347,22 @@ function CloudSQLIPTypeField({}));return (- <div className="mt-4 sm:col-span-3 sm:col-start-1">- <label className="textlabel block">- {t("instance.cloud-sql-ip-type.label")}- </label>- <RadioGroup- className="textlabel mt-2 gap-x-4"+ <FormField title={t("instance.cloud-sql-ip-type.label")}>+ <SegmentedControlvalue={String(current)}onValueChange={(next) => onChange(Number(next))}- >- {options.map((option) => (- <RadioGroupItem- key={option.value}- value={String(option.value)}- disabled={!allowEdit}- >- {option.label}- </RadioGroupItem>- ))}- </RadioGroup>- <p className="textinfolabel mt-1">+ ariaLabel={t("instance.cloud-sql-ip-type.label")}+ options={options.map((option) => ({+ value: String(option.value),+ label: option.label,+ }))}+ disabled={!allowEdit}+ size="sm"+ />+ <p className="text-sm text-control-light">{t("instance.cloud-sql-ip-type.description")}</p>- </div>+ </FormField>);}@@ -401,36 +385,36 @@ function AzureCredentialFields({: undefined;return (- <div className="mt-4 sm:col-span-3 sm:col-start-1">- <label className="textlabel block mt-2">- {t("instance.iam-extension.tenant-id")}- </label>- <Input- className="mt-2 w-full"- disabled={!allowEdit}- value={azure?.tenantId ?? ""}- onChange={(e) => onFieldChange("tenantId", e.target.value)}- />- <label className="textlabel block mt-2">- {t("instance.iam-extension.client-id")}- </label>- <Input- className="mt-2 w-full"- disabled={!allowEdit}- value={azure?.clientId ?? ""}- onChange={(e) => onFieldChange("clientId", e.target.value)}- />- <label className="textlabel block mt-2">- {t("instance.iam-extension.client-secret")}- </label>- <Input- type="password"- className="mt-2 w-full"- disabled={!allowEdit}- placeholder={t("instance.type-or-paste-credentials-write-only")}- value={azure?.clientSecret ?? ""}- onChange={(e) => onFieldChange("clientSecret", e.target.value)}- />+ <div className="flex flex-col gap-4">+ <FormField title={t("instance.iam-extension.tenant-id")}>+ <Input+ aria-label={t("instance.iam-extension.tenant-id")}+ className="w-full"+ disabled={!allowEdit}+ value={azure?.tenantId ?? ""}+ onChange={(e) => onFieldChange("tenantId", e.target.value)}+ />+ </FormField>+ <FormField title={t("instance.iam-extension.client-id")}>+ <Input+ aria-label={t("instance.iam-extension.client-id")}+ className="w-full"+ disabled={!allowEdit}+ value={azure?.clientId ?? ""}+ onChange={(e) => onFieldChange("clientId", e.target.value)}+ />+ </FormField>+ <FormField title={t("instance.iam-extension.client-secret")}>+ <Input+ aria-label={t("instance.iam-extension.client-secret")}+ type="password"+ className="w-full"+ disabled={!allowEdit}+ placeholder={t("instance.type-or-paste-credentials-write-only")}+ value={azure?.clientSecret ?? ""}+ onChange={(e) => onFieldChange("clientSecret", e.target.value)}+ />+ </FormField></div>);}@@ -459,55 +443,64 @@ function AwsCredentialFields({: undefined;return (- <div className="mt-4 sm:col-span-3 sm:col-start-1">- <label className="textlabel block mt-2">Access Key ID</label>- <Input- className="mt-2 w-full"- disabled={!allowEdit}- placeholder={t("common.sensitive-placeholder")}- value={aws?.accessKeyId ?? ""}- onChange={(e) => onFieldChange("accessKeyId", e.target.value)}- />- <label className="textlabel block mt-2">Secret Access Key</label>- <Input- className="mt-2 w-full"- disabled={!allowEdit}- placeholder={t("common.sensitive-placeholder")}- value={aws?.secretAccessKey ?? ""}- onChange={(e) => onFieldChange("secretAccessKey", e.target.value)}- />- <label className="textlabel block mt-2">Session Token</label>- <Input- className="mt-2 w-full"- disabled={!allowEdit}- placeholder={t("common.sensitive-placeholder")}- value={aws?.sessionToken ?? ""}- onChange={(e) => onFieldChange("sessionToken", e.target.value)}- />- <label className="textlabel block mt-2">{t("instance.role-arn")}</label>- <Input- className="mt-2 w-full"- disabled={!allowEdit}- placeholder={t("instance.role-arn-placeholder")}- value={aws?.roleArn ?? ""}- onChange={(e) => onFieldChange("roleArn", e.target.value)}- />- <div className="text-sm text-gray-500 mt-1">- {t("instance.role-arn-description")}- </div>- <label className="textlabel block mt-2">- {t("instance.external-id")}- </label>- <Input- className="mt-2 w-full"- disabled={!allowEdit}- placeholder={t("instance.external-id-placeholder")}- value={aws?.externalId ?? ""}- onChange={(e) => onFieldChange("externalId", e.target.value)}- />- <div className="text-sm text-gray-500 mt-1">- {t("instance.external-id-description")}- </div>+ <div className="flex flex-col gap-4">+ <FormField title={"Access Key ID"}>+ <Input+ aria-label={"Access Key ID"}+ className="w-full"+ disabled={!allowEdit}+ placeholder={t("common.sensitive-placeholder")}+ value={aws?.accessKeyId ?? ""}+ onChange={(e) => onFieldChange("accessKeyId", e.target.value)}+ />+ </FormField>+ <FormField title={"Secret Access Key"}>+ <Input+ aria-label={"Secret Access Key"}+ className="w-full"+ disabled={!allowEdit}+ placeholder={t("common.sensitive-placeholder")}+ value={aws?.secretAccessKey ?? ""}+ onChange={(e) => onFieldChange("secretAccessKey", e.target.value)}+ />+ </FormField>+ <FormField title={"Session Token"}>+ <Input+ aria-label={"Session Token"}+ className="w-full"+ disabled={!allowEdit}+ placeholder={t("common.sensitive-placeholder")}+ value={aws?.sessionToken ?? ""}+ onChange={(e) => onFieldChange("sessionToken", e.target.value)}+ />+ </FormField>+ <FormField title={t("instance.role-arn")}>+ <Input+ aria-label={t("instance.role-arn")}+ className="w-full"+ disabled={!allowEdit}+ placeholder={t("instance.role-arn-placeholder")}+ value={aws?.roleArn ?? ""}+ onChange={(e) => onFieldChange("roleArn", e.target.value)}+ />+ <div className="text-sm text-control-light">+ {t("instance.role-arn-description")}+ </div>+ </FormField>++ <FormField title={t("instance.external-id")}>+ <Input+ aria-label={t("instance.external-id")}+ className="w-full"+ disabled={!allowEdit}+ placeholder={t("instance.external-id-placeholder")}+ value={aws?.externalId ?? ""}+ onChange={(e) => onFieldChange("externalId", e.target.value)}+ />+ <div className="text-sm text-control-light">+ {t("instance.external-id-description")}+ </div>+ </FormField></div>);}@@ -549,7 +542,7 @@ function GcpCredentialField({};return (- <div className="mt-2 sm:col-span-3 sm:col-start-1">+ <FormField title={t("instance.iam-extension.specific-credential")}><div className="flex flex-col gap-y-1 w-full"><p className="textinfolabel"><span>{t("instance.create-gcp-credentials")}</span>@@ -577,6 +570,7 @@ function GcpCredentialField({</a></p><Textarea+ aria-label={t("instance.iam-extension.specific-credential")}value={value}placeholder={t("instance.type-or-paste-credentials-write-only")}className={`w-full h-24 whitespace-pre-wrap resize-none ${isDragOver ? "border-accent" : ""}`}@@ -586,7 +580,7 @@ function GcpCredentialField({onDrop={handleDrop}/></div>- </div>+ </FormField>);}@@ -598,7 +592,7 @@ function DefaultCredentialInfo({const { t } = useTranslation();return (- <div className="mt-1 sm:col-span-3 sm:col-start-1 textinfolabel !leading-6">+ <div className="text-sm leading-5 text-control-light">{authenticationType === DataSource_AuthenticationType.AZURE_IAM && (<Transt={t}@@ -638,7 +632,7 @@ function DefaultCredentialInfo({}function Code({ children }: { children?: React.ReactNode }) {- return <code className="bg-gray-100 p-1 rounded-sm mr-1">{children}</code>;+ return <code className="bg-control-bg p-1 rounded-sm mr-1">{children}</code>;}export { CredentialSourceForm };diff --git a/frontend/src/components/instance/DataSourceForm.test.ts b/frontend/src/components/instance/DataSourceForm.test.tsnew file mode 100644index 0000000000..35140bd6ee--- /dev/null+++ b/frontend/src/components/instance/DataSourceForm.test.ts@@ -0,0 +1,47 @@+import { readFileSync } from "node:fs";+import { join } from "node:path";+import { describe, expect, test } from "vitest";++const source = () =>+ readFileSync(+ join(process.cwd(), "src/components/instance/DataSourceForm.tsx"),+ "utf-8"+ );++describe("DataSourceForm password sources", () => {+ test("keeps a draft per instance data source and secret provider", () => {+ const form = source();++ expect(form).toContain("sourceDraftStateRef");+ expect(form).toContain("invalidateSourceDrafts");+ expect(form).toContain("dataSourceResetEvent");+ expect(form).toContain("sourceDraftsRef.current.get(dataSource.id)");+ expect(form).toContain("drafts.set(");+ expect(form).toContain("const existingDraft = drafts.get(secretType)");+ expect(form).toContain("ds.externalSecret = existingDraft");+ });++ test("exports Redis Sentinel fields for the connection mode panel", () => {+ expect(source()).toContain("export function RedisSentinelFields");+ });++ test("does not initialize a provider from another provider's identifiers", () => {+ const form = source();++ expect(form).not.toContain("ds.externalSecret?.secretName ??");+ expect(form).not.toContain("ds.externalSecret?.passwordKeyName ??");+ expect(form).toContain('secretName: ""');+ expect(form).toContain('passwordKeyName: ""');+ });++ test("keeps the password source selector beside the Bytebase password input", () => {+ const form = source();+ const sourceIndex = form.indexOf("{passwordSourceControl}");+ const inputIndex = form.indexOf('type="password"', sourceIndex);+ const storedHintIndex = form.indexOf("stored-in-bytebase");++ expect(sourceIndex).toBeGreaterThan(0);+ expect(inputIndex).toBeGreaterThan(sourceIndex);+ expect(storedHintIndex).toBeGreaterThan(sourceIndex);+ });+});diff --git a/frontend/src/components/instance/DataSourceForm.tsx b/frontend/src/components/instance/DataSourceForm.tsxindex 3d1fb50b14..24b91f3b9c 100644--- a/frontend/src/components/instance/DataSourceForm.tsx+++ b/frontend/src/components/instance/DataSourceForm.tsx@@ -10,15 +10,23 @@ import {FormControlRow,FormError,FormField,+ ResponsiveFormLayout,} from "@/components/ui/form";import { Input } from "@/components/ui/input";import { RadioGroup, RadioGroupItem } from "@/components/ui/radio-group";+import { SegmentedControl } from "@/components/ui/segmented-control";+import {+ Select,+ SelectContent,+ SelectItem,+ SelectTrigger,+ SelectValue,+} from "@/components/ui/select";import { cn } from "@/lib/utils";import { useAppStore } from "@/stores/app";import { Engine } from "@/types/proto-es/v1/common_pb";import {DataSource_AuthenticationType,- DataSource_RedisType,DataSourceExternalSecret_AppRoleAuthOption_SecretType,DataSourceExternalSecret_AppRoleAuthOptionSchema,DataSourceExternalSecret_AuthType,@@ -37,6 +45,7 @@ import { onlyAllowNumber } from "@/utils";import { CreateDataSourceExample } from "./CreateDataSourceExample";import { CredentialSourceForm } from "./CredentialSourceForm";import type { EditDataSource, TlsUpdateState } from "./common";+import { invalidateSourceDrafts } from "./data-source-drafts";import { useInstanceFormContext } from "./InstanceFormContext";import { hasInfoContent, type InfoSection } from "./info-content";import { SshConnectionForm } from "./SshConnectionForm";@@ -59,6 +68,8 @@ import {interface DataSourceFormProps {dataSource: EditDataSource;+ authOnly?: boolean;+ hideAuthentication?: boolean;hideOptions?: boolean;optionsOnly?: boolean;onDataSourceChange: (ds: EditDataSource) => void;@@ -88,14 +99,103 @@ const mergeTlsUpdateState = (};};+export function RedisSentinelFields({+ dataSource,+ isCreating,+ allowEdit,+ allowUsingEmptyPassword,+ onDataSourceChange,+}: Readonly<{+ dataSource: EditDataSource;+ isCreating: boolean;+ allowEdit: boolean;+ allowUsingEmptyPassword: boolean;+ onDataSourceChange: (dataSource: EditDataSource) => void;+}>) {+ const { t } = useTranslation();+ const update = (partial: Partial<EditDataSource>) => {+ onDataSourceChange({ ...dataSource, ...partial });+ };++ return (+ <>+ <FormField+ title={+ <>+ {t("instance.master-name")} <span className="text-error">*</span>+ </>+ }+ >+ <Input+ value={dataSource.masterName ?? ""}+ className="w-full"+ disabled={!allowEdit}+ onChange={(e) => update({ masterName: e.target.value })}+ />+ </FormField>+ <FormField title={t("instance.master-username")}>+ <Input+ value={dataSource.masterUsername ?? ""}+ className="w-full"+ disabled={!allowEdit}+ onChange={(e) => update({ masterUsername: e.target.value })}+ />+ </FormField>+ <FormField title={t("instance.master-password")}>+ <div>+ {!isCreating && allowUsingEmptyPassword && (+ <label className="flex items-center gap-x-1.5 mb-2 text-sm cursor-pointer">+ <Checkbox+ checked={dataSource.useEmptyMasterPassword ?? false}+ disabled={!allowEdit}+ onCheckedChange={(checked) => {+ update({+ useEmptyMasterPassword: checked,+ updatedMasterPassword: checked+ ? ""+ : dataSource.updatedMasterPassword,+ });+ }}+ />+ {t("instance.no-password")}+ </label>+ )}+ <Input+ type="password"+ className="w-full"+ autoComplete="off"+ placeholder={+ dataSource.useEmptyMasterPassword+ ? t("instance.no-password")+ : t("instance.password-write-only")+ }+ disabled={!allowEdit || !!dataSource.useEmptyMasterPassword}+ value={+ dataSource.useEmptyMasterPassword+ ? ""+ : dataSource.updatedMasterPassword+ }+ onChange={(e) =>+ update({ updatedMasterPassword: e.target.value.trim() })+ }+ />+ </div>+ </FormField>+ </>+ );+}+export function DataSourceForm({dataSource,+ authOnly = false,+ hideAuthentication = false,hideOptions = false,optionsOnly = false,onDataSourceChange,onOpenInfoPanel,}: Readonly<DataSourceFormProps>) {const { t } = useTranslation();+ const [showExtraParameters, setShowExtraParameters] = useState(false);const currentPlan = useAppStore((s) => s.currentPlan());const isSaaSMode = useAppStore((s) => s.isSaaSMode());const ctx = useInstanceFormContext();@@ -110,6 +210,7 @@ export function DataSourceForm({setMissingFeature,hideAdvancedFeatures,needsKeytabResupply,+ dataSourceResetEvent,} = ctx;const {@@ -139,6 +240,30 @@ export function DataSourceForm({getLocalTlsPosture(dataSource));const previousDataSourceIdRef = useRef(dataSource.id);+ const sourceDraftsRef = useRef(+ new Map<+ string,+ Map<+ DataSourceExternalSecret_SecretType,+ NonNullable<EditDataSource["externalSecret"]>+ >+ >()+ );+ const sourceDraftStateRef = useRef({+ instanceName: instance?.name,+ resetEvent: dataSourceResetEvent,+ });++ useEffect(() => {+ sourceDraftStateRef.current = invalidateSourceDrafts(+ sourceDraftsRef.current,+ sourceDraftStateRef.current,+ {+ instanceName: instance?.name,+ resetEvent: dataSourceResetEvent,+ }+ );+ }, [dataSourceResetEvent, instance?.name]);// Sync passwordType when externalSecret changesuseEffect(() => {@@ -307,7 +432,30 @@ export function DataSourceForm({const changeSecretType = (secretType: DataSourceExternalSecret_SecretType) => {- const ds = { ...dataSource };+ const ds = {+ ...dataSource,+ authenticationType: DataSource_AuthenticationType.PASSWORD,+ };+ const drafts =+ sourceDraftsRef.current.get(dataSource.id) ??+ new Map<+ DataSourceExternalSecret_SecretType,+ NonNullable<EditDataSource["externalSecret"]>+ >();+ if (dataSource.externalSecret) {+ drafts.set(+ dataSource.externalSecret.secretType,+ dataSource.externalSecret+ );+ }+ sourceDraftsRef.current.set(dataSource.id, drafts);+ const existingDraft = drafts.get(secretType);+ if (existingDraft) {+ ds.externalSecret = existingDraft;+ setPasswordType(secretType);+ onDataSourceChange(ds);+ return;+ }switch (secretType) {case DataSourceExternalSecret_SecretType.SECRET_TYPE_UNSPECIFIED:ds.externalSecret = undefined;@@ -317,8 +465,8 @@ export function DataSourceForm({authType: DataSourceExternalSecret_AuthType.TOKEN,secretType,authOption: { case: "token", value: "" },- secretName: ds.externalSecret?.secretName ?? "",- passwordKeyName: ds.externalSecret?.passwordKeyName ?? "",+ secretName: "",+ passwordKeyName: "",});break;case DataSourceExternalSecret_SecretType.AWS_SECRETS_MANAGER:@@ -326,8 +474,8 @@ export function DataSourceForm({authType: DataSourceExternalSecret_AuthType.AUTH_TYPE_UNSPECIFIED,secretType,authOption: { case: "token", value: "" },- secretName: ds.externalSecret?.secretName ?? "",- passwordKeyName: ds.externalSecret?.passwordKeyName ?? "",+ secretName: "",+ passwordKeyName: "",});break;case DataSourceExternalSecret_SecretType.GCP_SECRET_MANAGER:@@ -335,7 +483,7 @@ export function DataSourceForm({authType: DataSourceExternalSecret_AuthType.AUTH_TYPE_UNSPECIFIED,secretType,authOption: { case: "token", value: "" },- secretName: ds.externalSecret?.secretName ?? "",+ secretName: "",passwordKeyName: "",});break;@@ -344,8 +492,8 @@ export function DataSourceForm({authType: DataSourceExternalSecret_AuthType.AUTH_TYPE_UNSPECIFIED,secretType,authOption: { case: "token", value: "" },- url: ds.externalSecret?.url ?? "",- secretName: ds.externalSecret?.secretName ?? "",+ url: "",+ secretName: "",passwordKeyName: "",});break;@@ -591,1327 +739,1395 @@ export function DataSourceForm({[dataSource, localTlsClientCertSource, update]);- return (- <div className="grid grid-cols-1 gap-y-4 gap-x-4 border-none sm:grid-cols-3">- {!optionsOnly && (- <>- {/* Main credential fields */}- {showMainFields && (- <>- {/* Authentication type selector */}- {showAuthTypeRadio && (- <div className="sm:col-span-3 sm:col-start-1">- <div className="flex items-center gap-x-2">- <RadioGroup- className="textlabel gap-x-4"- value={String(dataSource.authenticationType)}- onValueChange={(value) =>- update({- authenticationType: Number(- value- ) as DataSource_AuthenticationType,- })- }- >- {supportedAuthenticationTypes.map((item) => (- <RadioGroupItem- key={item.value}- value={String(item.value)}- disabled={!allowEdit}- >- {item.label}- </RadioGroupItem>- ))}- </RadioGroup>- </div>- </div>- )}+ const passwordSourceOptions = [+ {+ value: DataSourceExternalSecret_SecretType.SECRET_TYPE_UNSPECIFIED,+ label: t("instance.password-source.bytebase"),+ },+ {+ value: DataSourceExternalSecret_SecretType.VAULT_KV_V2,+ label: t("instance.password-type.external-secret-vault"),+ },+ {+ value: DataSourceExternalSecret_SecretType.AWS_SECRETS_MANAGER,+ label: t("instance.password-type.external-secret-aws"),+ },+ {+ value: DataSourceExternalSecret_SecretType.GCP_SECRET_MANAGER,+ label: t("instance.password-type.external-secret-gcp"),+ },+ {+ value: DataSourceExternalSecret_SecretType.AZURE_KEY_VAULT,+ label: t("instance.password-type.external-secret-azure"),+ },+ ];- {/* Create data source example (edit mode only) */}- {!isCreating && (- <CreateDataSourceExample- className="sm:col-span-3 border-none"- createInstanceFlag={false}- engine={basicInfo.engine}- dataSourceType={dataSource.type}- authenticationType={dataSource.authenticationType}- />- )}+ const secretOptions = passwordSourceOptions.map((item) => ({+ value: `secret:${item.value}`,+ label: (+ <span className="flex items-center gap-x-1.5">+ {item.value ===+ DataSourceExternalSecret_SecretType.SECRET_TYPE_UNSPECIFIED+ ? t("common.password")+ : item.label}+ {item.value !==+ DataSourceExternalSecret_SecretType.SECRET_TYPE_UNSPECIFIED &&+ currentPlan === PlanType.FREE && (+ <span className="rounded-full border border-current px-1.5 py-0.5 text-xs">+ Pro+ </span>+ )}+ </span>+ ),+ }));++ const passwordSourceControl = !showAuthTypeRadio && !hideAdvancedFeatures && (+ <SegmentedControl+ ariaLabel={t("instance.password-source.self")}+ value={`secret:${passwordType}`}+ onValueChange={(value) =>+ changeSecretType(+ Number(value.split(":")[1]) as DataSourceExternalSecret_SecretType+ )+ }+ options={secretOptions}+ disabled={!allowEdit}+ size="sm"+ />+ );- {/* Hive authentication */}- {basicInfo.engine === Engine.HIVE && (- <div className="sm:col-span-3 sm:col-start-1">- <RadioGroup- className="textlabel gap-x-4"- value={hiveAuthentication}- onValueChange={(value) =>- onHiveAuthenticationChange(- value as typeof hiveAuthentication- )- }- >- <RadioGroupItem value="PASSWORD" disabled={!allowEdit}>- Plain Password- </RadioGroupItem>- <RadioGroupItem value="KERBEROS" disabled={!allowEdit}>- Kerberos- </RadioGroupItem>- </RadioGroup>- </div>- )}+ const authenticationOptions = supportedAuthenticationTypes.flatMap((item) =>+ item.value === DataSource_AuthenticationType.PASSWORD+ ? hideAdvancedFeatures+ ? secretOptions.slice(0, 1)+ : secretOptions+ : [{ value: `auth:${item.value}`, label: <>{item.label}</> }]+ );+ const authenticationValue = isPasswordAuth+ ? `secret:${passwordType}`+ : `auth:${dataSource.authenticationType}`;++ const authenticationTypeControl = showAuthTypeRadio && (+ <FormField+ title={t("instance.authentication")}+ className="sm:col-span-3 sm:col-start-1"+ >+ <Select+ value={authenticationValue}+ onValueChange={(value) => {+ if (!value) return;+ const [kind, type] = value.split(":");+ if (kind === "secret") {+ changeSecretType(+ Number(type) as DataSourceExternalSecret_SecretType+ );+ } else {+ update({+ authenticationType: Number(type) as DataSource_AuthenticationType,+ });+ }+ }}+ disabled={!allowEdit}+ >+ <SelectTrigger+ aria-label={t("instance.authentication")}+ className="w-full sm:w-80"+ >+ <SelectValue>+ {+ authenticationOptions.find(+ (item) => item.value === authenticationValue+ )?.label+ }+ </SelectValue>+ </SelectTrigger>+ <SelectContent>+ {authenticationOptions.map((item) => (+ <SelectItem key={item.value} value={item.value}>+ {item.label}+ </SelectItem>+ ))}+ </SelectContent>+ </Select>+ </FormField>+ );- {/* Kerberos config */}- {dataSource.saslConfig?.mechanism?.case === "krbConfig" && (+ return (+ <div className="grid grid-cols-1 gap-y-4 gap-x-4 border-none sm:grid-cols-3">+ {authOnly+ ? authenticationTypeControl+ : !optionsOnly && (+ <>+ {/* Main credential fields */}+ {showMainFields && (<>- <FormField- className="sm:col-span-3 sm:col-start-1"- title={- <>- {t("instance.kerberos-principal")}{" "}- <span className="text-error">*</span>- </>- }- >- <FormControlRow>- <Input- className="min-w-0 flex-1"- value={- dataSource.saslConfig.mechanism.value.primary ?? ""- }- disabled={!allowEdit}- placeholder={t("instance.kerberos-primary-placeholder")}- onChange={(e) => {- const updated = { ...dataSource };- if (- updated.saslConfig?.mechanism?.case === "krbConfig"- ) {- updated.saslConfig.mechanism.value.primary =- e.target.value;- }- onDataSourceChange(updated);- }}- />- <span className="shrink-0 whitespace-nowrap text-sm leading-5 text-control-light">- /- </span>- <Input- className="min-w-0 flex-1"- value={- dataSource.saslConfig.mechanism.value.instance ?? ""- }- disabled={!allowEdit}- placeholder={t(- "instance.kerberos-instance-placeholder"- )}- onChange={(e) => {- const updated = { ...dataSource };- if (- updated.saslConfig?.mechanism?.case === "krbConfig"- ) {- updated.saslConfig.mechanism.value.instance =- e.target.value;- }- onDataSourceChange(updated);- }}- />- <span className="shrink-0 whitespace-nowrap text-sm leading-5 text-control-light">- @- </span>- <Input- className="min-w-0 flex-1"- value={- dataSource.saslConfig.mechanism.value.realm ?? ""- }- disabled={!allowEdit}- placeholder={t("instance.kerberos-realm-placeholder")}- onChange={(e) => {- const updated = { ...dataSource };- if (- updated.saslConfig?.mechanism?.case === "krbConfig"- ) {- updated.saslConfig.mechanism.value.realm =- e.target.value;- }- onDataSourceChange(updated);- }}- />- </FormControlRow>- </FormField>- <FormField- className="sm:col-span-3 sm:col-start-1"- title={- <>- {t("instance.kerberos-kdc")}{" "}- <span className="text-error">*</span>- </>- }- >- <FormControlRow>+ {!hideAuthentication && authenticationTypeControl}++ {/* Create data source example (edit mode only) */}+ {!isCreating && (+ <CreateDataSourceExample+ className="sm:col-span-3 border-none"+ createInstanceFlag={false}+ engine={basicInfo.engine}+ dataSourceType={dataSource.type}+ authenticationType={dataSource.authenticationType}+ />+ )}++ {/* Hive authentication */}+ {basicInfo.engine === Engine.HIVE && (+ <div className="sm:col-span-3 sm:col-start-1"><RadioGroup- className="w-fit textlabel gap-x-3"- value={- dataSource.saslConfig?.mechanism?.value- ?.kdcTransportProtocol ?? ""+ className="textlabel gap-x-4"+ value={hiveAuthentication}+ onValueChange={(value) =>+ onHiveAuthenticationChange(+ value as typeof hiveAuthentication+ )}- onValueChange={(proto) => {- const updated = { ...dataSource };- if (- updated.saslConfig?.mechanism?.case === "krbConfig"- ) {- updated.saslConfig.mechanism.value.kdcTransportProtocol =- String(proto);- }- onDataSourceChange(updated);- }}>- {["tcp", "udp"].map((proto) => (- <RadioGroupItem- key={proto}- value={proto}- disabled={!allowEdit}- >- {proto.toUpperCase()}- </RadioGroupItem>- ))}+ <RadioGroupItem value="PASSWORD" disabled={!allowEdit}>+ Plain Password+ </RadioGroupItem>+ <RadioGroupItem value="KERBEROS" disabled={!allowEdit}>+ Kerberos+ </RadioGroupItem></RadioGroup>- <Input- className="min-w-0 flex-1"- value={- dataSource.saslConfig.mechanism.value.kdcHost ?? ""- }- disabled={!allowEdit}- placeholder={t(- "instance.kerberos-kdc-host-placeholder"- )}- onChange={(e) => {- const updated = { ...dataSource };- if (- updated.saslConfig?.mechanism?.case === "krbConfig"- ) {- updated.saslConfig.mechanism.value.kdcHost =- e.target.value;- }- onDataSourceChange(updated);- }}- />- <span className="shrink-0 whitespace-nowrap text-sm leading-5 text-control-light">- :- </span>- <Input- className="min-w-0 flex-1"- value={- dataSource.saslConfig.mechanism.value.kdcPort ?? ""- }- disabled={!allowEdit}- placeholder={t(- "instance.kerberos-kdc-port-placeholder"- )}- onChange={(e) => {- if (- e.target.value &&- !onlyAllowNumber(e.target.value)- )- return;- const updated = { ...dataSource };- if (- updated.saslConfig?.mechanism?.case === "krbConfig"- ) {- updated.saslConfig.mechanism.value.kdcPort =- e.target.value;- }- onDataSourceChange(updated);- }}- />- </FormControlRow>- </FormField>- <FormField- className="sm:col-span-3 sm:col-start-1"- title={- <>- {t("instance.keytab-file")}- {(dataSource.pendingCreate ||- keytabResupplyRequired) && (- <>- {" "}- <span className="text-error">*</span>- </>- )}- </>- }- >- <div- className={cn(- "mt-3 border-2 border-dashed rounded-sm p-6 text-center",- keytabResupplyRequired && "border-error"- )}- >- <input- type="file"- accept=".keytab"- className="hidden"- id="keytab-upload"- onChange={handleKeytabUpload}- />- <label- htmlFor="keytab-upload"- className="cursor-pointer textinfolabel"- >- {t("instance.keytab-upload-placeholder")}- </label>- {keytabFileName && (- <p className="mt-2 textinfolabel truncate">- {keytabFileName}- </p>- )}</div>- {/* The write-only hint offers to keep the stored keytab,- which is the offer the resupply error withdraws. */}- {!dataSource.pendingCreate && !keytabResupplyRequired && (- <p className="mt-1 textinfolabel">- {t("instance.keytab-write-only")}- </p>- )}- {keytabResupplyRequired && (- <FormError className="mt-1">- {t("instance.keytab-resupply-required")}- </FormError>- )}- </FormField>- </>- )}-- {/* Username field (non-Kerberos, non-Azure IAM) */}- {dataSource.saslConfig?.mechanism?.case !== "krbConfig" &&- !isAzureIAM && (- <FormField- className="sm:col-span-3 sm:col-start-1"- title={- <span className="flex items-center gap-x-1">- {t("common.username")}- {onOpenInfoPanel && hasAuthenticationInfo && (- <button- type="button"- className="inline-flex items-center gap-x-0.5 text-accent text-xs"- onClick={() => onOpenInfoPanel("authentication")}- >- <Info className="size-3.5" />- </button>- )}- </span>- }- >- <Input- value={dataSource.username}- className="w-full max-w-[48rem]"- disabled={!allowEdit}- placeholder={- basicInfo.engine === Engine.CLICKHOUSE- ? t("common.default")- : ""- }- onChange={(e) => update({ username: e.target.value })}- />- </FormField>- )}-- {/* IAM Credential Source Form */}- {isIAM && (- <CredentialSourceForm- dataSource={dataSource}- engine={basicInfo.engine}- allowEdit={allowEdit}- onDataSourceChange={update}- />- )}-- {/* AWS Region */}- {isAwsIAM && (- <AwsRegionField- region={dataSource.region ?? ""}- required- allowEdit={allowEdit}- onChange={(region) => update({ region })}- />- )}+ )}- {/* Password / External Secret */}- {isPasswordAuth &&- dataSource.saslConfig?.mechanism?.case !== "krbConfig" && (- <div className="sm:col-span-3 sm:col-start-1">- {!hideAdvancedFeatures && (- <div className="mb-4">- <RadioGroup- className="textlabel flex-wrap gap-x-4 gap-y-2"- value={String(passwordType)}- onValueChange={(value) =>- changeSecretType(- Number(- value- ) as DataSourceExternalSecret_SecretType- )- }+ {/* Kerberos config */}+ {dataSource.saslConfig?.mechanism?.case === "krbConfig" && (+ <FormField+ className="sm:col-span-3 sm:col-start-1"+ title="Kerberos"+ >+ <ResponsiveFormLayout>+ <fieldset+ aria-label="Kerberos"+ className="flex flex-col gap-4 rounded-xs border border-control-border px-3 py-2">- {[- {- value:- DataSourceExternalSecret_SecretType.SECRET_TYPE_UNSPECIFIED,- label: t("instance.password-type.password"),- },- {- value:- DataSourceExternalSecret_SecretType.VAULT_KV_V2,- label: t(- "instance.password-type.external-secret-vault"- ),- },- {- value:- DataSourceExternalSecret_SecretType.AWS_SECRETS_MANAGER,- label: t(- "instance.password-type.external-secret-aws"- ),- },- {- value:- DataSourceExternalSecret_SecretType.GCP_SECRET_MANAGER,- label: t(- "instance.password-type.external-secret-gcp"- ),- },- {- value:- DataSourceExternalSecret_SecretType.AZURE_KEY_VAULT,- label: t(- "instance.password-type.external-secret-azure"- ),- },- ].map((item) => (- <RadioGroupItem- key={item.value}- value={String(item.value)}- disabled={!allowEdit}- contentClassName="flex items-center gap-x-1.5"- >- {item.label}- {item.value !==- DataSourceExternalSecret_SecretType.SECRET_TYPE_UNSPECIFIED &&- currentPlan === PlanType.FREE && (- <span className="text-xs bg-indigo-100 text-indigo-800 px-1.5 py-0.5 rounded-full">- Pro- </span>- )}- </RadioGroupItem>- ))}- <LearnMoreLink- href="https://docs.bytebase.com/get-started/connect/overview#secret-manager-integration"- className="text-sm text-accent"- />- </RadioGroup>- </div>- )}-- {/* Plain password */}- {passwordType ===- DataSourceExternalSecret_SecretType.SECRET_TYPE_UNSPECIFIED && (- <FormField title={<>{t("common.password")}</>}>- <div>- {!isCreating && allowUsingEmptyPassword && (- <label className="flex items-center gap-x-1.5 mb-2 text-sm cursor-pointer">- <Checkbox- checked={dataSource.useEmptyPassword ?? false}- disabled={!allowEdit}- onCheckedChange={(checked) =>- toggleUseEmptyPassword(checked)- }- />- {t("instance.no-password")}- </label>- )}- <Input- type="password"- className="w-full max-w-[48rem]"- autoComplete="off"- placeholder={- dataSource.useEmptyPassword- ? t("instance.no-password")- : t("instance.password-write-only")- }- disabled={- !allowEdit || !!dataSource.useEmptyPassword- }- value={- dataSource.useEmptyPassword- ? ""- : dataSource.updatedPassword- }- onChange={(e) =>- update({- updatedPassword: e.target.value.trim(),- })+ <FormField+ title={+ <>+ {t("instance.kerberos-principal")}{" "}+ <span className="text-error">*</span>+ </>}- />- </div>- </FormField>- )}-- {/* External secret fields */}- {passwordType !==- DataSourceExternalSecret_SecretType.SECRET_TYPE_UNSPECIFIED &&- dataSource.externalSecret && (- <div className="flex flex-col gap-y-4">- {/* Vault KV V2 */}- {passwordType ===- DataSourceExternalSecret_SecretType.VAULT_KV_V2 && (- <div className="flex flex-col gap-y-4">- <FormField- title={- <>- {t(- "instance.external-secret-vault.vault-url"- )}{" "}- <span className="text-error">*</span>- </>- }- >- <Input- value={dataSource.externalSecret.url ?? ""}- required- className="w-full"- disabled={!allowEdit}- placeholder={t(- "instance.external-secret-vault.vault-url"- )}- onChange={(e) => {- const ds = { ...dataSource };- ds.externalSecret = {- ...ds.externalSecret!,- url: e.target.value,- };- onDataSourceChange(ds);- }}- />- </FormField>- <FormField- title={- <>- {t(- "instance.external-secret-vault.vault-auth-type.self"- )}- </>+ >+ <FormControlRow>+ <Input+ className="min-w-0 flex-1"+ value={+ dataSource.saslConfig.mechanism.value+ .primary ?? ""}- >- <RadioGroup- className="textlabel gap-x-4"- value={String(- dataSource.externalSecret.authType- )}- onValueChange={(value) =>- changeExternalSecretAuthType(- Number(- value- ) as DataSourceExternalSecret_AuthType- )- }- >- <RadioGroupItem- value={String(- DataSourceExternalSecret_AuthType.TOKEN- )}- >- {t(- "instance.external-secret-vault.vault-auth-type.token.self"- )}- </RadioGroupItem>- <RadioGroupItem- value={String(- DataSourceExternalSecret_AuthType.VAULT_APP_ROLE- )}- >- {t(- "instance.external-secret-vault.vault-auth-type.approle.self"- )}- </RadioGroupItem>- </RadioGroup>- </FormField>- {/* Token input */}- {dataSource.externalSecret.authType ===- DataSourceExternalSecret_AuthType.TOKEN &&- (() => {- const tokenType =- dataSource.externalSecret.tokenType ===- DataSourceExternalSecret_TokenType.ENVIRONMENT ||- dataSource.externalSecret.tokenType ===- DataSourceExternalSecret_TokenType.FILE- ? dataSource.externalSecret.tokenType- : DataSourceExternalSecret_TokenType.PLAIN;- const changeTokenType = (- type: DataSourceExternalSecret_TokenType- ) => {- const ds = { ...dataSource };- ds.externalSecret = {- ...ds.externalSecret!,- tokenType: type,- };- onDataSourceChange(ds);- };- const tokenLabel = t(- "instance.external-secret-vault.vault-auth-type.token.self"- );- let tokenPlaceholder = `${tokenLabel} - ${t("common.write-only")}`;+ disabled={!allowEdit}+ placeholder={t(+ "instance.kerberos-primary-placeholder"+ )}+ onChange={(e) => {+ const updated = { ...dataSource };if (- tokenType ===- DataSourceExternalSecret_TokenType.ENVIRONMENT- ) {- tokenPlaceholder = t(- "instance.external-secret-vault.vault-auth-type.token.env-name"- );- } else if (- tokenType ===- DataSourceExternalSecret_TokenType.FILE+ updated.saslConfig?.mechanism?.case ===+ "krbConfig") {- tokenPlaceholder = t(- "instance.external-secret-vault.vault-auth-type.token.file-path"- );+ updated.saslConfig.mechanism.value.primary =+ e.target.value;}- return (- <FormField- title={- <>- {tokenLabel}{" "}- <span className="text-error">*</span>- </>- }- >- {/* Token source is host-backed for env/file,- which is disallowed in SaaS mode; only- plain is offered there. */}- {!isSaaSMode && (- <RadioGroup- className="textlabel my-1 gap-x-4"- value={String(tokenType)}- onValueChange={(value) =>- changeTokenType(- Number(- value- ) as DataSourceExternalSecret_TokenType- )- }- >- <RadioGroupItem- value={String(- DataSourceExternalSecret_TokenType.PLAIN- )}- disabled={!allowEdit}- >- {t(- "instance.external-secret-vault.vault-auth-type.token.type-plain"- )}- </RadioGroupItem>- <RadioGroupItem- value={String(- DataSourceExternalSecret_TokenType.ENVIRONMENT- )}- disabled={!allowEdit}- >- {t(- "instance.external-secret-vault.vault-auth-type.token.type-environment"- )}- </RadioGroupItem>- <RadioGroupItem- value={String(- DataSourceExternalSecret_TokenType.FILE- )}- disabled={!allowEdit}- >- {t(- "instance.external-secret-vault.vault-auth-type.token.type-file"- )}- </RadioGroupItem>- </RadioGroup>- )}- <Input- value={- dataSource.externalSecret.authOption- ?.case === "token"- ? (dataSource.externalSecret- .authOption.value as string)- : ""- }- className="w-full"- disabled={!allowEdit}- placeholder={tokenPlaceholder}- onChange={(e) => {- const ds = { ...dataSource };- ds.externalSecret = {- ...ds.externalSecret!,- authOption: {- case: "token" as const,- value: e.target.value,- },- };- onDataSourceChange(ds);- }}- />- </FormField>- );- })()}- {/* AppRole fields */}- {dataSource.externalSecret.authOption?.case ===- "appRole" && (- <div className="flex flex-col gap-y-4">- <FormField- title={- <>- {t(- "instance.external-secret-vault.vault-auth-type.approle.role-id"- )}{" "}- <span className="text-error">*</span>- </>- }- >- <Input- value={- dataSource.externalSecret.authOption- .value.roleId ?? ""- }- className="w-full"- disabled={!allowEdit}- placeholder={`${t("instance.external-secret-vault.vault-auth-type.approle.role-id")} - ${t("common.write-only")}`}- onChange={(e) => {- const ds = { ...dataSource };- if (- ds.externalSecret?.authOption- ?.case === "appRole"- ) {- ds.externalSecret = {- ...ds.externalSecret,- authOption: {- ...ds.externalSecret.authOption,- value: {- ...ds.externalSecret.authOption- .value,- roleId: e.target.value,- },- },- };- }- onDataSourceChange(ds);- }}- />- </FormField>- <FormField- title={- <>- {t(- "instance.external-secret-vault.vault-auth-type.approle.secret-id"- )}{" "}- <span className="text-error">*</span>- </>- }- >- {/* Environment secret id reads from the host,- which is disallowed in SaaS mode; only plain- is offered there. */}- {!isSaaSMode && (- <RadioGroup- className="textlabel my-1 gap-x-4"- value={String(- dataSource.externalSecret.authOption- .value.type- )}- onValueChange={(value) => {- const ds = { ...dataSource };- if (- ds.externalSecret?.authOption- ?.case === "appRole"- ) {- ds.externalSecret = {- ...ds.externalSecret,- authOption: {- ...ds.externalSecret.authOption,- value: {- ...ds.externalSecret- .authOption.value,- type: Number(- value- ) as DataSourceExternalSecret_AppRoleAuthOption_SecretType,- },- },- };- }- onDataSourceChange(ds);- }}- >- <RadioGroupItem- value={String(- DataSourceExternalSecret_AppRoleAuthOption_SecretType.PLAIN- )}- disabled={!allowEdit}- >- {t(- "instance.external-secret-vault.vault-auth-type.approle.secret-plain-text"- )}- </RadioGroupItem>- <RadioGroupItem- value={String(- DataSourceExternalSecret_AppRoleAuthOption_SecretType.ENVIRONMENT- )}- disabled={!allowEdit}- >- {t(- "instance.external-secret-vault.vault-auth-type.approle.secret-env-name"- )}- </RadioGroupItem>- </RadioGroup>- )}- <Input- value={- dataSource.externalSecret.authOption- .value.secretId ?? ""- }- className="mt-2 w-full"- disabled={!allowEdit}- onChange={(e) => {- const ds = { ...dataSource };- if (- ds.externalSecret?.authOption- ?.case === "appRole"- ) {- ds.externalSecret = {- ...ds.externalSecret,- authOption: {- ...ds.externalSecret.authOption,- value: {- ...ds.externalSecret.authOption- .value,- secretId: e.target.value,- },- },- };- }- onDataSourceChange(ds);- }}- />- </FormField>- </div>- )}- {/* Vault TLS config */}- <FormField- title={- <>- {t(- "instance.external-secret-vault.vault-tls-config"- )}- </>- }- >- <SslCertificateForm- verify={- !dataSource.externalSecret- .skipVaultTlsVerification- }- onVerifyChange={(val) => {- const ds = { ...dataSource };- ds.externalSecret = {- ...ds.externalSecret!,- skipVaultTlsVerification: !val,- };- onDataSourceChange(ds);- }}- ca={dataSource.externalSecret.vaultSslCa}- onCaChange={(val) => {- const ds = { ...dataSource };- ds.externalSecret = {- ...ds.externalSecret!,- vaultSslCa: val,- };- onDataSourceChange(ds);- }}- cert={dataSource.externalSecret.vaultSslCert}- onCertChange={(val) => {- const ds = { ...dataSource };- ds.externalSecret = {- ...ds.externalSecret!,- vaultSslCert: val,- };- onDataSourceChange(ds);- }}- sslKey={dataSource.externalSecret.vaultSslKey}- onKeyChange={(val) => {- const ds = { ...dataSource };- ds.externalSecret = {- ...ds.externalSecret!,- vaultSslKey: val,- };- onDataSourceChange(ds);- }}- disabled={!allowEdit}- showKeyAndCert- />- </FormField>- {/* Engine name */}- <FormField- title={- <>- {t(- "instance.external-secret-vault.vault-secret-engine-name"- )}{" "}- <span className="text-error">*</span>- </>- }- description={- <>- {t(- "instance.external-secret-vault.vault-secret-engine-tips"- )}- </>+ onDataSourceChange(updated);+ }}+ />+ <span className="shrink-0 whitespace-nowrap text-sm leading-5 text-control-light">+ /+ </span>+ <Input+ className="min-w-0 flex-1"+ value={+ dataSource.saslConfig.mechanism.value+ .instance ?? ""}- >- <Input- value={- dataSource.externalSecret.engineName ?? ""+ disabled={!allowEdit}+ placeholder={t(+ "instance.kerberos-instance-placeholder"+ )}+ onChange={(e) => {+ const updated = { ...dataSource };+ if (+ updated.saslConfig?.mechanism?.case ===+ "krbConfig"+ ) {+ updated.saslConfig.mechanism.value.instance =+ e.target.value;}- required- className="w-full"- disabled={!allowEdit}- placeholder={t(- "instance.external-secret-vault.vault-secret-engine-name"- )}- onChange={(e) => {- const ds = { ...dataSource };- ds.externalSecret = {- ...ds.externalSecret!,- engineName: e.target.value,- };- onDataSourceChange(ds);- }}- />- </FormField>- </div>- )}-- {/* Azure Key Vault URL */}- {passwordType ===- DataSourceExternalSecret_SecretType.AZURE_KEY_VAULT && (- <FormField- title={- <>- {t(- "instance.external-secret-azure.vault-url"- )}{" "}- <span className="text-error">*</span>- </>- }- description={- <>- {t(- "instance.external-secret-azure.vault-url-tips"- )}- </>- }- >+ onDataSourceChange(updated);+ }}+ />+ <span className="shrink-0 whitespace-nowrap text-sm leading-5 text-control-light">+ @+ </span><Input- value={dataSource.externalSecret.url ?? ""}- required- className="w-full"+ className="min-w-0 flex-1"+ value={+ dataSource.saslConfig.mechanism.value.realm ??+ ""+ }disabled={!allowEdit}placeholder={t(- "instance.external-secret-azure.vault-url"+ "instance.kerberos-realm-placeholder")}onChange={(e) => {- const ds = { ...dataSource };- ds.externalSecret = {- ...ds.externalSecret!,- url: e.target.value,- };- onDataSourceChange(ds);+ const updated = { ...dataSource };+ if (+ updated.saslConfig?.mechanism?.case ===+ "krbConfig"+ ) {+ updated.saslConfig.mechanism.value.realm =+ e.target.value;+ }+ onDataSourceChange(updated);}}/>- </FormField>- )}-- {/* Secret name (common) */}+ </FormControlRow>+ </FormField><FormFieldtitle={<>- {secretNameLabel}{" "}+ {t("instance.kerberos-kdc")}{" "}<span className="text-error">*</span></>}- description={secretNameDescription}>- <Input- value={dataSource.externalSecret.secretName ?? ""}- required- className="w-full"- disabled={!allowEdit}- placeholder={secretNameLabel}- onChange={(e) => {- const ds = { ...dataSource };- ds.externalSecret = {- ...ds.externalSecret!,- secretName: e.target.value,- };- onDataSourceChange(ds);- }}- />- </FormField>-- {/* Secret key (not for GCP/Azure) */}- {passwordType !==- DataSourceExternalSecret_SecretType.GCP_SECRET_MANAGER &&- passwordType !==- DataSourceExternalSecret_SecretType.AZURE_KEY_VAULT && (- <FormField- title={- <>- {secretKeyLabel}{" "}- <span className="text-error">*</span>- </>+ <FormControlRow>+ <RadioGroup+ className="w-fit textlabel gap-x-3"+ value={+ dataSource.saslConfig?.mechanism?.value+ ?.kdcTransportProtocol ?? ""}+ onValueChange={(proto) => {+ const updated = { ...dataSource };+ if (+ updated.saslConfig?.mechanism?.case ===+ "krbConfig"+ ) {+ updated.saslConfig.mechanism.value.kdcTransportProtocol =+ String(proto);+ }+ onDataSourceChange(updated);+ }}>- <Input- value={- dataSource.externalSecret.passwordKeyName ??- ""+ {["tcp", "udp"].map((proto) => (+ <RadioGroupItem+ key={proto}+ value={proto}+ disabled={!allowEdit}+ >+ {proto.toUpperCase()}+ </RadioGroupItem>+ ))}+ </RadioGroup>+ <Input+ className="min-w-0 flex-1"+ value={+ dataSource.saslConfig.mechanism.value+ .kdcHost ?? ""+ }+ disabled={!allowEdit}+ placeholder={t(+ "instance.kerberos-kdc-host-placeholder"+ )}+ onChange={(e) => {+ const updated = { ...dataSource };+ if (+ updated.saslConfig?.mechanism?.case ===+ "krbConfig"+ ) {+ updated.saslConfig.mechanism.value.kdcHost =+ e.target.value;}- required- className="w-full"- disabled={!allowEdit}- placeholder={secretKeyLabel}- onChange={(e) => {- const ds = { ...dataSource };- ds.externalSecret = {- ...ds.externalSecret!,- passwordKeyName: e.target.value,- };- onDataSourceChange(ds);- }}- />- </FormField>- )}- </div>- )}-- {/* Redis Sentinel fields */}- {basicInfo.engine === Engine.REDIS &&- dataSource.redisType ===- DataSource_RedisType.SENTINEL && (- <>+ onDataSourceChange(updated);+ }}+ />+ <span className="shrink-0 whitespace-nowrap text-sm leading-5 text-control-light">+ :+ </span>+ <Input+ className="min-w-0 flex-1"+ value={+ dataSource.saslConfig.mechanism.value+ .kdcPort ?? ""+ }+ disabled={!allowEdit}+ placeholder={t(+ "instance.kerberos-kdc-port-placeholder"+ )}+ onChange={(e) => {+ if (+ e.target.value &&+ !onlyAllowNumber(e.target.value)+ )+ return;+ const updated = { ...dataSource };+ if (+ updated.saslConfig?.mechanism?.case ===+ "krbConfig"+ ) {+ updated.saslConfig.mechanism.value.kdcPort =+ e.target.value;+ }+ onDataSourceChange(updated);+ }}+ />+ </FormControlRow>+ </FormField><FormFieldtitle={<>- Master Name{" "}- <span className="text-error">*</span>+ {t("instance.keytab-file")}+ {(dataSource.pendingCreate ||+ keytabResupplyRequired) && (+ <>+ {" "}+ <span className="text-error">*</span>+ </>+ )}</>}>- <Input- value={dataSource.masterName ?? ""}- className="w-full"- disabled={!allowEdit}- onChange={(e) =>- update({ masterName: e.target.value })- }- />+ <div+ className={cn(+ "mt-3 border-2 border-dashed rounded-sm p-6 text-center",+ keytabResupplyRequired && "border-error"+ )}+ >+ <input+ type="file"+ accept=".keytab"+ className="hidden"+ id="keytab-upload"+ onChange={handleKeytabUpload}+ />+ <label+ htmlFor="keytab-upload"+ className="cursor-pointer textinfolabel"+ >+ {t("instance.keytab-upload-placeholder")}+ </label>+ {keytabFileName && (+ <p className="mt-2 textinfolabel truncate">+ {keytabFileName}+ </p>+ )}+ </div>+ {/* The write-only hint offers to keep the stored keytab,+ which is the offer the resupply error withdraws. */}+ {!dataSource.pendingCreate &&+ !keytabResupplyRequired && (+ <p className="mt-1 textinfolabel">+ {t("instance.keytab-write-only")}+ </p>+ )}+ {keytabResupplyRequired && (+ <FormError className="mt-1">+ {t("instance.keytab-resupply-required")}+ </FormError>+ )}</FormField>- <FormField title={<>Master Username</>}>- <Input- value={dataSource.masterUsername ?? ""}- className="w-full"- disabled={!allowEdit}- onChange={(e) =>- update({ masterUsername: e.target.value })- }+ </fieldset>+ </ResponsiveFormLayout>+ </FormField>+ )}++ {/* Username field (non-Kerberos, non-Azure IAM) */}+ {dataSource.saslConfig?.mechanism?.case !== "krbConfig" &&+ !isAzureIAM && (+ <FormField+ className="sm:col-span-3 sm:col-start-1"+ title={+ <span className="flex items-center gap-x-1">+ {t("common.username")}+ {onOpenInfoPanel && hasAuthenticationInfo && (+ <button+ type="button"+ className="inline-flex cursor-pointer items-center gap-x-0.5 text-accent text-xs"+ onClick={() =>+ onOpenInfoPanel("authentication")+ }+ >+ <Info className="size-3.5" />+ </button>+ )}+ </span>+ }+ >+ <Input+ aria-label={t("common.username")}+ value={dataSource.username}+ className="w-full"+ disabled={!allowEdit}+ placeholder={+ basicInfo.engine === Engine.CLICKHOUSE+ ? t("common.default")+ : ""+ }+ onChange={(e) => update({ username: e.target.value })}+ />+ </FormField>+ )}++ {/* IAM-specific configuration */}+ {isIAM && (+ <FormField+ className="sm:col-span-3 sm:col-start-1"+ title={+ supportedAuthenticationTypes.find(+ (item) => item.value === dataSource.authenticationType+ )?.label+ }+ >+ <ResponsiveFormLayout>+ <fieldset+ aria-label={t(+ "instance.iam-extension.credential-source"+ )}+ className="flex flex-col gap-4 rounded-xs border border-control-border px-3 py-2"+ >+ <CredentialSourceForm+ dataSource={dataSource}+ engine={basicInfo.engine}+ allowEdit={allowEdit}+ onDataSourceChange={update}+ />+ {isAwsIAM && (+ <AwsRegionField+ region={dataSource.region ?? ""}+ required+ allowEdit={allowEdit}+ onChange={(region) => update({ region })}/>- </FormField>- <FormField title={<>Master Password</>}>+ )}+ </fieldset>+ </ResponsiveFormLayout>+ </FormField>+ )}++ {/* Password / External Secret */}+ {isPasswordAuth &&+ dataSource.saslConfig?.mechanism?.case !== "krbConfig" && (+ <div className="sm:col-span-3 sm:col-start-1">+ {/* Plain password */}+ {passwordType ===+ DataSourceExternalSecret_SecretType.SECRET_TYPE_UNSPECIFIED && (+ <FormField title={<>{t("common.password")}</>}><div>{!isCreating && allowUsingEmptyPassword && (<label className="flex items-center gap-x-1.5 mb-2 text-sm cursor-pointer"><Checkboxchecked={- dataSource.useEmptyMasterPassword ?? false+ dataSource.useEmptyPassword ?? false}disabled={!allowEdit}- onCheckedChange={(checked) => {- update({- useEmptyMasterPassword: checked,- updatedMasterPassword: checked- ? ""- : dataSource.updatedMasterPassword,- });- }}+ onCheckedChange={(checked) =>+ toggleUseEmptyPassword(checked)+ }/>{t("instance.no-password")}</label>)}- <Input- type="password"- className="w-full"- autoComplete="off"- placeholder={- dataSource.useEmptyMasterPassword- ? t("instance.no-password")- : t("instance.password-write-only")- }- disabled={- !allowEdit ||- !!dataSource.useEmptyMasterPassword- }- value={- dataSource.useEmptyMasterPassword- ? ""- : dataSource.updatedMasterPassword- }- onChange={(e) =>- update({- updatedMasterPassword:- e.target.value.trim(),- })+ <div className="flex flex-col gap-2">+ {passwordSourceControl}+ <Input+ type="password"+ className="min-w-40 flex-1"+ autoComplete="off"+ placeholder={+ dataSource.useEmptyPassword+ ? t("instance.no-password")+ : t("instance.password-write-only")+ }+ disabled={+ !allowEdit || !!dataSource.useEmptyPassword+ }+ value={+ dataSource.useEmptyPassword+ ? ""+ : dataSource.updatedPassword+ }+ onChange={(e) =>+ update({+ updatedPassword: e.target.value.trim(),+ })+ }+ />+ </div>+ <p className="text-xs leading-4 text-control-light">+ {t(+ "instance.password-source.stored-in-bytebase"+ )}+ </p>+ </div>+ </FormField>+ )}++ {/* External secret fields */}+ {passwordType !==+ DataSourceExternalSecret_SecretType.SECRET_TYPE_UNSPECIFIED &&+ dataSource.externalSecret && (+ <div className="flex flex-col gap-y-4">+ <FormField+ title={+ passwordSourceOptions.find(+ (item) => item.value === passwordType+ )?.label}- />+ >+ <div className="flex flex-wrap items-center gap-2">+ {passwordSourceControl}+ <LearnMoreLink+ href="https://docs.bytebase.com/get-started/connect/overview#secret-manager-integration"+ className="text-sm text-accent"+ />+ </div>+ <ResponsiveFormLayout className="mt-2">+ <fieldset+ className="flex flex-col gap-4 rounded-xs border border-control-border px-3 py-2"+ aria-label={t(+ "instance.password-source.self"+ )}+ >+ {/* Vault KV V2 */}+ {passwordType ===+ DataSourceExternalSecret_SecretType.VAULT_KV_V2 && (+ <div className="flex flex-col gap-y-4">+ <FormField+ title={+ <>+ {t(+ "instance.external-secret-vault.vault-url"+ )}{" "}+ <span className="text-error">+ *+ </span>+ </>+ }+ >+ <Input+ value={+ dataSource.externalSecret.url ??+ ""+ }+ required+ className="w-full"+ disabled={!allowEdit}+ placeholder={t(+ "instance.external-secret-vault.vault-url"+ )}+ onChange={(e) => {+ const ds = { ...dataSource };+ ds.externalSecret = {+ ...ds.externalSecret!,+ url: e.target.value,+ };+ onDataSourceChange(ds);+ }}+ />+ </FormField>+ <FormField+ title={+ <>+ {t(+ "instance.external-secret-vault.vault-auth-type.self"+ )}+ </>+ }+ >+ <RadioGroup+ className="textlabel gap-x-4"+ value={String(+ dataSource.externalSecret.authType+ )}+ onValueChange={(value) =>+ changeExternalSecretAuthType(+ Number(+ value+ ) as DataSourceExternalSecret_AuthType+ )+ }+ >+ <RadioGroupItem+ value={String(+ DataSourceExternalSecret_AuthType.TOKEN+ )}+ >+ {t(+ "instance.external-secret-vault.vault-auth-type.token.self"+ )}+ </RadioGroupItem>+ <RadioGroupItem+ value={String(+ DataSourceExternalSecret_AuthType.VAULT_APP_ROLE+ )}+ >+ {t(+ "instance.external-secret-vault.vault-auth-type.approle.self"+ )}+ </RadioGroupItem>+ </RadioGroup>+ </FormField>+ {/* Token input */}+ {dataSource.externalSecret.authType ===+ DataSourceExternalSecret_AuthType.TOKEN &&+ (() => {+ const tokenType =+ dataSource.externalSecret+ .tokenType ===+ DataSourceExternalSecret_TokenType.ENVIRONMENT ||+ dataSource.externalSecret+ .tokenType ===+ DataSourceExternalSecret_TokenType.FILE+ ? dataSource.externalSecret+ .tokenType+ : DataSourceExternalSecret_TokenType.PLAIN;+ const changeTokenType = (+ type: DataSourceExternalSecret_TokenType+ ) => {+ const ds = { ...dataSource };+ ds.externalSecret = {+ ...ds.externalSecret!,+ tokenType: type,+ };+ onDataSourceChange(ds);+ };+ const tokenLabel = t(+ "instance.external-secret-vault.vault-auth-type.token.self"+ );+ let tokenPlaceholder = `${tokenLabel} - ${t("common.write-only")}`;+ if (+ tokenType ===+ DataSourceExternalSecret_TokenType.ENVIRONMENT+ ) {+ tokenPlaceholder = t(+ "instance.external-secret-vault.vault-auth-type.token.env-name"+ );+ } else if (+ tokenType ===+ DataSourceExternalSecret_TokenType.FILE+ ) {+ tokenPlaceholder = t(+ "instance.external-secret-vault.vault-auth-type.token.file-path"+ );+ }+ return (+ <FormField+ title={+ <>+ {tokenLabel}{" "}+ <span className="text-error">+ *+ </span>+ </>+ }+ >+ {/* Token source is host-backed for env/file,+ which is disallowed in SaaS mode; only+ plain is offered there. */}+ {!isSaaSMode && (+ <RadioGroup+ className="textlabel my-1 gap-x-4"+ value={String(tokenType)}+ onValueChange={(value) =>+ changeTokenType(+ Number(+ value+ ) as DataSourceExternalSecret_TokenType+ )+ }+ >+ <RadioGroupItem+ value={String(+ DataSourceExternalSecret_TokenType.PLAIN+ )}+ disabled={!allowEdit}+ >+ {t(+ "instance.external-secret-vault.vault-auth-type.token.type-plain"+ )}+ </RadioGroupItem>+ <RadioGroupItem+ value={String(+ DataSourceExternalSecret_TokenType.ENVIRONMENT+ )}+ disabled={!allowEdit}+ >+ {t(+ "instance.external-secret-vault.vault-auth-type.token.type-environment"+ )}+ </RadioGroupItem>+ <RadioGroupItem+ value={String(+ DataSourceExternalSecret_TokenType.FILE+ )}+ disabled={!allowEdit}+ >+ {t(+ "instance.external-secret-vault.vault-auth-type.token.type-file"+ )}+ </RadioGroupItem>+ </RadioGroup>+ )}+ <Input+ value={+ dataSource.externalSecret+ .authOption?.case ===+ "token"+ ? (dataSource+ .externalSecret+ .authOption+ .value as string)+ : ""+ }+ className="w-full"+ disabled={!allowEdit}+ placeholder={tokenPlaceholder}+ onChange={(e) => {+ const ds = {+ ...dataSource,+ };+ ds.externalSecret = {+ ...ds.externalSecret!,+ authOption: {+ case: "token" as const,+ value: e.target.value,+ },+ };+ onDataSourceChange(ds);+ }}+ />+ </FormField>+ );+ })()}+ {/* AppRole fields */}+ {dataSource.externalSecret.authOption+ ?.case === "appRole" && (+ <div className="flex flex-col gap-y-4">+ <FormField+ title={+ <>+ {t(+ "instance.external-secret-vault.vault-auth-type.approle.role-id"+ )}{" "}+ <span className="text-error">+ *+ </span>+ </>+ }+ >+ <Input+ value={+ dataSource.externalSecret+ .authOption.value.roleId ??+ ""+ }+ className="w-full"+ disabled={!allowEdit}+ placeholder={`${t("instance.external-secret-vault.vault-auth-type.approle.role-id")} - ${t("common.write-only")}`}+ onChange={(e) => {+ const ds = { ...dataSource };+ if (+ ds.externalSecret+ ?.authOption?.case ===+ "appRole"+ ) {+ ds.externalSecret = {+ ...ds.externalSecret,+ authOption: {+ ...ds.externalSecret+ .authOption,+ value: {+ ...ds.externalSecret+ .authOption.value,+ roleId:+ e.target.value,+ },+ },+ };+ }+ onDataSourceChange(ds);+ }}+ />+ </FormField>+ <FormField+ title={+ <>+ {t(+ "instance.external-secret-vault.vault-auth-type.approle.secret-id"+ )}{" "}+ <span className="text-error">+ *+ </span>+ </>+ }+ >+ {/* Environment secret id reads from the host,+ which is disallowed in SaaS mode; only plain+ is offered there. */}+ {!isSaaSMode && (+ <RadioGroup+ className="textlabel my-1 gap-x-4"+ value={String(+ dataSource.externalSecret+ .authOption.value.type+ )}+ onValueChange={(value) => {+ const ds = {+ ...dataSource,+ };+ if (+ ds.externalSecret+ ?.authOption?.case ===+ "appRole"+ ) {+ ds.externalSecret = {+ ...ds.externalSecret,+ authOption: {+ ...ds.externalSecret+ .authOption,+ value: {+ ...ds.externalSecret+ .authOption.value,+ type: Number(+ value+ ) as DataSourceExternalSecret_AppRoleAuthOption_SecretType,+ },+ },+ };+ }+ onDataSourceChange(ds);+ }}+ >+ <RadioGroupItem+ value={String(+ DataSourceExternalSecret_AppRoleAuthOption_SecretType.PLAIN+ )}+ disabled={!allowEdit}+ >+ {t(+ "instance.external-secret-vault.vault-auth-type.approle.secret-plain-text"+ )}+ </RadioGroupItem>+ <RadioGroupItem+ value={String(+ DataSourceExternalSecret_AppRoleAuthOption_SecretType.ENVIRONMENT+ )}+ disabled={!allowEdit}+ >+ {t(+ "instance.external-secret-vault.vault-auth-type.approle.secret-env-name"+ )}+ </RadioGroupItem>+ </RadioGroup>+ )}+ <Input+ value={+ dataSource.externalSecret+ .authOption.value+ .secretId ?? ""+ }+ className="mt-2 w-full"+ disabled={!allowEdit}+ onChange={(e) => {+ const ds = { ...dataSource };+ if (+ ds.externalSecret+ ?.authOption?.case ===+ "appRole"+ ) {+ ds.externalSecret = {+ ...ds.externalSecret,+ authOption: {+ ...ds.externalSecret+ .authOption,+ value: {+ ...ds.externalSecret+ .authOption.value,+ secretId:+ e.target.value,+ },+ },+ };+ }+ onDataSourceChange(ds);+ }}+ />+ </FormField>+ </div>+ )}+ {/* Vault TLS config */}+ <FormField+ title={+ <>+ {t(+ "instance.external-secret-vault.vault-tls-config"+ )}+ </>+ }+ >+ <SslCertificateForm+ verify={+ !dataSource.externalSecret+ .skipVaultTlsVerification+ }+ onVerifyChange={(val) => {+ const ds = { ...dataSource };+ ds.externalSecret = {+ ...ds.externalSecret!,+ skipVaultTlsVerification: !val,+ };+ onDataSourceChange(ds);+ }}+ ca={+ dataSource.externalSecret+ .vaultSslCa+ }+ onCaChange={(val) => {+ const ds = { ...dataSource };+ ds.externalSecret = {+ ...ds.externalSecret!,+ vaultSslCa: val,+ };+ onDataSourceChange(ds);+ }}+ cert={+ dataSource.externalSecret+ .vaultSslCert+ }+ onCertChange={(val) => {+ const ds = { ...dataSource };+ ds.externalSecret = {+ ...ds.externalSecret!,+ vaultSslCert: val,+ };+ onDataSourceChange(ds);+ }}+ sslKey={+ dataSource.externalSecret+ .vaultSslKey+ }+ onKeyChange={(val) => {+ const ds = { ...dataSource };+ ds.externalSecret = {+ ...ds.externalSecret!,+ vaultSslKey: val,+ };+ onDataSourceChange(ds);+ }}+ disabled={!allowEdit}+ showKeyAndCert+ />+ </FormField>+ {/* Engine name */}+ <FormField+ title={+ <>+ {t(+ "instance.external-secret-vault.vault-secret-engine-name"+ )}{" "}+ <span className="text-error">+ *+ </span>+ </>+ }+ description={+ <>+ {t(+ "instance.external-secret-vault.vault-secret-engine-tips"+ )}+ </>+ }+ >+ <Input+ value={+ dataSource.externalSecret+ .engineName ?? ""+ }+ required+ className="w-full"+ disabled={!allowEdit}+ placeholder={t(+ "instance.external-secret-vault.vault-secret-engine-name"+ )}+ onChange={(e) => {+ const ds = { ...dataSource };+ ds.externalSecret = {+ ...ds.externalSecret!,+ engineName: e.target.value,+ };+ onDataSourceChange(ds);+ }}+ />+ </FormField>+ </div>+ )}++ {/* Azure Key Vault URL */}+ {passwordType ===+ DataSourceExternalSecret_SecretType.AZURE_KEY_VAULT && (+ <FormField+ title={+ <>+ {t(+ "instance.external-secret-azure.vault-url"+ )}{" "}+ <span className="text-error">+ *+ </span>+ </>+ }+ description={+ <>+ {t(+ "instance.external-secret-azure.vault-url-tips"+ )}+ </>+ }+ >+ <Input+ value={+ dataSource.externalSecret.url ?? ""+ }+ required+ className="w-full"+ disabled={!allowEdit}+ placeholder={t(+ "instance.external-secret-azure.vault-url"+ )}+ onChange={(e) => {+ const ds = { ...dataSource };+ ds.externalSecret = {+ ...ds.externalSecret!,+ url: e.target.value,+ };+ onDataSourceChange(ds);+ }}+ />+ </FormField>+ )}++ {/* Secret name (common) */}+ <FormField+ title={+ <>+ {secretNameLabel}{" "}+ <span className="text-error">*</span>+ </>+ }+ description={secretNameDescription}+ >+ <Input+ value={+ dataSource.externalSecret+ .secretName ?? ""+ }+ required+ className="w-full"+ disabled={!allowEdit}+ placeholder={secretNameLabel}+ onChange={(e) => {+ const ds = { ...dataSource };+ ds.externalSecret = {+ ...ds.externalSecret!,+ secretName: e.target.value,+ };+ onDataSourceChange(ds);+ }}+ />+ </FormField>++ {/* Secret key (not for GCP/Azure) */}+ {passwordType !==+ DataSourceExternalSecret_SecretType.GCP_SECRET_MANAGER &&+ passwordType !==+ DataSourceExternalSecret_SecretType.AZURE_KEY_VAULT && (+ <FormField+ title={+ <>+ {secretKeyLabel}{" "}+ <span className="text-error">+ *+ </span>+ </>+ }+ >+ <Input+ value={+ dataSource.externalSecret+ .passwordKeyName ?? ""+ }+ required+ className="w-full"+ disabled={!allowEdit}+ placeholder={secretKeyLabel}+ onChange={(e) => {+ const ds = { ...dataSource };+ ds.externalSecret = {+ ...ds.externalSecret!,+ passwordKeyName: e.target.value,+ };+ onDataSourceChange(ds);+ }}+ />+ </FormField>+ )}+ </fieldset>+ </ResponsiveFormLayout>+ </FormField></div>- </FormField>- </>- )}- </div>- )}- </>- )}+ )}+ </div>+ )}+ </>+ )}- {/* Spanner/BigQuery auth */}- {(basicInfo.engine === Engine.SPANNER ||- basicInfo.engine === Engine.BIGQUERY) && (- <>- <RadioGroup- className="sm:col-span-3 sm:col-start-1 textlabel gap-x-4"- value={String(dataSource.authenticationType)}- onValueChange={(value) =>- update({- authenticationType: Number(- value- ) as DataSource_AuthenticationType,- })- }- >- {supportedAuthenticationTypes.map((item) => (- <RadioGroupItem- key={item.value}- value={String(item.value)}- disabled={!allowEdit}+ {/* Spanner/BigQuery auth */}+ {(basicInfo.engine === Engine.SPANNER ||+ basicInfo.engine === Engine.BIGQUERY) && (+ <>+ <RadioGroup+ className="sm:col-span-3 sm:col-start-1 textlabel gap-x-4"+ value={String(dataSource.authenticationType)}+ onValueChange={(value) =>+ update({+ authenticationType: Number(+ value+ ) as DataSource_AuthenticationType,+ })+ }>- {item.label}- </RadioGroupItem>- ))}- </RadioGroup>- <CredentialSourceForm- dataSource={dataSource}- engine={basicInfo.engine}- allowEdit={allowEdit}- onDataSourceChange={update}- />- </>- )}-- {/* DynamoDB AWS IAM credentials */}- {basicInfo.engine === Engine.DYNAMODB && (- <>- <CredentialSourceForm- dataSource={dynamoDBDataSource}- engine={basicInfo.engine}- allowEdit={allowEdit}- onDataSourceChange={updateDynamoDB}- />- <AwsRegionField- region={dataSource.region ?? ""}- required={dataSource.iamExtension?.case === "awsCredential"}- allowEdit={allowEdit}- onChange={(region) => updateDynamoDB({ region })}- />- </>- )}-- {/* Oracle SID/Service Name */}- {basicInfo.engine === Engine.ORACLE && (- <OracleSIDServiceNameInput- sid={dataSource.sid ?? ""}- serviceName={dataSource.serviceName ?? ""}- allowEdit={allowEdit}- onSidChange={(val) => update({ sid: val })}- onServiceNameChange={(val) => update({ serviceName: val })}- />- )}+ {supportedAuthenticationTypes.map((item) => (+ <RadioGroupItem+ key={item.value}+ value={String(item.value)}+ disabled={!allowEdit}+ >+ {item.label}+ </RadioGroupItem>+ ))}+ </RadioGroup>+ <CredentialSourceForm+ dataSource={dataSource}+ engine={basicInfo.engine}+ allowEdit={allowEdit}+ onDataSourceChange={update}+ />+ </>+ )}- {/* Snowflake keypair */}- {basicInfo.engine === Engine.SNOWFLAKE && (- <>- <FormField- className="sm:col-span-3 sm:col-start-1"- title={<>{t("data-source.ssh.private-key")}</>}- >- <div className="flex gap-x-2 text-sm">- <span className="textinfolabel">- {t("data-source.snowflake-keypair-tip")}- </span>- <LearnMoreLink- href="https://docs.snowflake.com/en/user-guide/key-pair-auth"- className="text-sm text-accent"+ {/* DynamoDB AWS IAM credentials */}+ {basicInfo.engine === Engine.DYNAMODB && (+ <>+ <CredentialSourceForm+ dataSource={dynamoDBDataSource}+ engine={basicInfo.engine}+ allowEdit={allowEdit}+ onDataSourceChange={updateDynamoDB}/>- </div>- <textarea- value={dataSource.authenticationPrivateKey ?? ""}- disabled={!allowEdit}- className="w-full h-32 whitespace-pre-wrap rounded-sm border border-control-border p-2 text-sm font-mono"- placeholder={`-----BEGIN PRIVATE KEY-----\nMIIEvQ...\n-----END PRIVATE KEY-----`}- onChange={(e) =>- update({ authenticationPrivateKey: e.target.value })- }- />- </FormField>- <FormField- className="sm:col-span-3 sm:col-start-1"- title={<>{t("data-source.private-key-passphrase")}</>}- description={<>{t("data-source.private-key-passphrase-tip")}</>}- >- <Input- value={dataSource.authenticationPrivateKeyPassphrase ?? ""}- type="password"- className="w-full"- disabled={!allowEdit}- placeholder={t(- "data-source.private-key-passphrase-placeholder"- )}- onChange={(e) =>- update({- authenticationPrivateKeyPassphrase: e.target.value,- })- }- />- </FormField>- </>- )}+ <AwsRegionField+ region={dataSource.region ?? ""}+ required={dataSource.iamExtension?.case === "awsCredential"}+ allowEdit={allowEdit}+ onChange={(region) => updateDynamoDB({ region })}+ />+ </>+ )}- {/* Databricks */}- {basicInfo.engine === Engine.DATABRICKS && (- <>- <FormField- title={- <>- Warehouse ID <span className="text-error">*</span>- </>- }- >- <Input- value={dataSource.warehouseId ?? ""}- disabled={!allowEdit}- onChange={(e) => update({ warehouseId: e.target.value })}- />- </FormField>- <FormField- title={- <>- Token <span className="text-error">*</span>- </>- }- >- <Input- type="password"- value={dataSource.updatedToken}- className="w-full"- autoComplete="off"- disabled={!allowEdit}- placeholder={- isCreating- ? "personal access token"- : t("instance.token-write-only")- }- onChange={(e) =>- update({ updatedToken: e.target.value.trim() })- }+ {/* Oracle SID/Service Name */}+ {basicInfo.engine === Engine.ORACLE && (+ <OracleSIDServiceNameInput+ sid={dataSource.sid ?? ""}+ serviceName={dataSource.serviceName ?? ""}+ allowEdit={allowEdit}+ onSidChange={(val) => update({ sid: val })}+ onServiceNameChange={(val) => update({ serviceName: val })}/>- </FormField>- </>- )}-- {/* MongoDB authentication database */}- {showAuthenticationDatabase && (- <FormField- className="sm:col-span-3 sm:col-start-1"- title={<>{t("instance.authentication-database")}</>}- >- <Input- className="w-full"- autoComplete="off"- placeholder="admin"- disabled={!allowEdit}- value={dataSource.authenticationDatabase ?? ""}- onChange={(e) =>- update({ authenticationDatabase: e.target.value.trim() })- }- />- </FormField>- )}+ )}- {/* Read-only replica host/port */}- {dataSource.type === DataSourceType.READ_ONLY &&- (hasReadonlyReplicaHost || hasReadonlyReplicaPort) && (- <>- {hasReadonlyReplicaHost && (+ {/* Snowflake keypair */}+ {basicInfo.engine === Engine.SNOWFLAKE && (+ <>+ <FormField+ className="sm:col-span-3 sm:col-start-1"+ title={<>{t("data-source.ssh.private-key")}</>}+ >+ <div className="flex gap-x-2 text-sm">+ <span className="textinfolabel">+ {t("data-source.snowflake-keypair-tip")}+ </span>+ <LearnMoreLink+ href="https://docs.snowflake.com/en/user-guide/key-pair-auth"+ className="text-sm text-accent"+ />+ </div>+ <textarea+ value={dataSource.authenticationPrivateKey ?? ""}+ disabled={!allowEdit}+ className="w-full h-32 whitespace-pre-wrap rounded-sm border border-control-border p-2 text-sm font-mono"+ placeholder={`-----BEGIN PRIVATE KEY-----\nMIIEvQ...\n-----END PRIVATE KEY-----`}+ onChange={(e) =>+ update({ authenticationPrivateKey: e.target.value })+ }+ />+ </FormField><FormFieldclassName="sm:col-span-3 sm:col-start-1"- title={<>{t("data-source.read-replica-host")}</>}+ title={<>{t("data-source.private-key-passphrase")}</>}+ description={+ <>{t("data-source.private-key-passphrase-tip")}</>+ }><Input+ value={+ dataSource.authenticationPrivateKeyPassphrase ?? ""+ }+ type="password"className="w-full"- autoComplete="off"- value={dataSource.host}disabled={!allowEdit}- onChange={(e) => handleHostInput(e.target.value)}+ placeholder={t(+ "data-source.private-key-passphrase-placeholder"+ )}+ onChange={(e) =>+ update({+ authenticationPrivateKeyPassphrase: e.target.value,+ })+ }+ />+ </FormField>+ </>+ )}++ {/* Databricks */}+ {basicInfo.engine === Engine.DATABRICKS && (+ <>+ <FormField+ title={+ <>+ Warehouse ID <span className="text-error">*</span>+ </>+ }+ >+ <Input+ value={dataSource.warehouseId ?? ""}+ disabled={!allowEdit}+ onChange={(e) => update({ warehouseId: e.target.value })}/></FormField>- )}- {hasReadonlyReplicaPort && (<FormField- className="sm:col-span-3 sm:col-start-1"- title={<>{t("data-source.read-replica-port")}</>}+ title={+ <>+ Token <span className="text-error">*</span>+ </>+ }><Input+ type="password"+ value={dataSource.updatedToken}className="w-full"autoComplete="off"- value={dataSource.port}disabled={!allowEdit}- onChange={(e) => {- if (e.target.value && !onlyAllowNumber(e.target.value))- return;- handlePortInput(e.target.value);- }}+ placeholder={+ isCreating+ ? "personal access token"+ : t("instance.token-write-only")+ }+ onChange={(e) =>+ update({ updatedToken: e.target.value.trim() })+ }/></FormField>+ </>+ )}++ {/* MongoDB authentication database */}+ {showAuthenticationDatabase && (+ <FormField+ className="sm:col-span-3 sm:col-start-1"+ title={<>{t("instance.authentication-database")}</>}+ >+ <Input+ className="w-full"+ autoComplete="off"+ placeholder="admin"+ disabled={!allowEdit}+ value={dataSource.authenticationDatabase ?? ""}+ onChange={(e) =>+ update({ authenticationDatabase: e.target.value.trim() })+ }+ />+ </FormField>+ )}++ {/* Read-only replica host/port */}+ {dataSource.type === DataSourceType.READ_ONLY &&+ (hasReadonlyReplicaHost || hasReadonlyReplicaPort) && (+ <>+ {hasReadonlyReplicaHost && (+ <FormField+ className="sm:col-span-3 sm:col-start-1"+ title={<>{t("data-source.read-replica-host")}</>}+ >+ <Input+ className="w-full"+ autoComplete="off"+ value={dataSource.host}+ disabled={!allowEdit}+ onChange={(e) => handleHostInput(e.target.value)}+ />+ </FormField>+ )}+ {hasReadonlyReplicaPort && (+ <FormField+ className="sm:col-span-3 sm:col-start-1"+ title={<>{t("data-source.read-replica-port")}</>}+ >+ <Input+ className="w-full"+ autoComplete="off"+ value={dataSource.port}+ disabled={!allowEdit}+ onChange={(e) => {+ if (+ e.target.value &&+ !onlyAllowNumber(e.target.value)+ )+ return;+ handlePortInput(e.target.value);+ }}+ />+ </FormField>+ )}+ </>)}- </>- )}- {/* Database field */}- {showDatabase && (- <FormField- className="sm:col-span-3 sm:col-start-1"- title={<>{t("common.database")}</>}- >- <Input- value={dataSource.database ?? ""}- className="w-full"- disabled={!allowEdit}- placeholder={t("common.database")}- onChange={(e) => update({ database: e.target.value })}- />- </FormField>+ {/* Database field */}+ {showDatabase && (+ <FormField+ className="sm:col-span-3 sm:col-start-1"+ title={<>{t("instance.connection-database")}</>}+ >+ <Input+ value={dataSource.database ?? ""}+ className="w-full"+ disabled={!allowEdit}+ placeholder={t("common.database")}+ onChange={(e) => update({ database: e.target.value })}+ />+ </FormField>+ )}+ </>)}- </>- )}{/* Connection options (SSL, SSH, Extra params) */}- {!hideOptions && (+ {!authOnly && !hideOptions && (<>{/* SSL */}{showSSL && isPasswordAuth && (@@ -1923,7 +2139,8 @@ export function DataSourceForm({{onOpenInfoPanel && hasSslInfo && (<buttontype="button"- className="inline-flex items-center gap-x-0.5 text-accent text-xs"+ aria-label={t("instance.authentication")}+ className="inline-flex cursor-pointer items-center gap-x-0.5 text-accent text-xs"onClick={() => onOpenInfoPanel("ssl")}><Info className="size-3.5" />@@ -2041,107 +2258,119 @@ export function DataSourceForm({{/* SSH */}{!hideAdvancedFeatures && showSSH && isPasswordAuth && (- <FormField- className="sm:col-span-3 sm:col-start-1"- title={- <span className="flex flex-row items-center gap-x-1">- {t("data-source.ssh-connection")}- {onOpenInfoPanel && hasSshInfo && (- <button- type="button"- className="inline-flex items-center gap-x-0.5 text-accent text-xs"- onClick={() => onOpenInfoPanel("ssh")}- >- <Info className="size-3.5" />- </button>- )}- </span>- }- >+ <div className="sm:col-span-3 sm:col-start-1"><SshConnectionForm+ title={+ <span className="flex flex-row items-center gap-x-1">+ {t("data-source.ssh-connection")}+ {onOpenInfoPanel && hasSshInfo && (+ <button+ type="button"+ className="inline-flex cursor-pointer items-center gap-x-0.5 text-accent text-xs"+ onClick={() => onOpenInfoPanel("ssh")}+ >+ <Info className="size-3.5" />+ </button>+ )}+ </span>+ }value={dataSource}instance={instance}disabled={!allowEdit}onChange={handleSSHChange}/>- </FormField>+ </div>)}{/* Extra connection parameters */}- {hasExtraParameters && (- <FormField- className="sm:col-span-3 sm:col-start-1"- title={t("data-source.extra-params.self")}- description={t("data-source.extra-params.description")}- >- <FormControlGroup className="mt-2">- {allowEdit && (- <FormControlRow>- <Input- value={newParamKey}- className="min-w-0 flex-1"- placeholder={t("instance.parameter-name-placeholder")}- onChange={(e) => setNewParamKey(e.target.value)}- />- <Input- value={newParamValue}- className="min-w-0 flex-1"- placeholder={t("instance.parameter-value-placeholder")}- onChange={(e) => setNewParamValue(e.target.value)}- />- <Button- appearance="outline"- className="shrink-0"- disabled={!newParamKey.trim()}- onClick={addNewParameter}- >- Add- </Button>- </FormControlRow>- )}-- {extraConnectionParamsList.map((param, index) => (- <FormControlRow key={param.key}>- <Input- className="min-w-0 flex-1"- value={param.key}- disabled={!allowEdit}- placeholder="Parameter name"- onChange={(e) =>- updateExtraConnectionParamKey(index, e.target.value)- }- />- <Input- className="min-w-0 flex-1"- value={param.value}- disabled={!allowEdit}- placeholder="Parameter value"- onChange={(e) =>- updateExtraConnectionParamValue(index, e.target.value)- }- />- {allowEdit && (+ {hasExtraParameters &&+ (showExtraParameters || extraConnectionParamsList.length > 0 ? (+ <FormField+ className="sm:col-span-3 sm:col-start-1"+ title={t("data-source.extra-params.self")}+ description={t("data-source.extra-params.description")}+ >+ <FormControlGroup className="mt-2">+ {allowEdit && (+ <FormControlRow>+ <Input+ value={newParamKey}+ className="min-w-0 flex-1"+ aria-label={t("instance.parameter-name-placeholder")}+ placeholder={t("instance.parameter-name-placeholder")}+ onChange={(e) => setNewParamKey(e.target.value)}+ />+ <Input+ value={newParamValue}+ className="min-w-0 flex-1"+ aria-label={t("instance.parameter-value-placeholder")}+ placeholder={t("instance.parameter-value-placeholder")}+ onChange={(e) => setNewParamValue(e.target.value)}+ /><Button- variant="destructive"+ appearance="outline"className="shrink-0"- onClick={() => removeExtraConnectionParam(index)}+ disabled={!newParamKey.trim()}+ onClick={addNewParameter}>- Remove+ {t("common.add")}</Button>- )}- </FormControlRow>- ))}- </FormControlGroup>-- {extraConnectionParamsList.length === 0 && (- <div className="textinfolabel text-sm italic mt-2">- {allowEdit- ? t("instance.no-params-yet-add-above")- : t("instance.no-extra-params-configured")}- </div>- )}- </FormField>- )}+ </FormControlRow>+ )}++ {extraConnectionParamsList.map((param, index) => (+ <FormControlRow key={param.key}>+ <Input+ className="min-w-0 flex-1"+ value={param.key}+ disabled={!allowEdit}+ aria-label={t("instance.parameter-name-placeholder")}+ placeholder={t("instance.parameter-name-placeholder")}+ onChange={(e) =>+ updateExtraConnectionParamKey(index, e.target.value)+ }+ />+ <Input+ className="min-w-0 flex-1"+ value={param.value}+ disabled={!allowEdit}+ aria-label={t("instance.parameter-value-placeholder")}+ placeholder={t("instance.parameter-value-placeholder")}+ onChange={(e) =>+ updateExtraConnectionParamValue(index, e.target.value)+ }+ />+ {allowEdit && (+ <Button+ variant="destructive"+ className="shrink-0"+ onClick={() => removeExtraConnectionParam(index)}+ >+ {t("common.remove")}+ </Button>+ )}+ </FormControlRow>+ ))}+ </FormControlGroup>++ {extraConnectionParamsList.length === 0 && (+ <div className="textinfolabel text-sm italic mt-2">+ {allowEdit+ ? t("instance.no-params-yet-add-above")+ : t("instance.no-extra-params-configured")}+ </div>+ )}+ </FormField>+ ) : (+ <Button+ appearance="link"+ className="justify-start sm:col-span-3"+ onClick={() => setShowExtraParameters(true)}+ disabled={!allowEdit}+ >+ {t("instance.add-parameter")}+ </Button>+ ))}</>)}</div>diff --git a/frontend/src/components/instance/DataSourceSection.tsx b/frontend/src/components/instance/DataSourceSection.tsxindex c0d1f04f2b..8df2596425 100644--- a/frontend/src/components/instance/DataSourceSection.tsx+++ b/frontend/src/components/instance/DataSourceSection.tsx@@ -15,11 +15,13 @@ import type { InfoSection } from "./info-content";interface DataSourceSectionProps {hideOptions?: boolean;+ hideAdminAuthentication?: boolean;onOpenInfoPanel?: (section: InfoSection) => void;}export function DataSourceSection({hideOptions = false,+ hideAdminAuthentication = false,onOpenInfoPanel,}: DataSourceSectionProps) {const { t } = useTranslation();@@ -149,7 +151,7 @@ export function DataSourceSection({/>)}- <div className="mt-2 gap-y-2 gap-x-4 border-none">+ <div className="mt-4 gap-y-2 gap-x-4 border-none">{/* Data source tabs */}{showDataSourceTabs && (<div className="mb-4 flex items-center gap-x-2 border-b border-block-border">@@ -222,6 +224,10 @@ export function DataSourceSection({<DataSourceFormdataSource={editingDataSource}hideOptions={hideOptions}+ hideAuthentication={+ hideAdminAuthentication &&+ editingDataSource.id === adminDataSource.id+ }onDataSourceChange={handleDataSourceChange}onOpenInfoPanel={onOpenInfoPanel}/>diff --git a/frontend/src/components/instance/InstanceDetailView.tsx b/frontend/src/components/instance/InstanceDetailView.tsxindex 2c52a87f99..2b3e6c89be 100644--- a/frontend/src/components/instance/InstanceDetailView.tsx+++ b/frontend/src/components/instance/InstanceDetailView.tsx@@ -35,6 +35,7 @@ import {import { SampleExpirationAlert } from "@/components/SampleExpirationAlert";import { Alert } from "@/components/ui/alert";import { Button } from "@/components/ui/button";+import { ResponsiveFormLayout } from "@/components/ui/form";import { Tabs, TabsList, TabsPanel, TabsTrigger } from "@/components/ui/tabs";import { useUnsavedChangesGuard } from "@/hooks/useUnsavedChangesGuard";import type { DatabaseFilter } from "@/lib/databaseFilter";@@ -627,9 +628,11 @@ export function InstanceDetailView({<TabsPanel value="overview"><InstanceFormProvider instance={instance} project={project}>- <InstanceFormBody />- <InstanceFormButtons />- <UnsavedChangesGuard />+ <ResponsiveFormLayout>+ <InstanceFormBody />+ <InstanceFormButtons />+ <UnsavedChangesGuard />+ </ResponsiveFormLayout></InstanceFormProvider></TabsPanel>diff --git a/frontend/src/components/instance/InstanceFormBody.test.ts b/frontend/src/components/instance/InstanceFormBody.test.tsindex 28403e4648..02ff789590 100644--- a/frontend/src/components/instance/InstanceFormBody.test.ts+++ b/frontend/src/components/instance/InstanceFormBody.test.ts@@ -4,7 +4,7 @@ import { join } from "node:path";import { describe, expect, test } from "vitest";describe("InstanceFormBody", () => {- test("uses boolean values for inert collapsible sections", () => {+ test("uses a boolean value for the engine selector disclosure", () => {const source = readFileSync(join(process.cwd(), "src/components/instance/InstanceFormBody.tsx"),"utf-8"@@ -13,15 +13,10 @@ describe("InstanceFormBody", () => {expect(source).not.toContain('inert={isEngineSelectorCollapsed ? "" : undefined}');- expect(source).not.toContain(- 'inert={isConnectionOptionsCollapsed ? "" : undefined}'- );expect(source).toContain("inert={isEngineSelectorCollapsed ? true : undefined}");- expect(source).toContain(- "inert={isConnectionOptionsCollapsed ? true : undefined}"- );+ expect(source).not.toContain("isConnectionOptionsCollapsed");});test("renders database sync controls inside the connection card", () => {@@ -33,14 +28,13 @@ describe("InstanceFormBody", () => {const basicInfoIndex = source.indexOf("{/* Basic Info Card */}");const connectionCardIndex = source.indexOf("{/* Connection Card */}");const syncDatabasesIndex = source.indexOf("<SyncDatabases");- const connectionOptionsIndex = source.indexOf(- "{/* Connection Options Card */}"- );+ const connectionOptionsIndex = source.indexOf("optionsOnly");expect(basicInfoIndex).toBeGreaterThanOrEqual(0);expect(connectionCardIndex).toBeGreaterThan(basicInfoIndex);expect(syncDatabasesIndex).toBeGreaterThan(connectionCardIndex);- expect(syncDatabasesIndex).toBeLessThan(connectionOptionsIndex);+ expect(connectionOptionsIndex).toBeGreaterThan(connectionCardIndex);+ expect(connectionOptionsIndex).toBeLessThan(syncDatabasesIndex);});test("renders database sync controls only once", () => {@@ -52,6 +46,31 @@ describe("InstanceFormBody", () => {expect(source.match(/<SyncDatabases/g)).toHaveLength(1);});+ test("groups Redis node and Sentinel master settings with the selected mode", () => {+ const source = readFileSync(+ join(process.cwd(), "src/components/instance/InstanceFormBody.tsx"),+ "utf-8"+ );+ const redisModeIndex = source.indexOf("{/* Redis connection type */}");+ const additionalAddressesIndex = source.indexOf(+ "<AdditionalAddressesFields",+ redisModeIndex+ );+ const sentinelFieldsIndex = source.indexOf(+ "<RedisSentinelFields",+ redisModeIndex+ );+ const credentialsIndex = source.indexOf(+ "{/* Credentials (auth method, username, password) */}",+ redisModeIndex+ );++ expect(redisModeIndex).toBeGreaterThanOrEqual(0);+ expect(additionalAddressesIndex).toBeGreaterThan(redisModeIndex);+ expect(sentinelFieldsIndex).toBeGreaterThan(additionalAddressesIndex);+ expect(credentialsIndex).toBeGreaterThan(sentinelFieldsIndex);+ });+test("labels project-aware database sync without a redundant alert", () => {const source = readFileSync(join(process.cwd(), "src/components/instance/InstanceFormBody.tsx"),@@ -109,19 +128,22 @@ describe("InstanceFormBody", () => {const descriptionIndex = source.indexOf('t("instance.sync-databases.description")');- const checkboxIndex = source.indexOf("<Checkbox", descriptionIndex);+ const syncControlIndex = source.indexOf(+ "<SegmentedControl",+ descriptionIndex+ );expect(source).toContain("onOpenInfoPanel?: (section: InfoSection) => void");expect(source).toContain("onOpenInfoPanel={onOpenInfoPanel}");expect(source).toContain(- 'className="inline-flex size-4 shrink-0 items-center justify-center text-accent leading-none"'+ 'className="inline-flex size-4 shrink-0 cursor-pointer items-center justify-center text-accent leading-none"');expect(source).toContain('<Info className="size-3.5" />');expect(infoTriggerIndex).toBeGreaterThan(titleIndex);expect(infoTriggerIndex).toBeLessThan(descriptionIndex);- expect(infoTriggerIndex).toBeLessThan(checkboxIndex);+ expect(infoTriggerIndex).toBeLessThan(syncControlIndex);});test("lets users load more database sync options", () => {@@ -161,7 +183,7 @@ describe("InstanceFormBody", () => {connectionTitleIndex);const connectionGridIndex = source.indexOf(- 'className="mt-3 grid grid-cols-1 gap-y-6 gap-x-4 sm:grid-cols-4"',+ 'className="flex flex-col gap-4"',connectionTitleIndex);@@ -181,14 +203,13 @@ describe("InstanceFormBody", () => {"utf-8");- expect(source).toContain("if (!updated.host && !isSaaSMode)");expect(source).toContain('t("instance.sentence.host.saas")');expect(source).toContain('t("instance.sentence.host.none-snowflake")');});- test("uses the localized testing label", () => {+ test("moves the localized testing label into the sticky form actions", () => {const source = readFileSync(- join(process.cwd(), "src/components/instance/InstanceFormBody.tsx"),+ join(process.cwd(), "src/components/instance/InstanceFormButtons.tsx"),"utf-8");@@ -198,14 +219,14 @@ describe("InstanceFormBody", () => {test("shows connection recovery for explicit test connection failures", () => {const source = readFileSync(- join(process.cwd(), "src/components/instance/InstanceFormBody.tsx"),+ join(process.cwd(), "src/components/instance/InstanceFormButtons.tsx"),"utf-8");expect(source).toContain("ConnectionRecovery");expect(source).toContain("testConnectionFailure");- expect(source).toContain("message: result.message");- expect(source).toContain("failureCategory: result.failureCategory");+ expect(source).toContain("message: testResult.message");+ expect(source).toContain("failureCategory: testResult.failureCategory");expect(source).toContain("setTestConnectionFailure(undefined)");expect(source).toContain("category={testConnectionFailure.failureCategory}"diff --git a/frontend/src/components/instance/InstanceFormBody.tsx b/frontend/src/components/instance/InstanceFormBody.tsxindex 029c97d491..b7585e7866 100644--- a/frontend/src/components/instance/InstanceFormBody.tsx+++ b/frontend/src/components/instance/InstanceFormBody.tsx@@ -8,7 +8,14 @@ import {Info,Trash2,} from "lucide-react";-import { useCallback, useEffect, useMemo, useRef, useState } from "react";+import {+ useCallback,+ useEffect,+ useId,+ useMemo,+ useRef,+ useState,+} from "react";import { useTranslation } from "react-i18next";import { EngineIcon } from "@/components/EngineIcon";import { EnvironmentSelect } from "@/components/EnvironmentSelect";@@ -25,10 +32,13 @@ import {FormControlRow,FormField,FormLabel,+ FormSection,+ ResponsiveFormLayout,} from "@/components/ui/form";import { Input } from "@/components/ui/input";import { RadioGroup, RadioGroupItem } from "@/components/ui/radio-group";-import { cn } from "@/lib/utils";+import { SegmentedControl } from "@/components/ui/segmented-control";+import { Switch } from "@/components/ui/switch";import { pushNotification } from "@/stores";import { useAppStore } from "@/stores/app";import {@@ -57,27 +67,19 @@ import {import {engineNameV1,extractInstanceResourceName,- isDev,- isValidBigQueryDataSource,- isValidSpannerDataSource,onlyAllowNumber,RE_GCP_INSTANCE_ID,RE_GCP_PROJECT_ID,supportedEngineV1List,urlfy,} from "@/utils";-import {- type ConnectionFailureCategory,- ConnectionRecovery,-} from "./ConnectionRecovery";import type { EditDataSource } from "./common";-import { hasSslConfig } from "./common";import {MongoDBConnectionStringSchemaList,RedisConnectionType,SnowflakeExtraLinkPlaceHolder,} from "./constants";-import { DataSourceForm } from "./DataSourceForm";+import { DataSourceForm, RedisSentinelFields } from "./DataSourceForm";import { DataSourceSection } from "./DataSourceSection";import { useInstanceFormContext } from "./InstanceFormContext";import { hasInfoContent, type InfoSection } from "./info-content";@@ -420,7 +422,6 @@ function ScanIntervalInput({return (<FormField- className="sm:col-span-4 sm:col-start-1"title={<span className="flex items-center gap-x-2">{t("instance.scan-interval.self")}@@ -477,6 +478,7 @@ function SyncDatabases({projectName,onOpenInfoPanel,syncDatabases,+ disabledReason,onSyncDatabasesChange,}: {isCreating: boolean;@@ -485,12 +487,14 @@ function SyncDatabases({projectName?: string;onOpenInfoPanel?: (section: InfoSection) => void;syncDatabases?: SyncDatabasesMessage;+ disabledReason?: string;onSyncDatabasesChange: (databases: string[], syncAll: boolean) => void;}) {const { t } = useTranslation();const ctx = useInstanceFormContext();const { hideAdvancedFeatures, instance, pendingCreateInstance } = ctx;+ const disabledReasonId = useId();const [syncAll, setSyncAll] = useState(syncDatabases === undefined);const [selectedSet, setSelectedSet] = useState<Set<string>>(() => new Set(syncDatabases?.databases ?? [])@@ -596,7 +600,6 @@ function SyncDatabases({return (<FormField- className="sm:col-span-4 sm:col-start-1"title={showLabel ? (<span className="flex items-center gap-x-1">@@ -604,7 +607,7 @@ function SyncDatabases({{onOpenInfoPanel && (<buttontype="button"- className="inline-flex size-4 shrink-0 items-center justify-center text-accent leading-none"+ className="inline-flex size-4 shrink-0 cursor-pointer items-center justify-center text-accent leading-none"onClick={() => onOpenInfoPanel("sync-databases")}><Info className="size-3.5" />@@ -618,16 +621,33 @@ function SyncDatabases({}><div className="flex flex-col gap-y-2">- <label className="flex items-center gap-x-2 cursor-pointer">- <Checkbox- checked={syncAll}- disabled={!allowEdit}- onCheckedChange={(checked) => setSyncAll(checked)}- />- {hasProjectContext- ? t("instance.sync-databases.project-sync-all")- : t("instance.sync-databases.sync-all")}- </label>+ <SegmentedControl+ value={syncAll ? "all" : "selected"}+ onValueChange={(value) => setSyncAll(value === "all")}+ options={[+ { value: "all", label: t("instance.sync-databases.all-databases") },+ {+ value: "selected",+ label: t("instance.sync-databases.selected-databases"),+ },+ ]}+ disabled={!allowEdit}+ ariaLabel={+ hasProjectContext+ ? t("instance.sync-databases.project-sync-all")+ : t("instance.sync-databases.self")+ }+ aria-describedby={disabledReason ? disabledReasonId : undefined}+ size="sm"+ />+ {disabledReason && (+ <p+ id={disabledReasonId}+ className="text-xs leading-4 text-control-light"+ >+ {disabledReason}+ </p>+ )}{!syncAll && (<div>{loading ? (@@ -635,7 +655,7 @@ function SyncDatabases({{t("common.loading")}...</div>) : (- <div className="border rounded-xs p-2 flex flex-col gap-y-2">+ <div className="pl-4 flex flex-col gap-y-2"><Inputvalue={searchText}className="w-full"@@ -690,6 +710,96 @@ function SyncDatabases({);}+function AdditionalAddressesFields({+ addresses,+ defaultPort,+ allowEdit,+ allowEditPort,+ onAdd,+ onRemove,+ onHostChange,+ onPortChange,+}: Readonly<{+ addresses: readonly { host: string; port: string }[];+ defaultPort: string;+ allowEdit: boolean;+ allowEditPort: boolean;+ onAdd: () => void;+ onRemove: (index: number) => void;+ onHostChange: (index: number, value: string) => void;+ onPortChange: (index: number, value: string) => void;+}>) {+ const { t } = useTranslation();+ const id = useId();++ return (+ <FormField title={t("data-source.additional-node-addresses")}>+ <FormControlGroup className="mt-1">+ {addresses.map((addr, index) => (+ <FormControlRow key={index} className="items-end">+ <FormField className="min-w-0 flex-1">+ <FormLabel+ htmlFor={`${id}-${index}-host`}+ className={index === 0 ? "font-normal!" : "sr-only"}+ >+ {t("instance.hostname")}+ </FormLabel>+ <Input+ id={`${id}-${index}-host`}+ value={addr.host}+ required+ className="w-full"+ disabled={!allowEdit}+ onChange={(e) => onHostChange(index, e.target.value)}+ />+ </FormField>+ <FormField className="w-32 shrink-0">+ <FormLabel+ htmlFor={`${id}-${index}-port`}+ className={index === 0 ? "font-normal!" : "sr-only"}+ >+ {t("instance.port")}+ </FormLabel>+ <Input+ id={`${id}-${index}-port`}+ value={addr.port}+ className="w-full"+ placeholder={defaultPort}+ disabled={!allowEdit || !allowEditPort}+ onChange={(e) => onPortChange(index, e.target.value)}+ />+ </FormField>+ <Button+ type="button"+ variant="destructive"+ appearance="secondary"+ size="sm"+ aria-label={t("common.delete")}+ disabled={!allowEdit}+ onClick={() => onRemove(index)}+ >+ <Trash2 className="size-4" />+ </Button>+ </FormControlRow>+ ))}+ <div>+ <Button+ appearance="outline"+ size="sm"+ className="w-12!"+ onClick={(e) => {+ e.preventDefault();+ onAdd();+ }}+ >+ {t("common.add")}+ </Button>+ </div>+ </FormControlGroup>+ </FormField>+ );+}+// --- Main component ---interface InstanceFormBodyProps {@@ -709,7 +819,6 @@ export function InstanceFormBody({ onOpenInfoPanel }: InstanceFormBodyProps) {const ctx = useInstanceFormContext();const {instance,- state,specs,isCreating,allowEdit,@@ -723,15 +832,17 @@ export function InstanceFormBody({ onOpenInfoPanel }: InstanceFormBodyProps) {setDataSourceEditState,adminDataSource,editingDataSource,- checkDataSource,- testConnection,resetDataSource,- showConnectionOptionsEvent,- emitShowConnectionOptions,setResourceIdValidated,parent,} = ctx;- const { isEngineBeta, defaultPort, instanceLink, allowEditPort } = specs;+ const {+ isEngineBeta,+ defaultPort,+ instanceLink,+ allowEditPort,+ allowUsingEmptyPassword,+ } = specs;const hasUnifiedInstanceLicense = useAppStore((s) =>s.hasUnifiedInstanceLicense()@@ -743,73 +854,7 @@ export function InstanceFormBody({ onOpenInfoPanel }: InstanceFormBodyProps) {const [isEngineSelectorCollapsed, setIsEngineSelectorCollapsed] =useState(false);- const [isConnectionOptionsCollapsed, setIsConnectionOptionsCollapsed] =- useState(true);- const [testConnectionFailure, setTestConnectionFailure] = useState<- | {- message: string;- failureCategory: ConnectionFailureCategory;- }- | undefined- >();-- // Auto-expand connection options when configured- const showConnectionOptionsCard =- basicInfo.engine !== Engine.DYNAMODB && !!editingDataSource;-- const hasConfiguredConnectionOptions = useMemo(() => {- const ds = editingDataSource;- if (!ds) return false;- const hasExtraParameters =- Object.keys(ds.extraConnectionParameters ?? {}).length > 0;- const hasSshConfig = !!(- ds.sshHost ||- ds.sshPort ||- ds.sshUser ||- ds.sshPassword ||- ds.sshPrivateKey- );- return hasExtraParameters || hasSslConfig(ds) || hasSshConfig;- }, [editingDataSource]);-- // Collapse state management based on visibility and configuration- const prevShowRef = useRef(showConnectionOptionsCard);- const prevConfiguredRef = useRef(hasConfiguredConnectionOptions);- useEffect(() => {- if (!showConnectionOptionsCard) {- prevShowRef.current = false;- return;- }- const becameVisible = !prevShowRef.current;- if (becameVisible) {- setIsConnectionOptionsCollapsed(- isCreating ? true : !hasConfiguredConnectionOptions- );- prevShowRef.current = true;- prevConfiguredRef.current = hasConfiguredConnectionOptions;- return;- }- if (- !isCreating &&- hasConfiguredConnectionOptions &&- !prevConfiguredRef.current- ) {- setIsConnectionOptionsCollapsed(false);- }- prevShowRef.current = showConnectionOptionsCard;- prevConfiguredRef.current = hasConfiguredConnectionOptions;- }, [showConnectionOptionsCard, isCreating, hasConfiguredConnectionOptions]);-- // Listen for show-connection-options event- const prevEventRef = useRef(showConnectionOptionsEvent);- useEffect(() => {- if (showConnectionOptionsEvent !== prevEventRef.current) {- prevEventRef.current = showConnectionOptionsEvent;- if (showConnectionOptionsCard) {- setIsConnectionOptionsCollapsed(false);- }- }- }, [showConnectionOptionsEvent, showConnectionOptionsCard]);+ const [showLabels, setShowLabels] = useState(false);// --- Computed values ---@@ -904,24 +949,6 @@ export function InstanceFormBody({ onOpenInfoPanel }: InstanceFormBodyProps) {return false;}, [basicInfo.engine, adminDataSource.srv, adminDataSource.redisType]);- const allowTestConnection = useMemo(() => {- if (!allowEdit || state.isRequesting || state.isTestingConnection) {- return false;- }- const ds = editingDataSource;- if (!ds) return false;- if (basicInfo.engine === Engine.SPANNER) {- return isValidSpannerDataSource(ds);- }- if (basicInfo.engine === Engine.BIGQUERY) {- return isValidBigQueryDataSource(ds);- }- if (basicInfo.engine !== Engine.DYNAMODB && ds.host === "") {- return false;- }- return checkDataSource([ds]);- }, [allowEdit, state, editingDataSource, basicInfo.engine, checkDataSource]);-const hasHostInfo = useMemo(() => hasInfoContent(basicInfo.engine, "host"),[basicInfo.engine]@@ -980,12 +1007,6 @@ export function InstanceFormBody({ onOpenInfoPanel }: InstanceFormBodyProps) {DataSource_AuthenticationType.AZURE_IAM;break;}- default: {- if (!updated.host && !isSaaSMode) {- updated.host = isDev() ? "127.0.0.1" : "host.docker.internal";- }- break;- }}return updated;});@@ -993,7 +1014,7 @@ export function InstanceFormBody({ onOpenInfoPanel }: InstanceFormBodyProps) {});setBasicInfo((prev) => ({ ...prev, engine }));},- [resetDataSource, setDataSourceEditState, setBasicInfo, isSaaSMode]+ [resetDataSource, setDataSourceEditState, setBasicInfo]);const handleSelectInstanceEngine = useCallback(@@ -1122,28 +1143,6 @@ export function InstanceFormBody({ onOpenInfoPanel }: InstanceFormBodyProps) {[instance, updateBasicInfo, t]);- const testConnectionForCurrentEditingDS = useCallback(async () => {- const ds = editingDataSource;- if (!ds) return;- setTestConnectionFailure(undefined);- const result = await testConnection(ds, false);- if (result.success) {- return;- }- setTestConnectionFailure({- message: result.message,- failureCategory: result.failureCategory,- });- if (hasConfiguredConnectionOptions) {- emitShowConnectionOptions();- }- }, [- editingDataSource,- testConnection,- hasConfiguredConnectionOptions,- emitShowConnectionOptions,- ]);-const handleDataSourceChange = useCallback((updated: EditDataSource) => {setDataSourceEditState((prev) => ({@@ -1207,53 +1206,33 @@ export function InstanceFormBody({ onOpenInfoPanel }: InstanceFormBodyProps) {);return (- <div className="flex flex-col gap-y-6 pb-2">- <div className="w-full flex flex-col gap-y-6">- {/* Engine Selector (create only) */}- {isCreating && (- <div className="rounded-sm border border-block-border bg-background">- <button- type="button"- className="w-full flex items-center justify-between gap-x-3 px-4 py-3 text-left transition-colors hover:bg-control-bg"- onClick={() => setIsEngineSelectorCollapsed((prev) => !prev)}- >- <div className="min-w-0">- <p className="text-[11px] font-medium uppercase tracking-[0.14em] text-control-light">- {t("database.engine")}- </p>- <div className="mt-1 flex items-center gap-x-1.5">- <EngineIcon engine={basicInfo.engine} className="size-4" />- <span className="text-sm font-medium text-main">+ <div className="flex flex-col pb-2">+ <div className="w-full max-w-5xl flex flex-col">+ {/* Basic Info Card */}+ <FormSection layout="stacked" title={t("instance.section.basic-info")}>+ <div className="flex flex-col gap-4">+ {isCreating && (+ <FormField title={t("database.engine")}>+ <Button+ appearance="outline"+ className="w-full justify-between"+ aria-expanded={!isEngineSelectorCollapsed}+ onClick={() => setIsEngineSelectorCollapsed((prev) => !prev)}+ >+ <span className="flex items-center gap-2">+ <EngineIcon engine={basicInfo.engine} className="size-4" />{engineNameV1(basicInfo.engine)}</span>- {isEngineBeta(basicInfo.engine) && (- <span className="rounded-full bg-accent/10 px-2 py-0.5 text-xs text-accent">- Beta- </span>+ {isEngineSelectorCollapsed ? (+ <ChevronRight />+ ) : (+ <ChevronDown />)}- </div>- </div>- <div className="shrink-0 text-control-light">- {!isEngineSelectorCollapsed ? (- <ChevronDown className="size-4" />- ) : (- <ChevronRight className="size-4" />- )}- </div>- </button>-- <div- className={cn(- "grid transition-[grid-template-rows] duration-200 ease-in-out",- !isEngineSelectorCollapsed && "border-t border-block-border"- )}- style={{- gridTemplateRows: !isEngineSelectorCollapsed ? "1fr" : "0fr",- }}- inert={isEngineSelectorCollapsed ? true : undefined}- >- <div className="overflow-hidden">- <div className="px-4 py-4">+ </Button>+ <div+ hidden={isEngineSelectorCollapsed}+ inert={isEngineSelectorCollapsed ? true : undefined}+ ><InstanceEngineRadioGridengine={basicInfo.engine}engineList={supportedEngineV1List()}@@ -1261,20 +1240,11 @@ export function InstanceFormBody({ onOpenInfoPanel }: InstanceFormBodyProps) {isEngineBeta={isEngineBeta}/></div>- </div>- </div>- </div>- )}-- {/* Basic Info Card */}- <div className="border border-block-border rounded-sm p-5">- <h3 className="text-base font-medium text-main">- {t("instance.section.basic-info")}- </h3>+ </FormField>+ )}- <div className="mt-3 grid grid-cols-1 gap-y-6 gap-x-4 sm:grid-cols-4">{/* Instance Name */}- <FormField className="sm:col-span-2 sm:col-start-1">+ <FormField><FormLabel htmlFor="name" className="flex flex-row items-center">{t("instance.instance-name")}<span className="ml-0.5 text-error">*</span>@@ -1286,6 +1256,7 @@ export function InstanceFormBody({ onOpenInfoPanel }: InstanceFormBodyProps) {)}</FormLabel><Input+ id="name"value={basicInfo.title}requiredclassName="w-full max-w-[40rem]"@@ -1293,15 +1264,36 @@ export function InstanceFormBody({ onOpenInfoPanel }: InstanceFormBodyProps) {maxLength={200}onChange={(e) => updateBasicInfo({ title: e.target.value })}/>+ <ResourceIdField+ suffix+ value={resourceId}+ resourceName={t("common.instance")}+ resourceTitle={basicInfo.title}+ readonly={!isCreating}+ validate={validateInstanceId}+ onChange={setResourceId}+ onValidationChange={setResourceIdValidated}+ /></FormField>{/* Activation toggle */}{currentPlan !== PlanType.FREE &&!hasUnifiedInstanceLicense &&allowEdit && (- <div className="sm:col-span-2 ml-0 sm:ml-3">- <label htmlFor="activation" className="textlabel block">- {t("subscription.instance-assignment.assign-license")} (+ <FormField+ title={t("subscription.instance-assignment.assign-license")}+ >+ <FormControlRow className="w-fit">+ <Switch+ aria-label={t(+ "subscription.instance-assignment.assign-license"+ )}+ checked={basicInfo.activation}+ disabled={+ !basicInfo.activation && availableLicenseCount === 0+ }+ onCheckedChange={changeInstanceActivation}+ /><RouterLinkto="/setting/subscription"className="accent-link"@@ -1310,100 +1302,83 @@ export function InstanceFormBody({ onOpenInfoPanel }: InstanceFormBodyProps) {n: availableLicenseCountText,})}</RouterLink>- )- </label>- <div className="h-8.5 flex flex-row items-center mt-1">- <label className="relative inline-flex items-center cursor-pointer">- <input- type="checkbox"- className="sr-only peer"- checked={basicInfo.activation}- disabled={- !basicInfo.activation && availableLicenseCount === 0- }- onChange={(e) =>- changeInstanceActivation(e.target.checked)- }- />- <div className="w-9 h-5 bg-control-border peer-focus:outline-none rounded-full peer peer-checked:bg-accent transition-colors after:content-[''] after:absolute after:top-0.5 after:left-0.5 after:bg-background after:rounded-full after:h-4 after:w-4 after:transition-all peer-checked:after:translate-x-4" />- </label>- </div>- </div>+ </FormControlRow>+ </FormField>)}- {/* Resource ID */}- <div className="sm:col-span-3 sm:col-start-1 -mt-4">- <ResourceIdField- suffix- value={resourceId}- resourceName={t("common.instance")}- resourceTitle={basicInfo.title}- readonly={!isCreating}- validate={validateInstanceId}- onChange={setResourceId}- onValidationChange={setResourceIdValidated}- />- </div>-{/* Environment */}- <FormField className="sm:col-span-2 sm:col-start-1">- <FormLabel htmlFor="environment">- {t("common.environment")}- </FormLabel>- <EnvironmentSelect- className="w-full max-w-[40rem]"- value={- isValidEnvironmentName(- `${environmentNamePrefix}${environment.id}`- )- ? `${environmentNamePrefix}${environment.id}`- : ""- }- disabled={!allowEdit}- onChange={(value) =>- handleSelectEnvironment(value || undefined)- }- />+ <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></FormField>{/* Labels */}- <FormField className="sm:col-span-3 sm:col-start-1">- <FormLabel htmlFor="labels">{t("common.labels")}</FormLabel>- <LabelListEditor- kvList={labelKVList}- onChange={setLabelKVList}- readonly={!allowEdit}- showErrors- onErrorsChange={ctx.setLabelErrors}- />- </FormField>+ {(showLabels || labelKVList.length > 0) && (+ <FormField title={t("common.labels")}>+ <LabelListEditor+ kvList={labelKVList}+ onChange={setLabelKVList}+ readonly={!allowEdit}+ showErrors+ onErrorsChange={ctx.setLabelErrors}+ />+ </FormField>+ )}{/* External link (edit mode only) */}{!isCreating && (- <FormField className="sm:col-span-3 sm:col-start-1">- <div className="inline-flex items-center">- <FormLabel htmlFor="external-link">- {basicInfo.engine === Engine.SNOWFLAKE- ? t("instance.snowflake-web-console")- : t("instance.external-link")}- </FormLabel>- {(basicInfo.externalLink ?? "").trim().length > 0 && (- <button- className="ml-1 btn-icon"- onClick={(e) => {- e.preventDefault();- window.open(- urlfy(basicInfo.externalLink ?? ""),- "_blank"- );- }}- >- <ExternalLink className="size-4" />- </button>- )}- </div>+ <FormField+ title={+ <div className="inline-flex items-center">+ <FormLabel htmlFor="external-link">+ {basicInfo.engine === Engine.SNOWFLAKE+ ? t("instance.snowflake-web-console")+ : t("instance.external-link")}+ </FormLabel>+ {(basicInfo.externalLink ?? "").trim().length > 0 && (+ <button+ className="ml-1 btn-icon"+ onClick={(e) => {+ e.preventDefault();+ window.open(+ urlfy(basicInfo.externalLink ?? ""),+ "_blank"+ );+ }}+ >+ <ExternalLink className="size-4" />+ </button>+ )}+ </div>+ }+ >{basicInfo.engine === Engine.SNOWFLAKE ? (<Input+ id="external-link"requiredclassName="w-full"disabled@@ -1415,6 +1390,7 @@ export function InstanceFormBody({ onOpenInfoPanel }: InstanceFormBodyProps) {{t("instance.sentence.console.snowflake")}</p><Input+ id="external-link"value={basicInfo.externalLink ?? ""}requiredclassName="w-full"@@ -1438,13 +1414,10 @@ export function InstanceFormBody({ onOpenInfoPanel }: InstanceFormBodyProps) {/>)}</div>- </div>+ </FormSection>{/* Connection Card */}- <div className="border border-block-border rounded-sm p-5">- <h3 className="text-base font-medium text-main">- {t("instance.section.connection")}- </h3>+ <FormSection layout="stacked" title={t("instance.section.connection")}>{isSaaSMode && (<Alert variant="info" className="mt-2"><a@@ -1458,84 +1431,71 @@ export function InstanceFormBody({ onOpenInfoPanel }: InstanceFormBodyProps) {</Alert>)}- <div className="mt-3 grid grid-cols-1 gap-y-6 gap-x-4 sm:grid-cols-4">+ <div className="flex flex-col gap-4">+ {editingDataSource?.id === adminDataSource.id && (+ <DataSourceForm+ authOnly+ dataSource={adminDataSource}+ onDataSourceChange={handleDataSourceChange}+ onOpenInfoPanel={onOpenInfoPanel}+ />+ )}{/* Host input */}- <div className="sm:col-span-3 sm:col-start-1">- {basicInfo.engine === Engine.SPANNER ? (- <SpannerHostInput- projectId={adminDataSource.projectId}- instanceId={adminDataSource.instanceId}- endpoint={adminDataSource.host}- port={adminDataSource.port}- onUpdate={(update) => updateAdminDS(update)}- allowEdit={allowEdit}- />- ) : basicInfo.engine === Engine.BIGQUERY ? (- <BigQueryHostInput- projectId={adminDataSource.projectId}- endpoint={adminDataSource.host}- port={adminDataSource.port}- onUpdate={(update) => updateAdminDS(update)}- allowEdit={allowEdit}- />- ) : (- <>- {basicInfo.engine === Engine.SNOWFLAKE ? (- <>- <div className="flex items-center gap-x-2">- <FormLabel htmlFor="host">- {t("instance.account-locator")}- <span className="text-error"> *</span>- </FormLabel>- <LearnMoreLink- href="https://docs.snowflake.com/en/user-guide/admin-account-identifier#using-an-account-locator-as-an-identifier"- className="text-sm normal-link"- />- </div>- </>- ) : basicInfo.engine === Engine.COSMOSDB ? (+ {basicInfo.engine === Engine.SPANNER ? (+ <SpannerHostInput+ projectId={adminDataSource.projectId}+ instanceId={adminDataSource.instanceId}+ endpoint={adminDataSource.host}+ port={adminDataSource.port}+ onUpdate={(update) => updateAdminDS(update)}+ allowEdit={allowEdit}+ />+ ) : basicInfo.engine === Engine.BIGQUERY ? (+ <BigQueryHostInput+ projectId={adminDataSource.projectId}+ endpoint={adminDataSource.host}+ port={adminDataSource.port}+ onUpdate={(update) => updateAdminDS(update)}+ allowEdit={allowEdit}+ />+ ) : (+ <FormField+ title={+ <span className="flex items-center gap-1"><FormLabel htmlFor="host">- {t("instance.endpoint")}- <span className="text-error"> *</span>- </FormLabel>- ) : adminDataSource.authenticationType ===- DataSource_AuthenticationType.GOOGLE_CLOUD_SQL_IAM ? (- <>- <FormLabel htmlFor="host">- {t("instance.sentence.google-cloud-sql.instance-name")}+ {basicInfo.engine === Engine.SNOWFLAKE+ ? t("instance.account-locator")+ : basicInfo.engine === Engine.COSMOSDB+ ? t("instance.endpoint")+ : adminDataSource.authenticationType ===+ DataSource_AuthenticationType.GOOGLE_CLOUD_SQL_IAM+ ? t(+ "instance.sentence.google-cloud-sql.instance-name"+ )+ : t("instance.hostname")}+ {basicInfo.engine !== Engine.DYNAMODB && (<span className="text-error"> *</span>- </FormLabel>- <p className="text-xs leading-4 text-control-light">- {t(- "instance.sentence.google-cloud-sql.instance-name-tips",- {- instance: "{project-id}:{region}:{instance-name}",- }- )}- </p>- </>- ) : (- <div className="flex items-center gap-x-1">- <FormLabel htmlFor="host">- {t("instance.host-or-socket")}- {basicInfo.engine !== Engine.DYNAMODB && (- <span className="text-error"> *</span>- )}- </FormLabel>- {onOpenInfoPanel && hasHostInfo && (- <button- type="button"- className="inline-flex items-center gap-x-0.5 text-accent text-xs"- onClick={() => openInfoPanel("host")}- >- <Info className="size-3.5" />- </button>)}- </div>- )}+ </FormLabel>+ {onOpenInfoPanel && hasHostInfo && (+ <Button+ appearance="link"+ size="xs"+ className="h-auto shrink-0 p-0"+ aria-label={t("instance.hostname")}+ onClick={() => openInfoPanel("host")}+ >+ <Info className="size-3.5" />+ </Button>+ )}+ </span>+ }+ >+ <div className="flex items-center gap-2"><Input+ id="host"value={adminDataSource.host}- required+ required={basicInfo.engine !== Engine.DYNAMODB}placeholder={basicInfo.engine === Engine.SNOWFLAKE? t("instance.your-snowflake-account-locator")@@ -1543,41 +1503,47 @@ export function InstanceFormBody({ onOpenInfoPanel }: InstanceFormBodyProps) {? t("instance.sentence.host.saas"): t("instance.sentence.host.none-snowflake")}- className="mt-1 w-full"+ className="min-w-0 flex-1"disabled={!allowEdit}onChange={(e) => updateAdminDS({ host: e.target.value })}/>- {basicInfo.engine === Engine.SNOWFLAKE && (- <p className="mt-2 text-xs leading-4 text-control-light">- {t("instance.sentence.proxy.snowflake")}- </p>- )}- </>- )}- </div>-- {/* Port input */}- {basicInfo.engine !== Engine.SPANNER &&- basicInfo.engine !== Engine.BIGQUERY &&- basicInfo.engine !== Engine.DATABRICKS &&- basicInfo.engine !== Engine.COSMOSDB &&- adminDataSource.authenticationType !==- DataSource_AuthenticationType.GOOGLE_CLOUD_SQL_IAM && (- <FormField className="sm:col-span-1">- <FormLabel htmlFor="port">{t("instance.port")}</FormLabel>- <Input- value={adminDataSource.port}- className="w-full"- placeholder={defaultPort}- disabled={!allowEdit || !allowEditPort}- onChange={handlePortChange}- />- </FormField>- )}+ {basicInfo.engine !== Engine.DATABRICKS &&+ basicInfo.engine !== Engine.COSMOSDB &&+ adminDataSource.authenticationType !==+ DataSource_AuthenticationType.GOOGLE_CLOUD_SQL_IAM && (+ <>+ <FormLabel htmlFor="port">+ {t("instance.port")}+ </FormLabel>+ <Input+ id="port"+ value={adminDataSource.port}+ className="w-20 shrink-0"+ placeholder={defaultPort}+ disabled={!allowEdit || !allowEditPort}+ onChange={handlePortChange}+ />+ </>+ )}+ </div>+ {adminDataSource.authenticationType ===+ DataSource_AuthenticationType.GOOGLE_CLOUD_SQL_IAM && (+ <p className="text-xs text-control-light">+ {t(+ "instance.sentence.google-cloud-sql.instance-name-tips",+ { instance: "{project-id}:{region}:{instance-name}" }+ )}+ </p>+ )}+ {basicInfo.engine === Engine.SNOWFLAKE && (+ <LearnMoreLink href="https://docs.snowflake.com/en/user-guide/admin-account-identifier#using-an-account-locator-as-an-identifier" />+ )}+ </FormField>+ )}{/* MongoDB connection string schema */}{basicInfo.engine === Engine.MONGODB && (- <FormField className="sm:col-span-4 sm:col-start-1">+ <FormField><FormLabel htmlFor="connectionStringSchema">{t("data-source.connection-string-schema")}</FormLabel>@@ -1594,12 +1560,75 @@ export function InstanceFormBody({ onOpenInfoPanel }: InstanceFormBodyProps) {</RadioGroupItem>))}</RadioGroup>+ {!adminDataSource.srv && (+ <ResponsiveFormLayout className="mt-2">+ <fieldset+ aria-label={t("data-source.connection-string-schema")}+ className="flex flex-col gap-4 rounded-xs border border-control-border px-3 py-2"+ >+ {/* Additional addresses */}+ {showAdditionalAddresses && (+ <AdditionalAddressesFields+ addresses={adminDataSource.additionalAddresses}+ defaultPort={defaultPort}+ allowEdit={allowEdit}+ allowEditPort={allowEditPort}+ onAdd={addDSAdditionalAddress}+ onRemove={removeDSAdditionalAddress}+ onHostChange={handleAdditionalAddressHostChange}+ onPortChange={handleAdditionalAddressPortChange}+ />+ )}+ {/* MongoDB replica set */}+ {basicInfo.engine === Engine.MONGODB &&+ !adminDataSource.srv && (+ <FormField>+ <FormLabel htmlFor="replicaSet">+ {t("data-source.replica-set")}+ </FormLabel>+ <Input+ value={adminDataSource.replicaSet}+ required+ className="w-full"+ disabled={!allowEdit}+ onChange={(e) =>+ updateAdminDS({ replicaSet: e.target.value })+ }+ />+ </FormField>+ )}+ {/* MongoDB direct connection */}+ {basicInfo.engine === Engine.MONGODB &&+ !adminDataSource.srv &&+ adminDataSource.additionalAddresses.length === 0 && (+ <FormControlRow className="w-fit">+ <Checkbox+ id="directConnection"+ checked={adminDataSource.directConnection}+ disabled={!allowEdit}+ onCheckedChange={(checked) =>+ updateAdminDS({+ directConnection: checked,+ })+ }+ />+ <FormLabel+ htmlFor="directConnection"+ className="font-normal!"+ >+ {t("data-source.direct-connection")}+ </FormLabel>+ </FormControlRow>+ )}{" "}+ </fieldset>+ </ResponsiveFormLayout>+ )}</FormField>)}{/* Redis connection type */}{basicInfo.engine === Engine.REDIS && (- <FormField className="sm:col-span-4 sm:col-start-1">+ <FormField><FormLabel htmlFor="connectionStringSchema">{t("data-source.connection-type")}</FormLabel>@@ -1616,137 +1645,93 @@ export function InstanceFormBody({ onOpenInfoPanel }: InstanceFormBodyProps) {</RadioGroupItem>))}</RadioGroup>- </FormField>- )}-- {/* Additional addresses */}- {showAdditionalAddresses && (- <FormField className="sm:col-span-4 sm:col-start-1">- <FormLabel htmlFor="additionalAddresses">- {t("data-source.additional-node-addresses")}- </FormLabel>- <FormControlGroup className="mt-1">- {adminDataSource.additionalAddresses.map((addr, index) => (- <FormControlRow key={index} className="items-end">- <FormField className="min-w-0 flex-1">- {index === 0 && (- <FormLabel- htmlFor="additionalAddressesHost"- className="font-normal!"- >- {t("instance.host-or-socket")}- </FormLabel>- )}- <Input- value={addr.host}- required- className="w-full"- disabled={!allowEdit}- onChange={(e) =>- handleAdditionalAddressHostChange(- index,- e.target.value- )- }- />- </FormField>- <FormField className="w-32 shrink-0">- {index === 0 && (- <FormLabel- htmlFor="additionalAddressesPort"- className="font-normal!"- >- {t("instance.port")}- </FormLabel>- )}- <Input- value={addr.port}- className="w-full"- placeholder={defaultPort}- disabled={!allowEdit || !allowEditPort}- onChange={(e) =>- handleAdditionalAddressPortChange(- index,- e.target.value- )- }- />- </FormField>- <button- type="button"- className="flex h-8.5 w-8.5 shrink-0 items-center justify-center text-control-light hover:text-error disabled:opacity-50"- disabled={!allowEdit}- onClick={() => removeDSAdditionalAddress(index)}- >- <Trash2 className="size-4" />- </button>- </FormControlRow>- ))}- <div>- <Button- appearance="outline"- size="sm"- className="w-12!"- onClick={(e) => {- e.preventDefault();- addDSAdditionalAddress();- }}+ {showAdditionalAddresses && (+ <ResponsiveFormLayout className="mt-2">+ <fieldset+ aria-label={currentRedisConnectionType}+ className="flex flex-col gap-4 rounded-xs border border-control-border px-3 py-2">- {t("common.add")}- </Button>- </div>- </FormControlGroup>+ <AdditionalAddressesFields+ addresses={adminDataSource.additionalAddresses}+ defaultPort={defaultPort}+ allowEdit={allowEdit}+ allowEditPort={allowEditPort}+ onAdd={addDSAdditionalAddress}+ onRemove={removeDSAdditionalAddress}+ onHostChange={handleAdditionalAddressHostChange}+ onPortChange={handleAdditionalAddressPortChange}+ />+ </fieldset>+ </ResponsiveFormLayout>+ )}+ {editingDataSource?.redisType ===+ DataSource_RedisType.SENTINEL && (+ <ResponsiveFormLayout className="mt-2">+ <RedisSentinelFields+ dataSource={editingDataSource}+ isCreating={isCreating}+ allowEdit={allowEdit}+ allowUsingEmptyPassword={allowUsingEmptyPassword}+ onDataSourceChange={handleDataSourceChange}+ />+ </ResponsiveFormLayout>+ )}</FormField>)}- {/* MongoDB replica set */}- {basicInfo.engine === Engine.MONGODB && !adminDataSource.srv && (- <FormField className="sm:col-span-2 sm:col-start-1">- <FormLabel htmlFor="replicaSet">- {t("data-source.replica-set")}- </FormLabel>- <Input- value={adminDataSource.replicaSet}- required- className="w-full"- disabled={!allowEdit}- onChange={(e) =>- updateAdminDS({ replicaSet: e.target.value })- }- />- </FormField>+ {/* Additional addresses */}+ {basicInfo.engine === Engine.CASSANDRA && (+ <AdditionalAddressesFields+ addresses={adminDataSource.additionalAddresses}+ defaultPort={defaultPort}+ allowEdit={allowEdit}+ allowEditPort={allowEditPort}+ onAdd={addDSAdditionalAddress}+ onRemove={removeDSAdditionalAddress}+ onHostChange={handleAdditionalAddressHostChange}+ onPortChange={handleAdditionalAddressPortChange}+ />)}-- {/* MongoDB direct connection */}- {basicInfo.engine === Engine.MONGODB &&- !adminDataSource.srv &&- adminDataSource.additionalAddresses.length === 0 && (- <div className="sm:col-span-4 sm:col-start-1">- <label className="flex items-center gap-x-2 cursor-pointer">- <Checkbox- checked={adminDataSource.directConnection}- disabled={!allowEdit}- onCheckedChange={(checked) =>- updateAdminDS({- directConnection: checked,- })- }- />- {t("data-source.direct-connection")}- </label>- </div>- )}</div>{/* Credentials (auth method, username, password) */}- <DataSourceSection hideOptions onOpenInfoPanel={onOpenInfoPanel} />+ <DataSourceSection+ hideOptions+ hideAdminAuthentication+ onOpenInfoPanel={onOpenInfoPanel}+ />++ {basicInfo.engine !== Engine.DYNAMODB && editingDataSource && (+ <div className="mt-4">+ <div>+ <DataSourceForm+ dataSource={editingDataSource}+ optionsOnly+ onDataSourceChange={handleDataSourceChange}+ onOpenInfoPanel={onOpenInfoPanel}+ />+ </div>+ </div>+ )}{basicInfo.engine !== Engine.DYNAMODB && (- <div className="mt-6">+ <div className="mt-4"><SyncDatabasesisCreating={isCreating}showLabelallowEdit={isCreating ? allowEdit && !!allowCreate : allowEdit}+ disabledReason={+ isCreating && allowEdit && !allowCreate+ ? !adminDataSource.host &&+ ![+ Engine.SPANNER,+ Engine.BIGQUERY,+ Engine.DYNAMODB,+ ].includes(basicInfo.engine)+ ? t("instance.sync-databases.hostname-required")+ : t("instance.sync-databases.required-fields")+ : undefined+ }projectName={parent}onOpenInfoPanel={onOpenInfoPanel}syncDatabases={basicInfo.syncDatabases}@@ -1754,74 +1739,7 @@ export function InstanceFormBody({ onOpenInfoPanel }: InstanceFormBodyProps) {/></div>)}- </div>-- {/* Connection Options Card */}- {basicInfo.engine !== Engine.DYNAMODB && editingDataSource && (- <div className="border border-block-border rounded-sm bg-background">- <button- type="button"- className="w-full flex items-center justify-between gap-x-3 px-5 py-4 text-left transition-colors hover:bg-control-bg"- onClick={() => setIsConnectionOptionsCollapsed((prev) => !prev)}- >- <h3 className="text-base font-medium text-main">- {t("instance.connection-options")}- </h3>- <div className="shrink-0 text-control-light">- {!isConnectionOptionsCollapsed ? (- <ChevronDown className="size-4" />- ) : (- <ChevronRight className="size-4" />- )}- </div>- </button>- <div- className={cn(- "grid transition-[grid-template-rows] duration-200 ease-in-out",- !isConnectionOptionsCollapsed && "border-t border-block-border"- )}- style={{- gridTemplateRows: !isConnectionOptionsCollapsed ? "1fr" : "0fr",- }}- inert={isConnectionOptionsCollapsed ? true : undefined}- >- <div className="overflow-hidden">- <div className="px-5 py-4">- <DataSourceForm- dataSource={editingDataSource}- optionsOnly- onDataSourceChange={handleDataSourceChange}- onOpenInfoPanel={onOpenInfoPanel}- />- </div>- </div>- </div>- </div>- )}-- {/* Test Connection button (create only) */}- {isCreating && !!editingDataSource && (- <div className="flex flex-col items-start gap-y-2">- <Button- appearance="outline"- disabled={!allowTestConnection || state.isTestingConnection}- onClick={(e) => {- e.preventDefault();- testConnectionForCurrentEditingDS();- }}- >- {state.isTestingConnection- ? t("instance.testing-connection")- : t("instance.test-connection")}- </Button>- {testConnectionFailure && (- <ConnectionRecovery- category={testConnectionFailure.failureCategory}- className="max-w-3xl"- />- )}- </div>- )}+ </FormSection></div></div>);diff --git a/frontend/src/components/instance/InstanceFormButtons.test.tsx b/frontend/src/components/instance/InstanceFormButtons.test.tsxindex 93223b234d..3c461249ee 100644--- a/frontend/src/components/instance/InstanceFormButtons.test.tsx+++ b/frontend/src/components/instance/InstanceFormButtons.test.tsx@@ -21,6 +21,8 @@ const mocks = vi.hoisted(() => ({routerPush: vi.fn(),pushNotification: vi.fn(),createInstance: vi.fn(),+ updateInstance: vi.fn(),+ getInstanceByName: vi.fn(),fetchDatabases: vi.fn(),batchUpdateDatabases: vi.fn(),captureMetric: vi.fn(),@@ -62,8 +64,12 @@ vi.mock("@/app/analytics/provider", () => ({vi.mock("@/stores/app", () => {const appState = {hasFeature: () => true,+ instanceLicenseCount: () => 100,+ activatedInstanceCount: () => 1,isSaaSMode: () => false,createInstance: mocks.createInstance,+ updateInstance: mocks.updateInstance,+ getInstanceByName: mocks.getInstanceByName,fetchDatabases: mocks.fetchDatabases,batchUpdateDatabases: mocks.batchUpdateDatabases,};@@ -79,6 +85,7 @@ vi.mock("@/stores", () => ({}));vi.mock("@/utils", () => ({+ calcUpdateMask: () => [],convertKVListToLabels: (list: { key: string; value: string }[]) =>Object.fromEntries(list.map(({ key, value }) => [key, value])),extractInstanceResourceName: (name: string) => name.split("/").at(-1) ?? "",@@ -214,6 +221,7 @@ beforeEach(() => {valueChanged: true,onDismiss: vi.fn(),emitShowConnectionOptions: vi.fn(),+ emitDataSourceReset: vi.fn(),};mocks.createInstance.mockResolvedValue(@@ -227,6 +235,61 @@ beforeEach(() => {});describe("InstanceFormButtons", () => {+ test("invalidates provider drafts only after a successful server-backed save", async () => {+ const saved = create(InstanceSchema, {+ name: "instances/prod",+ title: "Updated production",+ engine: Engine.POSTGRES,+ dataSources: [+ create(DataSourceSchema, {+ id: "admin",+ type: DataSourceType.ADMIN,+ host: "127.0.0.1",+ port: "5432",+ }),+ ],+ });+ let finishSave!: () => void;+ mocks.updateInstance.mockImplementation(+ () =>+ new Promise<void>((resolve) => {+ finishSave = resolve;+ })+ );+ mocks.getInstanceByName.mockReturnValue(saved);+ const emitDataSourceReset = vi.fn();+ mocks.context = {+ ...mocks.context,+ instance: create(InstanceSchema, { ...saved, title: "Old production" }),+ basicInfo: saved,+ isCreating: false,+ emitDataSourceReset,+ };+ const container = document.createElement("div");+ const root = createRoot(container);+ await act(async () => {+ root.render(<InstanceFormButtons />);+ });+ const update = Array.from(container.querySelectorAll("button")).find(+ (button) => button.textContent === "common.update"+ )!;+ expect(update.disabled).toBe(false);+ await act(async () => {+ update.click();+ });+ expect(mocks.updateInstance).toHaveBeenCalledOnce();+ expect(emitDataSourceReset).not.toHaveBeenCalled();+ await act(async () => {+ finishSave();+ });+ expect(mocks.getInstanceByName).toHaveBeenCalledWith(saved.name);+ expect(emitDataSourceReset).toHaveBeenCalledOnce();+ expect(mocks.context?.setDataSourceEditState).toHaveBeenCalledOnce();+ await act(async () => {+ root.unmount();+ });+ });+test("uses project-aware create action text when creating from a project", async () => {mocks.context = { ...mocks.context, parent: "projects/demo" };const container = document.createElement("div");diff --git a/frontend/src/components/instance/InstanceFormButtons.tsx b/frontend/src/components/instance/InstanceFormButtons.tsxindex 10926e6850..f8a137100d 100644--- a/frontend/src/components/instance/InstanceFormButtons.tsx+++ b/frontend/src/components/instance/InstanceFormButtons.tsx@@ -88,6 +88,8 @@ export function InstanceFormButtons({editingDataSource,readonlyDataSourceList,setDataSourceEditState,+ resetDataSource,+ emitDataSourceReset,hasReadonlyReplicaFeature,setMissingFeature,testConnection,@@ -111,6 +113,9 @@ export function InstanceFormButtons({const [connectionFailureResolver, setConnectionFailureResolver] = useState<((confirmed: boolean) => void) | undefined>();+ const [testConnectionFailure, setTestConnectionFailure] = useState<+ ConnectionFailureDialogState | undefined+ >();const checkExternalSecretFeature = (dataSources: DataSource[]) => {if (hasExternalSecretFeature) return true;@@ -163,6 +168,20 @@ export function InstanceFormButtons({checkDataSource,]);+ const allowTestConnection = useMemo(() => {+ if (!allowEdit || !editingDataSource) return false;+ if (basicInfo.engine === Engine.SPANNER) {+ return isValidSpannerDataSource(editingDataSource);+ }+ if (basicInfo.engine === Engine.BIGQUERY) {+ return isValidBigQueryDataSource(editingDataSource);+ }+ if (basicInfo.engine !== Engine.DYNAMODB && editingDataSource.host === "") {+ return false;+ }+ return checkDataSource([editingDataSource]);+ }, [allowEdit, basicInfo.engine, checkDataSource, editingDataSource]);+const hasConfiguredConnectionOptions = (ds: EditDataSource): boolean => {const hasExtraParameters =Object.keys(ds.extraConnectionParameters ?? {}).length > 0;@@ -214,10 +233,7 @@ export function InstanceFormButtons({const resetChanges = () => {const original = getOriginalEditState();setBasicInfo(cloneDeep(original.basicInfo));- setDataSourceEditState((prev) => ({- ...prev,- dataSources: cloneDeep(original.dataSources),- }));+ resetDataSource();};const buildCreateInstance = (): Instance => {@@ -490,6 +506,7 @@ export function InstanceFormButtons({.getState().getInstanceByName(inst.name);updateEditState(updatedInstance);+ emitDataSourceReset();pushNotification({module: "bytebase",style: "SUCCESS",@@ -508,6 +525,7 @@ export function InstanceFormButtons({const testConnectionForCurrentEditingDS = async () => {if (!editingDataSource) return;+ setTestConnectionFailure(undefined);behaviorAnalytics.captureMetric(createBehaviorMetric("instance connection test clicked", {routeId: router.currentRoute.value.name?.toString(),@@ -516,11 +534,29 @@ export function InstanceFormButtons({const testResult = await testConnection(editingDataSource, false);if (!testResult.success) {+ setTestConnectionFailure({+ open: false,+ message: testResult.message,+ failureCategory: testResult.failureCategory,+ });maybeOpenConnectionOptions(editingDataSource);}};+ const testConnectionFeedback = testConnectionFailure && (+ <div className="border-t border-block-border px-4 py-3 sm:px-6">+ <ConnectionRecovery+ category={testConnectionFailure.failureCategory}+ className="max-w-3xl"+ />+ <p className="mt-2 whitespace-pre-wrap break-all text-sm text-error">+ {testConnectionFailure.message}+ </p>+ </div>+ );+const cancel = () => {+ resetDataSource();onDismiss?.();};@@ -565,6 +601,7 @@ export function InstanceFormButtons({return (<>{connectionFailureDialog}+ {testConnectionFeedback}<StickyActionFooterclassName={className}left={@@ -579,20 +616,37 @@ export function InstanceFormButtons({) : undefined}right={- <Button- disabled={- !allowCreate || state.isRequesting || state.isTestingConnection- }- onClick={tryCreate}- >- {state.isRequesting- ? parent- ? t("instance.connecting-database-to-project")- : t("common.creating")- : parent- ? t("instance.connect-database-to-project")- : t("common.create")}- </Button>+ <>+ <Button+ appearance="secondary"+ disabled={+ !allowTestConnection ||+ state.isRequesting ||+ state.isTestingConnection+ }+ onClick={testConnectionForCurrentEditingDS}+ >+ {state.isTestingConnection+ ? t("instance.testing-connection")+ : t("instance.test-connection")}+ </Button>+ <Button+ disabled={+ !allowCreate ||+ state.isRequesting ||+ state.isTestingConnection+ }+ onClick={tryCreate}+ >+ {state.isRequesting+ ? parent+ ? t("instance.connecting-database-to-project")+ : t("common.creating")+ : parent+ ? t("instance.connect-database-to-project")+ : t("common.create")}+ </Button>+ </>}/></>@@ -605,6 +659,7 @@ export function InstanceFormButtons({return (<>{connectionFailureDialog}+ {testConnectionFeedback}<StickyActionFooterclassName={className}left={diff --git a/frontend/src/components/instance/InstanceFormContext.test.tsx b/frontend/src/components/instance/InstanceFormContext.test.tsxindex 9a4cb2321a..0757eda105 100644--- a/frontend/src/components/instance/InstanceFormContext.test.tsx+++ b/frontend/src/components/instance/InstanceFormContext.test.tsx@@ -189,6 +189,17 @@ const ConnectionProbe = ({);};+const DataSourceResetProbe = () => {+ const ctx = useInstanceFormContext();+ return (+ <button+ type="button"+ data-reset-event={String(ctx.dataSourceResetEvent)}+ onClick={ctx.resetDataSource}+ />+ );+};+const renderIntoContainer = () => {const container = document.createElement("div");const root = createRoot(container);@@ -256,6 +267,26 @@ describe("InstanceFormProvider", () => {harness.unmount();});+ test("emits a data source reset event for consumers with local form state", async () => {+ const harness = renderIntoContainer();++ await harness.render(+ <InstanceFormProvider>+ <DataSourceResetProbe />+ </InstanceFormProvider>+ );++ const trigger = harness.container.firstElementChild as HTMLButtonElement;+ expect(trigger.dataset.resetEvent).toBe("0");++ await act(async () => {+ trigger.click();+ });++ expect(trigger.dataset.resetEvent).toBe("1");+ harness.unmount();+ });+test.each([["HTTP 504", Code.Unavailable, false, false],["HTTP 504", Code.Unavailable, true, false],diff --git a/frontend/src/components/instance/InstanceFormContext.tsx b/frontend/src/components/instance/InstanceFormContext.tsxindex 58c02c4665..a92dc8c2fb 100644--- a/frontend/src/components/instance/InstanceFormContext.tsx+++ b/frontend/src/components/instance/InstanceFormContext.tsx@@ -131,6 +131,8 @@ export interface InstanceFormContextValue {valueChanged: boolean;isEditing: boolean;onDismiss?: () => void;+ dataSourceResetEvent: number;+ emitDataSourceReset: () => void;showConnectionOptionsEvent: number;emitShowConnectionOptions: () => void;}@@ -193,6 +195,7 @@ export function InstanceFormProvider({const [labelErrors, setLabelErrors] = useState<string[]>([]);const [showConnectionOptionsEvent, setShowConnectionOptionsEvent] =useState(0);+ const [dataSourceResetEvent, setDataSourceResetEvent] = useState(0);const syncedInstanceRef = useRef({name: instance?.name,state: instance?.state,@@ -478,9 +481,14 @@ export function InstanceFormProvider({hasPermission,]);+ const emitDataSourceReset = useCallback(() => {+ setDataSourceResetEvent((event) => event + 1);+ }, []);+const resetDataSource = useCallback(() => {setDataSourceEditState(extractDataSourceEditState(instance));- }, [instance]);+ emitDataSourceReset();+ }, [instance, emitDataSourceReset]);// Debounced to avoid expensive cloneDeep + extraction on every keystroke.const [pendingCreateInstance, setPendingCreateInstance] = useState<Instance>(@@ -724,6 +732,8 @@ export function InstanceFormProvider({valueChanged,isEditing,onDismiss,+ dataSourceResetEvent,+ emitDataSourceReset,showConnectionOptionsEvent,emitShowConnectionOptions,}),@@ -759,6 +769,8 @@ export function InstanceFormProvider({valueChanged,isEditing,onDismiss,+ dataSourceResetEvent,+ emitDataSourceReset,showConnectionOptionsEvent,emitShowConnectionOptions,]diff --git a/frontend/src/components/instance/SshConnectionForm.tsx b/frontend/src/components/instance/SshConnectionForm.tsxindex 11e6369964..17bad0f7a4 100644--- a/frontend/src/components/instance/SshConnectionForm.tsx+++ b/frontend/src/components/instance/SshConnectionForm.tsx@@ -1,7 +1,19 @@-import { type DragEvent, useCallback, useEffect, useState } from "react";+import {+ type DragEvent,+ type ReactNode,+ useCallback,+ useEffect,+ useState,+} from "react";import { useTranslation } from "react-i18next";+import {+ FormField,+ FormLabel,+ ResponsiveFormLayout,+} from "@/components/ui/form";import { Input } from "@/components/ui/input";-import { RadioGroup, RadioGroupItem } from "@/components/ui/radio-group";+import { SegmentedControl } from "@/components/ui/segmented-control";+import { Textarea } from "@/components/ui/textarea";import type { Instance } from "@/types/proto-es/v1/instance_service_pb";const SSH_TYPES = ["NONE", "TUNNEL+PK"] as const;@@ -16,6 +28,7 @@ interface SshValue {}interface SshConnectionFormProps {+ title?: ReactNode;value: SshValue;instance?: Instance;disabled?: boolean;@@ -37,6 +50,7 @@ function guessSshType(value: Partial<SshValue>): SshType {export function SshConnectionForm({value,+ title,instance: _instance,disabled = false,onChange,@@ -93,109 +107,99 @@ export function SshConnectionForm({}, []);return (- <>- {/* SSH type radio buttons */}- <RadioGroup- className="gap-x-4 mt-2"- value={sshType}- onValueChange={(value) => handleSelectType(value as SshType)}- >- {SSH_TYPES.map((type) => (- <RadioGroupItem- key={type}- value={type}+ <div className="flex flex-col gap-4">+ <FormField title={title ?? t("data-source.ssh-connection")}>+ <div className="flex flex-col gap-4">+ <SegmentedControl+ value={sshType}+ onValueChange={(value) => handleSelectType(value as SshType)}+ ariaLabel={t("data-source.ssh-connection")}+ options={SSH_TYPES.map((type) => ({+ value: type,+ label: getSshTypeLabel(type),+ }))}+ size="sm"disabled={disabled}- className="text-main"- >- {getSshTypeLabel(type)}- </RadioGroupItem>- ))}- </RadioGroup>-- {sshType !== "NONE" && (- <>- {/* Host and Port */}- <div className="sm:col-span-1 sm:col-start-1 mt-4 grid grid-cols-1 gap-y-6 gap-x-4 sm:grid-cols-4">- <div className="sm:col-span-3 sm:col-start-1">- <label htmlFor="sshHost" className="textlabel block">- {t("data-source.ssh.host")}- </label>- <Input- id="sshHost"- className="mt-2 w-full"- value={value.sshHost}- disabled={disabled}- onChange={(e) => onChange({ sshHost: e.target.value })}- />- </div>- <div className="sm:col-span-1">- <label htmlFor="sshPort" className="textlabel block">- {t("data-source.ssh.port")}- </label>- <Input- id="sshPort"- className="mt-2 w-full"- value={value.sshPort}- disabled={disabled}- onChange={(e) => {- const val = e.target.value;- if (val === "" || /^\d+$/.test(val)) {- onChange({ sshPort: val });- }- }}- />- </div>- </div>-- {/* User and Password */}- <div className="mt-2 grid grid-cols-1 gap-y-2 gap-x-4 border-none sm:grid-cols-3">- <div className="mt-2 sm:col-span-3 sm:col-start-1">- <label htmlFor="sshUser" className="textlabel block">- {t("data-source.ssh.user")}- </label>- <Input- id="sshUser"- className="mt-2 w-full"- value={value.sshUser}- disabled={disabled}- onChange={(e) => onChange({ sshUser: e.target.value })}- />- </div>- <div className="mt-2 sm:col-span-3 sm:col-start-1">- <label htmlFor="sshPassword" className="textlabel block">- {t("data-source.ssh.password")}- </label>- <Input- id="sshPassword"- className="mt-2 w-full"- placeholder={t("instance.password-write-only")}- value={value.sshPassword}- disabled={disabled}- onChange={(e) => onChange({ sshPassword: e.target.value })}- />- </div>- </div>-- {/* Private Key textarea with drag-and-drop */}- <div className="mt-4 sm:col-span-3 sm:col-start-1">- <div className="mt-2 sm:col-span-1 sm:col-start-1 flex flex-col">- <label htmlFor="sshPrivateKey" className="textlabel block">- {t("data-source.ssh.ssh-key")} ({t("common.optional")})- </label>- <textarea- id="sshPrivateKey"- className="w-full h-24 mt-2 whitespace-pre-wrap rounded-xs border border-control-border bg-transparent px-3 py-2 text-sm text-main transition-colors placeholder:text-control-placeholder focus:outline-hidden focus:ring-2 focus:ring-accent focus:border-accent disabled:cursor-not-allowed disabled:bg-control-bg disabled:opacity-50 resize-none"- value={value.sshPrivateKey}- disabled={disabled}- placeholder={t("common.sensitive-placeholder")}- onDrop={handleDrop}- onDragOver={handleDragOver}- onChange={(e) => onChange({ sshPrivateKey: e.target.value })}- />- </div>- </div>- </>- )}- </>+ />+ {sshType !== "NONE" && (+ <ResponsiveFormLayout>+ <fieldset className="flex flex-col gap-4 rounded-xs border border-control-border px-3 py-2">+ <legend className="px-1 textlabel">+ {t("data-source.ssh-connection")}+ </legend>+ <FormField>+ <FormLabel htmlFor="sshHost">+ {t("data-source.ssh.host")}+ </FormLabel>+ <div className="flex flex-wrap items-center gap-2">+ <Input+ id="sshHost"+ className="min-w-0 flex-1"+ value={value.sshHost}+ disabled={disabled}+ onChange={(e) => onChange({ sshHost: e.target.value })}+ />+ <FormLabel htmlFor="sshPort">+ {t("data-source.ssh.port")}+ </FormLabel>+ <Input+ id="sshPort"+ className="w-20 shrink-0"+ value={value.sshPort}+ disabled={disabled}+ onChange={(e) => {+ const val = e.target.value;+ if (val === "" || /^\d+$/.test(val))+ onChange({ sshPort: val });+ }}+ />+ </div>+ </FormField>+ <FormField>+ <FormLabel htmlFor="sshUser">+ {t("data-source.ssh.user")}+ </FormLabel>+ <Input+ id="sshUser"+ value={value.sshUser}+ disabled={disabled}+ onChange={(e) => onChange({ sshUser: e.target.value })}+ />+ </FormField>+ <FormField>+ <FormLabel htmlFor="sshPassword">+ {t("data-source.ssh.password")}+ </FormLabel>+ <Input+ id="sshPassword"+ placeholder={t("instance.password-write-only")}+ value={value.sshPassword}+ disabled={disabled}+ onChange={(e) => onChange({ sshPassword: e.target.value })}+ />+ </FormField>+ <FormField>+ <FormLabel htmlFor="sshPrivateKey">+ {t("data-source.ssh.ssh-key")} ({t("common.optional")})+ </FormLabel>+ <Textarea+ id="sshPrivateKey"+ className="w-full h-24 whitespace-pre-wrap resize-none"+ value={value.sshPrivateKey}+ disabled={disabled}+ placeholder={t("common.sensitive-placeholder")}+ onDrop={handleDrop}+ onDragOver={handleDragOver}+ onChange={(e) =>+ onChange({ sshPrivateKey: e.target.value })+ }+ />+ </FormField>+ </fieldset>+ </ResponsiveFormLayout>+ )}+ </div>+ </FormField>+ </div>);}diff --git a/frontend/src/components/instance/SslCertificateForm.test.tsx b/frontend/src/components/instance/SslCertificateForm.test.tsxindex d6473159ef..e7d384cde4 100644--- a/frontend/src/components/instance/SslCertificateForm.test.tsx+++ b/frontend/src/components/instance/SslCertificateForm.test.tsx@@ -191,7 +191,7 @@ describe("SslCertificateForm", () => {});});- test("keeps CA controls visible when verification is disabled", () => {+ test("hides CA controls when verification is disabled", () => {const container = document.createElement("div");document.body.appendChild(container);const root = createRoot(container);@@ -216,7 +216,9 @@ describe("SslCertificateForm", () => {expect(container.textContent).toContain("data-source.ssl.verification-disabled-description");- expect(container.textContent).toContain("data-source.ssl.ca-source.self");+ expect(container.textContent).not.toContain(+ "data-source.ssl.ca-source.self"+ );expect(container.textContent).not.toContain("data-source.ssl.ca-empty-uses-system-trust");@@ -482,6 +484,7 @@ describe("SslCertificateForm", () => {hasCertPath={true}hasKeyPath={true}showKeyAndCert={true}+ verify={true}/>);});diff --git a/frontend/src/components/instance/SslCertificateForm.tsx b/frontend/src/components/instance/SslCertificateForm.tsxindex 28db09ff9d..d7c1fb4a44 100644--- a/frontend/src/components/instance/SslCertificateForm.tsx+++ b/frontend/src/components/instance/SslCertificateForm.tsx@@ -1,8 +1,7 @@-import { Info } from "lucide-react";import { type DragEvent, useCallback } from "react";import { useTranslation } from "react-i18next";import { Badge } from "@/components/ui/badge";-import { FormField } from "@/components/ui/form";+import { FormField, ResponsiveFormLayout } from "@/components/ui/form";import { Input } from "@/components/ui/input";import {SegmentedControl,@@ -10,7 +9,6 @@ import {} from "@/components/ui/segmented-control";import { Switch } from "@/components/ui/switch";import { Tabs, TabsList, TabsPanel, TabsTrigger } from "@/components/ui/tabs";-import { Tooltip } from "@/components/ui/tooltip";import { Engine } from "@/types/proto-es/v1/common_pb";import {getLocalTlsCaSource,@@ -65,7 +63,6 @@ interface SslCertificateFormProps {caLabel?: string;certLabel?: string;keyLabel?: string;- showTooltip?: boolean;verify?: boolean;onVerifyChange?: (val: boolean) => void;engineType?: Engine;@@ -153,7 +150,6 @@ function CaSourceSelector({ariaLabel={t("data-source.ssl.ca-source.self")}options={options}disabled={disabled}- className="mt-2"size="sm"/>);@@ -203,7 +199,6 @@ function ClientCertSourceSelector({ariaLabel={t("data-source.ssl.client-cert-source.self")}options={options}disabled={disabled}- className="mt-2"size="sm"/>);@@ -244,7 +239,6 @@ export function SslCertificateForm({caLabel,certLabel,keyLabel,- showTooltip = true,verify = false,onVerifyChange,engineType = Engine.ENGINE_UNSPECIFIED,@@ -354,7 +348,7 @@ export function SslCertificateForm({) => (<divdata-slot="form-field-title"- className="flex items-center gap-x-2 text-base font-semibold leading-6 text-main"+ className="flex items-center gap-x-2 text-sm font-normal leading-5 text-control">{label}{showConfiguredBadge(hasStoredValue, visibleValue) && (@@ -405,8 +399,7 @@ export function SslCertificateForm({if (resolvedCaSource === LOCAL_TLS_CA_SOURCE_FILE_PATH) {return (- <FormField>- {renderLabel(resolvedCaPathLabel, hasCaPath, caPath)}+ <FormField title={renderLabel(resolvedCaPathLabel, hasCaPath, caPath)}><Inputdata-testid="tls-ca-path-input"value={caPath}@@ -419,8 +412,7 @@ export function SslCertificateForm({}return (- <FormField>- {renderLabel(resolvedCaLabel, hasCa, ca)}+ <FormField title={renderLabel(resolvedCaLabel, hasCa, ca)}><DroppableTextareavalue={ca}onChange={(val) => onCaChange?.(val)}@@ -440,9 +432,10 @@ export function SslCertificateForm({if (source === LOCAL_TLS_CLIENT_CERT_SOURCE_FILE_PATH) {return (- <div className="flex flex-col gap-y-2">- <FormField>- {renderLabel(resolvedCertPathLabel, hasCertPath, certPath)}+ <div className="flex flex-col gap-4">+ <FormField+ title={renderLabel(resolvedCertPathLabel, hasCertPath, certPath)}+ ><Inputdata-testid="tls-cert-path-input"value={certPath}@@ -451,8 +444,9 @@ export function SslCertificateForm({placeholder={resolvedCertPathLabel}/></FormField>- <FormField>- {renderLabel(resolvedKeyPathLabel, hasKeyPath, keyPath)}+ <FormField+ title={renderLabel(resolvedKeyPathLabel, hasKeyPath, keyPath)}+ ><Inputdata-testid="tls-key-path-input"value={keyPath}@@ -466,9 +460,8 @@ export function SslCertificateForm({}return (- <div className="flex flex-col gap-y-2">- <FormField>- {renderLabel(resolvedCertLabel, hasCert, cert)}+ <div className="flex flex-col gap-4">+ <FormField title={renderLabel(resolvedCertLabel, hasCert, cert)}><DroppableTextareavalue={cert}onChange={(val) => onCertChange?.(val)}@@ -476,8 +469,7 @@ export function SslCertificateForm({placeholder={resolvedCertPlaceholder}/></FormField>- <FormField>- {renderLabel(resolvedKeyLabel, hasKey, sslKey)}+ <FormField title={renderLabel(resolvedKeyLabel, hasKey, sslKey)}><DroppableTextareavalue={sslKey}onChange={(val) => onKeyChange?.(val)}@@ -492,9 +484,10 @@ export function SslCertificateForm({const renderLegacyMaterial = () => {if (resolvedCaSource === LOCAL_TLS_CA_SOURCE_FILE_PATH) {return (- <div className="flex flex-col gap-y-2">- <FormField>- {renderLabel(resolvedCaPathLabel, hasCaPath, caPath)}+ <div className="flex flex-col gap-4">+ <FormField+ title={renderLabel(resolvedCaPathLabel, hasCaPath, caPath)}+ ><Inputdata-testid="tls-ca-path-input"value={caPath}@@ -504,8 +497,9 @@ export function SslCertificateForm({/></FormField>{showKeyAndCertFields && (- <FormField>- {renderLabel(resolvedCertPathLabel, hasCertPath, certPath)}+ <FormField+ title={renderLabel(resolvedCertPathLabel, hasCertPath, certPath)}+ ><Inputdata-testid="tls-cert-path-input"value={certPath}@@ -516,8 +510,9 @@ export function SslCertificateForm({</FormField>)}{showKeyAndCertFields && (- <FormField>- {renderLabel(resolvedKeyPathLabel, hasKeyPath, keyPath)}+ <FormField+ title={renderLabel(resolvedKeyPathLabel, hasKeyPath, keyPath)}+ ><Inputdata-testid="tls-key-path-input"value={keyPath}@@ -607,24 +602,26 @@ export function SslCertificateForm({}return (- <div className="flex flex-row items-center gap-x-1">+ <FormField+ title={+ <span className="text-sm font-normal leading-5 text-control">+ {resolvedVerifyLabel}+ </span>+ }+ ><Switch+ className="self-start"+ aria-label={resolvedVerifyLabel}checked={verify}onCheckedChange={(val) => onVerifyChange?.(val)}disabled={disabled}/>- <span className="text-base font-semibold leading-6 text-main">- {resolvedVerifyLabel}- </span>- {showTooltip && (- <Tooltip- content={t("data-source.ssl.verify-certificate-tooltip")}- side="right"- >- <Info className="size-4 text-warning" />- </Tooltip>+ {!verify && (+ <p className="text-xs leading-4 text-control-light">+ {t("data-source.ssl.verification-disabled-description")}+ </p>)}- </div>+ </FormField>);};@@ -640,40 +637,47 @@ export function SslCertificateForm({return (<>- <fieldset className="flex flex-col gap-y-2 rounded-xs border border-control-border px-3 py-2">+ <fieldset className="flex flex-col gap-4 rounded-xs border border-control-border px-3 py-2"><legend className="px-1 textlabel">{t("data-source.ssl.server-identity")}</legend>{renderVerifyControl()}- {!verify && (- <p className="text-xs textinfolabel">- {t("data-source.ssl.verification-disabled-description")}- </p>+ {verify && (+ <div className="flex flex-col gap-4">+ {showCaSourceUi && (+ <FormField+ title={+ <span className="text-sm font-normal leading-5 text-control">+ {t("data-source.ssl.ca-source.self")}+ </span>+ }+ >+ <CaSourceSelector+ value={resolvedCaSource}+ onChange={onCaSourceChange!}+ disabled={disabled}+ isSaaSMode={isSaaSMode}+ />+ </FormField>+ )}+ {renderCaMaterial()}+ </div>)}- <div className="flex flex-col gap-y-2">- {showCaSourceUi && (- <FormField title={<>{t("data-source.ssl.ca-source.self")}</>}>- <CaSourceSelector- value={resolvedCaSource}- onChange={onCaSourceChange!}- disabled={disabled}- isSaaSMode={isSaaSMode}- />- </FormField>- )}- {renderCaMaterial()}- </div></fieldset>{resolvedPosture === LOCAL_TLS_POSTURE_MUTUAL_TLS && (- <fieldset className="flex flex-col gap-y-2 rounded-xs border border-control-border px-3 py-2">+ <fieldset className="flex flex-col gap-4 rounded-xs border border-control-border px-3 py-2"><legend className="px-1 textlabel">{t("data-source.ssl.client-identity")}</legend>- <div className="flex flex-col gap-y-2">+ <div className="flex flex-col gap-4">{showClientCertSourceUi && (<FormField- title={<>{t("data-source.ssl.client-cert-source.self")}</>}+ title={+ <span className="text-sm font-normal leading-5 text-control">+ {t("data-source.ssl.client-cert-source.self")}+ </span>+ }><ClientCertSourceSelectorvalue={clientIdentitySource}@@ -692,7 +696,7 @@ export function SslCertificateForm({};return (- <div className="mt-2 flex flex-col gap-y-3">+ <ResponsiveFormLayout className="flex flex-col gap-4">{showPostureUi && (<>{renderPostureControl()}@@ -707,7 +711,7 @@ export function SslCertificateForm({onCheckedChange={(val) => onUseSslChange?.(val)}disabled={disabled}/>- <span className="text-base font-semibold leading-6 text-main">+ <span className="text-sm font-normal leading-5 text-control">{t("data-source.ssl-connection")}</span></div>@@ -721,26 +725,36 @@ export function SslCertificateForm({renderLegacyMaterial()) : (<>- <div className="flex flex-col gap-y-2">- {showCaSourceUi && (- <FormField title={<>{t("data-source.ssl.ca-source.self")}</>}>- <CaSourceSelector- value={resolvedCaSource}- onChange={onCaSourceChange!}- disabled={disabled}- isSaaSMode={isSaaSMode}- />- </FormField>- )}- {renderCaMaterial()}- </div>+ {verify && (+ <div className="flex flex-col gap-4">+ {showCaSourceUi && (+ <FormField+ title={+ <span className="text-sm font-normal leading-5 text-control">+ {t("data-source.ssl.ca-source.self")}+ </span>+ }+ >+ <CaSourceSelector+ value={resolvedCaSource}+ onChange={onCaSourceChange!}+ disabled={disabled}+ isSaaSMode={isSaaSMode}+ />+ </FormField>+ )}+ {renderCaMaterial()}+ </div>+ )}{showKeyAndCertFields && (- <div className="flex flex-col gap-y-2">+ <div className="flex flex-col gap-4">{showClientCertSourceUi && (<FormFieldtitle={- <>{t("data-source.ssl.client-cert-source.self")}</>+ <span className="text-sm font-normal leading-5 text-control">+ {t("data-source.ssl.client-cert-source.self")}+ </span>}><ClientCertSourceSelector@@ -759,6 +773,6 @@ export function SslCertificateForm({)}</>)}- </div>+ </ResponsiveFormLayout>);}diff --git a/frontend/src/components/instance/data-source-drafts.test.ts b/frontend/src/components/instance/data-source-drafts.test.tsnew file mode 100644index 0000000000..5d7333b96f--- /dev/null+++ b/frontend/src/components/instance/data-source-drafts.test.ts@@ -0,0 +1,33 @@+import { describe, expect, test } from "vitest";+import {+ invalidateSourceDrafts,+ type SourceDraftState,+} from "./data-source-drafts";++const initialState: SourceDraftState = {+ instanceName: "instances/production",+ resetEvent: 0,+};++describe("invalidateSourceDrafts", () => {+ test("keeps drafts while switching providers in the same edit", () => {+ const drafts = new Map([["admin", new Map([[1, "vault token"]])]]);++ const next = invalidateSourceDrafts(drafts, initialState, initialState);++ expect(next).toEqual(initialState);+ expect(drafts.get("admin")?.get(1)).toBe("vault token");+ });++ test("discards abandoned provider credentials after a form reset", () => {+ const drafts = new Map([["admin", new Map([[1, "vault token"]])]]);++ const next = invalidateSourceDrafts(drafts, initialState, {+ ...initialState,+ resetEvent: 1,+ });++ expect(next.resetEvent).toBe(1);+ expect(drafts).toHaveLength(0);+ });+});diff --git a/frontend/src/components/instance/data-source-drafts.ts b/frontend/src/components/instance/data-source-drafts.tsnew file mode 100644index 0000000000..df6790bb23--- /dev/null+++ b/frontend/src/components/instance/data-source-drafts.ts@@ -0,0 +1,18 @@+export type SourceDraftState = {+ instanceName: string | undefined;+ resetEvent: number;+};++export function invalidateSourceDrafts<T>(+ drafts: Map<string, Map<number, T>>,+ previous: SourceDraftState,+ next: SourceDraftState+): SourceDraftState {+ if (+ previous.instanceName !== next.instanceName ||+ previous.resetEvent !== next.resetEvent+ ) {+ drafts.clear();+ }+ return next;+}diff --git a/frontend/src/components/ui/form.test.tsx b/frontend/src/components/ui/form.test.tsxindex afe99292a8..dba028285b 100644--- a/frontend/src/components/ui/form.test.tsx+++ b/frontend/src/components/ui/form.test.tsx@@ -3,12 +3,14 @@ import { join } from "node:path";import * as stylex from "@stylexjs/stylex";import { act, createElement, type ReactElement } from "react";import { createRoot } from "react-dom/client";-import { afterEach, describe, expect, test } from "vitest";+import { afterEach, describe, expect, test, vi } from "vitest";import {FormControlGroup,FormControlRow,FormError,FormField,+ FormLabel,+ ResponsiveFormLayout,FormFieldGroup,FormSection,FormTitle,@@ -260,3 +262,58 @@ describe("Form section layouts", () => {}});});++describe("responsive form fields", () => {+ test("preserves vertical consumers and associates labels after horizontal reflow", () => {+ const container = document.createElement("div");+ document.body.append(container);+ const root = createRoot(container);+ const field = (+ <FormField>+ <FormLabel htmlFor="form-test-host">Host</FormLabel>+ <input id="form-test-host" />+ </FormField>+ );+ act(() => root.render(field));+ expect(container.querySelector('[data-slot="form-field-control"]')).toBeNull();+ expect(container.querySelector("input")?.labels?.[0]?.textContent).toBe("Host");+ act(() => root.render(+ <ResponsiveFormLayout layout="horizontal">{field}</ResponsiveFormLayout>+ ));+ expect(container.querySelector('[data-slot="form-field-control"] input')).not.toBeNull();+ expect(container.querySelector("input")?.labels?.[0]?.textContent).toBe("Host");+ act(() => root.unmount());+ container.remove();+ });+});+++test("reflows with the form width and preserves input values", () => {+ let resize: ResizeObserverCallback | undefined;+ vi.stubGlobal("ResizeObserver", class {+ constructor(callback: ResizeObserverCallback) { resize = callback; }+ observe() {}+ disconnect() {}+ });+ const { container, unmount } = renderIntoContainer(+ <ResponsiveFormLayout>+ <FormField title="Name"><input defaultValue="production" /></FormField>+ </ResponsiveFormLayout>+ );+ try {+ act(() => resize?.(+ [{ contentRect: { width: 700 } } as ResizeObserverEntry],+ {} as ResizeObserver+ ));+ expect(container.querySelector('[data-slot="form-field-control"] input')).not.toBeNull();+ act(() => resize?.(+ [{ contentRect: { width: 400 } } as ResizeObserverEntry],+ {} as ResizeObserver+ ));+ expect(container.querySelector('[data-slot="form-field-control"]')).toBeNull();+ expect(container.querySelector("input")?.value).toBe("production");+ } finally {+ unmount();+ vi.unstubAllGlobals();+ }+});diff --git a/frontend/src/components/ui/form.tsx b/frontend/src/components/ui/form.tsxindex 2e32ad7666..ed17d0f1ba 100644--- a/frontend/src/components/ui/form.tsx+++ b/frontend/src/components/ui/form.tsx@@ -1,13 +1,29 @@import * as stylex from "@stylexjs/stylex";-import type { ComponentProps, ReactNode } from "react";+import {+ Children,+ type ComponentProps,+ createContext,+ forwardRef,+ type ReactNode,+ useContext,+ useEffect,+ useRef,+ useState,+} from "react";import { cn } from "@/lib/utils";import {+ denseFormContentStyle,+ denseFormHeaderStyle,+ denseFormSectionStyle,+ denseFormTitleStyle,formControlGroupStyle,formControlRowStyle,formErrorStyle,+ formFieldControlStyle,formFieldDescriptionStyle,formFieldGroupStyle,formFieldHeaderStyle,+ formFieldHorizontalStyle,formFieldStyle,formFieldTitleStyle,formLabelStyle,@@ -17,9 +33,72 @@ import {formSectionTitleStyle,} from "./styles.stylex";+type FormLayout = "vertical" | "horizontal";++const FormLayoutContext = createContext<FormLayout>("vertical");++interface ResponsiveFormLayoutProps extends Omit<ComponentProps<"div">, "ref"> {+ /**+ * Uses label/control rows when this layout region has enough room. This is+ * intentionally based on the region width, so a docked side panel does not+ * leave fields stranded in a viewport-sized two-column layout.+ */+ layout?: "responsive" | FormLayout;+ horizontalMinWidth?: number;+}++const ResponsiveFormLayout = forwardRef<+ HTMLDivElement,+ ResponsiveFormLayoutProps+>(function ResponsiveFormLayout(+ { children, horizontalMinWidth = 560, layout = "responsive", ...props },+ ref+) {+ const layoutRef = useRef<HTMLDivElement>(null);+ const [isHorizontal, setIsHorizontal] = useState(layout === "horizontal");++ useEffect(() => {+ if (layout !== "responsive") {+ setIsHorizontal(layout === "horizontal");+ return;+ }+ const element = layoutRef.current;+ if (!element) return;+ const update = (width: number) =>+ setIsHorizontal(width >= horizontalMinWidth);+ update(element.clientWidth);+ const observer = new ResizeObserver((entries) => {+ update(entries[0]?.contentRect.width ?? 0);+ });+ observer.observe(element);+ return () => observer.disconnect();+ }, [horizontalMinWidth, layout]);++ return (+ <FormLayoutContext.Provider+ value={isHorizontal ? "horizontal" : "vertical"}+ >+ <div+ ref={(element) => {+ layoutRef.current = element;+ if (typeof ref === "function") {+ ref(element);+ } else if (ref) {+ ref.current = element;+ }+ }}+ {...props}+ >+ {children}+ </div>+ </FormLayoutContext.Provider>+ );+});+interface FormFieldProps extends Omit<ComponentProps<"div">, "title"> {title?: ReactNode;description?: ReactNode;+ layout?: FormLayout;}/**@@ -41,12 +120,40 @@ function FormField({ref,style,title,+ layout: layoutOverride,...props}: FormFieldProps) {- const fieldStylexProps = stylex.props(formFieldStyle());+ const inheritedLayout = useContext(FormLayoutContext);+ const layout = layoutOverride ?? inheritedLayout;+ const fieldStylexProps = stylex.props(+ formFieldStyle(),+ (title !== undefined ||+ Children.toArray(children).some(+ (child) =>+ typeof child === "object" &&+ child !== null &&+ "type" in child &&+ child.type === FormLabel+ )) &&+ layout === "horizontal" &&+ formFieldHorizontalStyle()+ );const headerStylexProps = stylex.props(formFieldHeaderStyle());const descriptionStylexProps = stylex.props(formFieldDescriptionStyle());- const hasHeader = title !== undefined || description !== undefined;+ const controlStylexProps = stylex.props(formFieldControlStyle());+ const childArray = layout === "horizontal" ? Children.toArray(children) : [];+ const firstChild = childArray[0];+ const label =+ layout === "horizontal" &&+ title === undefined &&+ firstChild &&+ typeof firstChild === "object" &&+ "type" in firstChild &&+ firstChild.type === FormLabel+ ? firstChild+ : undefined;+ const controlChildren = label ? childArray.slice(1) : childArray;+ const hasHeader = title !== undefined || description !== undefined || label;return (<div@@ -62,7 +169,7 @@ function FormField({className={headerStylexProps.className}style={headerStylexProps.style}>- {title !== undefined && <FormTitle>{title}</FormTitle>}+ {title !== undefined ? <FormTitle>{title}</FormTitle> : label}{description !== undefined && (<divdata-slot="form-field-description"@@ -74,7 +181,19 @@ function FormField({)}</div>)}- {children}+ {layout === "horizontal" ? (+ <div+ data-slot="form-field-control"+ className={controlStylexProps.className}+ style={controlStylexProps.style}+ >+ <FormLayoutContext.Provider value="vertical">+ {controlChildren}+ </FormLayoutContext.Provider>+ </div>+ ) : (+ children+ )}</div>);}@@ -93,7 +212,10 @@ function FormField({* ```*/function FormTitle({ className, ref, style, ...props }: ComponentProps<"div">) {- const stylexProps = stylex.props(formFieldTitleStyle());+ const layout = useContext(FormLayoutContext);+ const stylexProps = stylex.props(+ layout === "horizontal" ? formLabelStyle() : formFieldTitleStyle()+ );return (<divref={ref}@@ -140,6 +262,7 @@ function FormFieldGroup({interface FormSectionProps extends Omit<ComponentProps<"section">, "title"> {title: ReactNode;+ layout?: "default" | "stacked";}/**@@ -163,12 +286,21 @@ function FormSection({ref,style,title,+ layout = "default",...props}: FormSectionProps) {- const sectionStylexProps = stylex.props(formSectionStyle());- const headerStylexProps = stylex.props(formSectionHeaderStyle());- const titleStylexProps = stylex.props(formSectionTitleStyle());- const contentStylexProps = stylex.props(formSectionContentStyle());+ const sectionStylexProps = stylex.props(+ layout === "stacked" ? denseFormSectionStyle() : formSectionStyle()+ );+ const headerStylexProps = stylex.props(+ layout === "stacked" ? denseFormHeaderStyle() : formSectionHeaderStyle()+ );+ const titleStylexProps = stylex.props(+ layout === "stacked" ? denseFormTitleStyle() : formSectionTitleStyle()+ );+ const contentStylexProps = stylex.props(+ layout === "stacked" ? denseFormContentStyle() : formSectionContentStyle()+ );return (<section@@ -336,4 +468,5 @@ export {FormLabel,FormSection,FormTitle,+ ResponsiveFormLayout,};diff --git a/frontend/src/components/ui/segmented-control.test.tsx b/frontend/src/components/ui/segmented-control.test.tsxnew file mode 100644index 0000000000..cdc9c929a1--- /dev/null+++ b/frontend/src/components/ui/segmented-control.test.tsx@@ -0,0 +1,116 @@+import { act, createElement, type ReactElement, useState } from "react";+import { createRoot } from "react-dom/client";+import { afterEach, describe, expect, test, vi } from "vitest";+import { SegmentedControl } from "./segmented-control";++(+ globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }+).IS_REACT_ACT_ENVIRONMENT = true;++const renderIntoContainer = (element: ReactElement) => {+ const container = document.createElement("div");+ document.body.appendChild(container);+ const root = createRoot(container);+ act(() => {+ root.render(element);+ });+ return {+ container,+ unmount: () =>+ act(() => {+ root.unmount();+ container.remove();+ }),+ };+};++const providerOptions = [+ { value: "password", label: "Password" },+ { value: "vault", label: "HashiCorp Vault" },+ { value: "aws", label: "AWS Secrets Manager" },+ { value: "gcp", label: "Google Secret Manager" },+ { value: "azure", label: "Azure Key Vault", disabled: true },+];++describe("SegmentedControl", () => {+ afterEach(() => {+ document.body.innerHTML = "";+ });++ test("keeps wrapped provider segments separated by control-border gutters", () => {+ const { container, unmount } = renderIntoContainer(+ createElement(SegmentedControl, {+ ariaLabel: "Password source",+ "aria-describedby": "password-source-description",+ value: "password",+ onValueChange: () => undefined,+ options: providerOptions,+ })+ );++ const group = container.querySelector('[role="radiogroup"]');+ expect(group?.className).toContain("flex-wrap");+ expect(group?.className).toContain("gap-px");+ expect(group?.className).toContain("border-control-border");+ expect(group?.className).toContain("bg-control-border");+ expect(group?.className?.split(" ")).not.toContain("p-px");+ expect(group?.getAttribute("aria-describedby")).toBe(+ "password-source-description"+ );++ const segments = [...container.querySelectorAll("label")];+ expect(segments).toHaveLength(providerOptions.length);+ expect(segments.every((segment) => segment.className.includes("flex-auto"))).toBe(+ true+ );+ expect(segments.every((segment) => !segment.className.includes("border-l"))).toBe(+ true+ );+ expect(segments[0]?.className).toContain("bg-accent");+ expect(segments[4]?.className).toContain("cursor-not-allowed");+ expect(segments[4]?.className).toContain("opacity-50");++ unmount();+ });++ test("keeps radio semantics and ignores disabled segments", () => {+ const onValueChange = vi.fn();+ function ControlledSegmentedControl() {+ const [value, setValue] = useState("password");+ return (+ <SegmentedControl+ ariaLabel="Password source"+ value={value}+ onValueChange={(nextValue) => {+ onValueChange(nextValue);+ setValue(nextValue);+ }}+ options={providerOptions}+ />+ );+ }++ const { container, unmount } = renderIntoContainer(+ createElement(ControlledSegmentedControl)+ );+ const radios = [+ ...container.querySelectorAll<HTMLElement>('[role="radio"]'),+ ];++ expect(radios).toHaveLength(providerOptions.length);+ expect(radios[0]?.getAttribute("aria-checked")).toBe("true");+ act(() => {+ radios[2]?.click();+ });+ expect(onValueChange).toHaveBeenLastCalledWith("aws");+ expect(radios[2]?.getAttribute("aria-checked")).toBe("true");++ act(() => {+ radios[4]?.click();+ });+ expect(onValueChange).toHaveBeenCalledTimes(1);+ expect(radios[4]?.getAttribute("aria-disabled")).toBe("true");++ unmount();+ });+});diff --git a/frontend/src/components/ui/segmented-control.tsx b/frontend/src/components/ui/segmented-control.tsxindex 5d28797b84..37bb3e8f07 100644--- a/frontend/src/components/ui/segmented-control.tsx+++ b/frontend/src/components/ui/segmented-control.tsx@@ -18,6 +18,7 @@ interface SegmentedControlProps<T extends string> {options: SegmentedControlOption<T>[];onValueChange: (value: T) => void;ariaLabel: string;+ "aria-describedby"?: string;appearance?: "solid" | "soft";disabled?: boolean;className?: string;@@ -30,6 +31,7 @@ export function SegmentedControl<T extends string>({options,onValueChange,ariaLabel,+ "aria-describedby": ariaDescribedBy,appearance = "solid",disabled = false,className,@@ -43,26 +45,22 @@ export function SegmentedControl<T extends string>({}}disabled={disabled}aria-label={ariaLabel}+ aria-describedby={ariaDescribedBy}className={cn(- "inline-flex max-w-full flex-wrap self-start rounded-xs border border-control-border bg-background",+ "inline-flex max-w-full flex-wrap gap-px self-start rounded-xs border border-control-border bg-control-border",className)}>- {options.map((option, index) => {+ {options.map((option) => {const selected = option.value === value;- const previousSelected =- index > 0 && options[index - 1]?.value === value;const optionDisabled = disabled || option.disabled;const stylexProps = stylex.props(controlMinHeightStyle(size));const segment = (<labelkey={option.value}className={cn(- "relative inline-flex items-center justify-center transition-colors focus-within:outline-hidden focus-within:ring-2 focus-within:ring-accent focus-within:ring-inset",+ "relative inline-flex flex-auto items-center justify-center transition-colors focus-within:outline-hidden focus-within:ring-2 focus-within:ring-accent focus-within:ring-inset",stylexProps.className,- index > 0 &&- !previousSelected &&- "border-l border-control-border",selected? appearance === "soft"? "bg-accent/10 text-accent"diff --git a/frontend/src/components/ui/styles.stylex.ts b/frontend/src/components/ui/styles.stylex.tsindex bf20cf3372..30c55fd40b 100644--- a/frontend/src/components/ui/styles.stylex.ts+++ b/frontend/src/components/ui/styles.stylex.ts@@ -212,6 +212,19 @@ const formStyles = stylex.create({flexDirection: "column",rowGap: 6,},+ fieldHorizontal: {+ alignItems: "start",+ columnGap: 16,+ display: "grid",+ gridTemplateColumns: "160px minmax(0, 1fr)",+ rowGap: 0,+ },+ fieldControl: {+ display: "flex",+ flexDirection: "column",+ minWidth: 0,+ rowGap: 6,+ },fieldGroup: {display: "flex",flexDirection: "column",@@ -281,6 +294,14 @@ export function formFieldStyle() {return formStyles.field;}+export function formFieldHorizontalStyle() {+ return formStyles.fieldHorizontal;+}++export function formFieldControlStyle() {+ return formStyles.fieldControl;+}+export function formLabelStyle() {return formStyles.label;}@@ -495,3 +516,32 @@ export function listRowSecondaryTextStyle() {export function interactiveRowStyle(size: RowSize = "sm") {return listRowStyle(size);}++const denseFormStyles = stylex.create({+ section: {+ display: "flex",+ flexDirection: "column",+ rowGap: 16,+ paddingBlock: 16,+ },+ header: { width: "100%" },+ content: { minWidth: 0 },+ title: {+ color: "rgb(var(--color-main))",+ fontSize: 16,+ lineHeight: "24px",+ fontWeight: 600,+ },+});+export function denseFormSectionStyle() {+ return denseFormStyles.section;+}+export function denseFormHeaderStyle() {+ return denseFormStyles.header;+}+export function denseFormContentStyle() {+ return denseFormStyles.content;+}+export function denseFormTitleStyle() {+ return denseFormStyles.title;+}diff --git a/frontend/src/components/ui/switch.tsx b/frontend/src/components/ui/switch.tsxindex cccc097ee5..ac07e97b24 100644--- a/frontend/src/components/ui/switch.tsx+++ b/frontend/src/components/ui/switch.tsx@@ -39,6 +39,7 @@ interface SwitchProps {*/"aria-label"?: string;"aria-labelledby"?: string;+ "aria-describedby"?: string;id?: string;}@@ -51,6 +52,7 @@ function Switch({id,"aria-label": ariaLabel,"aria-labelledby": ariaLabelledBy,+ "aria-describedby": ariaDescribedBy,}: SwitchProps) {const sizeClasses = SWITCH_SIZES[size];@@ -62,6 +64,7 @@ function Switch({id={id}aria-label={ariaLabel}aria-labelledby={ariaLabelledBy}+ aria-describedby={ariaDescribedBy}className={cn("relative inline-flex cursor-pointer items-center rounded-full transition-colors",sizeClasses.root,diff --git a/frontend/src/locales/en-US.json b/frontend/src/locales/en-US.jsonindex 0533c77b38..f0f53724f0 100644--- a/frontend/src/locales/en-US.json+++ b/frontend/src/locales/en-US.json@@ -682,9 +682,8 @@"tls": "TLS"},"server-identity": "Server identity",- "verification-disabled-description": "Verification is disabled. The connection is encrypted, but the server identity is not verified; CA settings are ignored.",- "verify-certificate": "Verify server certificate",- "verify-certificate-tooltip": "Enable TLS certificate verification for secure connections. Disable only for development or when certificates cannot be properly validated (e.g., self-signed certs, VPN environments). Warning: Disabling verification is insecure"+ "verification-disabled-description": "Verification is disabled. The connection is encrypted, but the server identity is not verified; CA settings are ignored. This is insecure. Enable verification for secure connections; disable it only temporarily for development or troubleshooting.",+ "verify-certificate": "Verify server certificate"},"ssl-connection": "SSL Connection"},@@ -964,6 +963,8 @@},"instance": {"account-locator": "Account Locator",+ "add-labels": "Add labels",+ "add-parameter": "Add parameter","advanced-search": {"scope": {"host": {@@ -978,6 +979,7 @@},"archive-instance-instance-name": "Archive instance '{{0}}'?","archived-instances-will-not-be-displayed": "Archived instances will not be displayed.",+ "authentication": "Authentication","authentication-database": "Authentication Database","cloud-sql-ip-type": {"description": "Use Private IP when the instance has no public IP and Bytebase runs in the same VPC.",@@ -989,8 +991,8 @@"connect-database-to-project": "Connect database to project","connect-instance": "Connect instance","connecting-database-to-project": "Connecting database...",+ "connection-database": "Connection database","connection-info": "Connection info",- "connection-options": "Connection Options","connection-recovery": {"auth": {"description": "Verify the username, password, token, or IAM authentication settings, then test the connection again.",@@ -1123,7 +1125,7 @@"gcp-endpoint-tip": "Optional. Overrides the default Google API endpoint, e.g. with a Private Service Connect endpoint like {{example}}.","gcp-endpoint-toggle": "Set a custom API endpoint","grants": "Grants",- "host-or-socket": "Host or Socket",+ "hostname": "Hostname","iam-extension": {"client-id": "Client ID","client-secret": "Client Secret",@@ -1212,6 +1214,9 @@"keytab-resupply-required": "This data source now connects somewhere new. Re-upload the keytab to confirm you still hold it.","keytab-upload-placeholder": "Click or drag your .keytab file here","keytab-write-only": "Keytab is write-only. Upload a new file to replace the existing one.",+ "master-name": "Master name",+ "master-password": "Master password",+ "master-username": "Master username","new-instance": "New Instance","no-environment": "This instance has not been bound to the environment","no-extra-params-configured": "No extra connection parameters configured",@@ -1220,6 +1225,11 @@"open-data-source": "Open this data source to see what it needs.","parameter-name-placeholder": "Parameter name","parameter-value-placeholder": "Parameter value",+ "password-source": {+ "bytebase": "Bytebase",+ "self": "Password source",+ "stored-in-bytebase": "Stored in Bytebase"+ },"password-type": {"aws-iam": "AWS RDS IAM","azure-iam": "Azure IAM",@@ -1329,9 +1339,13 @@},"sync-databases": {"add-database": "+ Add database, press enter to submit",+ "all-databases": "All databases","description": "Choose which databases to sync from this instance.",+ "hostname-required": "Enter a hostname to choose which databases to sync.","project-sync-all": "Sync all databases to this project",+ "required-fields": "Complete the required fields above to choose which databases to sync.","search-database": "Search database",+ "selected-databases": "Selected databases","self": "Sync Databases","sync-all": "Sync all databases"},diff --git a/frontend/src/locales/es-ES.json b/frontend/src/locales/es-ES.jsonindex cc258c405e..4a24ab6297 100644--- a/frontend/src/locales/es-ES.json+++ b/frontend/src/locales/es-ES.json@@ -682,9 +682,8 @@"tls": "TLS"},"server-identity": "Identidad del servidor",- "verification-disabled-description": "La verificación está deshabilitada. La conexión está cifrada, pero la identidad del servidor no se verifica; la configuración de CA se ignora.",- "verify-certificate": "Verificar certificado del servidor",- "verify-certificate-tooltip": "Habilitar la verificación del certificado TLS para conexiones seguras. Deshabilitar solo para desarrollo o cuando los certificados no se pueden validar correctamente (por ejemplo, certificados autofirmados, entornos VPN). Advertencia: Deshabilitar la verificación es inseguro"+ "verification-disabled-description": "La verificación está desactivada. La conexión está cifrada, pero no se verifica la identidad del servidor y se ignora la configuración de CA. Esto es inseguro. Activa la verificación para conexiones seguras; desactívala solo temporalmente durante el desarrollo o la resolución de problemas.",+ "verify-certificate": "Verificar certificado del servidor"},"ssl-connection": "Conexión SSL"},@@ -964,6 +963,8 @@},"instance": {"account-locator": "Localizadora de cuentas",+ "add-labels": "Añadir etiquetas",+ "add-parameter": "Añadir parámetro","advanced-search": {"scope": {"host": {@@ -978,6 +979,7 @@},"archive-instance-instance-name": "¿Archivar la instancia '{{0}}'?","archived-instances-will-not-be-displayed": "Las instancias archivadas no se mostrarán.",+ "authentication": "Autenticación","authentication-database": "Base de datos de autenticación","cloud-sql-ip-type": {"description": "Usa IP privada cuando la instancia no tiene IP pública y Bytebase se ejecuta en la misma VPC.",@@ -989,8 +991,8 @@"connect-database-to-project": "Conectar base de datos al proyecto","connect-instance": "Conectar instancia","connecting-database-to-project": "Conectando base de datos...",+ "connection-database": "Base de datos de conexión","connection-info": "Información de conexión",- "connection-options": "Opciones de conexión","connection-recovery": {"auth": {"description": "Verifica el usuario, la contraseña, el token o la configuración de autenticación IAM y vuelve a probar la conexión.",@@ -1123,7 +1125,7 @@"gcp-endpoint-tip": "Opcional. Reemplaza el punto de conexión predeterminado de la API de Google, p. ej., un punto de conexión de Private Service Connect como {{example}}.","gcp-endpoint-toggle": "Configurar un punto de conexión de API personalizado","grants": "Concesiones",- "host-or-socket": "Host o Socket",+ "hostname": "Nombre de host","iam-extension": {"client-id": "Client ID","client-secret": "Client Secret",@@ -1212,6 +1214,9 @@"keytab-resupply-required": "Esta fuente de datos ahora se conecta a un destino nuevo. Vuelva a subir el keytab para confirmar que todavía lo tiene.","keytab-upload-placeholder": "Haga clic o arrastre su archivo .keytab aquí","keytab-write-only": "El keytab es de solo escritura. Suba un archivo nuevo para reemplazar el existente.",+ "master-name": "Nombre del nodo maestro",+ "master-password": "Contraseña del nodo maestro",+ "master-username": "Usuario del nodo maestro","new-instance": "Nueva instancia","no-environment": "Esta instancia no ha sido ligada al entorno.","no-extra-params-configured": "No hay parámetros de conexión adicionales configurados",@@ -1220,6 +1225,11 @@"open-data-source": "Abra esta fuente de datos para ver qué necesita.","parameter-name-placeholder": "Nombre de parámetro","parameter-value-placeholder": "Valor de parámetro",+ "password-source": {+ "bytebase": "Bytebase",+ "self": "Origen de la contraseña",+ "stored-in-bytebase": "Almacenada en Bytebase"+ },"password-type": {"aws-iam": "AWS RDS IAM","azure-iam": "Azure IAM",@@ -1329,9 +1339,13 @@},"sync-databases": {"add-database": "+ Agregar base de datos, presione enter para enviar",+ "all-databases": "Todas las bases de datos","description": "Elige qué bases de datos sincronizar desde esta instancia.",+ "hostname-required": "Introduce un nombre de host para elegir qué bases de datos sincronizar.","project-sync-all": "Sincronizar todas las bases de datos con este proyecto",+ "required-fields": "Completa los campos obligatorios de arriba para elegir qué bases de datos sincronizar.","search-database": "Buscar en la base de datos",+ "selected-databases": "Bases de datos seleccionadas","self": "Sincronizar bases de datos","sync-all": "Sincronizar todas las bases de datos"},diff --git a/frontend/src/locales/ja-JP.json b/frontend/src/locales/ja-JP.jsonindex 418fee1f31..2706f2b752 100644--- a/frontend/src/locales/ja-JP.json+++ b/frontend/src/locales/ja-JP.json@@ -682,9 +682,8 @@"tls": "TLS"},"server-identity": "サーバー ID",- "verification-disabled-description": "検証は無効です。接続は暗号化されていますが、サーバーの ID は検証されず、CA 設定は無視されます。",- "verify-certificate": "サーバー証明書を検証",- "verify-certificate-tooltip": "安全な接続のためにTLS証明書の検証を有効にします。開発環境や証明書が適切に検証できない場合(自己署名証明書、VPN環境など)にのみ無効にしてください。警告:検証を無効にすることは安全ではありません"+ "verification-disabled-description": "検証が無効です。接続は暗号化されますが、サーバーの身元は検証されず、CA 設定は無視されます。これは安全ではありません。安全な接続のために検証を有効にし、開発やトラブルシューティング時にのみ一時的に無効にしてください。",+ "verify-certificate": "サーバー証明書を検証"},"ssl-connection": "SSL接続"},@@ -964,6 +963,8 @@},"instance": {"account-locator": "アカウントロケーター",+ "add-labels": "ラベルを追加",+ "add-parameter": "パラメータを追加","advanced-search": {"scope": {"host": {@@ -978,6 +979,7 @@},"archive-instance-instance-name": "インスタンス '{{0}}' をアーカイブしますか?","archived-instances-will-not-be-displayed": "アーカイブされたインスタンスは表示されなくなります。",+ "authentication": "認証","authentication-database": "認証データベース","cloud-sql-ip-type": {"description": "インスタンスにパブリック IP がなく、Bytebase が同じ VPC 内で実行されている場合は、プライベート IP を使用してください。",@@ -989,8 +991,8 @@"connect-database-to-project": "データベースをプロジェクトに接続","connect-instance": "インスタンスを接続","connecting-database-to-project": "データベースを接続中...",+ "connection-database": "接続先データベース","connection-info": "接続情報",- "connection-options": "接続オプション","connection-recovery": {"auth": {"description": "ユーザー名、パスワード、トークン、または IAM 認証設定を確認してから、もう一度接続をテストしてください。",@@ -1123,7 +1125,7 @@"gcp-endpoint-tip": "省略可能。デフォルトの Google API エンドポイントを上書きします(例:Private Service Connect エンドポイント {{example}})。","gcp-endpoint-toggle": "カスタム API エンドポイントを設定","grants": "権限",- "host-or-socket": "ホストまたはソケット",+ "hostname": "ホスト名","iam-extension": {"client-id": "Client ID","client-secret": "Client Secret",@@ -1212,6 +1214,9 @@"keytab-resupply-required": "このデータソースの接続先が変わりました。keytab を再アップロードして、引き続き保持していることを確認してください。","keytab-upload-placeholder": ".keytab ファイルをクリックまたはドラッグしてください","keytab-write-only": "キータブは書き込み専用です。新しいファイルをアップロードすると既存のものを置き換えます。",+ "master-name": "マスター名",+ "master-password": "マスターパスワード",+ "master-username": "マスターユーザー名","new-instance": "新しいインスタンス","no-environment": "このインスタンスは環境にバインドされていません","no-extra-params-configured": "追加の接続パラメーターは構成されていません",@@ -1220,6 +1225,11 @@"open-data-source": "このデータソースを開いて、何が必要か確認してください。","parameter-name-placeholder": "パラメーター名","parameter-value-placeholder": "パラメーター値",+ "password-source": {+ "bytebase": "Bytebase",+ "self": "パスワードの取得元",+ "stored-in-bytebase": "Bytebase に保存"+ },"password-type": {"aws-iam": "AWS RDS IAM","azure-iam": "Azure IAM",@@ -1329,9 +1339,13 @@},"sync-databases": {"add-database": "+ データベースを追加し、Enterキーを押して送信します",+ "all-databases": "すべてのデータベース","description": "このインスタンスから同期するデータベースを選択してください。",+ "hostname-required": "同期するデータベースを選択するには、ホスト名を入力してください。","project-sync-all": "すべてのデータベースをこのプロジェクトに同期する",+ "required-fields": "同期するデータベースを選択するには、上の必須項目を入力してください。","search-database": "データベースを検索",+ "selected-databases": "選択したデータベース","self": "データベースを同期する","sync-all": "すべてのデータベースを同期する"},diff --git a/frontend/src/locales/vi-VN.json b/frontend/src/locales/vi-VN.jsonindex d914adbaa8..40f0690120 100644--- a/frontend/src/locales/vi-VN.json+++ b/frontend/src/locales/vi-VN.json@@ -682,9 +682,8 @@"tls": "TLS"},"server-identity": "Danh tính máy chủ",- "verification-disabled-description": "Đã tắt xác minh. Kết nối được mã hóa, nhưng danh tính máy chủ không được xác minh; cài đặt CA sẽ bị bỏ qua.",- "verify-certificate": "Xác minh chứng chỉ máy chủ",- "verify-certificate-tooltip": "Bật xác minh chứng chỉ TLS để kết nối an toàn. Chỉ tắt cho môi trường phát triển hoặc khi không thể xác thực chứng chỉ đúng cách (ví dụ: chứng chỉ tự ký, môi trường VPN). Cảnh báo: Tắt xác minh là không an toàn"+ "verification-disabled-description": "Xác minh đã tắt. Kết nối vẫn được mã hóa nhưng danh tính máy chủ không được xác minh; cài đặt CA bị bỏ qua. Điều này không an toàn. Hãy bật xác minh để bảo đảm kết nối an toàn; chỉ tạm tắt khi phát triển hoặc khắc phục sự cố.",+ "verify-certificate": "Xác minh chứng chỉ máy chủ"},"ssl-connection": "Kết nối SSL"},@@ -964,6 +963,8 @@},"instance": {"account-locator": "Định vị tài khoản",+ "add-labels": "Thêm nhãn",+ "add-parameter": "Thêm tham số","advanced-search": {"scope": {"host": {@@ -978,6 +979,7 @@},"archive-instance-instance-name": "Lưu trữ phiên bản '{{0}}'?","archived-instances-will-not-be-displayed": "Các phiên bản đã lưu trữ sẽ không được hiển thị.",+ "authentication": "Xác thực","authentication-database": "Cơ sở dữ liệu xác thực","cloud-sql-ip-type": {"description": "Dùng IP riêng khi instance không có IP công khai và Bytebase chạy trong cùng một VPC.",@@ -989,8 +991,8 @@"connect-database-to-project": "Kết nối cơ sở dữ liệu với dự án","connect-instance": "Kết nối instance","connecting-database-to-project": "Đang kết nối cơ sở dữ liệu...",+ "connection-database": "Cơ sở dữ liệu kết nối","connection-info": "Thông tin kết nối",- "connection-options": "Tùy chọn kết nối","connection-recovery": {"auth": {"description": "Kiểm tra tên người dùng, mật khẩu, token hoặc cấu hình xác thực IAM, rồi kiểm tra kết nối lại.",@@ -1123,7 +1125,7 @@"gcp-endpoint-tip": "Tùy chọn. Ghi đè điểm cuối Google API mặc định, ví dụ: điểm cuối Private Service Connect như {{example}}.","gcp-endpoint-toggle": "Thiết lập điểm cuối API tùy chỉnh","grants": "Quyền",- "host-or-socket": "Máy chủ hoặc Socket",+ "hostname": "Tên máy chủ","iam-extension": {"client-id": "Client ID","client-secret": "Client Secret",@@ -1212,6 +1214,9 @@"keytab-resupply-required": "Nguồn dữ liệu này hiện kết nối tới một đích đến mới. Hãy tải lên lại keytab để xác nhận bạn vẫn giữ nó.","keytab-upload-placeholder": "Nhấp hoặc kéo tệp .keytab của bạn vào đây","keytab-write-only": "Keytab chỉ ghi. Tải lên tệp mới để thay thế keytab hiện có.",+ "master-name": "Tên nút chính",+ "master-password": "Mật khẩu nút chính",+ "master-username": "Tên người dùng nút chính","new-instance": "Phiên bản mới","no-environment": "Trường hợp này không bị ràng buộc với môi trường","no-extra-params-configured": "Không có thông số kết nối bổ sung được cấu hình",@@ -1220,6 +1225,11 @@"open-data-source": "Mở nguồn dữ liệu này để xem nó cần gì.","parameter-name-placeholder": "Tên tham số","parameter-value-placeholder": "Giá trị tham số",+ "password-source": {+ "bytebase": "Bytebase",+ "self": "Nguồn mật khẩu",+ "stored-in-bytebase": "Được lưu trong Bytebase"+ },"password-type": {"aws-iam": "AWS RDS IAM","azure-iam": "Azure IAM",@@ -1329,9 +1339,13 @@},"sync-databases": {"add-database": "+ Thêm cơ sở dữ liệu, nhấn enter để gửi",+ "all-databases": "Tất cả cơ sở dữ liệu","description": "Chọn cơ sở dữ liệu cần đồng bộ từ instance này.",+ "hostname-required": "Nhập tên máy chủ để chọn cơ sở dữ liệu cần đồng bộ.","project-sync-all": "Đồng bộ tất cả cơ sở dữ liệu vào dự án này",+ "required-fields": "Điền các trường bắt buộc ở trên để chọn cơ sở dữ liệu cần đồng bộ.","search-database": "Tìm kiếm cơ sở dữ liệu",+ "selected-databases": "Cơ sở dữ liệu được chọn","self": "Đồng bộ cơ sở dữ liệu","sync-all": "Đồng bộ tất cả cơ sở dữ liệu"},diff --git a/frontend/src/locales/zh-CN.json b/frontend/src/locales/zh-CN.jsonindex d5b7a73965..513d00355d 100644--- a/frontend/src/locales/zh-CN.json+++ b/frontend/src/locales/zh-CN.json@@ -682,9 +682,8 @@"tls": "TLS"},"server-identity": "服务器身份",- "verification-disabled-description": "已禁用验证。连接已加密,但未验证服务器身份;CA 设置将被忽略。",- "verify-certificate": "验证服务器证书",- "verify-certificate-tooltip": "启用 TLS 证书验证以确保安全连接。仅在开发环境或证书无法正确验证的情况下禁用(例如自签名证书、VPN 环境)。警告:禁用验证是不安全的"+ "verification-disabled-description": "验证已关闭。连接仍然加密,但不会验证服务器身份,CA 设置将被忽略。这存在安全风险。请启用证书验证,仅在开发或故障排查时临时关闭。",+ "verify-certificate": "验证服务器证书"},"ssl-connection": "SSL 连接"},@@ -964,6 +963,8 @@},"instance": {"account-locator": "账户定位符",+ "add-labels": "添加标签",+ "add-parameter": "添加参数","advanced-search": {"scope": {"host": {@@ -978,6 +979,7 @@},"archive-instance-instance-name": "归档实例'{{0}}'?","archived-instances-will-not-be-displayed": "不再会显示已归档实例。",+ "authentication": "身份验证","authentication-database": "认证数据库","cloud-sql-ip-type": {"description": "当实例没有公共 IP 且 Bytebase 运行在同一 VPC 内时,请使用私有 IP。",@@ -989,8 +991,8 @@"connect-database-to-project": "连接数据库到项目","connect-instance": "连接实例","connecting-database-to-project": "正在连接数据库...",+ "connection-database": "连接数据库","connection-info": "连接信息",- "connection-options": "连接选项","connection-recovery": {"auth": {"description": "请检查用户名、密码、令牌或 IAM 认证配置,然后重新测试连接。",@@ -1123,7 +1125,7 @@"gcp-endpoint-tip": "可选。覆盖默认的 Google API 端点,例如 Private Service Connect 端点 {{example}}。","gcp-endpoint-toggle": "设置自定义 API 端点","grants": "权限",- "host-or-socket": "Host 或 Socket",+ "hostname": "主机名","iam-extension": {"client-id": "Client ID","client-secret": "Client Secret",@@ -1212,6 +1214,9 @@"keytab-resupply-required": "该数据源现在连接到新的目标地址。请重新上传 keytab,以确认您仍持有它。","keytab-upload-placeholder": "点击或拖拽 .keytab 文件到此处","keytab-write-only": "Keytab 仅写入。上传新文件以替换现有 keytab。",+ "master-name": "主节点名称",+ "master-password": "主节点密码",+ "master-username": "主节点用户名","new-instance": "新实例","no-environment": "此实例尚未绑定到环境","no-extra-params-configured": "没有配置的额外连接参数",@@ -1220,6 +1225,11 @@"open-data-source": "打开该数据源,查看还需要什么。","parameter-name-placeholder": "参数名称","parameter-value-placeholder": "参数值",+ "password-source": {+ "bytebase": "Bytebase",+ "self": "密码来源",+ "stored-in-bytebase": "存储在 Bytebase 中"+ },"password-type": {"aws-iam": "AWS RDS IAM","azure-iam": "Azure IAM",@@ -1329,9 +1339,13 @@},"sync-databases": {"add-database": "+ 添加数据库,按回车键提交",+ "all-databases": "全部数据库","description": "选择要从此实例同步的数据库。",+ "hostname-required": "请输入主机名,然后选择要同步的数据库。","project-sync-all": "将所有数据库同步到此项目",+ "required-fields": "请填写上方必填字段,然后选择要同步的数据库。","search-database": "搜索数据库",+ "selected-databases": "指定数据库","self": "同步数据库","sync-all": "同步所有数据库"},