25 MB lightweight cross-platform database client for 100+ databases, including MySQL, PostgreSQL, SQLite, Redis, MongoDB, DuckDB, SQL Server, and Dameng. Built-in AI, MCP Server, CLI, desktop and Docker. | 轻量级跨平台数据库管理工具,支持 MySQL、PostgreSQL、SQLite、Redis、MongoDB、达梦等 100+ 数据库,提供桌面端、Docker、CLI、内置 AI 助手和 MCP。
TypeScript aicliclickhousedatabasedatabase-clientdatabase-managementdockerguimcpmongodbmysqlpostgresqlredisrustsql-serversqlitetaurivue
feat(nacos): improve service and instance management
二丫讲梵c754b852951b
diff --git a/apps/desktop/src/components/connection/ConnectionDialog.vue b/apps/desktop/src/components/connection/ConnectionDialog.vueindex f86036607a..dd7aca7a58 100644--- a/apps/desktop/src/components/connection/ConnectionDialog.vue+++ b/apps/desktop/src/components/connection/ConnectionDialog.vue@@ -19,7 +19,7 @@ import type { InfluxDbExternalConfig, InfluxDbVersion } from "@/types/influxdb";import type { VictoriaMetricsExternalConfig } from "@/types/victoriametrics";import type { MqAdminConfig, MqAuth, MqSystemKind } from "@/types/mq";import type { MqttConnectionConfig } from "@/types/mqtt";-import type { NacosAdminConfig, NacosAuthConfig, NacosImplementation, NacosMetricsMode, NacosRNacosConsoleAuth, NacosVersionMode } from "@/types/nacos";+import type { NacosAdminConfig, NacosAuthConfig, NacosImplementation, NacosMetricsMode, NacosNamespaceInfo, NacosRNacosConsoleAuth, NacosVersionMode } from "@/types/nacos";import { CONNECTION_ATTEMPT_CANCELLED_MESSAGE, useConnectionStore } from "@/stores/connectionStore";import { useTunnelProfileStore } from "@/stores/tunnelProfileStore";import { detachTunnelProfileLayer, tunnelProfileReferenceLayer, tunnelProfileSummary } from "@/lib/connection/tunnelProfiles";@@ -64,7 +64,8 @@ import { normalizeRabbitmqAddresses } from "@/lib/connection/rabbitmqAddresses";import { detectMqUiAuthKind, isMqAuthKindAllowedForSystem, type MqUiAuthKind } from "@/lib/connection/mqAuth";import { driverInstallProgressChannel, driverInstallProgressPercent, isDriverInstallProgressForOperation, type DriverInstallProgress } from "@/lib/connection/driverInstallProgressUi";import { requiresSqlServerLegacyCompatibilityComponent, setSqlServerLegacyCompatibilityConfig, sqlServerUsesLegacyCompatibility, SQLSERVER_LEGACY_COMPATIBILITY_DRIVER_KEY } from "@/lib/connection/sqlServerLegacyCompatibility";-import { nacosMetricsCandidates, normalizeNacosEndpoint, normalizeNacosMetricsUrl } from "@/lib/nacos/nacosAdmin";+import { normalizeNacosEndpoint, normalizeNacosMetricsUrl } from "@/lib/nacos/nacosAdmin";+import { normalizeNacosNamespaceSelection, normalizeNacosNamespacesForDisplay } from "@/lib/nacos/nacosNamespaceVisibility";import {ArrowLeft,ArrowDown,@@ -115,6 +116,7 @@ export type ConfigTab = "connection" | "advanced" | "tls" | "transport";type ProductionScope = "connection" | "databases";type MqTokenSigningMode = "none" | "hs256" | "rs256";type NacosAuthKind = NacosAuthConfig["kind"];+type NacosConnectionProfile = "v2" | "v3" | "rnacos";type DremioConnectionMode = "arrow-flight-sql" | "legacy";type JdbcDriverSelectItem = {id: string;@@ -128,6 +130,11 @@ const DREMIO_ARROW_FLIGHT_SQL_JDBC_DRIVER_CLASS = "org.apache.arrow.driver.jdbc.const DREMIO_LEGACY_JDBC_URL = "jdbc:dremio:direct=127.0.0.1:31010";const DREMIO_LEGACY_JDBC_DRIVER_CLASS = "com.dremio.jdbc.Driver";const DEFAULT_SSH_USER = "root";+const NACOS_CONNECTION_PROFILES: ReadonlyArray<{ value: NacosConnectionProfile; title: string }> = [+ { value: "v2", title: "Nacos 2.x" },+ { value: "v3", title: "Nacos 3.x" },+ { value: "rnacos", title: "r-nacos" },+];type LegacyTransportFields = {ssh_enabled?: boolean;@@ -150,7 +157,6 @@ type LegacyTransportFields = {type LegacyConnectionConfig = ConnectionConfig & LegacyTransportFields;type ConnectionForm = Omit<ConnectionConfig, "id">;type ConnectionTestState = ConnectionTestResult & { ok: boolean };-type SuccessfulConnectionTest = { result: ConnectionTestResult; config: ConnectionConfig };const { t } = useI18n();const { toast } = useToast();@@ -201,6 +207,12 @@ const visibleDatabaseSelection = ref<Set<string>>(new Set());const visibleDatabaseSearchText = ref("");const visibleDatabaseError = ref("");const visibleDatabaseShowSystem = ref(false);+const showVisibleNacosNamespacesDialog = ref(false);+const isLoadingVisibleNacosNamespaces = ref(false);+const visibleNacosNamespaces = ref<NacosNamespaceInfo[]>([]);+const visibleNacosNamespaceSelection = ref<Set<string>>(new Set());+const visibleNacosNamespaceSearchText = ref("");+const visibleNacosNamespaceError = ref("");const showProductionDatabasesDialog = ref(false);const isLoadingProductionDatabases = ref(false);const productionDatabaseNames = ref<string[]>([]);@@ -673,11 +685,11 @@ const mqKafkaSaslMechanismOptions = [{ value: "SCRAM-SHA-512", label: "SCRAM-SHA-512" },];const nacosImplementation = ref<NacosImplementation>("nacos");-const nacosVersionMode = ref<NacosVersionMode>("auto");+// Nacos 2 and 3 expose different API planes (and Nacos 3 commonly needs a+// separate Console address). New connections must therefore choose an+// explicit version instead of relying on endpoint-shape guessing.+const nacosVersionMode = ref<NacosVersionMode>("v2");const nacosServerAddr = ref("");-const nacosNamespace = ref("");-const nacosContextPath = ref("");-const nacosContextPathCustomized = ref(false);const nacosRNacosConsoleAddr = ref("");const nacosHistoryEnabled = ref(false);const nacosConsoleAuthKind = ref<NacosRNacosConsoleAuth["kind"]>("inherit");@@ -706,63 +718,20 @@ const mqttTlsSkipVerify = ref(false);const mqttKeepAliveSecs = ref(60);const mqttConnectTimeoutSecs = ref(30);const mqttMaxPacketSizeBytes = ref(16 * 1024 * 1024);--const nacosPrimaryAddressLabel = computed(() => {- if (nacosImplementation.value === "rnacos") return t("connection.nacosPrimaryAddressRNacos");- if (nacosVersionMode.value === "v2") return t("connection.nacosPrimaryAddressV2");- if (nacosVersionMode.value === "v3") return t("connection.nacosPrimaryAddressV3");- return t("connection.nacosPrimaryAddressAuto");-});const nacosPrimaryAddressPlaceholder = computed(() => {return "http://127.0.0.1:8848/nacos";});-const nacosNormalizedPreview = computed(() => {- if (!nacosServerAddr.value.trim()) return "";+const nacosV3AdminEndpointWarning = computed(() => {+ if (nacosImplementation.value !== "nacos" || nacosVersionMode.value !== "v3" || !nacosServerAddr.value.trim()) return "";try {- const normalized = normalizeNacosEndpoint(nacosServerAddr.value, {- implementation: nacosImplementation.value,- versionMode: nacosVersionMode.value,- contextPath: nacosContextPathCustomized.value ? nacosContextPath.value : undefined,- });- return `${normalized.serverAddr}${normalized.contextPath || ""}`;- } catch {- return "";- }-});-const nacosEffectiveContextPath = computed(() => {- if (!nacosServerAddr.value.trim()) {- return nacosContextPathCustomized.value ? nacosContextPath.value.trim() || "/" : "/nacos";- }- try {- const normalized = normalizeNacosEndpoint(nacosServerAddr.value, {- implementation: nacosImplementation.value,- versionMode: nacosVersionMode.value,- contextPath: nacosContextPathCustomized.value ? nacosContextPath.value : undefined,- });- return normalized.contextPath || "/";- } catch {- return nacosContextPathCustomized.value ? nacosContextPath.value.trim() || "/" : "/";- }-});-const nacosContextPathInput = computed({- get: () => (nacosContextPathCustomized.value ? nacosContextPath.value : nacosEffectiveContextPath.value),- set: (value: string) => {- nacosContextPathCustomized.value = true;- nacosContextPath.value = value;- },-});-const nacosMetricsAutoPreview = computed(() => {- if (!nacosNormalizedPreview.value) return "";- try {- const normalized = normalizeNacosEndpoint(nacosServerAddr.value, {- implementation: nacosImplementation.value,- versionMode: nacosVersionMode.value,- contextPath: nacosContextPathCustomized.value ? nacosContextPath.value : undefined,- });- return nacosMetricsCandidates(normalized.serverAddr, normalized.contextPath, nacosImplementation.value).join(" · ");+ const url = new URL(nacosServerAddr.value.trim());+ if (url.port === "8080") {+ return t("nacos.nacosV3ConsolePortWarning");+ }} catch {- return "";+ // The normal form validation will report an invalid URL on save.}+ return "";});const nacosMetricsUrlError = computed(() => {if (nacosMetricsMode.value !== "custom") return "";@@ -774,13 +743,22 @@ const nacosMetricsUrlError = computed(() => {}});-function resetNacosContextPathCustomization() {- nacosContextPathCustomized.value = false;- nacosContextPath.value = "";+const nacosConnectionProfile = computed<NacosConnectionProfile>(() => {+ if (nacosImplementation.value === "rnacos") return "rnacos";+ return nacosVersionMode.value === "v3" ? "v3" : "v2";+});++function selectNacosConnectionProfile(profile: NacosConnectionProfile) {+ if (profile === "rnacos") {+ nacosImplementation.value = "rnacos";+ return;+ }+ nacosImplementation.value = "nacos";+ nacosVersionMode.value = profile;}watch(nacosImplementation, (implementation) => {- if (implementation === "rnacos") nacosVersionMode.value = "auto";+ if (implementation === "rnacos") nacosVersionMode.value = "v2";if (implementation !== "rnacos") nacosHistoryEnabled.value = false;});@@ -1211,11 +1189,12 @@ watch(mqAuthKind, (kind) => {function resetNacosFields(config?: Partial<NacosAdminConfig>) {nacosImplementation.value = config?.implementation || (config?.rnacosConsoleAddr ? "rnacos" : "nacos");- nacosVersionMode.value = config?.versionMode || "auto";- nacosServerAddr.value = config?.serverAddr?.trim() || "";- nacosNamespace.value = config?.namespace || "";- nacosContextPath.value = config?.contextPath || "";- nacosContextPathCustomized.value = !!config?.contextPath;+ // Saved `auto` profiles are legacy records. The form always saves an+ // explicit selection and no longer relies on a separate Console address.+ nacosVersionMode.value = config?.versionMode === "v3" ? "v3" : "v2";+ const serverAddr = config?.serverAddr?.trim() || "";+ const contextPath = config?.contextPath?.trim() || "";+ nacosServerAddr.value = serverAddr && contextPath && contextPath !== "/" && !serverAddr.endsWith(contextPath) ? `${serverAddr.replace(/\/+$/, "")}/${contextPath.replace(/^\/+/, "")}` : serverAddr;nacosRNacosConsoleAddr.value = config?.rnacosConsoleAddr?.trim() || "";nacosHistoryEnabled.value = config?.rnacosHistoryEnabled ?? !!config?.rnacosConsoleAddr;const consoleAuth = config?.rnacosConsoleAuth || { kind: "inherit" };@@ -1507,13 +1486,14 @@ function buildNacosAdminConfig(): NacosAdminConfig {const normalized = normalizeNacosEndpoint(primaryAddress, {implementation: nacosImplementation.value,versionMode: nacosVersionMode.value,- contextPath: nacosContextPathCustomized.value ? nacosContextPath.value : undefined,+ contextPath: undefined,});if (nacosImplementation.value === "rnacos" && normalized.warnings.length) {throw new Error(t("connection.nacosRNacosOpenApiRequired"));}- const rnacosConsoleConfigured = nacosImplementation.value === "rnacos" && !!nacosRNacosConsoleAddr.value.trim();- if (nacosImplementation.value === "rnacos" && nacosHistoryEnabled.value && !rnacosConsoleConfigured) {+ const rnacosExtensionsEnabled = nacosImplementation.value === "rnacos" && nacosHistoryEnabled.value;+ const rnacosConsoleConfigured = rnacosExtensionsEnabled && !!nacosRNacosConsoleAddr.value.trim();+ if (rnacosExtensionsEnabled && !rnacosConsoleConfigured) {throw new Error(t("connection.nacosRNacosConsoleUrlRequired"));}let rnacosConsoleAuth: NacosRNacosConsoleAuth | undefined;@@ -1541,9 +1521,8 @@ function buildNacosAdminConfig(): NacosAdminConfig {implementation: nacosImplementation.value,versionMode: nacosImplementation.value === "nacos" ? nacosVersionMode.value : undefined,serverAddr: normalized.serverAddr,- namespace: nacosNamespace.value.trim() || undefined,contextPath: normalized.contextPath || undefined,- rnacosConsoleAddr: nacosImplementation.value === "rnacos" ? nacosRNacosConsoleAddr.value.trim() || undefined : undefined,+ rnacosConsoleAddr: rnacosExtensionsEnabled ? nacosRNacosConsoleAddr.value.trim() || undefined : undefined,rnacosHistoryEnabled: nacosImplementation.value === "rnacos" ? nacosHistoryEnabled.value : undefined,rnacosConsoleAuth,auth: buildNacosAuth(),@@ -1554,49 +1533,6 @@ function buildNacosAdminConfig(): NacosAdminConfig {};}-function dockerNacosConsoleFallbackUrl(serverAddr: string): string | null {- let parsed: URL;- try {- parsed = new URL(serverAddr);- } catch {- return null;- }- const port = parsed.port || (parsed.protocol === "https:" ? "443" : "80");- const host = parsed.hostname.toLowerCase();- if (port !== "8848" || !["127.0.0.1", "localhost", "::1"].includes(host)) return null;-- parsed.port = "8085";- return parsed.toString().replace(/\/$/, "");-}--function isNacosAdminEndpointNotFound(message: string): boolean {- return /Nacos admin endpoint was not found/i.test(message);-}--async function tryNacosDockerConsoleFallback(config: ConnectionConfig, originalError: string, runId: number): Promise<SuccessfulConnectionTest | null> {- if (config.db_type !== "nacos" || !isNacosAdminEndpointNotFound(originalError)) return null;-- const fallbackUrl = dockerNacosConsoleFallbackUrl(nacosServerAddr.value);- if (!fallbackUrl || fallbackUrl === nacosServerAddr.value.trim()) return null;-- const previousUrl = nacosServerAddr.value;- nacosServerAddr.value = fallbackUrl;- try {- const fallbackConfig = connectionConfigForSubmit(config.id, config.name);- const result = await testConnectionWithTimeout(fallbackConfig, runId);- return {- config: fallbackConfig,- result: {- ...result,- message: `${result.message} ${t("connection.nacosConsoleUrlAutoAdjusted", { from: previousUrl.trim(), to: fallbackUrl })}`,- },- };- } catch {- nacosServerAddr.value = previousUrl;- return null;- }-}-function errorMessage(error: unknown): string {if (error instanceof Error) return error.message;return String(error);@@ -2858,7 +2794,8 @@ const canUseTransportLayers = computed(() => form.value.db_type !== "sqlite" &&const shouldShowAgentDriverInstallHint = computed(() => showAgentDriverInstallHint(form.value.db_type, agentDrivers.value, form.value.driver_profile));const h2DriverMissing = computed(() => form.value.db_type === "h2" && isH2FileMode.value && agentDrivers.value.find((d) => d.db_type === "h2")?.installed !== true);const agentDriverFocus = computed<DriverStoreFocus>(() => ({ target: "driver", driver: agentDriverInstallKey(form.value.db_type, form.value.driver_profile) }));-const canChooseVisibleDatabases = computed(() => connectionCanChooseVisibleDatabases(form.value));+const canChooseVisibleNacosNamespaces = computed(() => form.value.db_type === "nacos");+const canChooseVisibleDatabases = computed(() => !canChooseVisibleNacosNamespaces.value && connectionCanChooseVisibleDatabases(form.value));const visibleFilterUsesSchemas = computed(() => connectionUsesVisibleSchemaFilter(form.value));const hasVisibleDatabaseFilter = computed(() => Array.isArray(form.value.visible_databases));const visibleDatabaseSummary = computed(() => {@@ -2882,6 +2819,16 @@ const visibleDatabaseTotalCount = computed(() => listedVisibleDatabaseNames.valuconst visibleDatabaseCanSave = computed(() => canSaveVisibleDatabaseSelection([...visibleDatabaseSelection.value]));const visibleDatabaseHasSystemObjects = computed(() => defaultListedVisibleDatabaseNames.value.length < visibleDatabaseNames.value.length);const visibleSystemObjectsLabelKey = computed(() => (visibleFilterUsesSchemas.value ? "visibleSchemas.showSystemSchemas" : "visibleDatabases.showSystemDatabases"));+const filteredVisibleNacosNamespaces = computed(() => {+ const query = visibleNacosNamespaceSearchText.value.trim().toLowerCase();+ if (!query) return visibleNacosNamespaces.value;+ return visibleNacosNamespaces.value.filter((namespace) => {+ const label = namespace.namespaceShowName || namespace.namespace || "public";+ return `${label} ${namespace.namespace}`.toLowerCase().includes(query);+ });+});+const visibleNacosNamespaceSelectedCount = computed(() => visibleNacosNamespaceSelection.value.size);+const visibleNacosNamespaceCanSave = computed(() => visibleNacosNamespaceSelection.value.size > 0);const filteredProductionDatabaseNames = computed(() => {const query = productionDatabaseSearchText.value.trim().toLowerCase();if (!query) return productionDatabaseNames.value;@@ -3028,7 +2975,7 @@ const agentInstallProgressLabel = computed(() => {});const canCloseAgentInstallDialog = computed(() => !agentInstallRunning.value || !!agentInstallError.value);const sqlServerDriverMode = computed<"auto" | "legacy">(() => (sqlServerUsesLegacyCompatibility(form.value) ? "legacy" : "auto"));-const shouldUseWideConnectionDialog = computed(() => dialogStep.value === "config" && (canChooseVisibleDatabases.value || (canChooseVisibleSchemas.value && !visibleFilterUsesSchemas.value)));+const shouldUseWideConnectionDialog = computed(() => dialogStep.value === "config" && (canChooseVisibleDatabases.value || canChooseVisibleNacosNamespaces.value || (canChooseVisibleSchemas.value && !visibleFilterUsesSchemas.value)));const connectionDialogContentClass = computed(() => {if (dialogStep.value === "select") return "connection-dialog-content--picker sm:h-[720px] sm:max-w-[880px]";const widthClass = shouldUseWideConnectionDialog.value ? "connection-dialog-content--wide sm:max-w-[660px]" : "connection-dialog-content--standard sm:max-w-[560px]";@@ -3147,21 +3094,13 @@ async function testConnection() {if (runId !== testRunId) return;const rawMessage = mongodbAuthFailureHint(errorMessage(e));const message = config ? connectionErrorWithDriverUpdateHint(config, rawMessage) : rawMessage;- const fallback = config ? await tryNacosDockerConsoleFallback(config, message, runId) : null;- if (runId !== testRunId) return;- if (fallback) {- applySuccessfulConnectionTest(fallback.result, fallback.config, submittedSourceName);- void persistSuccessfulConnectionTest(fallback.result, fallback.config, submittedSourceName, runId);- clearEditedConnectionErrorAfterSuccessfulTest();- } else {- const shouldShowSqlServerLegacyMode = config?.db_type === "sqlserver" && !sqlServerUsesLegacyCompatibility(config) && isSqlServerTlsHandshakeFailure(message);- if (shouldShowSqlServerLegacyMode) {- configTab.value = "advanced";- }- clearTestedConnectionInfo();- testResult.value = { ok: false, message };- showConnectionError(message);+ const shouldShowSqlServerLegacyMode = config?.db_type === "sqlserver" && !sqlServerUsesLegacyCompatibility(config) && isSqlServerTlsHandshakeFailure(message);+ if (shouldShowSqlServerLegacyMode) {+ configTab.value = "advanced";}+ clearTestedConnectionInfo();+ testResult.value = { ok: false, message };+ showConnectionError(message);} finally {if (runId === testRunId) {isTesting.value = false;@@ -3452,7 +3391,7 @@ function connectionConfigForSubmit(id: string, generatedName = ""): ConnectionCoapplyNacosServerAddr(config, nacosConfig.serverAddr);config.username = nacosAuthKind.value === "usernamePassword" ? nacosUsername.value.trim() : "";config.password = nacosAuthKind.value === "usernamePassword" ? nacosPassword.value : "";- config.database = nacosConfig.namespace || undefined;+ config.database = undefined;config.connection_string = undefined;config.url_params = "";} else if (config.db_type === "mqtt") {@@ -3898,6 +3837,15 @@ function resetVisibleDatabaseDraftState() {visibleDatabaseShowSystem.value = false;}+function resetVisibleNacosNamespaceDraftState() {+ showVisibleNacosNamespacesDialog.value = false;+ isLoadingVisibleNacosNamespaces.value = false;+ visibleNacosNamespaces.value = [];+ visibleNacosNamespaceSelection.value = new Set();+ visibleNacosNamespaceSearchText.value = "";+ visibleNacosNamespaceError.value = "";+}+function resetProductionDatabaseDraftState() {showProductionDatabasesDialog.value = false;isLoadingProductionDatabases.value = false;@@ -3967,6 +3915,78 @@ async function openVisibleDatabasesPicker() {}}+function nacosNamespaceValue(namespace: NacosNamespaceInfo): string {+ return namespace.namespace || "";+}++function nacosNamespaceLabel(namespace: NacosNamespaceInfo): string {+ return namespace.namespaceShowName || namespace.namespace || "public";+}++function normalizeVisibleNacosNamespaceSelection(selected: Iterable<string>, namespaces: NacosNamespaceInfo[]): string[] {+ return normalizeNacosNamespaceSelection(selected, namespaces);+}++async function openVisibleNacosNamespacesPicker() {+ if (!ensureConnectionHostResolvedFromUrl()) return;+ if (!canChooseVisibleNacosNamespaces.value || isLoadingVisibleNacosNamespaces.value) return;++ isLoadingVisibleNacosNamespaces.value = true;+ visibleNacosNamespaceError.value = "";+ visibleNacosNamespaceSearchText.value = "";+ const draftId = buildDraftVisibleDatabasesConnectionId(uuid());++ try {+ const draftConfig = {+ ...connectionConfigForSubmit(draftId),+ id: draftId,+ one_time: true,+ };+ await api.connectDb(draftConfig);+ const namespaces = normalizeNacosNamespacesForDisplay(await api.nacosListNamespaces(draftId));+ visibleNacosNamespaces.value = [...namespaces].sort((left, right) => nacosNamespaceLabel(left).localeCompare(nacosNamespaceLabel(right)));+ const configured = form.value.visible_databases;+ const initialSelection = Array.isArray(configured) ? normalizeVisibleNacosNamespaceSelection(configured, visibleNacosNamespaces.value) : visibleNacosNamespaces.value.map(nacosNamespaceValue);+ visibleNacosNamespaceSelection.value = new Set(initialSelection);+ showVisibleNacosNamespacesDialog.value = true;+ } catch (e: any) {+ visibleNacosNamespaces.value = [];+ visibleNacosNamespaceSelection.value = new Set();+ visibleNacosNamespaceError.value = errorMessage(e);+ testResult.value = { ok: false, message: visibleNacosNamespaceError.value };+ showVisibleNacosNamespacesDialog.value = true;+ } finally {+ await api.disconnectDb(draftId).catch(() => undefined);+ isLoadingVisibleNacosNamespaces.value = false;+ }+}++function toggleVisibleNacosNamespace(namespace: string) {+ const next = new Set(visibleNacosNamespaceSelection.value);+ if (next.has(namespace)) next.delete(namespace);+ else next.add(namespace);+ visibleNacosNamespaceSelection.value = next;+}++function selectAllVisibleNacosNamespaces() {+ visibleNacosNamespaceSelection.value = new Set(visibleNacosNamespaces.value.map(nacosNamespaceValue));+}++function clearVisibleNacosNamespaceSelection() {+ visibleNacosNamespaceSelection.value = new Set();+}++function showAllVisibleNacosNamespaces() {+ form.value.visible_databases = undefined;+ resetVisibleNacosNamespaceDraftState();+}++function saveVisibleNacosNamespaceSelection() {+ if (!visibleNacosNamespaceCanSave.value) return;+ form.value.visible_databases = normalizeVisibleNacosNamespaceSelection(visibleNacosNamespaceSelection.value, visibleNacosNamespaces.value);+ showVisibleNacosNamespacesDialog.value = false;+}+async function loadVisibleDatabaseNames(connectionId: string, config: ConnectionConfig): Promise<string[]> {if (connectionUsesVisibleSchemaFilter(config)) {return api.listSchemas(connectionId, config.database || "");@@ -4233,6 +4253,7 @@ function resetForm() {selectedDbCategory.value = "sql";configTab.value = "connection";resetVisibleDatabaseDraftState();+ resetVisibleNacosNamespaceDraftState();resetProductionDatabaseDraftState();resetVisibleSchemasState();resetTestState();@@ -5085,7 +5106,7 @@ function openExternalUrl(url: string) {</div><TabsContent value="connection" class="m-0 flex min-h-0 flex-1 flex-col overflow-hidden">- <div class="connection-form-body grid min-h-0 flex-1 gap-4 overflow-y-auto pt-4 pr-2 pb-2">+ <div class="connection-form-body grid min-h-0 flex-1 scroll-pb-6 gap-4 overflow-y-auto pt-4 pr-2 pb-6" :class="{ 'connection-form-body--nacos': form.db_type === 'nacos' }"><div v-if="!isJdbcConnection && form.db_type !== 'nacos'" class="grid grid-cols-4 items-center gap-4"><Label :class="connectionLabelClass">{{ t("connection.connectionUrlOptional") }}</Label><div class="col-span-3 flex items-center gap-1">@@ -5654,146 +5675,74 @@ function openExternalUrl(url: string) {<!-- Nacos: profile-aware endpoint, namespace and auth --><template v-else-if="form.db_type === 'nacos'">- <div class="grid grid-cols-4 items-center gap-4">- <Label :class="connectionLabelClass">{{ t("connection.nacosImplementation") }}</Label>- <div class="col-span-3 flex gap-2">- <Button size="sm" :variant="nacosImplementation === 'nacos' ? 'default' : 'outline'" @click="nacosImplementation = 'nacos'">Nacos</Button>- <Button size="sm" :variant="nacosImplementation === 'rnacos' ? 'default' : 'outline'" @click="nacosImplementation = 'rnacos'">r-nacos</Button>+ <section data-nacos-profile-selector class="overflow-hidden rounded-lg border bg-muted/10">+ <div class="border-b px-4 py-3">+ <div class="text-sm font-medium">{{ t("nacos.nacosConnectionPlan") }}</div>+ <p class="mt-0.5 text-xs leading-5 text-muted-foreground">{{ t("nacos.nacosConnectionPlanDescription") }}</p></div>- </div>- <div v-if="nacosImplementation === 'nacos'" class="grid grid-cols-4 items-center gap-4">- <Label :class="connectionLabelClass">{{ t("connection.nacosVersion") }}</Label>- <div class="col-span-3 flex flex-wrap gap-2">- <Button size="sm" :variant="nacosVersionMode === 'auto' ? 'default' : 'outline'" @click="nacosVersionMode = 'auto'">{{ t("connection.nacosVersionAuto") }}</Button>- <Button size="sm" :variant="nacosVersionMode === 'v2' ? 'default' : 'outline'" @click="nacosVersionMode = 'v2'">2.x</Button>- <Button size="sm" :variant="nacosVersionMode === 'v3' ? 'default' : 'outline'" @click="nacosVersionMode = 'v3'">3.x</Button>- </div>- </div>- <div class="grid grid-cols-4 items-center gap-4">- <Label :class="connectionLabelClass">{{ nacosPrimaryAddressLabel }}</Label>- <Input v-model="nacosServerAddr" class="col-span-3" :placeholder="nacosPrimaryAddressPlaceholder" />- </div>- <div class="grid grid-cols-4 items-start gap-4">- <span />- <p class="col-span-3 m-0 text-xs leading-5 text-muted-foreground">{{ t("connection.nacosPrimaryAddressHint") }}</p>- </div>- <div v-if="nacosNormalizedPreview" class="grid grid-cols-4 items-start gap-4">- <span />- <p class="col-span-3 m-0 text-xs leading-5 text-muted-foreground">{{ t("connection.nacosRequestsUse", { address: nacosNormalizedPreview }) }}</p>- </div>- <div class="grid grid-cols-4 items-center gap-4">- <Label :class="connectionLabelClass">{{ t("connection.nacosContextPath") }}</Label>- <div class="col-span-3 flex min-w-0 items-center gap-2">- <Input v-model="nacosContextPathInput" class="min-w-0 flex-1" :placeholder="t('connection.nacosContextPathPlaceholder')" />- <Button v-if="nacosContextPathCustomized" type="button" size="sm" variant="ghost" @click="resetNacosContextPathCustomization">{{ t("connection.nacosContextPathRestoreAuto") }}</Button>- </div>- </div>- <div class="grid grid-cols-4 items-center gap-4">- <Label :class="connectionLabelClass">{{ t("connection.nacosNamespace") }}</Label>- <Input v-model="nacosNamespace" class="col-span-3" placeholder="public" />- </div>- <div class="grid grid-cols-4 items-center gap-4">- <Label :class="connectionLabelClass">{{ t("connection.nacosMetrics") }}</Label>- <Select v-model="nacosMetricsMode">- <SelectTrigger class="col-span-3 h-9">- <SelectValue />- </SelectTrigger>- <SelectContent>- <SelectItem value="auto">{{ t("connection.nacosMetricsAuto") }}</SelectItem>- <SelectItem value="disabled">{{ t("connection.nacosMetricsDisabled") }}</SelectItem>- <SelectItem value="custom">{{ t("connection.nacosMetricsCustom") }}</SelectItem>- </SelectContent>- </Select>- </div>- <div v-if="nacosMetricsMode === 'auto' && nacosMetricsAutoPreview" class="grid grid-cols-4 items-start gap-4">- <span />- <p class="col-span-3 m-0 break-all text-xs leading-5 text-muted-foreground">{{ t("connection.nacosMetricsAutoHint", { addresses: nacosMetricsAutoPreview }) }}</p>- </div>- <div v-if="nacosMetricsMode === 'custom'" class="grid grid-cols-4 items-start gap-4">- <Label :class="connectionLabelClass">{{ t("connection.nacosMetricsUrl") }}</Label>- <div class="col-span-3">- <Input v-model="nacosMetricsUrl" :aria-invalid="!!nacosMetricsUrlError" :class="{ 'border-destructive focus-visible:ring-destructive': nacosMetricsUrlError }" placeholder="http://127.0.0.1:8818/nacos/actuator/prometheus" />- <p v-if="nacosMetricsUrlError" class="mt-1 text-xs text-destructive">{{ nacosMetricsUrlError }}</p>+ <div class="grid grid-cols-3 gap-2 p-3">+ <button+ v-for="profile in NACOS_CONNECTION_PROFILES"+ :key="profile.value"+ type="button"+ class="min-w-0 rounded-md border px-3 py-2.5 text-left transition-colors hover:bg-muted/50 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring"+ :class="nacosConnectionProfile === profile.value ? 'border-primary bg-primary/5 shadow-sm' : 'border-border bg-background'"+ :aria-pressed="nacosConnectionProfile === profile.value"+ @click="selectNacosConnectionProfile(profile.value)"+ >+ <span class="block truncate text-sm font-medium">{{ profile.title }}</span>+ </button></div>- </div>- <template v-if="nacosImplementation === 'rnacos'">- <div class="grid grid-cols-4 items-center gap-4">- <Label :class="connectionLabelClass">{{ t("connection.nacosConfigurationHistory") }}</Label>- <div class="col-span-3 flex items-center gap-2">- <label class="inline-flex items-center gap-2">- <Switch v-model="nacosHistoryEnabled" />- <span class="text-xs text-muted-foreground">{{ t("connection.nacosConfigurationHistoryEnable") }}</span>- </label>- <Tooltip>- <TooltipTrigger as-child>- <CircleHelp class="h-3.5 w-3.5 cursor-help text-muted-foreground hover:text-foreground" />- </TooltipTrigger>- <TooltipContent side="top" align="start" class="max-w-[360px] text-xs leading-relaxed">- {{ t("connection.nacosConfigurationHistoryHint") }}- </TooltipContent>- </Tooltip>+ </section>++ <section data-nacos-endpoint-section class="rounded-lg border p-4">+ <div class="grid gap-4">+ <div class="grid gap-1.5">+ <Label>{{ t("nacos.nacosServiceAddress") }}</Label>+ <Input v-model="nacosServerAddr" :placeholder="nacosPrimaryAddressPlaceholder" />+ <p class="text-xs leading-5 text-muted-foreground">+ <template>{{ t("nacos.nacosServiceAddressHint") }}</template>+ </p></div>+ <p v-if="nacosV3AdminEndpointWarning" class="rounded-md border border-amber-500/30 bg-amber-500/5 px-3 py-2 text-xs leading-5 text-amber-700 dark:text-amber-400">+ {{ nacosV3AdminEndpointWarning }}+ </p></div>- <div class="grid grid-cols-4 items-center gap-4">- <Label :class="connectionLabelClass">{{ t("connection.nacosRNacosConsoleUrl") }}</Label>- <Input v-model="nacosRNacosConsoleAddr" class="col-span-3" :placeholder="t('connection.nacosRNacosConsoleUrlPlaceholder')" />- </div>- <div class="grid grid-cols-4 items-start gap-4">- <span />- <p class="col-span-3 m-0 text-xs leading-5 text-muted-foreground">{{ t("connection.nacosRNacosConsoleUrlHint") }}</p>+ </section>++ <section data-nacos-access-section class="rounded-lg border p-4">+ <div class="mb-4">+ <div class="text-sm font-medium">{{ t("nacos.nacosAuth") }}</div>+ <p class="mt-0.5 text-xs text-muted-foreground">{{ t("nacos.nacosAuthHint") }}</p></div>- <template v-if="nacosRNacosConsoleAddr.trim()">- <div class="grid grid-cols-4 items-center gap-4">- <Label :class="connectionLabelClass">{{ t("connection.nacosConsoleAuthentication") }}</Label>- <div class="col-span-3 flex gap-2">- <Button size="sm" :variant="nacosConsoleAuthKind === 'inherit' ? 'default' : 'outline'" :disabled="nacosAuthKind === 'none'" @click="nacosConsoleAuthKind = 'inherit'">{{ t("connection.nacosConsoleAuthInherit") }}</Button>- <Button size="sm" :variant="nacosConsoleAuthKind === 'usernamePassword' ? 'default' : 'outline'" @click="nacosConsoleAuthKind = 'usernamePassword'">{{ t("connection.nacosConsoleAuthSeparate") }}</Button>+ <div class="grid max-w-md gap-1.5">+ <div class="grid gap-1.5">+ <div class="flex h-9 items-center gap-1 rounded-md border bg-muted/20 p-0.5">+ <Button type="button" size="sm" class="h-8 flex-1" :variant="nacosAuthKind === 'none' ? 'default' : 'ghost'" @click="nacosAuthKind = 'none'">{{ t("connection.nacosAuthNone") }}</Button>+ <Button type="button" size="sm" class="h-8 flex-1" :variant="nacosAuthKind === 'usernamePassword' ? 'default' : 'ghost'" @click="nacosAuthKind = 'usernamePassword'">{{ t("nacos.nacosUsernamePassword") }}</Button></div></div>- <div v-if="nacosConsoleAuthKind === 'inherit' && nacosAuthKind === 'none'" class="grid grid-cols-4 items-start gap-4">- <span />- <p class="col-span-3 m-0 text-xs text-destructive">{{ t("connection.nacosConsoleAuthPrimaryNone") }}</p>- </div>- <template v-if="nacosConsoleAuthKind === 'usernamePassword'">- <div class="grid grid-cols-4 items-center gap-4">- <Label :class="connectionLabelClass">{{ t("connection.nacosConsoleUser") }}</Label- ><Input v-model="nacosConsoleUsername" class="col-span-3" />- </div>- <div class="grid grid-cols-4 items-center gap-4">- <Label :class="connectionLabelClass">{{ t("connection.nacosConsolePassword") }}</Label- ><PasswordInput v-model="nacosConsolePassword" class="col-span-3" />- </div>- </template>- </template>- </template>- <div class="grid grid-cols-4 items-center gap-4">- <Label :class="connectionLabelClass">{{ t("connection.nacosAuth") }}</Label>- <div class="col-span-3 flex flex-wrap gap-2">- <Button size="sm" :variant="nacosAuthKind === 'none' ? 'default' : 'outline'" @click="nacosAuthKind = 'none'">{{ t("connection.nacosAuthNone") }}</Button>- <Button size="sm" :variant="nacosAuthKind === 'usernamePassword' ? 'default' : 'outline'" @click="nacosAuthKind = 'usernamePassword'">{{ t("connection.nacosAuthUserPassword") }}</Button></div>- </div>- <template v-if="nacosAuthKind === 'usernamePassword'">- <div class="grid grid-cols-4 items-center gap-4">- <Label :class="connectionLabelClass">{{ t("connection.user") }}</Label>- <Input v-model="nacosUsername" class="col-span-3" placeholder="nacos" />+ <div v-if="nacosAuthKind === 'usernamePassword'" class="mt-4 grid gap-4 sm:grid-cols-2">+ <div class="grid gap-1.5">+ <Label>{{ t("connection.user") }}</Label>+ <Input v-model="nacosUsername" placeholder="nacos" />+ </div>+ <div class="grid gap-1.5">+ <Label>{{ t("connection.password") }}</Label>+ <PasswordInput v-model="nacosPassword" />+ </div></div>- <div class="grid grid-cols-4 items-center gap-4">- <Label :class="connectionLabelClass">{{ t("connection.password") }}</Label>- <PasswordInput v-model="nacosPassword" class="col-span-3" />+ </section>++ <section data-nacos-advanced-hint class="flex items-start gap-3 rounded-lg border border-dashed bg-muted/20 px-4 py-3">+ <CircleHelp class="mt-0.5 h-4 w-4 shrink-0 text-muted-foreground" />+ <div class="min-w-0 flex-1">+ <div class="text-sm font-medium">{{ t("nacos.nacosAdvancedHint") }}</div>+ <p class="mt-0.5 text-xs leading-5 text-muted-foreground">{{ t("nacos.nacosAdvancedHintDescription") }}</p></div>- </template>- <div class="grid grid-cols-4 items-center gap-4">- <Label :class="connectionLabelSmallClass">{{ t("connection.nacosTls") }}</Label>- <label class="col-span-3 inline-flex items-center gap-2">- <input type="checkbox" v-model="nacosTlsSkipVerify" class="mr-0" />- <span class="text-xs text-muted-foreground">{{ t("connection.nacosTlsSkipVerify") }}</span>- </label>- </div>- <div class="grid grid-cols-4 items-center gap-4">- <Label :class="connectionLabelClass">{{ t("connection.nacosPageSize") }}</Label>- <Input v-model.number="nacosPageSize" type="number" min="1" max="500" class="col-span-3" />- </div>+ <Button type="button" variant="outline" size="sm" class="shrink-0" @click="configTab = 'advanced'">{{ t("nacos.nacosGoAdvanced") }}</Button>+ </section></template><!-- Redis: host, port, user, password, ssl -->@@ -6674,7 +6623,7 @@ function openExternalUrl(url: string) {</TabsContent><TabsContent v-if="supportsTlsToggle" value="tls" class="m-0 flex min-h-0 flex-1 flex-col overflow-hidden">- <div class="connection-form-body grid min-h-0 flex-1 gap-4 overflow-y-auto overflow-x-hidden pt-4 pr-2">+ <div class="connection-form-body grid min-h-0 flex-1 scroll-pb-6 gap-4 overflow-y-auto overflow-x-hidden pt-4 pr-2 pb-6"><div v-if="!supportsPostgresTlsOptions && !supportsMysqlTlsOptions" class="grid grid-cols-4 items-center gap-4"><Label :class="connectionLabelSmallClass">SSL/TLS</Label><label class="col-span-3 flex items-center gap-2 cursor-pointer">@@ -6974,7 +6923,101 @@ function openExternalUrl(url: string) {</TabsContent><TabsContent value="advanced" class="m-0 flex min-h-0 flex-1 flex-col overflow-hidden">- <div class="connection-form-body grid min-h-0 flex-1 gap-4 overflow-y-auto pt-4 pr-2">+ <div class="connection-form-body grid min-h-0 flex-1 scroll-pb-6 gap-4 overflow-y-auto pt-4 pr-2 pb-6">+ <section v-if="form.db_type === 'nacos'" data-nacos-advanced-settings class="overflow-hidden rounded-lg border">+ <div class="border-b bg-muted/20 px-4 py-3">+ <div class="text-sm font-medium">{{ t("nacos.nacosAdvancedTitle") }}</div>+ <p class="mt-0.5 text-xs leading-5 text-muted-foreground">{{ t("nacos.nacosAdvancedDescription") }}</p>+ </div>+ <div class="grid gap-5 p-4">+ <div class="grid gap-1.5">+ <Label>{{ t("connection.nacosPageSize") }}</Label>+ <Input v-model.number="nacosPageSize" type="number" min="1" max="500" />+ <p class="text-[11px] leading-4 text-muted-foreground">{{ t("nacos.nacosPageSizeHint") }}</p>+ </div>++ <div class="grid gap-2 border-t pt-4">+ <div class="grid gap-1.5 sm:grid-cols-[minmax(0,1fr)_180px] sm:items-center">+ <div>+ <Label>{{ t("connection.nacosMetrics") }}</Label>+ <p class="mt-1 text-[11px] leading-4 text-muted-foreground">{{ t("nacos.nacosMetricsHint") }}</p>+ </div>+ <Select v-model="nacosMetricsMode">+ <SelectTrigger class="h-9">+ <SelectValue />+ </SelectTrigger>+ <SelectContent>+ <SelectItem value="auto">{{ t("connection.nacosMetricsAuto") }}</SelectItem>+ <SelectItem value="disabled">{{ t("connection.nacosMetricsDisabled") }}</SelectItem>+ <SelectItem value="custom">{{ t("connection.nacosMetricsCustom") }}</SelectItem>+ </SelectContent>+ </Select>+ </div>+ <div v-if="nacosMetricsMode === 'custom'" class="grid gap-1.5">+ <Label>{{ t("connection.nacosMetricsUrl") }}</Label>+ <Input v-model="nacosMetricsUrl" :aria-invalid="!!nacosMetricsUrlError" :class="{ 'border-destructive focus-visible:ring-destructive': nacosMetricsUrlError }" placeholder="http://127.0.0.1:8848/nacos/actuator/prometheus" />+ <p v-if="nacosMetricsUrlError" class="text-xs text-destructive">{{ nacosMetricsUrlError }}</p>+ </div>+ </div>++ <div v-if="nacosImplementation === 'rnacos'" class="grid gap-4 border-t pt-4">+ <div class="flex items-start justify-between gap-4">+ <div>+ <Label>{{ t("nacos.nacosRnacosExtension") }}</Label>+ <p class="mt-1 text-[11px] leading-4 text-muted-foreground">{{ t("nacos.nacosRnacosExtensionHint") }}</p>+ </div>+ <label class="inline-flex shrink-0 items-center gap-2">+ <Switch v-model="nacosHistoryEnabled" />+ <span class="text-xs text-muted-foreground">{{ t("nacos.nacosEnabled") }}</span>+ </label>+ </div>+ <template v-if="nacosHistoryEnabled">+ <div class="grid gap-1.5">+ <Label>{{ t("connection.nacosRNacosConsoleUrl") }}</Label>+ <Input v-model="nacosRNacosConsoleAddr" :placeholder="t('connection.nacosRNacosConsoleUrlPlaceholder')" />+ <p class="text-[11px] leading-4 text-muted-foreground">{{ t("nacos.nacosRnacosConsoleUrlHint") }}</p>+ </div>+ <template v-if="nacosRNacosConsoleAddr.trim()">+ <div class="grid gap-1.5">+ <Label>{{ t("connection.nacosConsoleAuthentication") }}</Label>+ <div class="flex items-center gap-1 rounded-md border bg-muted/20 p-0.5">+ <Button type="button" size="sm" class="h-8 flex-1" :variant="nacosConsoleAuthKind === 'inherit' ? 'default' : 'ghost'" :disabled="nacosAuthKind === 'none'" @click="nacosConsoleAuthKind = 'inherit'">+ {{ t("connection.nacosConsoleAuthInherit") }}+ </Button>+ <Button type="button" size="sm" class="h-8 flex-1" :variant="nacosConsoleAuthKind === 'usernamePassword' ? 'default' : 'ghost'" @click="nacosConsoleAuthKind = 'usernamePassword'">+ {{ t("connection.nacosConsoleAuthSeparate") }}+ </Button>+ </div>+ <p v-if="nacosConsoleAuthKind === 'inherit' && nacosAuthKind === 'none'" class="text-xs text-destructive">{{ t("connection.nacosConsoleAuthPrimaryNone") }}</p>+ </div>+ <div v-if="nacosConsoleAuthKind === 'usernamePassword'" class="grid gap-4 sm:grid-cols-2">+ <div class="grid gap-1.5">+ <Label>{{ t("connection.nacosConsoleUser") }}</Label>+ <Input v-model="nacosConsoleUsername" />+ </div>+ <div class="grid gap-1.5">+ <Label>{{ t("connection.nacosConsolePassword") }}</Label>+ <PasswordInput v-model="nacosConsolePassword" />+ </div>+ </div>+ </template>+ </template>+ <p v-else class="text-[11px] leading-4 text-muted-foreground">{{ t("nacos.nacosRnacosDisabledHint") }}</p>+ </div>++ <label class="flex items-start justify-between gap-4 border-t pt-4">+ <div>+ <div class="text-sm font-medium">{{ t("connection.nacosTls") }}</div>+ <p class="mt-1 text-[11px] leading-4 text-muted-foreground">{{ t("nacos.nacosTlsHint") }}</p>+ </div>+ <span class="inline-flex shrink-0 items-center gap-2">+ <input v-model="nacosTlsSkipVerify" type="checkbox" class="mr-0" />+ <span class="text-xs text-muted-foreground">{{ t("connection.nacosTlsSkipVerify") }}</span>+ </span>+ </label>+ </div>+ </section>+<div v-if="showGaussdbConnectionMode" class="grid grid-cols-4 items-start gap-4"><Label :class="connectionLabelSmallPaddedClass">{{ t("connection.gaussdbConnectionMode") }}</Label><div class="col-span-3 grid gap-1">@@ -7131,7 +7174,7 @@ function openExternalUrl(url: string) {</TabsContent><TabsContent v-if="canUseTransportLayers" value="transport" class="m-0 flex min-h-0 flex-1 flex-col overflow-hidden">- <div class="connection-form-body grid min-h-0 flex-1 gap-4 overflow-y-auto overflow-x-hidden pt-4 pr-2">+ <div class="connection-form-body grid min-h-0 flex-1 scroll-pb-6 gap-4 overflow-y-auto overflow-x-hidden pt-4 pr-2 pb-6"><div class="connection-label-wide-grid grid min-w-0 grid-cols-4 items-start gap-4"><Label :class="connectionLabelSmallPaddedClass">{{ t("connection.sshHops") }}</Label><div class="col-span-3 grid min-w-0 gap-3">@@ -7397,7 +7440,12 @@ function openExternalUrl(url: string) {</Button></template></div>- <Button v-if="canChooseVisibleDatabases" variant="outline" class="shrink-0" :disabled="isTesting || isSaving || isLoadingVisibleDatabases || !hasRequiredConnectionTarget" @click="openVisibleDatabasesPicker">+ <Button v-if="canChooseVisibleNacosNamespaces" variant="outline" class="shrink-0" :disabled="isTesting || isSaving || isLoadingVisibleNacosNamespaces || !hasRequiredConnectionTarget" @click="openVisibleNacosNamespacesPicker">+ <Loader2 v-if="isLoadingVisibleNacosNamespaces" class="mr-1.5 h-4 w-4 animate-spin" />+ <ListFilter v-else class="mr-1.5 h-4 w-4" />+ {{ t("nacos.nacosVisibleNamespacesTitle") }}+ </Button>+ <Button v-else-if="canChooseVisibleDatabases" variant="outline" class="shrink-0" :disabled="isTesting || isSaving || isLoadingVisibleDatabases || !hasRequiredConnectionTarget" @click="openVisibleDatabasesPicker"><Loader2 v-if="isLoadingVisibleDatabases" class="mr-1.5 h-4 w-4 animate-spin" /><ListFilter v-else class="mr-1.5 h-4 w-4" />{{ hasVisibleObjectFilter ? visibleObjectSummary : visibleFilterUsesSchemas ? t("contextMenu.configureVisibleObjects") : t("contextMenu.selectVisibleDatabases") }}@@ -7481,6 +7529,58 @@ function openExternalUrl(url: string) {</DialogContent></Dialog>+ <Dialog v-model:open="showVisibleNacosNamespacesDialog">+ <DialogContent class="sm:max-w-[460px]" @interact-outside.prevent @escape-key-down.prevent>+ <DialogHeader>+ <DialogTitle>{{ t("nacos.nacosVisibleNamespacesTitle") }}</DialogTitle>+ <p class="text-sm text-muted-foreground">{{ t("nacos.nacosVisibleNamespacesDescription", { name: form.name || selectedProfile().label }) }}</p>+ </DialogHeader>++ <div class="flex items-center gap-2 rounded-md border bg-background px-2">+ <Search class="h-4 w-4 shrink-0 text-muted-foreground" />+ <Input v-model="visibleNacosNamespaceSearchText" :placeholder="t('nacos.nacosSearchNamespaces')" class="h-8 border-0 px-0 shadow-none focus-visible:ring-0" :disabled="isLoadingVisibleNacosNamespaces || !!visibleNacosNamespaceError" />+ </div>++ <div class="flex items-center justify-between text-xs text-muted-foreground">+ <span>{{ t("nacos.nacosSelectedNamespaces", { selected: visibleNacosNamespaceSelectedCount, total: visibleNacosNamespaces.length }) }}</span>+ <div class="flex items-center gap-2">+ <button class="hover:text-foreground disabled:opacity-50" :disabled="isLoadingVisibleNacosNamespaces" @click="selectAllVisibleNacosNamespaces">{{ t("nacos.nacosSelectAll") }}</button>+ <button class="hover:text-foreground disabled:opacity-50" :disabled="isLoadingVisibleNacosNamespaces" @click="clearVisibleNacosNamespaceSelection">{{ t("nacos.nacosClearSelection") }}</button>+ <button class="hover:text-foreground disabled:opacity-50" :disabled="isLoadingVisibleNacosNamespaces" @click="showAllVisibleNacosNamespaces">{{ t("nacos.nacosShowAll") }}</button>+ </div>+ </div>+ <p v-if="!isLoadingVisibleNacosNamespaces && !visibleNacosNamespaceError && !visibleNacosNamespaceCanSave" class="text-xs text-destructive">{{ t("nacos.nacosNamespaceSelectionRequired") }}</p>++ <div class="h-72 overflow-y-auto rounded-md border bg-background/50 p-1">+ <div v-if="isLoadingVisibleNacosNamespaces" class="flex h-full items-center justify-center gap-2 text-sm text-muted-foreground">+ <Loader2 class="h-4 w-4 animate-spin" />+ {{ t("common.loading") }}+ </div>+ <div v-else-if="visibleNacosNamespaceError" class="p-3 text-sm text-destructive">{{ t("nacos.nacosLoadNamespacesFailed", { message: visibleNacosNamespaceError }) }}</div>+ <div v-else-if="!filteredVisibleNacosNamespaces.length" class="p-3 text-sm text-muted-foreground">{{ t("grid.noSearchResults") }}</div>+ <template v-else>+ <button+ v-for="namespace in filteredVisibleNacosNamespaces"+ :key="nacosNamespaceValue(namespace) || '__public__'"+ type="button"+ class="flex min-h-9 w-full min-w-0 items-center gap-2 rounded-sm px-2 py-1.5 text-left text-sm hover:bg-accent hover:text-accent-foreground focus-visible:bg-accent focus-visible:text-accent-foreground focus-visible:outline-none"+ @click="toggleVisibleNacosNamespace(nacosNamespaceValue(namespace))"+ >+ <CheckSquare v-if="visibleNacosNamespaceSelection.has(nacosNamespaceValue(namespace))" class="h-4 w-4 shrink-0 text-primary" />+ <Square v-else class="h-4 w-4 shrink-0 text-muted-foreground" />+ <span class="min-w-0 flex-1 truncate">{{ nacosNamespaceLabel(namespace) }}</span>+ <span v-if="namespace.namespace && namespace.namespace !== nacosNamespaceLabel(namespace)" class="shrink-0 truncate text-xs text-muted-foreground">{{ namespace.namespace }}</span>+ </button>+ </template>+ </div>++ <DialogFooter>+ <Button variant="outline" @click="showVisibleNacosNamespacesDialog = false">{{ t("dangerDialog.cancel") }}</Button>+ <Button :disabled="isLoadingVisibleNacosNamespaces || !!visibleNacosNamespaceError || !visibleNacosNamespaceCanSave" @click="saveVisibleNacosNamespaceSelection">{{ t("nacos.save") }}</Button>+ </DialogFooter>+ </DialogContent>+ </Dialog>+<Dialog v-model:open="showVisibleDatabasesDialog"><DialogContent class="sm:max-w-[520px]" @keydown="preventDialogDocumentSelectAll"><DialogHeader>@@ -7654,16 +7754,23 @@ function openExternalUrl(url: string) {min-height: 0;}+.connection-dialog-content--config .connection-form-body {+ /* Preserve every form section's natural height; the form viewport owns+ * scrolling and must never shrink cards into collapsed grid rows. */+ align-content: start;+}++.connection-form-body--nacos {+ /* Authentication fields are conditional. Keep every Nacos card at its+ * max-content height when they appear, and scroll the form as a whole. */+ grid-auto-rows: max-content;+}+@media (max-height: 720px) {.connection-dialog-content--config {/* A definite flex height lets tab bodies shrink and scroll above the fixed footer. */height: calc(var(--dbx-viewport-height) - 2rem);}-- .connection-dialog-content--config .connection-form-body {- /* Keep grid rows compact when the scroll viewport is taller than the form. */- align-content: start;- }}/* Legacy responsive layout rules live in public/connection-dialog-legacy.cssdiff --git a/apps/desktop/src/components/nacos/NacosAdminConsole.vue b/apps/desktop/src/components/nacos/NacosAdminConsole.vueindex 31fc70f41e..9f8924ba57 100644--- a/apps/desktop/src/components/nacos/NacosAdminConsole.vue+++ b/apps/desktop/src/components/nacos/NacosAdminConsole.vue@@ -40,6 +40,8 @@ import {type NacosConfigDeleteSnapshot,} from "@/lib/nacos/nacosAdmin";import { createNacosNamespaceRequestGuard, subscribeNacosNamespacesChanged, type NacosNamespacesChangedDetail } from "@/lib/nacos/nacosNamespaceCache";+import { nacosInstanceMatchesPatch, nacosInstanceRefIdentity, nacosIpAddressIsValid, nacosServiceDetailMatches } from "@/lib/nacos/nacosServiceManagement";+import { nacosNamespaceIdentity, normalizeNacosNamespacesForDisplay } from "@/lib/nacos/nacosNamespaceVisibility";import { copyToClipboard, readTextFromClipboard } from "@/lib/common/clipboard";import { trimmedSelectionLayer } from "@/lib/editor/codemirrorTrimmedSelectionLayer";import { safeLocalStorageGet, safeLocalStorageSet } from "@/lib/backend/safeStorage";@@ -61,10 +63,15 @@ import type {NacosContentSearchResult,NacosConflictPolicy,NacosInstanceInfo,+ NacosInstancePatch,+ NacosInstanceRef,+ NacosOperationCapability,NacosNamespaceInfo,NacosNamespaceScope,NacosSearchProgress,NacosServiceInfo,+ NacosServiceDetail,+ NacosServiceUpsert,} from "@/types/nacos";import { Splitpanes, Pane } from "splitpanes";import "splitpanes/dist/splitpanes.css";@@ -139,7 +146,7 @@ const rnacosConsoleCaptcha = ref("");const rnacosConsoleAuthError = ref("");const rnacosConsoleAuthLoading = ref(false);const rnacosConsoleRetryAction = shallowRef<(() => Promise<void>) | null>(null);-const rnacosConsoleRetryErrorTarget = ref<"config" | "history">("history");+const rnacosConsoleRetryErrorTarget = ref<"config" | "history" | "instances">("history");const configFormatOptions = ["text", "json", "xml", "yaml", "html", "properties", "toml"];const configEditorHost = ref<HTMLDivElement | null>(null);const configEditorView = shallowRef<EditorView | null>(null);@@ -186,11 +193,38 @@ const servicePageSize = ref(20);const services = ref<NacosServiceInfo[]>([]);const serviceTotal = ref(0);const selectedService = ref<NacosServiceInfo | null>(null);+const selectedServiceDetail = ref<NacosServiceDetail | null>(null);+const serviceDetailLoading = ref(false);+const serviceDetailError = ref("");+const serviceDetailExpanded = ref(false);const instances = ref<NacosInstanceInfo[]>([]);const instancesLoading = ref(false);const instancesError = ref("");-const updatingInstanceKey = ref("");-const pendingInstanceUpdate = ref<{ instance: NacosInstanceInfo; patch: Partial<NacosInstanceInfo> } | null>(null);+const updatingInstanceKeys = ref<Record<string, number>>({});+const instanceWeightDrafts = ref<Record<string, string>>({});+const pendingInstanceUpdate = ref<{ instance: NacosInstanceInfo; patch: NacosInstancePatch } | null>(null);+const instanceEditorOpen = ref(false);+const instanceEditorError = ref("");+const instanceEditorTarget = ref<NacosInstanceInfo | null>(null);+const instanceEditor = ref({ weight: "1", metadata: "{}" });+const serviceEditorOpen = ref(false);+const serviceEditorLoading = ref(false);+const serviceEditorError = ref("");+const serviceEditorMode = ref<"create" | "update">("create");+const serviceEditor = ref({ serviceName: "", groupName: "", metadata: "{}", protectThreshold: "0", selector: "" });+const pendingServiceDelete = ref<NacosServiceInfo | null>(null);+const deletingService = ref(false);+const registeringInstance = ref(false);+const registerInstanceOpen = ref(false);+const registerInstanceError = ref("");+const registerInstance = ref({ ip: "", port: "", clusterName: "DEFAULT", weight: "1", metadata: "{}" });+const pendingInstanceDeregister = ref<NacosInstanceInfo | null>(null);+const servicesRequestGuard = createNacosLatestRequestGuard();+const serviceDetailRequestGuard = createNacosLatestRequestGuard();+const instancesRequestGuard = createNacosLatestRequestGuard();+let instanceUpdateSequence = 0;+let instanceOperationToken = 0;+let serviceMutationSequence = 0;const NACOS_SPLIT_SIZE_KEY = "dbx-nacos-admin-split-size";const savedNacosSplitSize = Number(safeLocalStorageGet(NACOS_SPLIT_SIZE_KEY));@@ -211,6 +245,55 @@ const batchTargetConnections = computed<NacosConfigTransferTarget[]>(() =>}),);const supportsConfigHistory = computed(() => connectionInfo.value?.capabilities.supportsConfigHistory !== false);+function operationCapability(capability: NacosOperationCapability | boolean | undefined, legacySupported = true): NacosOperationCapability {+ if (typeof capability === "boolean") return { supported: capability, reason: capability ? undefined : "notVerified" };+ return capability ?? { supported: legacySupported, reason: legacySupported ? undefined : "notVerified" };+}++const serviceCapabilities = computed(() => connectionInfo.value?.capabilities.serviceManagement);+const legacyServiceManagementSupported = computed(() => connectionInfo.value != null && connectionInfo.value.capabilities.supportsServiceManagement !== false);+const legacyInstanceUpdateSupported = computed(() => connectionInfo.value != null && connectionInfo.value.capabilities.supportsInstanceUpdate !== false);+const listServicesCapability = computed(() => operationCapability(serviceCapabilities.value?.listServices, legacyServiceManagementSupported.value));+const getServiceCapability = computed(() => operationCapability(serviceCapabilities.value?.getService, listServicesCapability.value.supported));+const createServiceCapability = computed(() => operationCapability(serviceCapabilities.value?.createService, legacyServiceManagementSupported.value));+const updateServiceCapability = computed(() => operationCapability(serviceCapabilities.value?.updateService, createServiceCapability.value.supported));+const deleteServiceCapability = computed(() => operationCapability(serviceCapabilities.value?.deleteService, createServiceCapability.value.supported));+const listInstancesCapability = computed(() => operationCapability(serviceCapabilities.value?.listInstances, listServicesCapability.value.supported));+const updateInstanceCapability = computed(() => operationCapability(serviceCapabilities.value?.updateInstance, legacyInstanceUpdateSupported.value));+const registerInstanceCapability = computed(() => operationCapability(serviceCapabilities.value?.registerInstance, updateInstanceCapability.value.supported));+const deregisterInstanceCapability = computed(() => operationCapability(serviceCapabilities.value?.deregisterInstance, updateInstanceCapability.value.supported));+const supportsServiceManagement = computed(() => listServicesCapability.value.supported);+const supportsInstanceUpdate = computed(() => updateInstanceCapability.value.supported);++function capabilityReason(capability: NacosOperationCapability) {+ if (props.readOnly) return t("nacos.capabilityReadOnly");+ switch (capability.reason) {+ case "implementationReadOnly":+ return t("nacos.capabilityReadOnlyWrite");+ case "versionUnsupported":+ return t("nacos.capabilityVersionUnsupported");+ case "endpointUnavailable":+ return t("nacos.capabilityEndpointUnavailable");+ case "connectionReadOnly":+ return t("nacos.capabilityReadOnly");+ default:+ return t("nacos.capabilityNotVerified");+ }+}++const serviceWriteNotice = computed(() => {+ if (props.readOnly) return t("nacos.capabilityHeaderReadOnly");+ const unsupported = [createServiceCapability.value, updateServiceCapability.value, deleteServiceCapability.value, updateInstanceCapability.value, registerInstanceCapability.value, deregisterInstanceCapability.value].find((capability) => !capability.supported);+ return unsupported ? capabilityReason(unsupported) : "";+});+const selectedServiceProtectionTriggered = computed(() => {+ if (selectedService.value?.triggerFlag === "true") return true;+ const threshold = selectedServiceDetail.value?.protectThreshold;+ if (threshold == null || threshold <= 0 || serviceCluster.value.trim()) return false;+ const total = selectedService.value?.ipCount ?? instances.value.length;+ const healthy = selectedService.value?.healthyInstanceCount ?? instances.value.filter((instance) => instance.healthy === true).length;+ return total > 0 && healthy / total < threshold;+});const configHistoryUnavailableTitle = computed(() => {if (supportsConfigHistory.value) return undefined;const reason = connectionInfo.value?.capabilities.historyUnavailableReason;@@ -249,6 +332,19 @@ const canRequestConfigDelete = computed(() => canStartNacosConfigDelete(configMuconst pendingDeleteDetails = computed(() => (pendingDeleteConfig.value ? buildNacosConfigDeleteConfirm(pendingDeleteConfig.value.config, pendingDeleteConfig.value.key.namespace || "") : ""));const pendingHistoryRollbackDetails = computed(() => (pendingHistoryRollback.value ? buildNacosConfigHistoryRollbackConfirm(pendingHistoryRollback.value, namespace.value) : ""));const pendingInstanceDetails = computed(() => (pendingInstanceUpdate.value && selectedService.value ? buildNacosInstanceConfirm(selectedService.value, pendingInstanceUpdate.value.instance, pendingInstanceUpdate.value.patch, serviceGroup.value, namespace.value) : ""));+const pendingInstanceDeregisterDetails = computed(() => {+ if (!pendingInstanceDeregister.value || !selectedService.value) return "";+ const ref = instanceRef(pendingInstanceDeregister.value);+ const lifetime = ref.ephemeral === true ? t("nacos.instanceEphemeral") : ref.ephemeral === false ? t("nacos.instancePersistent") : t("nacos.instanceUnknown");+ return t("nacos.instanceConfirmDetails", {+ namespace: ref.namespace || "public",+ service: `${ref.groupName || "DEFAULT_GROUP"}@@${ref.serviceName}`,+ ip: ref.ip,+ port: ref.port,+ cluster: ref.clusterName || "DEFAULT",+ type: lifetime,+ });+});const selectedConfigCount = computed(() => selectedConfigKeys.value.length);const hasSearchSession = computed(() => !!(searchResult.value || searchProgress.value || searchError.value));const retainedSearchMatchCount = computed(() => searchResult.value?.matches.length ?? searchProgress.value?.matches.length ?? 0);@@ -880,7 +976,7 @@ async function navigateToContentMatch(match: NacosContentMatch, keyword: string)await openTargetConfig(match.dataId, match.group, keyword);return;}- const namespaceInfo = batchNamespaces.value.find((item) => item.namespace === targetNamespace);+ const namespaceInfo = batchNamespaces.value.find((item) => nacosNamespaceIdentity(item.namespace) === nacosNamespaceIdentity(targetNamespace));queryStore.openNacosAdmin(props.connectionId, {namespace: targetNamespace,namespaceName: namespaceInfo?.namespaceShowName || targetNamespace || "public",@@ -897,7 +993,7 @@ async function loadBatchNamespaces(options: { force?: boolean } = {}) {try {const namespaces = await api.nacosListNamespaces(connectionId);if (!batchNamespacesRequestGuard.isCurrent(requestId, props.connectionId)) return;- batchNamespaces.value = namespaces;+ batchNamespaces.value = normalizeNacosNamespacesForDisplay(namespaces);} catch (error) {if (!batchNamespacesRequestGuard.isCurrent(requestId, props.connectionId)) return;batchError.value = error instanceof Error ? error.message : String(error);@@ -911,7 +1007,7 @@ async function loadBatchTargetNamespaces(connectionId: string, options: { force?try {const namespaces = await api.nacosListNamespaces(connectionId);if (!batchTargetNamespacesRequestGuard.isCurrent(requestId, connectionId) || batchTargetConnectionId.value !== connectionId) return;- batchTargetNamespaces.value = namespaces;+ batchTargetNamespaces.value = normalizeNacosNamespacesForDisplay(namespaces);} catch (error) {if (!batchTargetNamespacesRequestGuard.isCurrent(requestId, connectionId) || batchTargetConnectionId.value !== connectionId) return;batchError.value = error instanceof Error ? error.message : String(error);@@ -1122,12 +1218,13 @@ async function loadConfigHistory(page = historyPageNo.value) {}}-function setRNacosConsoleActionError(target: "config" | "history", message: string) {+function setRNacosConsoleActionError(target: "config" | "history" | "instances", message: string) {if (target === "config") configError.value = message;- else historyError.value = message;+ else if (target === "history") historyError.value = message;+ else instancesError.value = message;}-async function handleRNacosConsoleError(error: unknown, retryAction: () => Promise<void>, target: "config" | "history") {+async function handleRNacosConsoleError(error: unknown, retryAction: () => Promise<void>, target: "config" | "history" | "instances") {const message = error instanceof Error ? error.message : String(error);if (!message.includes("[rnacosConsoleCaptchaRequired]")) {setRNacosConsoleActionError(target, message);@@ -1415,23 +1512,35 @@ async function deleteConfig() {}async function loadServices(page = servicePageNo.value) {+ const requestId = servicesRequestGuard.begin();+ const connectionId = props.connectionId;+ const requestNamespace = namespace.value;+ const requestGroup = serviceGroup.value.trim();+ const requestName = serviceName.value.trim();servicesLoading.value = true;servicesError.value = "";servicePageNo.value = page;try {- const result = await api.nacosListServices(props.connectionId, {- namespace: namespace.value || undefined,- groupName: serviceGroup.value.trim() || undefined,- serviceName: serviceName.value.trim() || undefined,- pageNo: servicePageNo.value,+ const result = await api.nacosListServices(connectionId, {+ namespace: requestNamespace || undefined,+ groupName: requestGroup || undefined,+ serviceName: requestName || undefined,+ pageNo: page,pageSize: servicePageSize.value,});+ if (!servicesRequestGuard.isCurrent(requestId) || connectionId !== props.connectionId || requestNamespace !== namespace.value || requestGroup !== serviceGroup.value.trim() || requestName !== serviceName.value.trim()) return;services.value = result.items;serviceTotal.value = result.totalCount;+ const selectedIdentity = serviceIdentity(selectedService.value);+ if (selectedIdentity) {+ const refreshedSelection = result.items.find((item) => serviceIdentity(item) === selectedIdentity);+ if (refreshedSelection) selectedService.value = refreshedSelection;+ }} catch (error) {+ if (!servicesRequestGuard.isCurrent(requestId)) return;servicesError.value = error instanceof Error ? error.message : String(error);} finally {- servicesLoading.value = false;+ if (servicesRequestGuard.isCurrent(requestId)) servicesLoading.value = false;}}@@ -1444,56 +1553,503 @@ async function loadServicesWithRetry(page = servicePageNo.value) {}async function selectService(service: NacosServiceInfo) {+ serviceMutationSequence += 1;+ instanceUpdateSequence += 1;selectedService.value = service;- await loadInstances();+ selectedServiceDetail.value = null;+ serviceDetailError.value = "";+ instances.value = [];+ instancesError.value = "";+ await Promise.all([loadServiceDetail(), loadInstances()]);+}++function serviceIdentity(service: NacosServiceInfo | null) {+ return service ? `${service.groupName || "DEFAULT_GROUP"}\u0000${service.serviceName}` : "";+}++async function loadServiceDetail() {+ const service = selectedService.value ? { ...selectedService.value } : null;+ if (!service || !getServiceCapability.value.supported) return;+ const requestId = serviceDetailRequestGuard.begin();+ const connectionId = props.connectionId;+ const requestNamespace = namespace.value;+ const identity = serviceIdentity(service);+ serviceDetailLoading.value = true;+ serviceDetailError.value = "";+ try {+ const detail = await api.nacosGetService(connectionId, {+ namespace: requestNamespace || undefined,+ serviceName: service.serviceName,+ groupName: service.groupName || serviceGroup.value || undefined,+ });+ if (!serviceDetailRequestGuard.isCurrent(requestId) || connectionId !== props.connectionId || requestNamespace !== namespace.value || identity !== serviceIdentity(selectedService.value)) return;+ selectedServiceDetail.value = detail;+ } catch (error) {+ if (!serviceDetailRequestGuard.isCurrent(requestId)) return;+ serviceDetailError.value = error instanceof Error ? error.message : String(error);+ } finally {+ if (serviceDetailRequestGuard.isCurrent(requestId)) serviceDetailLoading.value = false;+ }+}++async function reconcileServiceMutation(expected: NacosServiceUpsert, mutationId: number) {+ const expectedIdentity = `${expected.groupName || "DEFAULT_GROUP"}\u0000${expected.serviceName}`;+ for (const retryDelay of [0, 250, 750]) {+ if (retryDelay) await delay(retryDelay);+ if (mutationId !== serviceMutationSequence || expectedIdentity !== serviceIdentity(selectedService.value)) return;+ try {+ const detail = await api.nacosGetService(props.connectionId, {+ namespace: expected.namespace,+ serviceName: expected.serviceName,+ groupName: expected.groupName,+ });+ if (mutationId !== serviceMutationSequence || expectedIdentity !== serviceIdentity(selectedService.value)) return;+ if (nacosServiceDetailMatches(detail, expected)) {+ selectedServiceDetail.value = detail;+ serviceDetailError.value = "";+ await loadServicesWithRetry(1);+ if (expectedIdentity === serviceIdentity(selectedService.value)) await loadInstances();+ return;+ }+ } catch {+ // The explicit warning below preserves the optimistic detail and gives+ // the user a deliberate refresh path when Nacos is briefly stale.+ }+ }+ if (mutationId === serviceMutationSequence) serviceDetailError.value = t("nacos.serviceUpdateUnconfirmed");+}++function instanceRef(instance: NacosInstanceInfo, service = selectedService.value): NacosInstanceRef {+ return {+ namespace: namespace.value || undefined,+ serviceName: service?.serviceName || instance.serviceName || "",+ groupName: instance.groupName || service?.groupName || serviceGroup.value || undefined,+ ip: instance.ip,+ port: instance.port,+ clusterName: instance.clusterName,+ ephemeral: instance.ephemeral,+ };+}++function instanceIdentity(instance: NacosInstanceInfo, service = selectedService.value) {+ return instanceRefIdentity(instanceRef(instance, service));+}++function instanceRefIdentity(ref: NacosInstanceRef) {+ return nacosInstanceRefIdentity(ref);+}++function beginInstanceOperation(key: string) {+ const token = ++instanceOperationToken;+ updatingInstanceKeys.value = { ...updatingInstanceKeys.value, [key]: token };+ return token;+}++function isInstanceUpdating(instance: NacosInstanceInfo) {+ return Object.prototype.hasOwnProperty.call(updatingInstanceKeys.value, instanceIdentity(instance));+}++function clearInstanceOperation(key: string, token: number) {+ if (updatingInstanceKeys.value[key] !== token) return;+ const next = { ...updatingInstanceKeys.value };+ delete next[key];+ updatingInstanceKeys.value = next;+}++function instanceWeightDraft(instance: NacosInstanceInfo) {+ return instanceWeightDrafts.value[instanceIdentity(instance)] ?? String(instance.weight ?? 1);+}++function updateInstanceWeightDraft(instance: NacosInstanceInfo, value: string | number) {+ instanceWeightDrafts.value[instanceIdentity(instance)] = String(value);+}++function hasInstanceWeightDraft(instance: NacosInstanceInfo) {+ const value = instanceWeightDraft(instance).trim();+ return value !== "" && Number.isFinite(Number(value)) && Number(value) !== (instance.weight ?? 1);+}++function resetInstanceWeightDraft(instance: NacosInstanceInfo) {+ delete instanceWeightDrafts.value[instanceIdentity(instance)];+}++function requestInstanceWeightUpdate(instance: NacosInstanceInfo) {+ const value = instanceWeightDraft(instance).trim();+ const weight = Number(value);+ if (!value || !Number.isFinite(weight) || weight < 0) {+ instancesError.value = t("nacos.invalidWeight");+ return;+ }+ requestUpdateInstance(instance, { weight });+}++function openInstanceEditor(instance: NacosInstanceInfo) {+ instanceEditorTarget.value = instance;+ instanceEditor.value = {+ weight: String(instance.weight ?? 1),+ metadata: JSON.stringify(instance.metadata ?? {}, null, 2),+ };+ instanceEditorError.value = "";+ instanceEditorOpen.value = true;+}++function submitInstanceEditor() {+ const instance = instanceEditorTarget.value;+ const weight = Number(instanceEditor.value.weight);+ if (!instance || !Number.isFinite(weight) || weight < 0) {+ instanceEditorError.value = t("nacos.invalidWeightInput");+ return;+ }+ try {+ const metadata = parseJsonObject(instanceEditor.value.metadata, t("nacos.metadataLabel"));+ instanceEditorOpen.value = false;+ requestUpdateInstance(instance, { weight, metadata });+ } catch (error) {+ instanceEditorError.value = error instanceof Error ? error.message : String(error);+ }+}++function instanceMatchesPatch(instance: NacosInstanceInfo, patch: NacosInstancePatch) {+ return nacosInstanceMatchesPatch(instance, patch);}async function loadInstances() {if (!selectedService.value) return;+ instanceUpdateSequence += 1;+ if (!listInstancesCapability.value.supported) {+ instancesError.value = capabilityReason(listInstancesCapability.value);+ return;+ }+ const requestId = instancesRequestGuard.begin();+ const connectionId = props.connectionId;+ const requestNamespace = namespace.value;+ const service = { ...selectedService.value };+ const selectedIdentity = serviceIdentity(service);+ const clusters = serviceCluster.value.trim();instancesLoading.value = true;instancesError.value = "";try {- instances.value = await api.nacosListInstances(props.connectionId, {- namespace: namespace.value || undefined,- serviceName: selectedService.value.serviceName,- groupName: selectedService.value.groupName || serviceGroup.value || undefined,- clusters: serviceCluster.value.trim() || undefined,+ const result = await api.nacosListInstances(connectionId, {+ namespace: requestNamespace || undefined,+ serviceName: service.serviceName,+ groupName: service.groupName || serviceGroup.value || undefined,+ clusters: clusters || undefined,});+ if (!instancesRequestGuard.isCurrent(requestId) || connectionId !== props.connectionId || requestNamespace !== namespace.value || selectedIdentity !== serviceIdentity(selectedService.value) || clusters !== serviceCluster.value.trim()) return;+ instances.value = result;} catch (error) {- instancesError.value = error instanceof Error ? error.message : String(error);+ if (!instancesRequestGuard.isCurrent(requestId)) return;+ await handleRNacosConsoleError(error, () => loadInstances(), "instances");} finally {- instancesLoading.value = false;+ if (instancesRequestGuard.isCurrent(requestId)) instancesLoading.value = false;}}-function requestUpdateInstance(instance: NacosInstanceInfo, patch: Partial<NacosInstanceInfo>) {- if (!selectedService.value || props.readOnly) return;+async function refreshSelectedService() {+ if (!selectedService.value) return;+ await Promise.all([loadServiceDetail(), loadInstances(), loadServices(servicePageNo.value)]);+}++function requestUpdateInstance(instance: NacosInstanceInfo, patch: NacosInstancePatch) {+ if (!selectedService.value || props.readOnly || !supportsInstanceUpdate.value) return;+ if (patch.weight != null && (!Number.isFinite(patch.weight) || patch.weight < 0)) {+ instancesError.value = t("nacos.invalidWeight");+ return;+ }pendingInstanceUpdate.value = { instance, patch };}-async function updateInstance(instance: NacosInstanceInfo, patch: Partial<NacosInstanceInfo>) {- if (!selectedService.value || props.readOnly) return;- updatingInstanceKey.value = `${instance.ip}:${instance.port}`;+async function reconcileInstanceUpdate(ref: NacosInstanceRef, patch: NacosInstancePatch, updateId: number) {+ const currentService = selectedService.value;+ if (!currentService || serviceIdentity(currentService) !== `${ref.groupName || "DEFAULT_GROUP"}\u0000${ref.serviceName}`) return;+ for (const retryDelay of [0, 250, 750]) {+ if (retryDelay) await delay(retryDelay);+ if (updateId !== instanceUpdateSequence || serviceIdentity(selectedService.value) !== serviceIdentity(currentService)) return;+ try {+ const result = await api.nacosListInstances(props.connectionId, {+ namespace: ref.namespace,+ serviceName: ref.serviceName,+ groupName: ref.groupName,+ clusters: serviceCluster.value.trim() || undefined,+ });+ if (updateId !== instanceUpdateSequence || serviceIdentity(selectedService.value) !== serviceIdentity(currentService)) return;+ const actual = result.find((candidate) => instanceIdentity(candidate, currentService) === instanceRefIdentity(ref));+ if (actual && instanceMatchesPatch(actual, patch)) {+ instances.value = result;+ void loadServices(servicePageNo.value);+ return;+ }+ } catch {+ // Keep the optimistic result visible. The final warning gives the user a+ // deliberate refresh path instead of silently replacing it with stale data.+ }+ }+ if (updateId === instanceUpdateSequence) instancesError.value = t("nacos.instanceUpdateUnconfirmed");+}++async function reconcileInstancePresence(ref: NacosInstanceRef, shouldExist: boolean, updateId: number) {+ const currentService = selectedService.value;+ if (!currentService || serviceIdentity(currentService) !== `${ref.groupName || "DEFAULT_GROUP"}\u0000${ref.serviceName}`) return;+ for (const retryDelay of [0, 250, 750]) {+ if (retryDelay) await delay(retryDelay);+ if (updateId !== instanceUpdateSequence || serviceIdentity(selectedService.value) !== serviceIdentity(currentService)) return;+ try {+ const result = await api.nacosListInstances(props.connectionId, {+ namespace: ref.namespace,+ serviceName: ref.serviceName,+ groupName: ref.groupName,+ clusters: serviceCluster.value.trim() || undefined,+ });+ if (updateId !== instanceUpdateSequence || serviceIdentity(selectedService.value) !== serviceIdentity(currentService)) return;+ const exists = result.some((candidate) => instanceIdentity(candidate, currentService) === instanceRefIdentity(ref));+ if (exists === shouldExist) {+ instances.value = result;+ instancesError.value = "";+ void loadServices(servicePageNo.value);+ return;+ }+ } catch {+ // Keep the optimistic list until the final warning offers a refresh.+ }+ }+ if (updateId === instanceUpdateSequence) instancesError.value = shouldExist ? t("nacos.instanceRegisterUnconfirmed") : t("nacos.instanceDeregisterUnconfirmed");+}++async function updateInstance(instance: NacosInstanceInfo, patch: NacosInstancePatch) {+ if (!selectedService.value || props.readOnly || !supportsInstanceUpdate.value) return;+ const ref = instanceRef(instance);+ const key = instanceIdentity(instance);+ const updateId = ++instanceUpdateSequence;+ const operationToken = beginInstanceOperation(key);+ try {+ await api.nacosUpdateInstance(props.connectionId, { target: ref, patch });+ if (updateId !== instanceUpdateSequence) return;+ instances.value = instances.value.map((candidate) => (instanceIdentity(candidate) === key ? { ...candidate, ...patch } : candidate));+ if (patch.weight != null) delete instanceWeightDrafts.value[key];+ pendingInstanceUpdate.value = null;+ void reconcileInstanceUpdate(ref, patch, updateId);+ } catch (error) {+ if (updateId === instanceUpdateSequence) {+ pendingInstanceUpdate.value = null;+ instancesError.value = error instanceof Error ? error.message : String(error);+ }+ } finally {+ clearInstanceOperation(key, operationToken);+ }+}++function parseJsonObject(value: string, label: string): Record<string, unknown> {+ const parsed = JSON.parse(value || "{}") as unknown;+ if (!parsed || Array.isArray(parsed) || typeof parsed !== "object") throw new Error(`${label}${t("nacos.jsonObjectValidation")}`);+ return parsed as Record<string, unknown>;+}++function parseOptionalJsonObject(value: string, label: string): Record<string, unknown> | undefined {+ const trimmed = value.trim();+ // Nacos rejects an empty selector object because it has no selector type.+ // Treat an empty editor or `{}` as the absence of a selector instead.+ if (!trimmed || trimmed === "{}") return undefined;+ return parseJsonObject(trimmed, label);+}++function openCreateService() {+ serviceEditorMode.value = "create";+ serviceEditor.value = { serviceName: "", groupName: serviceGroup.value || "DEFAULT_GROUP", metadata: "{}", protectThreshold: "0", selector: "" };+ serviceEditorError.value = "";+ serviceEditorOpen.value = true;+}++async function openUpdateService(service: NacosServiceInfo) {+ serviceEditorLoading.value = true;+ serviceEditorError.value = "";+ try {+ const detail: NacosServiceDetail = await api.nacosGetService(props.connectionId, { namespace: namespace.value || undefined, serviceName: service.serviceName, groupName: service.groupName });+ serviceEditorMode.value = "update";+ serviceEditor.value = {+ serviceName: detail.serviceName,+ groupName: detail.groupName || service.groupName || "DEFAULT_GROUP",+ metadata: JSON.stringify(detail.metadata ?? {}, null, 2),+ protectThreshold: String(detail.protectThreshold ?? 0),+ selector: detail.selector && typeof detail.selector === "object" && !Array.isArray(detail.selector) && Object.keys(detail.selector).length > 0 ? JSON.stringify(detail.selector, null, 2) : "",+ };+ serviceEditorOpen.value = true;+ } catch (error) {+ instancesError.value = error instanceof Error ? error.message : String(error);+ } finally {+ serviceEditorLoading.value = false;+ }+}++async function submitServiceEditor() {+ const threshold = Number(serviceEditor.value.protectThreshold);+ if (!serviceEditor.value.serviceName.trim() || !serviceEditor.value.groupName.trim() || !Number.isFinite(threshold) || threshold < 0 || threshold > 1) {+ serviceEditorError.value = t("nacos.serviceValidation");+ return;+ }+ serviceEditorLoading.value = true;+ serviceEditorError.value = "";+ try {+ const isCreating = serviceEditorMode.value === "create";+ const targetGroup = isCreating ? serviceEditor.value.groupName.trim() : selectedService.value?.groupName || serviceEditor.value.groupName.trim();+ const req: NacosServiceUpsert = {+ namespace: namespace.value || undefined,+ serviceName: serviceEditor.value.serviceName.trim(),+ groupName: targetGroup,+ metadata: parseJsonObject(serviceEditor.value.metadata, t("nacos.metadataLabel")),+ protectThreshold: threshold,+ selector: parseOptionalJsonObject(serviceEditor.value.selector, t("nacos.selectorLabel")),+ };+ const mutationId = ++serviceMutationSequence;+ if (isCreating) await api.nacosCreateService(props.connectionId, req);+ else await api.nacosUpdateService(props.connectionId, req);+ serviceEditorOpen.value = false;+ if (isCreating && req.groupName) serviceGroup.value = req.groupName;+ selectedService.value = isCreating ? { serviceName: req.serviceName, groupName: req.groupName } : { ...(selectedService.value ?? {}), serviceName: req.serviceName, groupName: req.groupName };+ if (isCreating) instances.value = [];+ selectedServiceDetail.value = {+ serviceName: req.serviceName,+ groupName: req.groupName,+ metadata: req.metadata ?? {},+ protectThreshold: req.protectThreshold,+ selector: req.selector,+ ephemeral: selectedServiceDetail.value?.ephemeral,+ };+ serviceDetailError.value = "";+ await loadServicesWithRetry(1);+ void reconcileServiceMutation(req, mutationId);+ } catch (error) {+ serviceEditorError.value = error instanceof Error ? error.message : String(error);+ } finally {+ serviceEditorLoading.value = false;+ }+}++async function requestDeleteService(service: NacosServiceInfo) {+ try {+ const existing = await api.nacosListInstances(props.connectionId, { namespace: namespace.value || undefined, serviceName: service.serviceName, groupName: service.groupName });+ if (existing.length) {+ instancesError.value = t("nacos.serviceHasInstances");+ return;+ }+ pendingServiceDelete.value = service;+ } catch (error) {+ instancesError.value = error instanceof Error ? error.message : String(error);+ }+}++async function reconcileServiceDeletion(service: NacosServiceInfo, mutationId: number) {+ const groupName = service.groupName || "DEFAULT_GROUP";+ for (const retryDelay of [0, 250, 750]) {+ if (retryDelay) await delay(retryDelay);+ if (mutationId !== serviceMutationSequence) return;+ try {+ const result = await api.nacosListServices(props.connectionId, {+ namespace: namespace.value || undefined,+ groupName,+ serviceName: service.serviceName,+ pageNo: 1,+ pageSize: servicePageSize.value,+ });+ if (mutationId !== serviceMutationSequence) return;+ const stillExists = result.items.some((item) => serviceIdentity(item) === `${groupName}\u0000${service.serviceName}`);+ if (!stillExists) {+ servicesError.value = "";+ await loadServicesWithRetry(1);+ return;+ }+ } catch {+ // A transient read failure is not proof that the service disappeared.+ }+ }+ if (mutationId === serviceMutationSequence) servicesError.value = t("nacos.serviceDeleteUnconfirmed");+}++async function deleteService(service: NacosServiceInfo) {+ deletingService.value = true;+ try {+ const mutationId = ++serviceMutationSequence;+ await api.nacosDeleteService(props.connectionId, { namespace: namespace.value || undefined, serviceName: service.serviceName, groupName: service.groupName });+ pendingServiceDelete.value = null;+ services.value = services.value.filter((candidate) => serviceIdentity(candidate) !== serviceIdentity(service));+ if (serviceIdentity(selectedService.value) === serviceIdentity(service)) {+ selectedService.value = null;+ selectedServiceDetail.value = null;+ instances.value = [];+ }+ void reconcileServiceDeletion(service, mutationId);+ } catch (error) {+ pendingServiceDelete.value = null;+ servicesError.value = error instanceof Error ? error.message : String(error);+ } finally {+ deletingService.value = false;+ }+}++async function submitInstanceRegistration() {+ if (!selectedService.value) return;+ const port = Number(registerInstance.value.port);+ const weight = Number(registerInstance.value.weight);+ if (!nacosIpAddressIsValid(registerInstance.value.ip) || !Number.isInteger(port) || port < 1 || port > 65535 || !Number.isFinite(weight) || weight < 0) {+ registerInstanceError.value = t("nacos.instanceValidation");+ return;+ }+ registeringInstance.value = true;+ registerInstanceError.value = "";try {- await api.nacosUpdateInstance(props.connectionId, {+ const registration = {namespace: namespace.value || undefined,serviceName: selectedService.value.serviceName,- groupName: instance.groupName || selectedService.value.groupName || serviceGroup.value || undefined,- clusterName: instance.clusterName,- ip: instance.ip,- port: instance.port,- healthy: patch.healthy ?? instance.healthy,- enabled: patch.enabled ?? instance.enabled,- ephemeral: patch.ephemeral ?? instance.ephemeral,- weight: patch.weight ?? instance.weight,- metadata: instance.metadata,- });- pendingInstanceUpdate.value = null;- await loadInstances();+ groupName: selectedService.value.groupName || serviceGroup.value || undefined,+ ip: registerInstance.value.ip.trim(),+ port,+ clusterName: registerInstance.value.clusterName.trim() || undefined,+ weight,+ metadata: parseJsonObject(registerInstance.value.metadata, t("nacos.metadataLabel")),+ };+ const updateId = ++instanceUpdateSequence;+ await api.nacosRegisterInstance(props.connectionId, registration);+ const ref: NacosInstanceRef = { ...registration, ephemeral: false };+ if (!instances.value.some((candidate) => instanceIdentity(candidate) === instanceRefIdentity(ref))) {+ instances.value = [+ ...instances.value,+ {+ ip: registration.ip,+ port: registration.port,+ serviceName: registration.serviceName,+ groupName: registration.groupName,+ clusterName: registration.clusterName,+ enabled: true,+ ephemeral: false,+ weight: registration.weight,+ metadata: registration.metadata,+ },+ ];+ }+ registerInstanceOpen.value = false;+ void reconcileInstancePresence(ref, true, updateId);+ } catch (error) {+ registerInstanceError.value = error instanceof Error ? error.message : String(error);+ } finally {+ registeringInstance.value = false;+ }+}++async function deregisterInstance(instance: NacosInstanceInfo) {+ if (!selectedService.value) return;+ const key = instanceIdentity(instance);+ const operationToken = beginInstanceOperation(key);+ try {+ const ref = instanceRef(instance);+ const updateId = ++instanceUpdateSequence;+ await api.nacosDeregisterInstance(props.connectionId, ref);+ pendingInstanceDeregister.value = null;+ instances.value = instances.value.filter((candidate) => instanceIdentity(candidate) !== instanceIdentity(instance));+ void reconcileInstancePresence(ref, false, updateId);} catch (error) {+ pendingInstanceDeregister.value = null;instancesError.value = error instanceof Error ? error.message : String(error);} finally {- updatingInstanceKey.value = "";+ clearInstanceOperation(key, operationToken);}}@@ -1552,6 +2108,15 @@ watch(originalConfigContent.value = "";destroyConfigEditor();selectedService.value = null;+ selectedServiceDetail.value = null;+ serviceDetailError.value = "";+ servicesRequestGuard.invalidate();+ serviceDetailRequestGuard.invalidate();+ instancesRequestGuard.invalidate();+ instanceUpdateSequence += 1;+ serviceMutationSequence += 1;+ instances.value = [];+ instancesError.value = "";selectedConfigKeys.value = [];try {await connectionStore.ensureConnected(props.connectionId);@@ -1577,6 +2142,11 @@ onMounted(async () => {onBeforeUnmount(() => {configDetailRequestGuard.invalidate();+ servicesRequestGuard.invalidate();+ serviceDetailRequestGuard.invalidate();+ instancesRequestGuard.invalidate();+ instanceUpdateSequence += 1;+ serviceMutationSequence += 1;configEditorSessionId += 1;latestConfigSaveRequestId += 1;batchNamespacesRequestGuard.invalidate();@@ -1633,7 +2203,7 @@ onBeforeUnmount(() => {<div class="flex shrink-0 items-center gap-1 border-b px-3 py-1.5"><button class="rounded px-3 py-1.5 text-sm" :class="activeTab === 'configs' ? 'bg-accent font-medium' : 'text-muted-foreground hover:bg-accent/60'" @click="activeTab = 'configs'">{{ t("nacos.configs") }}</button>- <button class="rounded px-3 py-1.5 text-sm" :class="activeTab === 'services' ? 'bg-accent font-medium' : 'text-muted-foreground hover:bg-accent/60'" @click="activeTab = 'services'">{{ t("nacos.services") }}</button>+ <button class="rounded px-3 py-1.5 text-sm" :class="activeTab === 'services' ? 'bg-accent font-medium' : 'text-muted-foreground hover:bg-accent/60'" :disabled="!supportsServiceManagement" @click="activeTab = 'services'">{{ t("nacos.services") }}</button></div><Splitpanes v-if="activeTab === 'configs'" class="nacos-admin-splitpanes min-h-0 flex-1" @resized="handleNacosSplitResized">@@ -1900,10 +2470,13 @@ onBeforeUnmount(() => {<Splitpanes v-else-if="activeTab === 'services'" class="nacos-admin-splitpanes min-h-0 flex-1" @resized="handleNacosSplitResized"><Pane :size="nacosSplitSize" min-size="24"><div class="flex h-full min-h-0 flex-col">- <div class="grid shrink-0 grid-cols-[minmax(0,1fr)_minmax(0,1fr)_minmax(0,1fr)_auto] gap-2 border-b p-2">+ <div class="grid shrink-0 grid-cols-[minmax(0,1fr)_minmax(0,1fr)_auto_auto] gap-2 border-b p-2"><Input v-model="serviceName" class="h-8 min-w-0" :placeholder="t('nacos.service')" @keyup.enter="loadServicesWithRetry(1)" /><Input v-model="serviceGroup" class="h-8 min-w-0" :placeholder="t('nacos.allGroups')" @keyup.enter="loadServicesWithRetry(1)" />- <Input v-model="serviceCluster" class="h-8 min-w-0" :placeholder="t('nacos.cluster')" @keyup.enter="loadInstances" />+ <Button size="sm" variant="outline" class="h-8 gap-1.5" :disabled="readOnly || !createServiceCapability.supported" :title="readOnly || !createServiceCapability.supported ? capabilityReason(createServiceCapability) : undefined" @click="openCreateService">+ <Plus class="h-3.5 w-3.5" />+ {{ t("nacos.service") }}+ </Button><Button size="sm" variant="outline" class="h-8 gap-1.5" :disabled="servicesLoading" @click="loadServicesWithRetry(1)"><Loader2 v-if="servicesLoading" class="h-3.5 w-3.5 animate-spin" /><RefreshCw v-else class="h-3.5 w-3.5" />@@ -1921,10 +2494,13 @@ onBeforeUnmount(() => {@click="selectService(service)"><span class="truncate font-medium">{{ service.serviceName }}</span>- <span class="flex items-center gap-2 text-xs text-muted-foreground">+ <span class="flex flex-wrap items-center gap-2 text-xs text-muted-foreground"><Server class="h-3.5 w-3.5" />{{ service.groupName || serviceGroup }}<span v-if="service.ipCount != null">· {{ t("nacos.instanceCount", { count: service.ipCount }) }}</span>+ <span v-if="service.healthyInstanceCount != null">· {{ t("nacos.healthy") }} {{ service.healthyInstanceCount }}</span>+ <span v-if="service.clusterCount != null">· {{ t("nacos.cluster") }} {{ service.clusterCount }}</span>+ <Badge v-if="service.triggerFlag === 'true'" variant="outline" class="h-5 border-amber-500 text-amber-700">{{ t("nacos.protectionTriggered") }}</Badge></span></button><div v-if="!servicesLoading && services.length === 0" class="flex h-full items-center justify-center text-sm text-muted-foreground">{{ t("nacos.noServices") }}</div>@@ -1942,65 +2518,183 @@ onBeforeUnmount(() => {<Pane :size="100 - nacosSplitSize" min-size="20"><div class="flex h-full min-h-0 flex-col">- <div class="flex shrink-0 items-center justify-between border-b px-3 py-2">- <div class="truncate text-sm font-medium">{{ selectedService?.serviceName || t("nacos.instances") }}</div>- <Button size="sm" variant="outline" class="h-8 gap-1.5" :disabled="!selectedService || instancesLoading" @click="loadInstances">- <Loader2 v-if="instancesLoading" class="h-3.5 w-3.5 animate-spin" />- <RefreshCw v-else class="h-3.5 w-3.5" />- {{ t("nacos.refresh") }}- </Button>+ <header class="shrink-0 border-b bg-background">+ <div class="flex min-h-16 flex-wrap items-center gap-x-3 gap-y-2 px-4 py-3">+ <div class="min-w-0 flex-1">+ <div class="truncate text-base font-semibold">{{ selectedService?.serviceName || t("nacos.instances") }}</div>+ <div v-if="selectedService" class="mt-1 flex flex-wrap items-center gap-x-2 gap-y-1 text-xs text-muted-foreground">+ <span>{{ selectedService.groupName || "DEFAULT_GROUP" }}</span>+ <span>· {{ t("nacos.loadedInstances", { count: instances.length }) }}</span>+ <Badge v-if="selectedServiceProtectionTriggered" variant="outline" class="h-5 border-amber-500 text-amber-700">{{ t("nacos.protectionTriggered") }}</Badge>+ </div>+ </div>+ <Button size="sm" variant="outline" class="h-8 shrink-0 gap-1.5" :disabled="!selectedService || instancesLoading || serviceDetailLoading" @click="refreshSelectedService">+ <Loader2 v-if="instancesLoading" class="h-3.5 w-3.5 animate-spin" />+ <RefreshCw v-else class="h-3.5 w-3.5" />+ {{ t("nacos.refresh") }}+ </Button>+ </div>+ <div v-if="selectedService" class="flex flex-wrap items-center gap-x-4 gap-y-2 border-t bg-muted/30 px-4 py-2">+ <div class="flex shrink-0 items-center gap-1">+ <Input v-model="serviceCluster" class="h-8 w-40" :placeholder="t('nacos.filterInstanceCluster')" @keyup.enter="loadInstances" />+ <Button size="sm" variant="secondary" class="h-8" :disabled="instancesLoading" @click="loadInstances">{{ t("nacos.filter") }}</Button>+ <Button+ size="sm"+ variant="ghost"+ class="h-8 px-2"+ :class="{ invisible: !serviceCluster }"+ :disabled="instancesLoading || !serviceCluster"+ @click="+ serviceCluster = '';+ loadInstances();+ "+ >{{ t("nacos.clear") }}</Button+ >+ </div>+ <div class="ml-auto flex flex-wrap items-center gap-2">+ <div class="flex items-center gap-1 rounded-md border bg-background p-1">+ <span class="px-1 text-xs text-muted-foreground">{{ t("nacos.serviceSettings") }}</span>+ <Button+ size="sm"+ variant="ghost"+ class="h-7"+ :disabled="readOnly || !updateServiceCapability.supported || serviceEditorLoading"+ :title="readOnly || !updateServiceCapability.supported ? capabilityReason(updateServiceCapability) : undefined"+ @click="openUpdateService(selectedService)"+ >{{ t("nacos.edit") }}</Button+ >+ <Button+ size="sm"+ variant="ghost"+ class="h-7 text-destructive hover:text-destructive"+ :disabled="readOnly || !deleteServiceCapability.supported"+ :title="readOnly || !deleteServiceCapability.supported ? capabilityReason(deleteServiceCapability) : undefined"+ @click="requestDeleteService(selectedService)"+ >{{ t("nacos.delete") }}</Button+ >+ </div>+ <div class="flex items-center gap-1 rounded-md border bg-background p-1">+ <span class="px-1 text-xs text-muted-foreground">{{ t("nacos.instances") }}</span>+ <Button size="sm" class="h-7" :disabled="readOnly || !registerInstanceCapability.supported" :title="readOnly || !registerInstanceCapability.supported ? capabilityReason(registerInstanceCapability) : undefined" @click="registerInstanceOpen = true">{{+ t("nacos.registerInstance")+ }}</Button>+ </div>+ </div>+ </div>+ </header>+ <div v-if="serviceWriteNotice" class="shrink-0 border-b bg-muted/40 px-3 py-2 text-xs text-muted-foreground">+ {{ serviceWriteNotice }}+ </div>+ <div v-if="selectedServiceProtectionTriggered" class="shrink-0 border-b border-amber-200 bg-amber-50 px-3 py-2 text-xs text-amber-900 dark:border-amber-900/60 dark:bg-amber-950/30 dark:text-amber-200">+ {{ t("nacos.protectionTriggeredDescription") }}</div>+ <section v-if="selectedService" class="shrink-0 border-b bg-background px-3 py-2">+ <button type="button" class="flex w-full items-center justify-between gap-3 text-left" @click="serviceDetailExpanded = !serviceDetailExpanded">+ <span class="text-xs font-medium">{{ t("nacos.serviceDetails") }}</span>+ <span class="text-xs text-muted-foreground">{{ serviceDetailExpanded ? t("nacos.collapse") : t("nacos.expand") }}</span>+ </button>+ <div class="mt-2 grid grid-cols-2 gap-2 text-xs sm:grid-cols-4">+ <div class="rounded border bg-muted/20 px-2 py-1.5">+ <div class="text-muted-foreground">{{ t("nacos.instanceStat") }}</div>+ <div class="mt-0.5 font-medium">{{ selectedService.ipCount ?? instances.length }}</div>+ </div>+ <div class="rounded border bg-muted/20 px-2 py-1.5">+ <div class="text-muted-foreground">{{ t("nacos.healthyInstances") }}</div>+ <div class="mt-0.5 font-medium">{{ selectedService.healthyInstanceCount ?? instances.filter((instance) => instance.healthy === true).length }}</div>+ </div>+ <div class="rounded border bg-muted/20 px-2 py-1.5">+ <div class="text-muted-foreground">{{ t("nacos.clusterCount") }}</div>+ <div class="mt-0.5 font-medium">{{ selectedService.clusterCount ?? new Set(instances.map((instance) => instance.clusterName || "DEFAULT")).size }}</div>+ </div>+ <div class="rounded border bg-muted/20 px-2 py-1.5">+ <div class="text-muted-foreground">{{ t("nacos.protectThreshold") }}</div>+ <div class="mt-0.5 font-medium">{{ selectedServiceDetail?.protectThreshold ?? "-" }}</div>+ </div>+ </div>+ <div v-if="serviceDetailExpanded" class="mt-2 grid gap-2 text-xs lg:grid-cols-2">+ <div class="min-w-0 rounded border p-2">+ <div class="mb-1 flex items-center justify-between text-muted-foreground">+ <span>{{ t("nacos.metadataLabel") }}</span+ ><span>{{ t("nacos.itemCount", { count: selectedServiceDetail?.metadata && typeof selectedServiceDetail.metadata === "object" ? Object.keys(selectedServiceDetail.metadata).length : 0 }) }}</span>+ </div>+ <pre class="max-h-28 overflow-auto whitespace-pre-wrap break-all rounded bg-muted p-2 font-mono text-[11px]">{{ JSON.stringify(selectedServiceDetail?.metadata ?? {}, null, 2) }}</pre>+ </div>+ <div class="min-w-0 rounded border p-2">+ <div class="mb-1 flex items-center justify-between text-muted-foreground">+ <span>{{ t("nacos.selectorLabel") }}</span+ ><span v-if="selectedServiceDetail?.ephemeral != null">{{ selectedServiceDetail.ephemeral ? t("nacos.temporaryService") : t("nacos.persistent") }}</span>+ </div>+ <pre class="max-h-28 overflow-auto whitespace-pre-wrap break-all rounded bg-muted p-2 font-mono text-[11px]">{{ JSON.stringify(selectedServiceDetail?.selector ?? {}, null, 2) }}</pre>+ </div>+ </div>+ <div v-if="serviceDetailLoading" class="mt-2 text-xs text-muted-foreground">{{ t("nacos.loadingServiceDetail") }}</div>+ <div v-if="serviceDetailError" class="mt-2 flex items-center justify-between gap-2 text-xs text-destructive">+ <span>{{ serviceDetailError }}</span>+ <Button size="sm" variant="outline" class="h-7 shrink-0" @click="loadServiceDetail">{{ t("nacos.refreshDetail") }}</Button>+ </div>+ </section><div v-if="instancesError" class="border-b px-3 py-2 text-xs text-destructive">{{ instancesError }}</div>- <div class="min-h-0 flex-1 overflow-auto">- <table v-if="instances.length" class="w-full text-left text-sm">- <thead class="sticky top-0 bg-muted/80 text-xs text-muted-foreground">- <tr>- <th class="px-3 py-2 font-medium">{{ t("nacos.address") }}</th>- <th class="px-3 py-2 font-medium">{{ t("nacos.cluster") }}</th>- <th class="px-3 py-2 font-medium">{{ t("nacos.weight") }}</th>- <th class="px-3 py-2 font-medium">metadata</th>- <th class="px-3 py-2 font-medium">{{ t("nacos.state") }}</th>- <th class="px-3 py-2 text-right font-medium">{{ t("nacos.actions") }}</th>- </tr>- </thead>- <tbody>- <tr v-for="instance in instances" :key="`${instance.ip}:${instance.port}`" class="border-b">- <td class="px-3 py-2 font-mono text-xs">{{ instance.ip }}:{{ instance.port }}</td>- <td class="px-3 py-2">{{ instance.clusterName || "-" }}</td>- <td class="px-3 py-2">- <Input- :model-value="instance.weight ?? 1"- type="number"- min="0"- step="0.1"- class="h-7 w-20 text-xs"- :disabled="readOnly || updatingInstanceKey === `${instance.ip}:${instance.port}`"- @change="(event: Event) => requestUpdateInstance(instance, { weight: Number((event.target as HTMLInputElement).value) })"- />- </td>- <td class="max-w-56 truncate px-3 py-2 font-mono text-xs" :title="JSON.stringify(instance.metadata ?? null)">{{ JSON.stringify(instance.metadata ?? null) }}</td>- <td class="px-3 py-2">- <div class="flex flex-wrap gap-1">- <Badge :variant="instance.healthy === false ? 'outline' : 'secondary'">{{ instance.healthy === false ? t("nacos.unhealthy") : t("nacos.healthy") }}</Badge>- <Badge :variant="instance.enabled === false ? 'outline' : 'secondary'">{{ instance.enabled === false ? t("nacos.offline") : t("nacos.enabled") }}</Badge>+ <div class="min-h-0 flex-1 overflow-auto bg-muted/20 p-3">+ <div v-if="instances.length" class="space-y-2">+ <article v-for="instance in instances" :key="instanceIdentity(instance)" class="rounded-lg border bg-background p-3 shadow-sm">+ <div class="flex flex-col gap-3 xl:flex-row xl:items-start xl:justify-between">+ <div class="min-w-0 flex-1">+ <div class="flex flex-wrap items-center gap-2">+ <span class="font-mono text-sm font-medium">{{ instance.ip }}:{{ instance.port }}</span>+ <Badge variant="outline">{{ instance.clusterName || "DEFAULT" }}</Badge>+ <Badge :variant="instance.healthy === false ? 'outline' : 'secondary'" :class="instance.healthy === false ? 'border-destructive/50 text-destructive' : ''">{{ instance.healthy === false ? t("nacos.unhealthy") : t("nacos.healthy") }}</Badge>+ <Badge :variant="instance.enabled === false ? 'outline' : 'secondary'" :class="instance.enabled === false ? 'border-muted-foreground/50 text-muted-foreground' : ''">{{ instance.enabled === false ? t("nacos.offline") : t("nacos.enabled") }}</Badge><Badge v-if="instance.ephemeral != null" variant="outline">{{ instance.ephemeral ? t("nacos.ephemeral") : t("nacos.persistent") }}</Badge></div>- </td>- <td class="px-3 py-2 text-right">- <div class="inline-flex gap-2">- <Button size="sm" variant="outline" class="h-7 gap-1" :disabled="readOnly || updatingInstanceKey === `${instance.ip}:${instance.port}`" @click="requestUpdateInstance(instance, { enabled: !instance.enabled })">- <Loader2 v-if="updatingInstanceKey === `${instance.ip}:${instance.port}`" class="h-3 w-3 animate-spin" />- {{ instance.enabled === false ? t("nacos.enable") : t("nacos.disable") }}- </Button>- <Button size="sm" variant="outline" class="h-7" :disabled="readOnly || updatingInstanceKey === `${instance.ip}:${instance.port}`" @click="requestUpdateInstance(instance, { healthy: !instance.healthy })">- {{ instance.healthy === false ? t("nacos.markHealthy") : t("nacos.markUnhealthy") }}- </Button>+ <div class="mt-3 grid gap-x-5 gap-y-3 text-xs sm:grid-cols-[auto_minmax(0,1fr)]">+ <div class="flex items-end gap-1 self-start">+ <label class="grid gap-1 text-muted-foreground">+ <span>{{ t("nacos.weight") }}</span>+ <Input+ :model-value="instanceWeightDraft(instance)"+ type="number"+ min="0"+ step="0.1"+ class="h-7 w-24 text-xs text-foreground"+ :disabled="readOnly || !supportsInstanceUpdate || isInstanceUpdating(instance)"+ @update:model-value="(value: string | number) => updateInstanceWeightDraft(instance, value)"+ />+ </label>+ <div v-if="hasInstanceWeightDraft(instance)" class="flex items-end gap-1">+ <Button size="sm" class="h-7" :disabled="readOnly || !supportsInstanceUpdate || isInstanceUpdating(instance)" @click="requestInstanceWeightUpdate(instance)">{{ t("nacos.save") }}</Button>+ <Button size="sm" variant="ghost" class="h-7 px-2" :disabled="isInstanceUpdating(instance)" @click="resetInstanceWeightDraft(instance)">{{ t("nacos.restore") }}</Button>+ </div>+ </div>+ <details v-if="instance.metadata && Object.keys(instance.metadata).length" class="min-w-0 self-start text-muted-foreground">+ <summary class="cursor-pointer select-none hover:text-foreground">{{ t("nacos.metadataLabel") }}({{ t("nacos.itemCount", { count: Object.keys(instance.metadata).length }) }})</summary>+ <pre class="mt-1 max-h-32 max-w-full overflow-auto rounded bg-muted p-2 font-mono text-[11px] text-foreground">{{ JSON.stringify(instance.metadata, null, 2) }}</pre>+ </details>+ <span v-else class="self-start text-muted-foreground">{{ t("nacos.noMetadata") }}</span></div>- </td>- </tr>- </tbody>- </table>- <div v-else class="flex h-full items-center justify-center text-sm text-muted-foreground">{{ t("nacos.selectService") }}</div>+ </div>+ <div class="flex shrink-0 flex-wrap items-center gap-2 xl:justify-end">+ <Button size="sm" variant="outline" class="h-7" :disabled="readOnly || !supportsInstanceUpdate || isInstanceUpdating(instance)" @click="openInstanceEditor(instance)">{{ t("nacos.edit") }}</Button>+ <Button size="sm" variant="outline" class="h-7 gap-1" :disabled="readOnly || !supportsInstanceUpdate || isInstanceUpdating(instance)" @click="requestUpdateInstance(instance, { enabled: !instance.enabled })">+ <Loader2 v-if="isInstanceUpdating(instance)" class="h-3 w-3 animate-spin" />+ {{ instance.enabled === false ? t("nacos.enable") : t("nacos.disable") }}+ </Button>+ <Button size="sm" variant="outline" class="h-7" :disabled="readOnly || !supportsInstanceUpdate || isInstanceUpdating(instance)" @click="requestUpdateInstance(instance, { healthy: !instance.healthy })">+ {{ instance.healthy === false ? t("nacos.markHealthy") : t("nacos.markUnhealthy") }}+ </Button>+ <Button+ size="sm"+ variant="outline"+ class="h-7 text-destructive"+ :disabled="readOnly || !deregisterInstanceCapability.supported || isInstanceUpdating(instance)"+ :title="readOnly || !deregisterInstanceCapability.supported ? capabilityReason(deregisterInstanceCapability) : undefined"+ @click="pendingInstanceDeregister = instance"+ >{{ t("nacos.deregister") }}</Button+ >+ </div>+ </div>+ </article>+ </div>+ <div v-else class="flex h-full items-center justify-center text-sm text-muted-foreground">{{ selectedService ? t("nacos.noInstances") : t("nacos.selectService") }}</div></div></div></Pane>@@ -2104,6 +2798,99 @@ onBeforeUnmount(() => {@confirm="requestRollbackComparedHistory"/>+ <Dialog v-model:open="serviceEditorOpen">+ <DialogContent class="sm:max-w-xl" @pointer-down-outside.prevent @interact-outside.prevent @escape-key-down.prevent>+ <DialogHeader>+ <DialogTitle>{{ serviceEditorMode === "create" ? t("nacos.createNacosService") : t("nacos.editNacosService") }}</DialogTitle>+ <DialogDescription>{{ t("nacos.manageServiceMetadata") }}</DialogDescription>+ </DialogHeader>+ <div class="grid gap-3 sm:grid-cols-2">+ <div class="space-y-1.5">+ <Label>{{ t("nacos.serviceName") }}</Label+ ><Input v-model="serviceEditor.serviceName" :disabled="serviceEditorMode === 'update'" />+ </div>+ <div class="space-y-1.5">+ <Label>{{ t("nacos.groupName") }}</Label+ ><Input v-model="serviceEditor.groupName" :disabled="serviceEditorMode === 'update'" />+ </div>+ <div class="space-y-1.5">+ <Label>{{ t("nacos.protectThreshold") }}</Label+ ><Input v-model="serviceEditor.protectThreshold" inputmode="decimal" :placeholder="t('nacos.thresholdExample')" />+ </div>+ <div class="space-y-1.5">+ <Label>{{ t("nacos.metadataLabel") }}({{ t("nacos.jsonObject") }})</Label><textarea v-model="serviceEditor.metadata" class="min-h-24 w-full rounded-md border bg-background p-2 font-mono text-xs" />+ </div>+ <div class="space-y-1.5 sm:col-span-2">+ <Label>{{ t("nacos.selectorLabel") }}({{ t("nacos.optionalJsonObject") }})</Label><textarea v-model="serviceEditor.selector" class="min-h-20 w-full rounded-md border bg-background p-2 font-mono text-xs" />+ </div>+ <p v-if="serviceEditorError" class="text-xs text-destructive sm:col-span-2">{{ serviceEditorError }}</p>+ </div>+ <DialogFooter+ ><Button variant="outline" :disabled="serviceEditorLoading" @click="serviceEditorOpen = false">{{ t("nacos.cancel") }}</Button+ ><Button :disabled="serviceEditorLoading" @click="submitServiceEditor"><Loader2 v-if="serviceEditorLoading" class="mr-2 h-4 w-4 animate-spin" />{{ t("nacos.save") }}</Button></DialogFooter+ >+ </DialogContent>+ </Dialog>++ <Dialog v-model:open="registerInstanceOpen">+ <DialogContent class="sm:max-w-lg" @pointer-down-outside.prevent @interact-outside.prevent @escape-key-down.prevent>+ <DialogHeader+ ><DialogTitle>{{ t("nacos.registerPersistentInstance") }}</DialogTitle+ ><DialogDescription>{{ t("nacos.persistentInstanceHint") }}</DialogDescription></DialogHeader+ >+ <div class="grid gap-3 sm:grid-cols-2">+ <div class="space-y-1.5">+ <Label>{{ t("nacos.ipAddress") }}</Label+ ><Input v-model="registerInstance.ip" />+ </div>+ <div class="space-y-1.5">+ <Label>{{ t("nacos.port") }}</Label+ ><Input v-model="registerInstance.port" type="number" min="1" max="65535" />+ </div>+ <div class="space-y-1.5">+ <Label>{{ t("nacos.cluster") }}</Label+ ><Input v-model="registerInstance.clusterName" />+ </div>+ <div class="space-y-1.5">+ <Label>{{ t("nacos.weight") }}</Label+ ><Input v-model="registerInstance.weight" type="number" min="0" step="0.1" />+ </div>+ <div class="space-y-1.5 sm:col-span-2">+ <Label>{{ t("nacos.metadataLabel") }}({{ t("nacos.jsonObject") }})</Label><textarea v-model="registerInstance.metadata" class="min-h-20 w-full rounded-md border bg-background p-2 font-mono text-xs" />+ </div>+ <p v-if="registerInstanceError" class="text-xs text-destructive sm:col-span-2">{{ registerInstanceError }}</p>+ </div>+ <DialogFooter+ ><Button variant="outline" :disabled="registeringInstance" @click="registerInstanceOpen = false">{{ t("nacos.cancel") }}</Button+ ><Button :disabled="registeringInstance" @click="submitInstanceRegistration"><Loader2 v-if="registeringInstance" class="mr-2 h-4 w-4 animate-spin" />{{ t("nacos.registerInstance") }}</Button></DialogFooter+ >+ </DialogContent>+ </Dialog>++ <Dialog v-model:open="instanceEditorOpen">+ <DialogContent class="sm:max-w-lg" @pointer-down-outside.prevent @interact-outside.prevent @escape-key-down.prevent>+ <DialogHeader>+ <DialogTitle>{{ t("nacos.instanceEditorTitle") }}</DialogTitle>+ <DialogDescription>{{ instanceEditorTarget ? `${instanceEditorTarget.ip}:${instanceEditorTarget.port} · ${instanceEditorTarget.clusterName || "DEFAULT"}` : "" }}</DialogDescription>+ </DialogHeader>+ <div class="grid gap-3">+ <div class="space-y-1.5">+ <Label>{{ t("nacos.weight") }}</Label>+ <Input v-model="instanceEditor.weight" type="number" min="0" step="0.1" />+ </div>+ <div class="space-y-1.5">+ <Label>{{ t("nacos.metadataLabel") }}({{ t("nacos.jsonObject") }})</Label>+ <textarea v-model="instanceEditor.metadata" class="min-h-36 w-full rounded-md border bg-background p-2 font-mono text-xs" />+ </div>+ <p v-if="instanceEditorError" class="text-xs text-destructive">{{ instanceEditorError }}</p>+ </div>+ <DialogFooter>+ <Button variant="outline" @click="instanceEditorOpen = false">{{ t("nacos.cancel") }}</Button>+ <Button @click="submitInstanceEditor">{{ t("nacos.save") }}</Button>+ </DialogFooter>+ </DialogContent>+ </Dialog>+<DangerConfirmDialog:open="!!pendingDeleteConfig":title="t('nacos.confirmDeleteTitle')"@@ -2142,15 +2929,47 @@ onBeforeUnmount(() => {:message="t('nacos.confirmInstanceMessage')":details="pendingInstanceDetails":confirm-label="t('dangerDialog.confirm')"- :loading="!!updatingInstanceKey"+ :loading="pendingInstanceUpdate ? isInstanceUpdating(pendingInstanceUpdate.instance) : false":close-on-confirm="false"@update:open="(value: boolean) => {- if (!value && !updatingInstanceKey) pendingInstanceUpdate = null;+ if (!value && (!pendingInstanceUpdate || !isInstanceUpdating(pendingInstanceUpdate.instance))) pendingInstanceUpdate = null;}"@confirm="pendingInstanceUpdate && updateInstance(pendingInstanceUpdate.instance, pendingInstanceUpdate.patch)"/>++ <DangerConfirmDialog+ :open="!!pendingServiceDelete"+ :title="t('nacos.deleteNacosService')"+ :message="t('nacos.confirmEmptyServiceDelete')"+ :details="pendingServiceDelete ? `${pendingServiceDelete.groupName || 'DEFAULT_GROUP'}@@${pendingServiceDelete.serviceName}` : ''"+ :confirm-label="t('nacos.delete')"+ :loading="deletingService"+ :close-on-confirm="false"+ @update:open="+ (value: boolean) => {+ if (!value && !deletingService) pendingServiceDelete = null;+ }+ "+ @confirm="pendingServiceDelete && deleteService(pendingServiceDelete)"+ />++ <DangerConfirmDialog+ :open="!!pendingInstanceDeregister"+ :title="t('nacos.deregisterNacosInstance')"+ :message="t('nacos.confirmInstanceDeregister')"+ :details="pendingInstanceDeregisterDetails"+ :confirm-label="t('nacos.deregister')"+ :loading="pendingInstanceDeregister ? isInstanceUpdating(pendingInstanceDeregister) : false"+ :close-on-confirm="false"+ @update:open="+ (value: boolean) => {+ if (!value && (!pendingInstanceDeregister || !isInstanceUpdating(pendingInstanceDeregister))) pendingInstanceDeregister = null;+ }+ "+ @confirm="pendingInstanceDeregister && deregisterInstance(pendingInstanceDeregister)"+ /></div></template>diff --git a/apps/desktop/src/components/nacos/NacosConfigBatchDialog.vue b/apps/desktop/src/components/nacos/NacosConfigBatchDialog.vueindex b707bdc784..fc86044d94 100644--- a/apps/desktop/src/components/nacos/NacosConfigBatchDialog.vue+++ b/apps/desktop/src/components/nacos/NacosConfigBatchDialog.vue@@ -6,6 +6,7 @@ import { Badge } from "@/components/ui/badge";import { Button } from "@/components/ui/button";import { Dialog, DialogContent, DialogDescription, DialogFooter, DialogHeader, DialogTitle } from "@/components/ui/dialog";import type { NacosBatchPreview, NacosBatchReport, NacosConfigSelectionScope, NacosConflictPolicy, NacosNamespaceInfo } from "@/types/nacos";+import { nacosNamespaceIdentity } from "@/lib/nacos/nacosNamespaceVisibility";export type NacosBatchDialogMode = "export" | "import" | "copy";@@ -48,7 +49,7 @@ const targetNamespace = ref("");const titleKey = computed(() => `nacos.batch${props.mode[0].toUpperCase()}${props.mode.slice(1)}Title`);const descriptionKey = computed(() => `nacos.batch${props.mode[0].toUpperCase()}${props.mode.slice(1)}Description`);-const targetNamespaces = computed(() => props.namespaces.filter((item) => props.targetConnectionId !== props.sourceConnectionId || item.namespace !== props.currentNamespace));+const targetNamespaces = computed(() => props.namespaces.filter((item) => props.targetConnectionId !== props.sourceConnectionId || nacosNamespaceIdentity(item.namespace) !== nacosNamespaceIdentity(props.currentNamespace)));const selectedTargetNamespace = computed(() => {try {const namespace = JSON.parse(targetNamespace.value);diff --git a/apps/desktop/src/components/nacos/__tests__/NacosAdminConsoleLayout.spec.ts b/apps/desktop/src/components/nacos/__tests__/NacosAdminConsoleLayout.spec.tsindex f58ea546a9..4d408b3459 100644--- a/apps/desktop/src/components/nacos/__tests__/NacosAdminConsoleLayout.spec.ts+++ b/apps/desktop/src/components/nacos/__tests__/NacosAdminConsoleLayout.spec.ts@@ -39,4 +39,55 @@ describe("NacosAdminConsole config workbench layout", () => {expect(source.indexOf("batchTransferRequest.value = null;", staleBranch)).toBeGreaterThan(staleBranch);expect(source.indexOf('batchError.value = t("nacos.previewExpired");', staleBranch)).toBeGreaterThan(staleBranch);});++ it("keeps service detail and instance loading as independent guarded requests", () => {+ expect(source).toContain("const serviceDetailRequestGuard = createNacosLatestRequestGuard();");+ expect(source).toContain("const instancesRequestGuard = createNacosLatestRequestGuard();");+ expect(source).toContain("await Promise.all([loadServiceDetail(), loadInstances()]);");+ });++ it("keeps instance weight edits as drafts until the explicit save action", () => {+ expect(source).toContain("instanceWeightDrafts.value[instanceIdentity(instance)] = String(value);");+ expect(source).toContain('@click="requestInstanceWeightUpdate(instance)"');+ expect(source).not.toContain('@change="requestInstanceWeightUpdate(instance)"');+ });++ it("tracks instance operations by token so stale requests cannot lock a row forever", () => {+ expect(source).toContain("const updatingInstanceKeys = ref<Record<string, number>>({});");+ expect(source).toContain("const operationToken = beginInstanceOperation(key);");+ expect(source).toContain("clearInstanceOperation(key, operationToken);");+ expect(source).not.toContain('if (updateId === instanceUpdateSequence) updatingInstanceKey.value = "";');+ });++ it("prevents service-management dialogs from closing through outside clicks or Escape", () => {+ expect(source.match(/@pointer-down-outside\.prevent/g)?.length).toBeGreaterThanOrEqual(3);+ expect(source.match(/@interact-outside\.prevent/g)?.length).toBeGreaterThanOrEqual(3);+ expect(source.match(/@escape-key-down\.prevent/g)?.length).toBeGreaterThanOrEqual(3);+ });++ it("renders service details before the independently scrollable instance cards", () => {+ const detail = source.indexOf("nacos.serviceDetails");+ const instanceCards = source.indexOf('v-for="instance in instances"');+ expect(detail).toBeGreaterThan(0);+ expect(instanceCards).toBeGreaterThan(detail);+ });++ it("keeps verbose service details collapsed until the user expands them", () => {+ expect(source).toContain("const serviceDetailExpanded = ref(false);");+ });++ it("reserves the cluster-clear action space so entering a filter cannot reflow the toolbar", () => {+ expect(source).toContain('class="min-w-0 flex-1"');+ expect(source).toContain('class="flex shrink-0 items-center gap-1"');+ expect(source).toContain(':class="{ invisible: !serviceCluster }"');+ expect(source).toContain(':disabled="instancesLoading || !serviceCluster"');+ expect(source).not.toContain('v-if="serviceCluster"\n size="sm"');+ });++ it("separates the service header, filtering controls, and management actions", () => {+ expect(source).toContain('<header class="shrink-0 border-b bg-background">');+ expect(source).toContain('class="flex flex-wrap items-center gap-x-4 gap-y-2 border-t bg-muted/30 px-4 py-2"');+ expect(source).toContain('t("nacos.serviceSettings")');+ expect(source).toContain('t("nacos.registerInstance")');+ });});diff --git a/apps/desktop/src/i18n/locales/en.ts b/apps/desktop/src/i18n/locales/en.tsindex c5ebc6f7e0..76125776a8 100644--- a/apps/desktop/src/i18n/locales/en.ts+++ b/apps/desktop/src/i18n/locales/en.ts@@ -7007,5 +7007,98 @@ export default {next: "Next",test: "Test",readOnly: "Read only",+ nacosConnectionPlan: "Connection plan",+ nacosConnectionPlanDescription: "Choose the service implementation and API version.",+ nacosServiceAddress: "Service address",+ nacosServiceAddressHint: "Enter the service address. The default port is 8848, for example http://host:8848/nacos.",+ nacosAuth: "Authentication",+ nacosAuthHint: "These credentials are used for connection tests and daily management.",+ nacosUsernamePassword: "Username / password",+ nacosAdvancedHint: "More connection options are available on the Advanced tab.",+ nacosAdvancedHintDescription: "Configure Prometheus metrics, page size, TLS verification, and r-nacos extensions there.",+ nacosGoAdvanced: "Go to Advanced",+ nacosV3ConsolePortWarning: "8080 is the default Nacos 3 Web Console port. Use the Server / Admin API address on port 8848 for service management, for example http://127.0.0.1:8848/nacos.",+ nacosAdvancedTitle: "Nacos advanced connection options",+ nacosAdvancedDescription: "These settings have safe defaults and usually only need adjustment for custom deployments, metrics, or r-nacos extensions.",+ nacosPageSizeHint: "Used for configuration and service lists; 1–500 items per page.",+ nacosMetricsHint: "Query metrics from the service address automatically; choose a custom URL when the metrics endpoint differs.",+ nacosRnacosExtension: "r-nacos extensions",+ nacosRnacosExtensionHint: "Enables config history, config descriptions, and disabled-instance management.",+ nacosEnabled: "Enabled",+ nacosRnacosConsoleUrlHint: "Usually http://host:10848.",+ nacosRnacosDisabledHint: "When disabled, only the service address is used; basic configuration and service management remain available.",+ nacosTlsHint: "Enable only for a trusted self-signed HTTPS certificate.",+ nacosVisibleNamespacesTitle: "Choose visible namespaces",+ nacosVisibleNamespacesDescription: "Choose the namespaces to show in the sidebar for {name}.",+ nacosSearchNamespaces: "Search namespaces...",+ nacosSelectedNamespaces: "{selected}/{total} selected",+ nacosSelectAll: "Select all",+ nacosClearSelection: "Clear",+ nacosShowAll: "Show all",+ nacosNamespaceSelectionRequired: "Select at least one namespace, or use “Show all” to clear the filter.",+ nacosLoadNamespacesFailed: "Failed to load namespaces: {message}",+ capabilityReadOnly: "This connection is read-only.",+ capabilityReadOnlyWrite: "This implementation currently exposes read operations only; write compatibility is not verified.",+ capabilityVersionUnsupported: "This Nacos version does not support the operation.",+ capabilityEndpointUnavailable: "This connection does not provide the management endpoint.",+ capabilityNotVerified: "This operation has not been verified for the current implementation.",+ capabilityHeaderReadOnly: "This connection is read-only; service and instance writes are disabled.",+ protectionTriggeredDescription: "Protection mode is triggered because the healthy-instance ratio is below the configured threshold. Nacos may still return unhealthy instances instead of an empty list.",+ instanceEphemeral: "Ephemeral instance",+ instancePersistent: "Persistent instance",+ instanceUnknown: "Unknown instance type",+ instanceConfirmDetails: "Namespace: {namespace}\nService: {service}\nAddress: {ip}:{port}\nCluster: {cluster}\nType: {type}",+ serviceUpdateUnconfirmed: "The service update was submitted, but Nacos has not returned the target state. Refresh the service details to confirm.",+ invalidWeight: "Weight must be a finite number greater than or equal to 0.",+ invalidWeightInput: "Enter a finite weight greater than or equal to 0.",+ metadataLabel: "Metadata",+ selectorLabel: "Selector",+ instanceUpdateUnconfirmed: "The instance update was submitted, but Nacos has not returned the new state. Refresh to check the server state.",+ instanceRegisterUnconfirmed: "Instance registration was submitted, but Nacos has not returned the instance. Refresh to confirm.",+ instanceDeregisterUnconfirmed: "Instance deregistration was submitted, but Nacos still returns the instance. Refresh to confirm.",+ serviceValidation: "Service name and group are required; the protection threshold must be between 0 and 1.",+ serviceHasInstances: "The service still contains instances and cannot be deleted.",+ serviceDeleteUnconfirmed: "Service deletion was submitted, but Nacos still returns the service. Reload and confirm.",+ instanceValidation: "Enter a valid IP, port, and non-negative weight.",+ protectionTriggered: "Protection mode triggered",+ loadedInstances: "{count} loaded instances",+ filterInstanceCluster: "Filter instance cluster",+ filter: "Filter",+ clear: "Clear",+ serviceSettings: "Service settings",+ serviceDetails: "Service details",+ expand: "Expand",+ instanceStat: "Instances",+ healthyInstances: "Healthy instances",+ clusterCount: "Clusters",+ protectThreshold: "Protection threshold",+ itemCount: "{count} items",+ temporaryService: "Ephemeral service",+ loadingServiceDetail: "Loading service details…",+ refreshDetail: "Refresh details",+ noMetadata: "No metadata",+ noInstances: "No instances",+ createNacosService: "Create Nacos service",+ editNacosService: "Edit Nacos service",+ manageServiceMetadata: "Manage service metadata and protection threshold.",+ serviceName: "Service name",+ groupName: "Group",+ thresholdExample: "For example 0.5",+ jsonObject: "JSON object",+ optionalJsonObject: "JSON object, optional",+ jsonObjectValidation: " must be a JSON object.",+ registerPersistentInstance: "Register persistent instance",+ persistentInstanceHint: "DBX does not register ephemeral instances because it cannot maintain their heartbeat.",+ ipAddress: "IP address",+ port: "Port",+ instanceEditorTitle: "Edit instance",+ deleteNacosService: "Delete Nacos service",+ confirmEmptyServiceDelete: "Delete this empty service? This action cannot be undone.",+ deregisterNacosInstance: "Deregister Nacos instance",+ confirmInstanceDeregister: "Deregister this instance from the current service?",+ edit: "Edit",+ restore: "Restore",+ registerInstance: "Register instance",+ deregister: "Deregister",},};diff --git a/apps/desktop/src/i18n/locales/es.ts b/apps/desktop/src/i18n/locales/es.tsindex 6564cd1ae8..6cfbb0e519 100644--- a/apps/desktop/src/i18n/locales/es.ts+++ b/apps/desktop/src/i18n/locales/es.ts@@ -5730,6 +5730,99 @@ export default withEnglishFallback({next: "Siguiente",test: "Probar",readOnly: "Solo lectura",+ nacosConnectionPlan: "Plan de conexión",+ nacosConnectionPlanDescription: "Elige la implementación del servicio y la versión de la API.",+ nacosServiceAddress: "Dirección del servicio",+ nacosServiceAddressHint: "Introduce la dirección del servicio. El puerto predeterminado es 8848, por ejemplo http://host:8848/nacos.",+ nacosAuth: "Autenticación",+ nacosAuthHint: "Estas credenciales se usan para probar la conexión y para la administración diaria.",+ nacosUsernamePassword: "Usuario / contraseña",+ nacosAdvancedHint: "Hay más opciones de conexión en la pestaña Avanzado.",+ nacosAdvancedHintDescription: "Configura allí las métricas de Prometheus, el tamaño de página, la validación TLS y las extensiones de r-nacos.",+ nacosGoAdvanced: "Ir a Avanzado",+ nacosV3ConsolePortWarning: "8080 es el puerto predeterminado de la consola web de Nacos 3. Para administrar servicios, usa la dirección Server / Admin API del puerto 8848, por ejemplo http://127.0.0.1:8848/nacos.",+ nacosAdvancedTitle: "Opciones avanzadas de conexión de Nacos",+ nacosAdvancedDescription: "Estos parámetros tienen valores seguros y normalmente solo deben ajustarse para despliegues personalizados, métricas o extensiones de r-nacos.",+ nacosPageSizeHint: "Se usa para las listas de configuraciones y servicios; entre 1 y 500 elementos por página.",+ nacosMetricsHint: "Consulta automáticamente las métricas desde la dirección del servicio; elige una URL personalizada si el endpoint es diferente.",+ nacosRnacosExtension: "Extensiones de r-nacos",+ nacosRnacosExtensionHint: "Permite consultar el historial y las descripciones de configuración, y administrar instancias deshabilitadas.",+ nacosEnabled: "Habilitado",+ nacosRnacosConsoleUrlHint: "Normalmente http://host:10848.",+ nacosRnacosDisabledHint: "Si está deshabilitado, solo se usa la dirección del servicio; la configuración y la administración básica de servicios siguen disponibles.",+ nacosTlsHint: "Actívalo solo para un certificado HTTPS autofirmado de confianza.",+ nacosVisibleNamespacesTitle: "Elegir namespaces visibles",+ nacosVisibleNamespacesDescription: "Elige los namespaces que se mostrarán en la barra lateral de {name}.",+ nacosSearchNamespaces: "Buscar namespaces...",+ nacosSelectedNamespaces: "{selected}/{total} seleccionados",+ nacosSelectAll: "Seleccionar todo",+ nacosClearSelection: "Borrar",+ nacosShowAll: "Mostrar todo",+ nacosNamespaceSelectionRequired: "Selecciona al menos un namespace o usa “Mostrar todo” para borrar el filtro.",+ nacosLoadNamespacesFailed: "No se pudieron cargar los namespaces: {message}",+ capabilityReadOnly: "Esta conexión es de solo lectura.",+ capabilityReadOnlyWrite: "Esta implementación solo expone operaciones de lectura; la compatibilidad de escritura no está verificada.",+ capabilityVersionUnsupported: "Esta versión de Nacos no admite la operación.",+ capabilityEndpointUnavailable: "Esta conexión no proporciona el endpoint de administración.",+ capabilityNotVerified: "Esta operación no se ha verificado para la implementación actual.",+ capabilityHeaderReadOnly: "Esta conexión es de solo lectura; las escrituras de servicios e instancias están deshabilitadas.",+ protectionTriggeredDescription: "El modo de protección está activo porque la proporción de instancias saludables es inferior al umbral configurado. Nacos aún puede devolver instancias no saludables en lugar de una lista vacía.",+ instanceEphemeral: "Instancia efímera",+ instancePersistent: "Instancia persistente",+ instanceUnknown: "Tipo de instancia desconocido",+ instanceConfirmDetails: "Namespace: {namespace}\nServicio: {service}\nDirección: {ip}:{port}\nClúster: {cluster}\nTipo: {type}",+ serviceUpdateUnconfirmed: "La actualización del servicio se envió, pero Nacos aún no ha devuelto el estado solicitado. Actualiza los detalles del servicio para confirmarlo.",+ invalidWeight: "El peso debe ser un número finito mayor o igual que 0.",+ invalidWeightInput: "Introduce un peso finito mayor o igual que 0.",+ metadataLabel: "Metadatos",+ selectorLabel: "Selector",+ instanceUpdateUnconfirmed: "La actualización de la instancia se envió, pero Nacos aún no ha devuelto el nuevo estado. Actualiza para comprobar el estado del servidor.",+ instanceRegisterUnconfirmed: "El registro de la instancia se envió, pero Nacos aún no la ha devuelto. Actualiza para confirmarlo.",+ instanceDeregisterUnconfirmed: "La baja de la instancia se envió, pero Nacos todavía la devuelve. Actualiza para confirmarlo.",+ serviceValidation: "El nombre del servicio y el grupo son obligatorios; el umbral de protección debe estar entre 0 y 1.",+ serviceHasInstances: "El servicio todavía contiene instancias y no se puede eliminar.",+ serviceDeleteUnconfirmed: "La eliminación del servicio se envió, pero Nacos todavía lo devuelve. Recarga y confirma.",+ instanceValidation: "Introduce una IP, un puerto y un peso no negativo válidos.",+ protectionTriggered: "Modo de protección activo",+ loadedInstances: "{count} instancias cargadas",+ filterInstanceCluster: "Filtrar clúster de instancia",+ filter: "Filtrar",+ clear: "Borrar",+ serviceSettings: "Ajustes del servicio",+ serviceDetails: "Detalles del servicio",+ expand: "Expandir",+ instanceStat: "Instancias",+ healthyInstances: "Instancias saludables",+ clusterCount: "Clústeres",+ protectThreshold: "Umbral de protección",+ itemCount: "{count} elementos",+ temporaryService: "Servicio efímero",+ loadingServiceDetail: "Cargando detalles del servicio…",+ refreshDetail: "Actualizar detalles",+ noMetadata: "Sin metadatos",+ noInstances: "No hay instancias",+ createNacosService: "Crear servicio Nacos",+ editNacosService: "Editar servicio Nacos",+ manageServiceMetadata: "Administra los metadatos y el umbral de protección del servicio.",+ serviceName: "Nombre del servicio",+ groupName: "Grupo",+ thresholdExample: "Por ejemplo, 0.5",+ jsonObject: "Objeto JSON",+ optionalJsonObject: "Objeto JSON, opcional",+ jsonObjectValidation: " debe ser un objeto JSON.",+ registerPersistentInstance: "Registrar instancia persistente",+ persistentInstanceHint: "DBX no registra instancias efímeras porque no puede mantener sus latidos.",+ ipAddress: "Dirección IP",+ port: "Puerto",+ instanceEditorTitle: "Editar instancia",+ deleteNacosService: "Eliminar servicio Nacos",+ confirmEmptyServiceDelete: "¿Eliminar este servicio vacío? Esta acción no se puede deshacer.",+ deregisterNacosInstance: "Dar de baja instancia Nacos",+ confirmInstanceDeregister: "¿Dar de baja esta instancia del servicio actual?",+ edit: "Editar",+ restore: "Restaurar",+ registerInstance: "Registrar instancia",+ deregister: "Dar de baja",},gridfsBrowser: {bucketCount: "Cantidad de buckets",diff --git a/apps/desktop/src/i18n/locales/it.ts b/apps/desktop/src/i18n/locales/it.tsindex 24b1c11dd0..25227713dd 100644--- a/apps/desktop/src/i18n/locales/it.ts+++ b/apps/desktop/src/i18n/locales/it.ts@@ -5730,6 +5730,99 @@ export default withEnglishFallback({next: "Succ.",test: "Test",readOnly: "Sola lettura",+ nacosConnectionPlan: "Piano di connessione",+ nacosConnectionPlanDescription: "Scegli l'implementazione del servizio e la versione API.",+ nacosServiceAddress: "Indirizzo del servizio",+ nacosServiceAddressHint: "Inserisci l'indirizzo del servizio. La porta predefinita è 8848, ad esempio http://host:8848/nacos.",+ nacosAuth: "Autenticazione",+ nacosAuthHint: "Queste credenziali vengono usate per i test di connessione e la gestione quotidiana.",+ nacosUsernamePassword: "Nome utente / password",+ nacosAdvancedHint: "Altre opzioni di connessione sono disponibili nella scheda Avanzate.",+ nacosAdvancedHintDescription: "Configura qui metriche Prometheus, dimensione pagina, verifica TLS ed estensioni r-nacos.",+ nacosGoAdvanced: "Vai ad Avanzate",+ nacosV3ConsolePortWarning: "8080 è la porta predefinita della Web Console Nacos 3. Per la gestione dei servizi usa l'indirizzo Server / Admin API sulla porta 8848, ad esempio http://127.0.0.1:8848/nacos.",+ nacosAdvancedTitle: "Opzioni di connessione avanzate Nacos",+ nacosAdvancedDescription: "Questi parametri hanno valori sicuri e di solito richiedono modifiche solo per distribuzioni personalizzate, metriche o estensioni r-nacos.",+ nacosPageSizeHint: "Usato per gli elenchi di configurazioni e servizi; da 1 a 500 elementi per pagina.",+ nacosMetricsHint: "Interroga automaticamente le metriche dall'indirizzo del servizio; scegli un URL personalizzato se l'endpoint è diverso.",+ nacosRnacosExtension: "Estensioni r-nacos",+ nacosRnacosExtensionHint: "Abilita la cronologia e le descrizioni delle configurazioni e la gestione delle istanze disabilitate.",+ nacosEnabled: "Abilitato",+ nacosRnacosConsoleUrlHint: "Di solito http://host:10848.",+ nacosRnacosDisabledHint: "Quando è disabilitato viene usato solo l'indirizzo del servizio; la configurazione e la gestione di base dei servizi restano disponibili.",+ nacosTlsHint: "Abilita solo per un certificato HTTPS autofirmato attendibile.",+ nacosVisibleNamespacesTitle: "Scegli i namespace visibili",+ nacosVisibleNamespacesDescription: "Scegli i namespace da mostrare nella barra laterale di {name}.",+ nacosSearchNamespaces: "Cerca namespace...",+ nacosSelectedNamespaces: "{selected}/{total} selezionati",+ nacosSelectAll: "Seleziona tutto",+ nacosClearSelection: "Cancella",+ nacosShowAll: "Mostra tutto",+ nacosNamespaceSelectionRequired: "Seleziona almeno un namespace oppure usa “Mostra tutto” per cancellare il filtro.",+ nacosLoadNamespacesFailed: "Impossibile caricare i namespace: {message}",+ capabilityReadOnly: "Questa connessione è di sola lettura.",+ capabilityReadOnlyWrite: "Questa implementazione espone solo operazioni di lettura; la compatibilità di scrittura non è verificata.",+ capabilityVersionUnsupported: "Questa versione di Nacos non supporta l'operazione.",+ capabilityEndpointUnavailable: "Questa connessione non fornisce l'endpoint di gestione.",+ capabilityNotVerified: "Questa operazione non è stata verificata per l'implementazione corrente.",+ capabilityHeaderReadOnly: "Questa connessione è di sola lettura; le scritture di servizi e istanze sono disabilitate.",+ protectionTriggeredDescription: "La modalità di protezione è attiva perché la percentuale di istanze sane è inferiore alla soglia configurata. Nacos può comunque restituire istanze non sane invece di un elenco vuoto.",+ instanceEphemeral: "Istanza effimera",+ instancePersistent: "Istanza persistente",+ instanceUnknown: "Tipo di istanza sconosciuto",+ instanceConfirmDetails: "Namespace: {namespace}\nServizio: {service}\nIndirizzo: {ip}:{port}\nCluster: {cluster}\nTipo: {type}",+ serviceUpdateUnconfirmed: "L'aggiornamento del servizio è stato inviato, ma Nacos non ha ancora restituito lo stato previsto. Aggiorna i dettagli del servizio per confermare.",+ invalidWeight: "Il peso deve essere un numero finito maggiore o uguale a 0.",+ invalidWeightInput: "Inserisci un peso finito maggiore o uguale a 0.",+ metadataLabel: "Metadati",+ selectorLabel: "Selettore",+ instanceUpdateUnconfirmed: "L'aggiornamento dell'istanza è stato inviato, ma Nacos non ha ancora restituito il nuovo stato. Aggiorna per controllare lo stato del server.",+ instanceRegisterUnconfirmed: "La registrazione dell'istanza è stata inviata, ma Nacos non ha ancora restituito l'istanza. Aggiorna per confermare.",+ instanceDeregisterUnconfirmed: "La rimozione dell'istanza è stata inviata, ma Nacos restituisce ancora l'istanza. Aggiorna per confermare.",+ serviceValidation: "Nome del servizio e gruppo sono obbligatori; la soglia di protezione deve essere compresa tra 0 e 1.",+ serviceHasInstances: "Il servizio contiene ancora istanze e non può essere eliminato.",+ serviceDeleteUnconfirmed: "L'eliminazione del servizio è stata inviata, ma Nacos restituisce ancora il servizio. Ricarica e conferma.",+ instanceValidation: "Inserisci un IP, una porta e un peso non negativo validi.",+ protectionTriggered: "Modalità di protezione attiva",+ loadedInstances: "{count} istanze caricate",+ filterInstanceCluster: "Filtra cluster dell'istanza",+ filter: "Filtra",+ clear: "Cancella",+ serviceSettings: "Impostazioni servizio",+ serviceDetails: "Dettagli servizio",+ expand: "Espandi",+ instanceStat: "Istanze",+ healthyInstances: "Istanze sane",+ clusterCount: "Cluster",+ protectThreshold: "Soglia di protezione",+ itemCount: "{count} elementi",+ temporaryService: "Servizio effimero",+ loadingServiceDetail: "Caricamento dettagli servizio…",+ refreshDetail: "Aggiorna dettagli",+ noMetadata: "Nessun metadato",+ noInstances: "Nessuna istanza",+ createNacosService: "Crea servizio Nacos",+ editNacosService: "Modifica servizio Nacos",+ manageServiceMetadata: "Gestisci i metadati e la soglia di protezione del servizio.",+ serviceName: "Nome servizio",+ groupName: "Gruppo",+ thresholdExample: "Ad esempio 0,5",+ jsonObject: "Oggetto JSON",+ optionalJsonObject: "Oggetto JSON, facoltativo",+ jsonObjectValidation: " deve essere un oggetto JSON.",+ registerPersistentInstance: "Registra istanza persistente",+ persistentInstanceHint: "DBX non registra istanze effimere perché non può mantenerne l'heartbeat.",+ ipAddress: "Indirizzo IP",+ port: "Porta",+ instanceEditorTitle: "Modifica istanza",+ deleteNacosService: "Elimina servizio Nacos",+ confirmEmptyServiceDelete: "Eliminare questo servizio vuoto? L'azione non può essere annullata.",+ deregisterNacosInstance: "Rimuovi istanza Nacos",+ confirmInstanceDeregister: "Rimuovere questa istanza dal servizio corrente?",+ edit: "Modifica",+ restore: "Ripristina",+ registerInstance: "Registra istanza",+ deregister: "Rimuovi",},gridfsBrowser: {bucketCount: "Bucket",diff --git a/apps/desktop/src/i18n/locales/ja.ts b/apps/desktop/src/i18n/locales/ja.tsindex 215036192b..3a6c22cb89 100644--- a/apps/desktop/src/i18n/locales/ja.ts+++ b/apps/desktop/src/i18n/locales/ja.ts@@ -5785,6 +5785,99 @@ export default withEnglishFallback({namespaceNamePlaceholder: "名前空間名を入力",namespaceDesc: "説明",namespaceDescPlaceholder: "デフォルトは名前空間名",+ nacosConnectionPlan: "接続方式",+ nacosConnectionPlanDescription: "サービス実装と API バージョンを選択します。",+ nacosServiceAddress: "サービスアドレス",+ nacosServiceAddressHint: "サービスアドレスを入力してください。既定のポートは 8848 です(例: http://host:8848/nacos)。",+ nacosAuth: "認証",+ nacosAuthHint: "接続テストと日常の管理に使用する認証情報です。",+ nacosUsernamePassword: "ユーザー名 / パスワード",+ nacosAdvancedHint: "その他の接続オプションは「詳細」タブにあります。",+ nacosAdvancedHintDescription: "Prometheus メトリクス、ページサイズ、TLS 検証、r-nacos 拡張を設定できます。",+ nacosGoAdvanced: "詳細へ移動",+ nacosV3ConsolePortWarning: "8080 は Nacos 3 Web Console の既定ポートです。サービス管理には 8848 の Server / Admin API アドレス(例: http://127.0.0.1:8848/nacos)を使用してください。",+ nacosAdvancedTitle: "Nacos 詳細接続オプション",+ nacosAdvancedDescription: "安全な既定値が設定されています。通常はカスタム構成、メトリクス、r-nacos 拡張を使用する場合だけ変更します。",+ nacosPageSizeHint: "設定とサービスの一覧に使用します。1 ページあたり 1~500 件です。",+ nacosMetricsHint: "サービスアドレスからメトリクスを自動取得します。エンドポイントが異なる場合はカスタム URL を選択してください。",+ nacosRnacosExtension: "r-nacos 拡張",+ nacosRnacosExtensionHint: "設定履歴・設定説明の取得と、無効なインスタンスの管理を有効にします。",+ nacosEnabled: "有効",+ nacosRnacosConsoleUrlHint: "通常は http://host:10848 です。",+ nacosRnacosDisabledHint: "無効の場合はサービスアドレスだけを使用します。基本的な設定とサービス管理は引き続き利用できます。",+ nacosTlsHint: "信頼できる自己署名 HTTPS 証明書の場合だけ有効にしてください。",+ nacosVisibleNamespacesTitle: "表示する名前空間を選択",+ nacosVisibleNamespacesDescription: "「{name}」のサイドバーに表示する名前空間を選択します。",+ nacosSearchNamespaces: "名前空間を検索...",+ nacosSelectedNamespaces: "{selected}/{total} 件を選択",+ nacosSelectAll: "すべて選択",+ nacosClearSelection: "クリア",+ nacosShowAll: "すべて表示",+ nacosNamespaceSelectionRequired: "少なくとも 1 つ選択するか、「すべて表示」でフィルターを解除してください。",+ nacosLoadNamespacesFailed: "名前空間の読み込みに失敗しました: {message}",+ capabilityReadOnly: "この接続は読み取り専用です。",+ capabilityReadOnlyWrite: "この実装は読み取り操作のみ提供します。書き込み互換性は検証されていません。",+ capabilityVersionUnsupported: "この Nacos バージョンは操作をサポートしていません。",+ capabilityEndpointUnavailable: "この接続には管理エンドポイントがありません。",+ capabilityNotVerified: "この操作は現在の実装で検証されていません。",+ capabilityHeaderReadOnly: "読み取り専用接続のため、サービスとインスタンスの書き込みは無効です。",+ protectionTriggeredDescription: "健全なインスタンスの割合が設定したしきい値を下回ったため、保護モードが有効です。Nacos は空の一覧ではなく不健全なインスタンスを返す場合があります。",+ instanceEphemeral: "一時インスタンス",+ instancePersistent: "永続インスタンス",+ instanceUnknown: "不明なインスタンスタイプ",+ instanceConfirmDetails: "名前空間: {namespace}\nサービス: {service}\nアドレス: {ip}:{port}\nクラスター: {cluster}\n種類: {type}",+ serviceUpdateUnconfirmed: "サービス更新は送信されましたが、Nacos は対象状態をまだ返していません。サービス詳細を更新して確認してください。",+ invalidWeight: "重みは 0 以上の有限数である必要があります。",+ invalidWeightInput: "0 以上の有限な重みを入力してください。",+ metadataLabel: "メタデータ",+ selectorLabel: "セレクター",+ instanceUpdateUnconfirmed: "インスタンス更新は送信されましたが、Nacos は新しい状態をまだ返していません。更新してサーバーの状態を確認してください。",+ instanceRegisterUnconfirmed: "インスタンス登録は送信されましたが、Nacos はまだインスタンスを返していません。更新して確認してください。",+ instanceDeregisterUnconfirmed: "インスタンス解除は送信されましたが、Nacos はまだインスタンスを返しています。更新して確認してください。",+ serviceValidation: "サービス名とグループは必須です。保護しきい値は 0~1 の範囲で指定してください。",+ serviceHasInstances: "サービスにまだインスタンスがあるため削除できません。",+ serviceDeleteUnconfirmed: "サービス削除は送信されましたが、Nacos はまだサービスを返しています。再読み込みして確認してください。",+ instanceValidation: "有効な IP、ポート、0 以上の重みを入力してください。",+ protectionTriggered: "保護モードが有効",+ loadedInstances: "{count} 件のインスタンスを読み込み済み",+ filterInstanceCluster: "インスタンスのクラスターを絞り込み",+ filter: "絞り込み",+ clear: "クリア",+ serviceSettings: "サービス設定",+ serviceDetails: "サービス詳細",+ expand: "展開",+ instanceStat: "インスタンス",+ healthyInstances: "健全なインスタンス",+ clusterCount: "クラスター",+ protectThreshold: "保護しきい値",+ itemCount: "{count} 件",+ temporaryService: "一時サービス",+ loadingServiceDetail: "サービス詳細を読み込み中…",+ refreshDetail: "詳細を更新",+ noMetadata: "メタデータなし",+ noInstances: "インスタンスなし",+ createNacosService: "Nacos サービスを作成",+ editNacosService: "Nacos サービスを編集",+ manageServiceMetadata: "サービスのメタデータと保護しきい値を管理します。",+ serviceName: "サービス名",+ groupName: "グループ",+ thresholdExample: "例: 0.5",+ jsonObject: "JSON オブジェクト",+ optionalJsonObject: "JSON オブジェクト(任意)",+ jsonObjectValidation: " は JSON オブジェクトである必要があります。",+ registerPersistentInstance: "永続インスタンスを登録",+ persistentInstanceHint: "DBX はハートビートを維持できないため、一時インスタンスを登録しません。",+ ipAddress: "IP アドレス",+ port: "ポート",+ instanceEditorTitle: "インスタンスを編集",+ deleteNacosService: "Nacos サービスを削除",+ confirmEmptyServiceDelete: "この空のサービスを削除しますか?この操作は元に戻せません。",+ deregisterNacosInstance: "Nacos インスタンスを解除",+ confirmInstanceDeregister: "現在のサービスからこのインスタンスを解除しますか?",+ edit: "編集",+ restore: "元に戻す",+ registerInstance: "インスタンスを登録",+ deregister: "解除",},gridfsBrowser: {bucketCount: "バケット",diff --git a/apps/desktop/src/i18n/locales/ko.ts b/apps/desktop/src/i18n/locales/ko.tsindex 95f88f6e9c..ddffafa647 100644--- a/apps/desktop/src/i18n/locales/ko.ts+++ b/apps/desktop/src/i18n/locales/ko.ts@@ -6530,5 +6530,98 @@ export default withEnglishFallback({next: "다음",test: "테스트",readOnly: "읽기 전용",+ nacosConnectionPlan: "연결 방식",+ nacosConnectionPlanDescription: "서비스 구현과 API 버전을 선택합니다.",+ nacosServiceAddress: "서비스 주소",+ nacosServiceAddressHint: "서비스 주소를 입력하세요. 기본 포트는 8848입니다(예: http://host:8848/nacos).",+ nacosAuth: "인증",+ nacosAuthHint: "이 자격 증명은 연결 테스트와 일상적인 관리에 사용됩니다.",+ nacosUsernamePassword: "사용자 이름 / 비밀번호",+ nacosAdvancedHint: "추가 연결 옵션은 고급 탭에서 설정할 수 있습니다.",+ nacosAdvancedHintDescription: "Prometheus 메트릭, 페이지 크기, TLS 검증 및 r-nacos 확장을 설정합니다.",+ nacosGoAdvanced: "고급으로 이동",+ nacosV3ConsolePortWarning: "8080은 Nacos 3 Web Console의 기본 포트입니다. 서비스 관리는 8848 포트의 Server / Admin API 주소(예: http://127.0.0.1:8848/nacos)를 사용하세요.",+ nacosAdvancedTitle: "Nacos 고급 연결 옵션",+ nacosAdvancedDescription: "안전한 기본값이 적용되어 있으며, 사용자 지정 배포·메트릭·r-nacos 확장을 사용할 때만 조정하면 됩니다.",+ nacosPageSizeHint: "구성 및 서비스 목록에 사용되며 페이지당 1~500개입니다.",+ nacosMetricsHint: "서비스 주소에서 메트릭을 자동으로 조회합니다. 메트릭 엔드포인트가 다르면 사용자 지정 URL을 선택하세요.",+ nacosRnacosExtension: "r-nacos 확장",+ nacosRnacosExtensionHint: "구성 이력·설명 조회와 비활성 인스턴스 관리를 활성화합니다.",+ nacosEnabled: "활성화됨",+ nacosRnacosConsoleUrlHint: "일반적으로 http://host:10848입니다.",+ nacosRnacosDisabledHint: "비활성화하면 서비스 주소만 사용하며, 기본 구성 및 서비스 관리는 계속 사용할 수 있습니다.",+ nacosTlsHint: "신뢰할 수 있는 자체 서명 HTTPS 인증서에만 활성화하세요.",+ nacosVisibleNamespacesTitle: "표시할 네임스페이스 선택",+ nacosVisibleNamespacesDescription: "{name}의 사이드바에 표시할 네임스페이스를 선택합니다.",+ nacosSearchNamespaces: "네임스페이스 검색...",+ nacosSelectedNamespaces: "{selected}/{total}개 선택됨",+ nacosSelectAll: "모두 선택",+ nacosClearSelection: "지우기",+ nacosShowAll: "모두 표시",+ nacosNamespaceSelectionRequired: "하나 이상 선택하거나 “모두 표시”로 필터를 해제하세요.",+ nacosLoadNamespacesFailed: "네임스페이스를 불러오지 못했습니다: {message}",+ capabilityReadOnly: "이 연결은 읽기 전용입니다.",+ capabilityReadOnlyWrite: "이 구현은 읽기 작업만 제공하며 쓰기 호환성은 확인되지 않았습니다.",+ capabilityVersionUnsupported: "이 Nacos 버전은 해당 작업을 지원하지 않습니다.",+ capabilityEndpointUnavailable: "이 연결에는 관리 엔드포인트가 없습니다.",+ capabilityNotVerified: "현재 구현에서 이 작업이 검증되지 않았습니다.",+ capabilityHeaderReadOnly: "읽기 전용 연결이므로 서비스 및 인스턴스 쓰기가 비활성화되었습니다.",+ protectionTriggeredDescription: "정상 인스턴스 비율이 설정된 보호 임계값보다 낮아 보호 모드가 활성화되었습니다. Nacos는 빈 목록 대신 비정상 인스턴스를 반환할 수 있습니다.",+ instanceEphemeral: "임시 인스턴스",+ instancePersistent: "영구 인스턴스",+ instanceUnknown: "알 수 없는 인스턴스 유형",+ instanceConfirmDetails: "네임스페이스: {namespace}\n서비스: {service}\n주소: {ip}:{port}\n클러스터: {cluster}\n유형: {type}",+ serviceUpdateUnconfirmed: "서비스 업데이트를 제출했지만 Nacos가 대상 상태를 아직 반환하지 않았습니다. 서비스 세부 정보를 새로 고쳐 확인하세요.",+ invalidWeight: "가중치는 0 이상인 유한한 숫자여야 합니다.",+ invalidWeightInput: "0 이상인 유한한 가중치를 입력하세요.",+ metadataLabel: "메타데이터",+ selectorLabel: "셀렉터",+ instanceUpdateUnconfirmed: "인스턴스 업데이트를 제출했지만 Nacos가 새 상태를 아직 반환하지 않았습니다. 새로 고쳐 서버 상태를 확인하세요.",+ instanceRegisterUnconfirmed: "인스턴스 등록을 제출했지만 Nacos가 인스턴스를 아직 반환하지 않았습니다. 새로 고쳐 확인하세요.",+ instanceDeregisterUnconfirmed: "인스턴스 등록 해제를 제출했지만 Nacos가 아직 인스턴스를 반환합니다. 새로 고쳐 확인하세요.",+ serviceValidation: "서비스 이름과 그룹은 필수이며 보호 임계값은 0~1 사이여야 합니다.",+ serviceHasInstances: "서비스에 아직 인스턴스가 있어 삭제할 수 없습니다.",+ serviceDeleteUnconfirmed: "서비스 삭제를 제출했지만 Nacos가 아직 서비스를 반환합니다. 다시 불러와 확인하세요.",+ instanceValidation: "유효한 IP, 포트 및 음수가 아닌 가중치를 입력하세요.",+ protectionTriggered: "보호 모드 활성화",+ loadedInstances: "{count}개 인스턴스 로드됨",+ filterInstanceCluster: "인스턴스 클러스터 필터",+ filter: "필터",+ clear: "지우기",+ serviceSettings: "서비스 설정",+ serviceDetails: "서비스 세부 정보",+ expand: "펼치기",+ instanceStat: "인스턴스",+ healthyInstances: "정상 인스턴스",+ clusterCount: "클러스터",+ protectThreshold: "보호 임계값",+ itemCount: "{count}개 항목",+ temporaryService: "임시 서비스",+ loadingServiceDetail: "서비스 세부 정보 로드 중…",+ refreshDetail: "세부 정보 새로 고침",+ noMetadata: "메타데이터 없음",+ noInstances: "인스턴스 없음",+ createNacosService: "Nacos 서비스 만들기",+ editNacosService: "Nacos 서비스 편집",+ manageServiceMetadata: "서비스 메타데이터와 보호 임계값을 관리합니다.",+ serviceName: "서비스 이름",+ groupName: "그룹",+ thresholdExample: "예: 0.5",+ jsonObject: "JSON 객체",+ optionalJsonObject: "JSON 객체(선택 사항)",+ jsonObjectValidation: " JSON 객체여야 합니다.",+ registerPersistentInstance: "영구 인스턴스 등록",+ persistentInstanceHint: "DBX는 하트비트를 유지할 수 없으므로 임시 인스턴스를 등록하지 않습니다.",+ ipAddress: "IP 주소",+ port: "포트",+ instanceEditorTitle: "인스턴스 편집",+ deleteNacosService: "Nacos 서비스 삭제",+ confirmEmptyServiceDelete: "이 빈 서비스를 삭제하시겠습니까? 이 작업은 취소할 수 없습니다.",+ deregisterNacosInstance: "Nacos 인스턴스 등록 해제",+ confirmInstanceDeregister: "현재 서비스에서 이 인스턴스의 등록을 해제하시겠습니까?",+ edit: "편집",+ restore: "복원",+ registerInstance: "인스턴스 등록",+ deregister: "등록 해제",},});diff --git a/apps/desktop/src/i18n/locales/pt-BR.ts b/apps/desktop/src/i18n/locales/pt-BR.tsindex 7e27efbc32..9c518037e3 100644--- a/apps/desktop/src/i18n/locales/pt-BR.ts+++ b/apps/desktop/src/i18n/locales/pt-BR.ts@@ -5732,6 +5732,99 @@ export default withEnglishFallback({next: "Próximo",test: "Testar",readOnly: "Somente leitura",+ nacosConnectionPlan: "Plano de conexão",+ nacosConnectionPlanDescription: "Escolha a implementação do serviço e a versão da API.",+ nacosServiceAddress: "Endereço do serviço",+ nacosServiceAddressHint: "Informe o endereço do serviço. A porta padrão é 8848, por exemplo http://host:8848/nacos.",+ nacosAuth: "Autenticação",+ nacosAuthHint: "Essas credenciais são usadas nos testes de conexão e no gerenciamento diário.",+ nacosUsernamePassword: "Usuário / senha",+ nacosAdvancedHint: "Mais opções de conexão estão disponíveis na aba Avançado.",+ nacosAdvancedHintDescription: "Configure ali as métricas do Prometheus, o tamanho da página, a validação TLS e as extensões do r-nacos.",+ nacosGoAdvanced: "Ir para Avançado",+ nacosV3ConsolePortWarning: "8080 é a porta padrão do Web Console do Nacos 3. Para gerenciar serviços, use o endereço Server / Admin API na porta 8848, por exemplo http://127.0.0.1:8848/nacos.",+ nacosAdvancedTitle: "Opções avançadas de conexão do Nacos",+ nacosAdvancedDescription: "Esses parâmetros têm valores seguros e normalmente só precisam ser ajustados para implantações personalizadas, métricas ou extensões do r-nacos.",+ nacosPageSizeHint: "Usado nas listas de configurações e serviços; de 1 a 500 itens por página.",+ nacosMetricsHint: "Consulta as métricas automaticamente pelo endereço do serviço; escolha uma URL personalizada se o endpoint for diferente.",+ nacosRnacosExtension: "Extensões do r-nacos",+ nacosRnacosExtensionHint: "Ativa o histórico e as descrições de configurações e o gerenciamento de instâncias desativadas.",+ nacosEnabled: "Ativado",+ nacosRnacosConsoleUrlHint: "Normalmente http://host:10848.",+ nacosRnacosDisabledHint: "Quando desativado, somente o endereço do serviço é usado; a configuração e o gerenciamento básico de serviços continuam disponíveis.",+ nacosTlsHint: "Ative somente para um certificado HTTPS autoassinado confiável.",+ nacosVisibleNamespacesTitle: "Escolher namespaces visíveis",+ nacosVisibleNamespacesDescription: "Escolha os namespaces que serão exibidos na barra lateral de {name}.",+ nacosSearchNamespaces: "Pesquisar namespaces...",+ nacosSelectedNamespaces: "{selected}/{total} selecionados",+ nacosSelectAll: "Selecionar tudo",+ nacosClearSelection: "Limpar",+ nacosShowAll: "Mostrar tudo",+ nacosNamespaceSelectionRequired: "Selecione pelo menos um namespace ou use “Mostrar tudo” para limpar o filtro.",+ nacosLoadNamespacesFailed: "Falha ao carregar namespaces: {message}",+ capabilityReadOnly: "Esta conexão é somente leitura.",+ capabilityReadOnlyWrite: "Esta implementação oferece apenas operações de leitura; a compatibilidade de escrita não foi verificada.",+ capabilityVersionUnsupported: "Esta versão do Nacos não oferece suporte à operação.",+ capabilityEndpointUnavailable: "Esta conexão não fornece o endpoint de gerenciamento.",+ capabilityNotVerified: "Esta operação não foi verificada para a implementação atual.",+ capabilityHeaderReadOnly: "Esta conexão é somente leitura; as gravações de serviços e instâncias estão desativadas.",+ protectionTriggeredDescription: "O modo de proteção foi ativado porque a proporção de instâncias saudáveis está abaixo do limite configurado. O Nacos ainda pode retornar instâncias não saudáveis em vez de uma lista vazia.",+ instanceEphemeral: "Instância efêmera",+ instancePersistent: "Instância persistente",+ instanceUnknown: "Tipo de instância desconhecido",+ instanceConfirmDetails: "Namespace: {namespace}\nServiço: {service}\nEndereço: {ip}:{port}\nCluster: {cluster}\nTipo: {type}",+ serviceUpdateUnconfirmed: "A atualização do serviço foi enviada, mas o Nacos ainda não retornou o estado esperado. Atualize os detalhes do serviço para confirmar.",+ invalidWeight: "O peso deve ser um número finito maior ou igual a 0.",+ invalidWeightInput: "Informe um peso finito maior ou igual a 0.",+ metadataLabel: "Metadados",+ selectorLabel: "Seletor",+ instanceUpdateUnconfirmed: "A atualização da instância foi enviada, mas o Nacos ainda não retornou o novo estado. Atualize para verificar o estado do servidor.",+ instanceRegisterUnconfirmed: "O registro da instância foi enviado, mas o Nacos ainda não retornou a instância. Atualize para confirmar.",+ instanceDeregisterUnconfirmed: "A remoção da instância foi enviada, mas o Nacos ainda retorna a instância. Atualize para confirmar.",+ serviceValidation: "O nome do serviço e o grupo são obrigatórios; o limite de proteção deve estar entre 0 e 1.",+ serviceHasInstances: "O serviço ainda contém instâncias e não pode ser excluído.",+ serviceDeleteUnconfirmed: "A exclusão do serviço foi enviada, mas o Nacos ainda retorna o serviço. Recarregue e confirme.",+ instanceValidation: "Informe um IP, uma porta e um peso não negativo válidos.",+ protectionTriggered: "Modo de proteção ativado",+ loadedInstances: "{count} instâncias carregadas",+ filterInstanceCluster: "Filtrar cluster da instância",+ filter: "Filtrar",+ clear: "Limpar",+ serviceSettings: "Configurações do serviço",+ serviceDetails: "Detalhes do serviço",+ expand: "Expandir",+ instanceStat: "Instâncias",+ healthyInstances: "Instâncias saudáveis",+ clusterCount: "Clusters",+ protectThreshold: "Limite de proteção",+ itemCount: "{count} itens",+ temporaryService: "Serviço efêmero",+ loadingServiceDetail: "Carregando detalhes do serviço…",+ refreshDetail: "Atualizar detalhes",+ noMetadata: "Sem metadados",+ noInstances: "Nenhuma instância",+ createNacosService: "Criar serviço Nacos",+ editNacosService: "Editar serviço Nacos",+ manageServiceMetadata: "Gerencie os metadados e o limite de proteção do serviço.",+ serviceName: "Nome do serviço",+ groupName: "Grupo",+ thresholdExample: "Por exemplo, 0,5",+ jsonObject: "Objeto JSON",+ optionalJsonObject: "Objeto JSON, opcional",+ jsonObjectValidation: " deve ser um objeto JSON.",+ registerPersistentInstance: "Registrar instância persistente",+ persistentInstanceHint: "O DBX não registra instâncias efêmeras porque não consegue manter seus heartbeats.",+ ipAddress: "Endereço IP",+ port: "Porta",+ instanceEditorTitle: "Editar instância",+ deleteNacosService: "Excluir serviço Nacos",+ confirmEmptyServiceDelete: "Excluir este serviço vazio? Essa ação não pode ser desfeita.",+ deregisterNacosInstance: "Remover instância Nacos",+ confirmInstanceDeregister: "Remover esta instância do serviço atual?",+ edit: "Editar",+ restore: "Restaurar",+ registerInstance: "Registrar instância",+ deregister: "Remover registro",},gridfsBrowser: {bucketCount: "Buckets",diff --git a/apps/desktop/src/i18n/locales/zh-CN.ts b/apps/desktop/src/i18n/locales/zh-CN.tsindex 4d5435668a..9b0297008e 100644--- a/apps/desktop/src/i18n/locales/zh-CN.ts+++ b/apps/desktop/src/i18n/locales/zh-CN.ts@@ -394,7 +394,7 @@ export default withEnglishFallback({nacosConfigurationHistoryHint: "r-nacos 的配置历史仅通过独立控制台提供(通常为 10848 端口)。控制台与兼容 Nacos 的 OpenAPI 使用不同的登录会话:OpenAPI 可以不启用认证,而控制台仍需登录。通常填写同一套 r-nacos 用户凭据;仅在需要使用另一账号时单独设置。",nacosRNacosConsoleUrl: "r-nacos 控制台 URL",nacosRNacosConsoleUrlPlaceholder: "http://127.0.0.1:10848",- nacosRNacosConsoleUrlHint: "可选。使用独立控制台服务地址(通常为 10848),不是 OpenAPI 地址;它用于配置历史,以及读取 r-nacos 配置的类型和描述。",+ nacosRNacosConsoleUrlHint: "可选。使用独立控制台服务地址(通常为 10848),不是 OpenAPI 地址;它用于配置历史、读取 r-nacos 配置的类型和描述,以及在服务管理中展示已禁用实例。",nacosRNacosOpenApiRequired: "r-nacos 主地址必须使用兼容 Nacos 的 API 地址,不能使用独立控制台 URL。",nacosRNacosConsoleUrlRequired: "启用 r-nacos 配置历史时必须填写控制台 URL。",nacosConsoleAuthSeparateRequired: "主连接未启用认证;请单独设置控制台凭据。",@@ -6920,7 +6920,7 @@ export default withEnglishFallback({historyConsoleUrlMissing: "配置历史需要填写 r-nacos 控制台地址。",historyConsoleCredentialsMissing: "配置历史需要填写 r-nacos 控制台凭据。",rnacosConsoleAuthTitle: "r-nacos 控制台验证",- rnacosConsoleAuthDescription: "请输入 r-nacos 控制台验证码,以读取配置类型、描述和配置历史。",+ rnacosConsoleAuthDescription: "请输入 r-nacos 控制台验证码,以读取配置类型、描述、配置历史和完整服务实例列表(含已禁用实例)。",rnacosCaptchaLabel: "验证码",rnacosCaptchaPlaceholder: "输入上图中的验证码",rnacosCaptchaRequired: "请输入验证码。",@@ -7002,5 +7002,98 @@ export default withEnglishFallback({next: "下一页",test: "测试",readOnly: "只读",+ nacosConnectionPlan: "连接方案",+ nacosConnectionPlanDescription: "选择服务实现和 API 版本。",+ nacosServiceAddress: "服务地址",+ nacosServiceAddressHint: "填写服务地址即可,默认端口为 8848,例如 http://主机:8848/nacos。",+ nacosAuth: "认证",+ nacosAuthHint: "认证信息同时用于连接测试和日常管理。",+ nacosUsernamePassword: "账号密码",+ nacosAdvancedHint: "更多连接选项位于“高级”页",+ nacosAdvancedHintDescription: "可在高级页配置 Prometheus 指标、分页大小、TLS 证书校验和 r-nacos 扩展。",+ nacosGoAdvanced: "前往高级",+ nacosV3ConsolePortWarning: "8080 是 Nacos 3 默认 Web 控制台端口。服务管理请使用 8848 端口的 Server / Admin API 地址,例如 http://127.0.0.1:8848/nacos。",+ nacosAdvancedTitle: "Nacos 高级连接选项",+ nacosAdvancedDescription: "这些参数均有安全默认值,通常只有自定义部署、指标采集或 r-nacos 扩展能力需要调整。",+ nacosPageSizeHint: "用于配置和服务列表,每页 1–500 条。",+ nacosMetricsHint: "自动使用服务地址查询指标;若指标端点不同,请选择“自定义地址”。",+ nacosRnacosExtension: "r-nacos 扩展控制台",+ nacosRnacosExtensionHint: "启用后可使用配置历史、配置描述和禁用实例管理。",+ nacosEnabled: "启用",+ nacosRnacosConsoleUrlHint: "通常为 http://主机:10848。",+ nacosRnacosDisabledHint: "未启用时仅使用服务地址,基础配置和服务管理仍可用。",+ nacosTlsHint: "仅在使用自签名 HTTPS 证书且确认目标可信时开启。",+ nacosVisibleNamespacesTitle: "选择显示的命名空间",+ nacosVisibleNamespacesDescription: "选择「{name}」下要在侧边栏显示的命名空间。",+ nacosSearchNamespaces: "搜索命名空间...",+ nacosSelectedNamespaces: "已选择 {selected}/{total}",+ nacosSelectAll: "全选",+ nacosClearSelection: "清空",+ nacosShowAll: "显示全部",+ nacosNamespaceSelectionRequired: "至少选择一个命名空间,或使用“显示全部”清除过滤。",+ nacosLoadNamespacesFailed: "加载命名空间失败:{message}",+ capabilityReadOnly: "当前连接为只读连接。",+ capabilityReadOnlyWrite: "当前服务实现仅开放读取能力,写操作尚未验证兼容。",+ capabilityVersionUnsupported: "当前 Nacos 版本不支持此操作。",+ capabilityEndpointUnavailable: "当前连接未提供此管理接口。",+ capabilityNotVerified: "此操作尚未在当前服务实现中验证。",+ capabilityHeaderReadOnly: "当前连接为只读连接,服务和实例写操作已禁用。",+ protectionTriggeredDescription: "保护模式已触发:健康实例比例低于服务设置的保护阈值。为避免客户端拿到空实例列表,Nacos 仍可能返回不健康实例。",+ instanceEphemeral: "临时实例",+ instancePersistent: "持久实例",+ instanceUnknown: "实例类型未知",+ instanceConfirmDetails: "命名空间:{namespace}\n服务:{service}\n地址:{ip}:{port}\n集群:{cluster}\n类型:{type}",+ serviceUpdateUnconfirmed: "服务更新已提交,但 Nacos 尚未返回目标状态。请刷新服务详情后确认。",+ invalidWeight: "实例权重必须是大于或等于 0 的有限数字。",+ invalidWeightInput: "请输入大于或等于 0 的有限权重。",+ metadataLabel: "元数据",+ selectorLabel: "选择器",+ instanceUpdateUnconfirmed: "实例更新已提交,但 Nacos 尚未返回新状态。请刷新后查看服务端状态。",+ instanceRegisterUnconfirmed: "实例注册已提交,但 Nacos 尚未返回该实例。请刷新后确认。",+ instanceDeregisterUnconfirmed: "实例注销已提交,但 Nacos 仍返回该实例。请刷新后确认。",+ serviceValidation: "服务名称和分组不能为空,保护阈值必须在 0 到 1 之间。",+ serviceHasInstances: "服务仍包含实例,无法删除。",+ serviceDeleteUnconfirmed: "服务删除已提交,但 Nacos 仍返回该服务。请重新加载后确认。",+ instanceValidation: "请输入有效的 IP、端口和非负权重。",+ protectionTriggered: "保护模式已触发",+ loadedInstances: "{count} 个已加载实例",+ filterInstanceCluster: "筛选实例集群",+ filter: "筛选",+ clear: "清除",+ serviceSettings: "服务设置",+ serviceDetails: "服务详情",+ expand: "展开",+ instanceStat: "实例",+ healthyInstances: "健康实例",+ clusterCount: "集群",+ protectThreshold: "保护阈值",+ itemCount: "{count} 项",+ temporaryService: "临时服务",+ loadingServiceDetail: "正在加载服务详情…",+ refreshDetail: "刷新详情",+ noMetadata: "无元数据",+ noInstances: "暂无实例",+ createNacosService: "创建 Nacos 服务",+ editNacosService: "编辑 Nacos 服务",+ manageServiceMetadata: "管理服务元数据和保护阈值。",+ serviceName: "服务名称",+ groupName: "分组",+ thresholdExample: "例如 0.5",+ jsonObject: "JSON 对象",+ optionalJsonObject: "JSON 对象,可选",+ jsonObjectValidation: "必须是 JSON 对象。",+ registerPersistentInstance: "注册持久实例",+ persistentInstanceHint: "DBX 不注册临时实例,因为无法为其提供心跳维持。",+ ipAddress: "IP 地址",+ port: "端口",+ instanceEditorTitle: "编辑实例",+ deleteNacosService: "删除 Nacos 服务",+ confirmEmptyServiceDelete: "确认删除这个空服务吗?此操作不可撤销。",+ deregisterNacosInstance: "注销 Nacos 实例",+ confirmInstanceDeregister: "确认从当前服务中注销这个实例吗?",+ edit: "编辑",+ restore: "还原",+ registerInstance: "注册实例",+ deregister: "注销",},});diff --git a/apps/desktop/src/i18n/locales/zh-TW.ts b/apps/desktop/src/i18n/locales/zh-TW.tsindex 2dfce18ae9..6fb1f873a7 100644--- a/apps/desktop/src/i18n/locales/zh-TW.ts+++ b/apps/desktop/src/i18n/locales/zh-TW.ts@@ -5195,6 +5195,99 @@ export default withEnglishFallback({namespaceNamePlaceholder: "輸入命名空間名稱",namespaceDesc: "描述",namespaceDescPlaceholder: "預設為命名空間名稱",+ nacosConnectionPlan: "連線方案",+ nacosConnectionPlanDescription: "選擇服務實作與 API 版本。",+ nacosServiceAddress: "服務位址",+ nacosServiceAddressHint: "填寫服務位址即可,預設連接埠為 8848,例如 http://host:8848/nacos。",+ nacosAuth: "驗證",+ nacosAuthHint: "這些驗證資訊會用於連線測試與日常管理。",+ nacosUsernamePassword: "使用者名稱 / 密碼",+ nacosAdvancedHint: "更多連線選項位於「進階」頁。",+ nacosAdvancedHintDescription: "可在此設定 Prometheus 指標、分頁大小、TLS 驗證與 r-nacos 擴充功能。",+ nacosGoAdvanced: "前往進階",+ nacosV3ConsolePortWarning: "8080 是 Nacos 3 Web Console 的預設連接埠。服務管理請使用 8848 連接埠的 Server / Admin API 位址,例如 http://127.0.0.1:8848/nacos。",+ nacosAdvancedTitle: "Nacos 進階連線選項",+ nacosAdvancedDescription: "這些參數都有安全的預設值,通常只有自訂部署、指標或 r-nacos 擴充功能需要調整。",+ nacosPageSizeHint: "用於設定與服務清單,每頁 1–500 筆。",+ nacosMetricsHint: "自動使用服務位址查詢指標;若指標端點不同,請選擇自訂 URL。",+ nacosRnacosExtension: "r-nacos 擴充功能",+ nacosRnacosExtensionHint: "啟用設定歷史、設定描述與停用實例管理。",+ nacosEnabled: "啟用",+ nacosRnacosConsoleUrlHint: "通常為 http://host:10848。",+ nacosRnacosDisabledHint: "停用時只使用服務位址;基本設定與服務管理仍可使用。",+ nacosTlsHint: "僅在使用可信任的自簽 HTTPS 憑證時啟用。",+ nacosVisibleNamespacesTitle: "選擇顯示的命名空間",+ nacosVisibleNamespacesDescription: "選擇要在「{name}」側邊欄顯示的命名空間。",+ nacosSearchNamespaces: "搜尋命名空間...",+ nacosSelectedNamespaces: "已選 {selected}/{total}",+ nacosSelectAll: "全選",+ nacosClearSelection: "清除",+ nacosShowAll: "顯示全部",+ nacosNamespaceSelectionRequired: "至少選擇一個命名空間,或使用「顯示全部」清除篩選。",+ nacosLoadNamespacesFailed: "載入命名空間失敗:{message}",+ capabilityReadOnly: "此連線為唯讀連線。",+ capabilityReadOnlyWrite: "目前實作僅提供讀取操作,寫入相容性尚未驗證。",+ capabilityVersionUnsupported: "此 Nacos 版本不支援此操作。",+ capabilityEndpointUnavailable: "此連線未提供管理端點。",+ capabilityNotVerified: "此操作尚未在目前實作中驗證。",+ capabilityHeaderReadOnly: "此連線為唯讀連線,服務與實例寫入操作已停用。",+ protectionTriggeredDescription: "健康實例比例低於設定的保護閾值,因此已觸發保護模式。Nacos 仍可能回傳不健康實例,而非空清單。",+ instanceEphemeral: "臨時實例",+ instancePersistent: "持久實例",+ instanceUnknown: "未知實例類型",+ instanceConfirmDetails: "命名空間:{namespace}\n服務:{service}\n位址:{ip}:{port}\n叢集:{cluster}\n類型:{type}",+ serviceUpdateUnconfirmed: "服務更新已送出,但 Nacos 尚未回傳目標狀態。請重新整理服務詳細資料以確認。",+ invalidWeight: "權重必須是大於或等於 0 的有限數字。",+ invalidWeightInput: "請輸入大於或等於 0 的有限權重。",+ metadataLabel: "中繼資料",+ selectorLabel: "選取器",+ instanceUpdateUnconfirmed: "實例更新已送出,但 Nacos 尚未回傳新狀態。請重新整理以查看伺服器狀態。",+ instanceRegisterUnconfirmed: "實例註冊已送出,但 Nacos 尚未回傳該實例。請重新整理確認。",+ instanceDeregisterUnconfirmed: "實例註銷已送出,但 Nacos 仍回傳該實例。請重新整理確認。",+ serviceValidation: "服務名稱和群組為必填,保護閾值必須介於 0 到 1 之間。",+ serviceHasInstances: "服務仍包含實例,無法刪除。",+ serviceDeleteUnconfirmed: "服務刪除已送出,但 Nacos 仍回傳該服務。請重新載入確認。",+ instanceValidation: "請輸入有效的 IP、連接埠和非負權重。",+ protectionTriggered: "已觸發保護模式",+ loadedInstances: "已載入 {count} 個實例",+ filterInstanceCluster: "篩選實例叢集",+ filter: "篩選",+ clear: "清除",+ serviceSettings: "服務設定",+ serviceDetails: "服務詳細資料",+ expand: "展開",+ instanceStat: "實例",+ healthyInstances: "健康實例",+ clusterCount: "叢集",+ protectThreshold: "保護閾值",+ itemCount: "{count} 項",+ temporaryService: "臨時服務",+ loadingServiceDetail: "正在載入服務詳細資料…",+ refreshDetail: "重新整理詳細資料",+ noMetadata: "沒有中繼資料",+ noInstances: "沒有實例",+ createNacosService: "建立 Nacos 服務",+ editNacosService: "編輯 Nacos 服務",+ manageServiceMetadata: "管理服務中繼資料與保護閾值。",+ serviceName: "服務名稱",+ groupName: "群組",+ thresholdExample: "例如 0.5",+ jsonObject: "JSON 物件",+ optionalJsonObject: "JSON 物件,可選",+ jsonObjectValidation: "必須是 JSON 物件。",+ registerPersistentInstance: "註冊持久實例",+ persistentInstanceHint: "DBX 不註冊臨時實例,因為無法維持其心跳。",+ ipAddress: "IP 位址",+ port: "連接埠",+ instanceEditorTitle: "編輯實例",+ deleteNacosService: "刪除 Nacos 服務",+ confirmEmptyServiceDelete: "確定要刪除此空服務嗎?此操作無法復原。",+ deregisterNacosInstance: "註銷 Nacos 實例",+ confirmInstanceDeregister: "確定要從目前服務註銷此實例嗎?",+ edit: "編輯",+ restore: "還原",+ registerInstance: "註冊實例",+ deregister: "註銷",},userAdmin: {title: "使用者與權限",diff --git a/apps/desktop/src/lib/__tests__/connection/connectionDialogScrolling.spec.ts b/apps/desktop/src/lib/__tests__/connection/connectionDialogScrolling.spec.tsindex edf7d95e6e..8409413025 100644--- a/apps/desktop/src/lib/__tests__/connection/connectionDialogScrolling.spec.ts+++ b/apps/desktop/src/lib/__tests__/connection/connectionDialogScrolling.spec.ts@@ -7,13 +7,19 @@ describe("connection dialog scrolling", () => {it("keeps every configuration tab inside a shrinkable form viewport", () => {expect(dialogSource).toContain("return `${widthClass} connection-dialog-content--config`;");expect(dialogSource.match(/<TabsContent[^>]*class="m-0 flex min-h-0 flex-1 flex-col overflow-hidden">/g)).toHaveLength(4);- expect(dialogSource.match(/class="connection-form-body grid min-h-0 flex-1 gap-4 overflow-y-auto/g)).toHaveLength(4);+ expect(dialogSource.match(/class="connection-form-body grid min-h-0 flex-1 scroll-pb-6 gap-4 overflow-y-auto/g)).toHaveLength(4);+ expect(dialogSource).not.toMatch(/\.connection-dialog-content--config\s*\{[\s\S]*?height:\s*min\(720px/);expect(dialogSource).toMatch(/@media \(max-height: 720px\)[\s\S]*?height:\s*calc\(var\(--dbx-viewport-height\) - 2rem\);/);expect(dialogSource).toMatch(/\.connection-dialog-content--config \.connection-form-body\s*\{[\s\S]*?align-content:\s*start;/);});it("keeps the transport form inside a shrinkable scroll viewport", () => {expect(dialogSource).toContain('<TabsContent v-if="canUseTransportLayers" value="transport" class="m-0 flex min-h-0 flex-1 flex-col overflow-hidden">');- expect(dialogSource).toContain('class="connection-form-body grid min-h-0 flex-1 gap-4 overflow-y-auto overflow-x-hidden pt-4 pr-2"');+ expect(dialogSource).toContain('class="connection-form-body grid min-h-0 flex-1 scroll-pb-6 gap-4 overflow-y-auto overflow-x-hidden pt-4 pr-2 pb-6"');+ });++ it("keeps conditional Nacos authentication fields from shrinking earlier cards", () => {+ expect(dialogSource).toContain(":class=\"{ 'connection-form-body--nacos': form.db_type === 'nacos' }\"");+ expect(dialogSource).toMatch(/\.connection-form-body--nacos\s*\{[\s\S]*?grid-auto-rows:\s*max-content;/);});});diff --git a/apps/desktop/src/lib/__tests__/connection/nacosConnectionDialog.spec.ts b/apps/desktop/src/lib/__tests__/connection/nacosConnectionDialog.spec.tsnew file mode 100644index 0000000000..8cd262c0ea--- /dev/null+++ b/apps/desktop/src/lib/__tests__/connection/nacosConnectionDialog.spec.ts@@ -0,0 +1,66 @@+import { readFileSync } from "node:fs";+import { describe, expect, it } from "vitest";++const source = readFileSync(new URL("../../../components/connection/ConnectionDialog.vue", import.meta.url), "utf8");++describe("Nacos connection dialog layout", () => {+ it("presents implementation and version as one explicit connection profile", () => {+ expect(source).toContain("data-nacos-profile-selector");+ expect(source).toContain('v-for="profile in NACOS_CONNECTION_PROFILES"');+ expect(source).toContain("selectNacosConnectionProfile(profile.value)");+ expect(source).not.toContain("nacosVersionMode = 'auto'");+ expect(source).not.toContain("tryNacosDockerConsoleFallback");+ expect(source).not.toContain("dockerNacosConsoleFallbackUrl");+ });++ it("keeps the primary form focused on endpoints and authentication", () => {+ const mainStart = source.indexOf("data-nacos-profile-selector");+ const mainEnd = source.indexOf("<!-- Redis: host, port, user, password, ssl -->", mainStart);+ const main = source.slice(mainStart, mainEnd);++ expect(main).toContain("data-nacos-endpoint-section");+ expect(main).toContain("data-nacos-access-section");+ expect(main).toContain("data-nacos-advanced-hint");+ expect(main).toContain('t("nacos.nacosAdvancedHint")');+ expect(main).toContain("@click=\"configTab = 'advanced'\"");+ expect(main).toContain('v-model="nacosServerAddr"');+ expect(main).not.toContain('v-model="nacosV3ConsoleAddr"');+ expect(main).not.toContain('v-model="nacosNamespace"');+ expect(main).toContain('t("nacos.nacosAuthHint")');+ expect(main).not.toContain('v-model="nacosMetricsMode"');+ expect(main).not.toContain('v-model.number="nacosPageSize"');+ });++ it("moves low-frequency and r-nacos console settings to the advanced tab", () => {+ const advancedStart = source.indexOf("data-nacos-advanced-settings");+ const advancedEnd = source.indexOf('v-if="showGaussdbConnectionMode"', advancedStart);+ const advanced = source.slice(advancedStart, advancedEnd);++ expect(advanced).not.toContain('v-model="nacosContextPathInput"');+ expect(advanced).not.toContain("配置上下文路径");+ expect(advanced).toContain('v-model="nacosMetricsMode"');+ expect(advanced).toContain('v-model="nacosRNacosConsoleAddr"');+ expect(advanced).toContain('v-if="nacosHistoryEnabled"');+ expect(advanced).toContain('t("nacos.nacosRnacosDisabledHint")');+ expect(advanced).toContain('v-model="nacosTlsSkipVerify"');+ expect(advanced).toContain('v-model.number="nacosPageSize"');+ });++ it("documents product default ports instead of local Docker mappings", () => {+ expect(source).toContain('t("nacos.nacosServiceAddressHint")');+ expect(source).toContain('t("nacos.nacosMetricsHint")');+ expect(source).not.toContain("DBX 不需要配置该地址");+ const mainStart = source.indexOf("data-nacos-profile-selector");+ const mainEnd = source.indexOf("<!-- Redis: host, port, user, password, ssl -->", mainStart);+ expect(source.slice(mainStart, mainEnd)).not.toContain('placeholder="http://127.0.0.1:8080"');+ expect(source).not.toContain("http://127.0.0.1:8010");+ expect(source).not.toContain("http://127.0.0.1:8818");+ });++ it("uses a dedicated namespace selector instead of the database selector", () => {+ expect(source).toContain('t("nacos.nacosVisibleNamespacesTitle")');+ expect(source).toContain("openVisibleNacosNamespacesPicker");+ expect(source).toContain("api.nacosListNamespaces(draftId)");+ expect(source).toContain("showVisibleNacosNamespacesDialog");+ });+});diff --git a/apps/desktop/src/lib/__tests__/nacos/nacosAdmin.spec.ts b/apps/desktop/src/lib/__tests__/nacos/nacosAdmin.spec.tsindex d6e7c4f3ca..42fbbfa2f4 100644--- a/apps/desktop/src/lib/__tests__/nacos/nacosAdmin.spec.ts+++ b/apps/desktop/src/lib/__tests__/nacos/nacosAdmin.spec.ts@@ -195,8 +195,10 @@ describe("nacosAdmin helpers", () => {it("includes identifying fields in confirmations", () => {expect(buildNacosConfigDeleteConfirm({ namespace: "", dataId: "app.yaml", group: "DEFAULT_GROUP" })).toContain("dataId=app.yaml");- const details = buildNacosInstanceConfirm({ serviceName: "DEFAULT_GROUP@@svc", groupName: "DEFAULT_GROUP" }, { ip: "127.0.0.1", port: 8080, enabled: true, metadata: null }, { enabled: false }, "", "public");+ const details = buildNacosInstanceConfirm({ serviceName: "DEFAULT_GROUP@@svc", groupName: "DEFAULT_GROUP" }, { ip: "127.0.0.1", port: 8080, clusterName: "blue", ephemeral: false, enabled: true, metadata: null }, { enabled: false }, "", "public");expect(details).toContain("serviceName=DEFAULT_GROUP@@svc");+ expect(details).toContain("cluster=blue");+ expect(details).toContain("ephemeral=false");expect(details).toContain("targetEnabled=false");});diff --git a/apps/desktop/src/lib/__tests__/nacos/nacosNamespaceVisibility.spec.ts b/apps/desktop/src/lib/__tests__/nacos/nacosNamespaceVisibility.spec.tsnew file mode 100644index 0000000000..25ee83db4e--- /dev/null+++ b/apps/desktop/src/lib/__tests__/nacos/nacosNamespaceVisibility.spec.ts@@ -0,0 +1,33 @@+import { describe, expect, it } from "vitest";+import { filterNacosNamespacesForSidebar, normalizeNacosNamespaceSelection, normalizeNacosNamespacesForDisplay } from "@/lib/nacos/nacosNamespaceVisibility";++const namespaces = [+ { namespace: "", namespaceShowName: "public" },+ { namespace: "dev", namespaceShowName: "开发" },+ { namespace: "prod", namespaceShowName: "生产" },+];++describe("filterNacosNamespacesForSidebar", () => {+ it("keeps all namespaces when no visibility filter is configured", () => {+ expect(filterNacosNamespacesForSidebar(namespaces, undefined)).toEqual(namespaces);+ });++ it("filters by namespace id and preserves the public empty identifier", () => {+ expect(filterNacosNamespacesForSidebar(namespaces, ["", "prod"])).toEqual([namespaces[0], namespaces[2]]);+ });++ it("matches a legacy empty public selection with a concrete public namespace", () => {+ const v3Namespaces = [{ namespace: "public", namespaceShowName: "public" }, namespaces[2]];+ expect(filterNacosNamespacesForSidebar(v3Namespaces, ["", "prod"])).toEqual(v3Namespaces);+ expect(normalizeNacosNamespaceSelection([""], v3Namespaces)).toEqual(["public"]);+ });++ it("preserves the endpoint-specific public ID when normalizing selections", () => {+ expect(normalizeNacosNamespaceSelection(["public"], namespaces)).toEqual([""]);+ });++ it("keeps only the concrete public namespace when both legacy forms are returned", () => {+ const duplicatePublic = [namespaces[0], { namespace: "public", namespaceShowName: "public" }, namespaces[1]];+ expect(normalizeNacosNamespacesForDisplay(duplicatePublic)).toEqual([duplicatePublic[1], duplicatePublic[2]]);+ });+});diff --git a/apps/desktop/src/lib/backend/api.ts b/apps/desktop/src/lib/backend/api.tsindex c9a4bcbd47..4e54ca3174 100644--- a/apps/desktop/src/lib/backend/api.ts+++ b/apps/desktop/src/lib/backend/api.ts@@ -359,8 +359,14 @@ export const nacosRollbackConfig = forward("nacosRollbackConfig");export const nacosGetRNacosConsoleCaptcha = forward("nacosGetRNacosConsoleCaptcha");export const nacosLoginRNacosConsole = forward("nacosLoginRNacosConsole");export const nacosListServices = forward("nacosListServices");+export const nacosGetService = forward("nacosGetService");+export const nacosCreateService = forward("nacosCreateService");+export const nacosUpdateService = forward("nacosUpdateService");+export const nacosDeleteService = forward("nacosDeleteService");export const nacosListInstances = forward("nacosListInstances");export const nacosUpdateInstance = forward("nacosUpdateInstance");+export const nacosRegisterInstance = forward("nacosRegisterInstance");+export const nacosDeregisterInstance = forward("nacosDeregisterInstance");export const nacosGetDashboard = forward("nacosGetDashboard");export const nacosRawRequest = forward("nacosRawRequest");diff --git a/apps/desktop/src/lib/backend/http.ts b/apps/desktop/src/lib/backend/http.tsindex 47af07f5fe..7cfe1e195b 100644--- a/apps/desktop/src/lib/backend/http.ts+++ b/apps/desktop/src/lib/backend/http.ts@@ -183,8 +183,10 @@ import type {NacosConnectionInfo,NacosRNacosConsoleCaptcha,NacosInstanceInfo,+ NacosInstanceRef,+ NacosInstanceRegistration,NacosInstanceQuery,- NacosInstanceUpdate,+ NacosInstanceUpdateRequest,NacosDashboardQuery,NacosDashboardSnapshot,NacosNamespaceCreate,@@ -193,7 +195,9 @@ import type {NacosRawRequest,NacosRawResponse,NacosServiceList,+ NacosServiceDetail,NacosServiceQuery,+ NacosServiceUpsert,NacosSearchProgress,} from "@/types/nacos";import { safeLocalStorageGet, safeLocalStorageSet } from "@/lib/backend/safeStorage";@@ -2806,14 +2810,38 @@ export async function nacosListServices(connectionId: string, query: NacosServicreturn post("/api/nacos/services/list", { connectionId, query });}+export async function nacosGetService(connectionId: string, query: NacosServiceQuery): Promise<NacosServiceDetail> {+ return post("/api/nacos/services/get", { connectionId, query });+}++export async function nacosCreateService(connectionId: string, req: NacosServiceUpsert): Promise<void> {+ return post("/api/nacos/services/create", { connectionId, req });+}++export async function nacosUpdateService(connectionId: string, req: NacosServiceUpsert): Promise<void> {+ return post("/api/nacos/services/update", { connectionId, req });+}++export async function nacosDeleteService(connectionId: string, query: NacosServiceQuery): Promise<void> {+ return post("/api/nacos/services/delete", { connectionId, query });+}+export async function nacosListInstances(connectionId: string, query: NacosInstanceQuery): Promise<NacosInstanceInfo[]> {return post("/api/nacos/instances/list", { connectionId, query });}-export async function nacosUpdateInstance(connectionId: string, req: NacosInstanceUpdate): Promise<void> {+export async function nacosUpdateInstance(connectionId: string, req: NacosInstanceUpdateRequest): Promise<void> {return post("/api/nacos/instances/update", { connectionId, req });}+export async function nacosRegisterInstance(connectionId: string, req: NacosInstanceRegistration): Promise<void> {+ return post("/api/nacos/instances/register", { connectionId, req });+}++export async function nacosDeregisterInstance(connectionId: string, req: NacosInstanceRef): Promise<void> {+ return post("/api/nacos/instances/deregister", { connectionId, req });+}+export async function nacosGetDashboard(connectionId: string, query: NacosDashboardQuery): Promise<NacosDashboardSnapshot> {return post("/api/nacos/dashboard", { connectionId, query });}diff --git a/apps/desktop/src/lib/backend/nacos-tauri.ts b/apps/desktop/src/lib/backend/nacos-tauri.tsindex 5b1107b7aa..975ee0ab26 100644--- a/apps/desktop/src/lib/backend/nacos-tauri.ts+++ b/apps/desktop/src/lib/backend/nacos-tauri.ts@@ -21,15 +21,19 @@ import type {NacosDashboardSnapshot,NacosRNacosConsoleCaptcha,NacosInstanceInfo,+ NacosInstanceRef,+ NacosInstanceRegistration,NacosInstanceQuery,- NacosInstanceUpdate,+ NacosInstanceUpdateRequest,NacosNamespaceCreate,NacosNamespaceInfo,NacosNamespaceUpdate,NacosRawRequest,NacosRawResponse,NacosServiceList,+ NacosServiceDetail,NacosServiceQuery,+ NacosServiceUpsert,NacosSearchProgress,} from "@/types/nacos";@@ -121,14 +125,38 @@ export async function nacosListServices(connectionId: string, query: NacosServicreturn invoke("nacos_list_services", { connectionId, query });}+export async function nacosGetService(connectionId: string, query: NacosServiceQuery): Promise<NacosServiceDetail> {+ return invoke("nacos_get_service", { connectionId, query });+}++export async function nacosCreateService(connectionId: string, req: NacosServiceUpsert): Promise<void> {+ return invoke("nacos_create_service", { connectionId, req });+}++export async function nacosUpdateService(connectionId: string, req: NacosServiceUpsert): Promise<void> {+ return invoke("nacos_update_service", { connectionId, req });+}++export async function nacosDeleteService(connectionId: string, query: NacosServiceQuery): Promise<void> {+ return invoke("nacos_delete_service", { connectionId, query });+}+export async function nacosListInstances(connectionId: string, query: NacosInstanceQuery): Promise<NacosInstanceInfo[]> {return invoke("nacos_list_instances", { connectionId, query });}-export async function nacosUpdateInstance(connectionId: string, req: NacosInstanceUpdate): Promise<void> {+export async function nacosUpdateInstance(connectionId: string, req: NacosInstanceUpdateRequest): Promise<void> {return invoke("nacos_update_instance", { connectionId, req });}+export async function nacosRegisterInstance(connectionId: string, req: NacosInstanceRegistration): Promise<void> {+ return invoke("nacos_register_instance", { connectionId, req });+}++export async function nacosDeregisterInstance(connectionId: string, req: NacosInstanceRef): Promise<void> {+ return invoke("nacos_deregister_instance", { connectionId, req });+}+export async function nacosGetDashboard(connectionId: string, query: NacosDashboardQuery): Promise<NacosDashboardSnapshot> {return invoke("nacos_get_dashboard", { connectionId, query });}diff --git a/apps/desktop/src/lib/nacos/__tests__/nacosServiceManagement.spec.ts b/apps/desktop/src/lib/nacos/__tests__/nacosServiceManagement.spec.tsnew file mode 100644index 0000000000..5eea470dfa--- /dev/null+++ b/apps/desktop/src/lib/nacos/__tests__/nacosServiceManagement.spec.ts@@ -0,0 +1,34 @@+import { describe, expect, it } from "vitest";++import { nacosInstanceMatchesPatch, nacosInstanceRefIdentity, nacosIpAddressIsValid, nacosJsonObjectMatches, nacosServiceDetailMatches } from "../nacosServiceManagement";++describe("Nacos service management state reconciliation", () => {+ it("keeps unknown, persistent and ephemeral instances as separate identities", () => {+ const base = { serviceName: "api", ip: "127.0.0.1", port: 8080, clusterName: "blue" };+ expect(new Set([nacosInstanceRefIdentity(base), nacosInstanceRefIdentity({ ...base, ephemeral: false }), nacosInstanceRefIdentity({ ...base, ephemeral: true })]).size).toBe(3);+ });++ it("validates IPv4 and IPv6 instance addresses without accepting host names", () => {+ expect(nacosIpAddressIsValid("127.0.0.1")).toBe(true);+ expect(nacosIpAddressIsValid("2001:db8::1")).toBe(true);+ expect(nacosIpAddressIsValid("999.0.0.1")).toBe(false);+ expect(nacosIpAddressIsValid("localhost")).toBe(false);+ });++ it("compares metadata independently of object key order", () => {+ expect(nacosJsonObjectMatches({ owner: "dbx", nested: { b: 2, a: 1 } }, { nested: { a: 1, b: 2 }, owner: "dbx" })).toBe(true);+ });++ it("verifies only fields present in an instance patch", () => {+ const instance = { ip: "127.0.0.1", port: 8080, weight: 0.3, enabled: false, healthy: true, metadata: { role: "api" } };+ expect(nacosInstanceMatchesPatch(instance, { weight: 0.3000000001, metadata: { role: "api" } })).toBe(true);+ expect(nacosInstanceMatchesPatch(instance, { metadata: { role: "worker" } })).toBe(false);+ expect(nacosInstanceMatchesPatch({ ip: "127.0.0.1", port: 8080 }, { weight: 1 })).toBe(false);+ });++ it("treats Nacos none selectors as the UI's unconfigured selector", () => {+ const expected = { serviceName: "api", metadata: { owner: "dbx" }, protectThreshold: 0.5 };+ expect(nacosServiceDetailMatches({ serviceName: "api", metadata: { owner: "dbx" }, protectThreshold: 0.5, selector: { type: "NoneSelector", contextType: "NONE" } }, expected)).toBe(true);+ expect(nacosServiceDetailMatches({ serviceName: "api", metadata: { owner: "dbx" } }, expected)).toBe(false);+ });+});diff --git a/apps/desktop/src/lib/nacos/nacosAdmin.ts b/apps/desktop/src/lib/nacos/nacosAdmin.tsindex 4799a6223e..eae21668ce 100644--- a/apps/desktop/src/lib/nacos/nacosAdmin.ts+++ b/apps/desktop/src/lib/nacos/nacosAdmin.ts@@ -12,26 +12,26 @@ export interface NacosRawTemplate {}export const NACOS_RAW_TEMPLATES: NacosRawTemplate[] = [- { key: "serverState", method: "GET", path: "/v3/console/server/state", query: "", body: "" },- { key: "namespaceList", method: "GET", path: "/v3/console/core/namespace/list", query: "", body: "" },+ { key: "serverState", method: "GET", path: "/v3/admin/core/state", query: "", body: "" },+ { key: "namespaceList", method: "GET", path: "/v3/admin/core/namespace/list", query: "", body: "" },{key: "configDetail",method: "GET",- path: "/v3/console/cs/config",+ path: "/v3/admin/cs/config",query: "dataId=application.yaml&groupName=DEFAULT_GROUP&namespaceId=",body: "",},{key: "serviceList",method: "GET",- path: "/v3/console/ns/service/list",+ path: "/v3/admin/ns/service/list",query: "pageNo=1&pageSize=20&namespaceId=",body: "",},{key: "instanceList",method: "GET",- path: "/v3/console/ns/instance/list",+ path: "/v3/admin/ns/instance/list",query: "serviceName=DEFAULT_GROUP@@example&namespaceId=",body: "",},@@ -702,8 +702,12 @@ export function buildNacosInstanceConfirm(service: NacosServiceInfo, instance: N`serviceName=${service.serviceName}`,`group=${instance.groupName || service.groupName || fallbackGroup || "DEFAULT_GROUP"}`,`instance=${instance.ip}:${instance.port}`,+ `cluster=${instance.clusterName || "DEFAULT"}`,+ `ephemeral=${instance.ephemeral === true ? "true" : instance.ephemeral === false ? "false" : "unknown"}`,patch.enabled == null ? "" : `targetEnabled=${targetEnabled === false ? "false" : "true"}`,patch.healthy == null ? "" : `targetHealthy=${targetHealthy === false ? "false" : "true"}`,+ patch.weight == null ? "" : `targetWeight=${patch.weight}`,+ patch.metadata == null ? "" : `targetMetadata=${JSON.stringify(patch.metadata)}`,].filter(Boolean).join("\n");diff --git a/apps/desktop/src/lib/nacos/nacosNamespaceVisibility.ts b/apps/desktop/src/lib/nacos/nacosNamespaceVisibility.tsnew file mode 100644index 0000000000..e129bd8dd8--- /dev/null+++ b/apps/desktop/src/lib/nacos/nacosNamespaceVisibility.ts@@ -0,0 +1,51 @@+import type { NacosNamespaceInfo } from "@/types/nacos";++/**+ * Nacos 2/r-nacos may represent the default namespace with an empty ID, while+ * Nacos 3 returns the concrete `public` ID. Older backend builds could expose+ * both forms at once; prefer the concrete ID and keep every other namespace.+ */+export function normalizeNacosNamespacesForDisplay(namespaces: NacosNamespaceInfo[]): NacosNamespaceInfo[] {+ const normalized = new Map<string, NacosNamespaceInfo>();+ for (const namespace of namespaces) {+ const identity = nacosNamespaceIdentity(namespace.namespace);+ const existing = normalized.get(identity);+ // Prefer the concrete public ID when both legacy representations are returned.+ if (!existing || (identity === "public" && namespace.namespace === "public" && existing.namespace === "")) {+ normalized.set(identity, namespace);+ }+ }+ return [...normalized.values()];+}++/** Returns the stable display/filter identity without changing the value sent to Nacos. */+export function nacosNamespaceIdentity(namespace: string): string {+ return namespace === "" || namespace === "public" ? "public" : namespace;+}++/** Converts selected identities back to the namespace IDs returned by this Nacos endpoint. */+export function normalizeNacosNamespaceSelection(selected: Iterable<string>, namespaces: NacosNamespaceInfo[]): string[] {+ const available = new Map<string, string>();+ for (const namespace of normalizeNacosNamespacesForDisplay(namespaces)) {+ available.set(nacosNamespaceIdentity(namespace.namespace), namespace.namespace);+ }+ const result: string[] = [];+ const seen = new Set<string>();+ for (const value of selected) {+ const identity = nacosNamespaceIdentity(value);+ const namespace = available.get(identity);+ if (namespace !== undefined && !seen.has(identity)) {+ seen.add(identity);+ result.push(namespace);+ }+ }+ return result;+}++/** `visible_databases` stores the namespace identifiers selected for a Nacos connection. */+export function filterNacosNamespacesForSidebar(namespaces: NacosNamespaceInfo[], visibleNamespaces: string[] | undefined): NacosNamespaceInfo[] {+ const normalized = normalizeNacosNamespacesForDisplay(namespaces);+ if (!Array.isArray(visibleNamespaces)) return normalized;+ const visible = new Set(visibleNamespaces.map(nacosNamespaceIdentity));+ return normalized.filter((namespace) => visible.has(nacosNamespaceIdentity(namespace.namespace)));+}diff --git a/apps/desktop/src/lib/nacos/nacosServiceManagement.ts b/apps/desktop/src/lib/nacos/nacosServiceManagement.tsnew file mode 100644index 0000000000..5b2d3b66ad--- /dev/null+++ b/apps/desktop/src/lib/nacos/nacosServiceManagement.ts@@ -0,0 +1,57 @@+import type { NacosInstanceInfo, NacosInstancePatch, NacosInstanceRef, NacosServiceDetail, NacosServiceUpsert } from "@/types/nacos";++function canonicalJson(value: unknown): unknown {+ if (Array.isArray(value)) return value.map(canonicalJson);+ if (value && typeof value === "object") {+ return Object.fromEntries(+ Object.entries(value as Record<string, unknown>)+ .sort(([left], [right]) => left.localeCompare(right))+ .map(([key, nested]) => [key, canonicalJson(nested)]),+ );+ }+ return value;+}++export function nacosJsonObjectMatches(left: unknown, right: unknown) {+ return JSON.stringify(canonicalJson(left ?? {})) === JSON.stringify(canonicalJson(right ?? {}));+}++export function nacosIpAddressIsValid(value: string) {+ const input = value.trim();+ if (!input) return false;+ if (input.includes(":")) {+ try {+ const parsed = new URL(`http://[${input}]/`);+ return parsed.hostname.startsWith("[") && parsed.hostname.endsWith("]");+ } catch {+ return false;+ }+ }+ const octets = input.split(".");+ return octets.length === 4 && octets.every((octet) => /^\d{1,3}$/.test(octet) && (octet === "0" || !octet.startsWith("0")) && Number(octet) <= 255);+}++export function nacosInstanceRefIdentity(ref: NacosInstanceRef) {+ const lifetime = ref.ephemeral === true ? "ephemeral" : ref.ephemeral === false ? "persistent" : "unknown";+ return [ref.namespace || "public", ref.groupName || "DEFAULT_GROUP", ref.serviceName, ref.ip, ref.port, ref.clusterName || "DEFAULT", lifetime].join("\u0000");+}++export function nacosInstanceMatchesPatch(instance: NacosInstanceInfo, patch: NacosInstancePatch) {+ const weightMatches = patch.weight == null || (instance.weight != null && Math.abs(instance.weight - patch.weight) <= 1e-6);+ const metadataMatches = patch.metadata == null || nacosJsonObjectMatches(instance.metadata, patch.metadata);+ return (patch.enabled == null || instance.enabled === patch.enabled) && (patch.healthy == null || instance.healthy === patch.healthy) && weightMatches && metadataMatches;+}++export function normalizeNacosSelector(value: unknown): unknown {+ if (!value || typeof value !== "object" || Array.isArray(value) || Object.keys(value).length === 0) return null;+ const selector = value as Record<string, unknown>;+ const type = String(selector.type ?? "").toLowerCase();+ const contextType = String(selector.contextType ?? "").toUpperCase();+ if (type === "none" || type === "noneselector" || contextType === "NONE") return null;+ return canonicalJson(selector);+}++export function nacosServiceDetailMatches(detail: NacosServiceDetail, expected: NacosServiceUpsert) {+ const thresholdMatches = expected.protectThreshold == null || (detail.protectThreshold != null && Math.abs(detail.protectThreshold - expected.protectThreshold) <= 1e-6);+ return nacosJsonObjectMatches(detail.metadata, expected.metadata) && thresholdMatches && JSON.stringify(normalizeNacosSelector(detail.selector)) === JSON.stringify(normalizeNacosSelector(expected.selector));+}diff --git a/apps/desktop/src/stores/connectionStore.ts b/apps/desktop/src/stores/connectionStore.tsindex 07cb2f9437..702499a849 100644--- a/apps/desktop/src/stores/connectionStore.ts+++ b/apps/desktop/src/stores/connectionStore.ts@@ -109,6 +109,7 @@ import { normalizeRedisDatabaseAliases, redisDatabaseAlias, redisDatabaseLabel }import { appendAgentDriverUpdateHint, hasAgentDriverUpdate, hasInstalledAgentVersion, type AgentDriverInstallState } from "@/lib/connection/agentDriverInstallHint";import { appendConnectionErrorHints } from "@/lib/connection/connectionErrorHints";import { appendVisibleDatabaseSelection } from "@/lib/connection/connectionVisibleDatabases";+import { filterNacosNamespacesForSidebar } from "@/lib/nacos/nacosNamespaceVisibility";import { configuredDatabaseProductName, connectionConfigFingerprint, normalizeDatabaseConnectionInfo } from "@/lib/connection/connectionDatabaseInfo";import { createMetadataLoadTrace, logMetadataLoadTrace, MetadataLoadCoordinator, type MetadataLoadTraceLogger } from "@/lib/metadata/metadataLoadCoordinator";import type { MetadataScopeInput } from "@/lib/metadata/metadataLoadScope";@@ -3438,7 +3439,8 @@ export const useConnectionStore = defineStore("connection", () => {if (useCachedChildren(node, options, load)) return;const namespaces = await api.nacosListNamespaces(connectionId);- const sorted = [...namespaces].sort((left, right) => {+ const visibleNamespaces = filterNacosNamespacesForSidebar(namespaces, getConfig(connectionId)?.visible_databases);+ const sorted = [...visibleNamespaces].sort((left, right) => {const leftLabel = left.namespaceShowName || left.namespace || "public";const rightLabel = right.namespaceShowName || right.namespace || "public";return leftLabel.localeCompare(rightLabel);diff --git a/apps/desktop/src/types/nacos.ts b/apps/desktop/src/types/nacos.tsindex 15ebd2be03..be392b3061 100644--- a/apps/desktop/src/types/nacos.ts+++ b/apps/desktop/src/types/nacos.ts@@ -5,6 +5,28 @@ export interface NacosCapabilities {supportsServiceManagement: boolean;supportsInstanceUpdate: boolean;supportsRawApi: boolean;+ /** Naming capabilities are intentionally granular: servers such as r-nacos+ * can expose discovery reads without supporting the official write APIs. */+ serviceManagement?: NacosServiceCapabilities;+}++export interface NacosServiceCapabilities {+ listServices: NacosOperationCapability;+ getService: NacosOperationCapability;+ createService: NacosOperationCapability;+ updateService: NacosOperationCapability;+ deleteService: NacosOperationCapability;+ listInstances: NacosOperationCapability;+ updateInstance: NacosOperationCapability;+ registerInstance: NacosOperationCapability;+ deregisterInstance: NacosOperationCapability;+}++export type NacosCapabilityReason = "implementationReadOnly" | "versionUnsupported" | "endpointUnavailable" | "notVerified" | "connectionReadOnly";++export interface NacosOperationCapability {+ supported: boolean;+ reason?: NacosCapabilityReason;}export interface NacosConnectionInfo {@@ -58,7 +80,6 @@ export interface NacosAdminConfig {implementation?: NacosImplementation;versionMode?: NacosVersionMode;serverAddr: string;- namespace?: string;contextPath?: string;rnacosConsoleAddr?: string;/** Undefined keeps the legacy behaviour: history is enabled when a console address exists. */@@ -313,6 +334,25 @@ export interface NacosServiceList {items: NacosServiceInfo[];}+export interface NacosServiceDetail {+ serviceName: string;+ groupName?: string;+ metadata?: unknown;+ protectThreshold?: number;+ selector?: unknown;+ ephemeral?: boolean;+}++export interface NacosServiceUpsert {+ namespace?: string;+ serviceName: string;+ groupName?: string;+ metadata?: unknown;+ protectThreshold?: number;+ selector?: unknown;+ ephemeral?: boolean;+}+export interface NacosInstanceQuery {namespace?: string;serviceName: string;@@ -333,18 +373,37 @@ export interface NacosInstanceInfo {metadata?: unknown;}-export interface NacosInstanceUpdate {+export interface NacosInstanceRef {namespace?: string;serviceName: string;ip: string;port: number;groupName?: string;clusterName?: string;+ ephemeral?: boolean;+}++export interface NacosInstancePatch {healthy?: boolean;enabled?: boolean;- ephemeral?: boolean;weight?: number;- metadata?: unknown;+ metadata?: Record<string, unknown>;+}++export interface NacosInstanceUpdateRequest {+ target: NacosInstanceRef;+ patch: NacosInstancePatch;+}++export interface NacosInstanceRegistration {+ namespace?: string;+ serviceName: string;+ ip: string;+ port: number;+ groupName?: string;+ clusterName?: string;+ weight?: number;+ metadata?: Record<string, unknown>;}export interface NacosDashboardQuery {diff --git a/crates/dbx-core/src/nacos/batch.rs b/crates/dbx-core/src/nacos/batch.rsindex 6f92fc8900..70a509878d 100644--- a/crates/dbx-core/src/nacos/batch.rs+++ b/crates/dbx-core/src/nacos/batch.rs@@ -618,11 +618,31 @@ mod tests {Err("unused".to_string())}+ async fn get_service(&self, _: NacosServiceQuery) -> Result<NacosServiceDetail, String> {+ Err("unused".to_string())+ }+ async fn create_service(&self, _: NacosServiceUpsert) -> Result<(), String> {+ Err("unused".to_string())+ }+ async fn update_service(&self, _: NacosServiceUpsert) -> Result<(), String> {+ Err("unused".to_string())+ }+ async fn delete_service(&self, _: NacosServiceQuery) -> Result<(), String> {+ Err("unused".to_string())+ }+async fn list_instances(&self, _: NacosInstanceQuery) -> Result<Vec<NacosInstanceInfo>, String> {Err("unused".to_string())}- async fn update_instance(&self, _: NacosInstanceUpdate) -> Result<(), String> {+ async fn update_instance(&self, _: NacosInstanceUpdateRequest) -> Result<(), String> {+ Err("unused".to_string())+ }++ async fn register_instance(&self, _: NacosInstanceRegistration) -> Result<(), String> {+ Err("unused".to_string())+ }+ async fn deregister_instance(&self, _: NacosInstanceRef) -> Result<(), String> {Err("unused".to_string())}diff --git a/crates/dbx-core/src/nacos/config.rs b/crates/dbx-core/src/nacos/config.rsindex 9a15f865b7..d4ac7b2f6d 100644--- a/crates/dbx-core/src/nacos/config.rs+++ b/crates/dbx-core/src/nacos/config.rs@@ -147,10 +147,9 @@ impl NacosAdminConfig {}let context_path_is_explicit_root = self.context_path.trim() == "/";self.context_path = normalize_context_path(&self.context_path);- // Nacos 3 separates the console (normally :8080) from the server-side- // Admin API (normally :8848/nacos). Older DBX connection records did- // not persist the default server context, so repair only explicit- // Nacos 3 profiles here while preserving custom contexts.+ // Nacos 3 management uses the server-side Admin API, normally+ // `:8848/nacos`. Keep the documented default context for explicit V3+ // profiles while preserving custom reverse-proxy prefixes.if self.context_path.is_empty()&& !context_path_is_explicit_root&& matches!(self.implementation, Some(NacosImplementation::Nacos))diff --git a/crates/dbx-core/src/nacos/http.rs b/crates/dbx-core/src/nacos/http.rsindex 33884ced89..3a4f62f0d6 100644--- a/crates/dbx-core/src/nacos/http.rs+++ b/crates/dbx-core/src/nacos/http.rs@@ -1,4 +1,5 @@use std::collections::{HashMap, HashSet};+use std::sync::atomic::{AtomicBool, AtomicU8, Ordering};use std::sync::Arc;use std::time::{Duration, Instant};@@ -66,6 +67,8 @@ pub struct NacosOpenApiAdmin {http: reqwest::Client,token: Mutex<Option<AccessToken>>,rnacos_console_session: RNacosConsoleSessionHandle,+ detected_rnacos: AtomicBool,+ detected_major_version: AtomicU8,}impl NacosOpenApiAdmin {@@ -82,22 +85,34 @@ impl NacosOpenApiAdmin {builder = builder.danger_accept_invalid_certs(true);}let http = builder.build().map_err(|e| format!("Failed to build Nacos HTTP client: {e}"))?;- Ok(Self { cfg, http, token: Mutex::new(None), rnacos_console_session })+ let detected_rnacos = AtomicBool::new(matches!(cfg.implementation, Some(NacosImplementation::RNacos)));+ let detected_major_version = AtomicU8::new(match cfg.version_mode {+ Some(NacosVersionMode::V3) => 3,+ // New connections must choose a version in the UI. Keep legacy+ // omitted/`auto` values deterministic rather than probing across+ // API generations: they follow the established v2 Naming API.+ Some(NacosVersionMode::V2) | Some(NacosVersionMode::Auto) | None => 2,+ });+ Ok(Self { cfg, http, token: Mutex::new(None), rnacos_console_session, detected_rnacos, detected_major_version })}fn endpoint_with_context(&self, path: &str, context_path: &str) -> Result<String, String> {+ self.endpoint_with_base(&self.cfg.server_addr, path, context_path)+ }++ fn endpoint_with_base(&self, server_addr: &str, path: &str, context_path: &str) -> Result<String, String> {let path = normalize_api_path(path);let context_path = normalize_api_path(context_path).trim_end_matches('/').to_string();- let base = format!("{}{}", self.cfg.server_addr, context_path);+ let base = format!("{server_addr}{context_path}");let base = base.trim_end_matches('/');let full = if path.starts_with("/nacos/") && context_path == "/nacos" {- format!("{}{}", self.cfg.server_addr, path)+ format!("{server_addr}{path}")} else if path.starts_with("/rnacos/") && context_path.ends_with("/nacos") {// r-nacos documents this auth endpoint outside the Nacos-compatible// `/nacos` context. Preserve an optional proxy prefix such as// `/gateway/nacos` while replacing that final segment.let proxy_prefix = context_path.strip_suffix("/nacos").unwrap_or(&context_path);- format!("{}{}{}", self.cfg.server_addr, proxy_prefix, path)+ format!("{server_addr}{proxy_prefix}{path}")} else {format!("{base}{path}")};@@ -134,7 +149,8 @@ impl NacosOpenApiAdmin {form: Option<&[(String, String)]>,body: Option<&Value>,) -> Result<reqwest::Response, String> {- let mut req = self.http.request(method, self.endpoint_with_context(path, context_path)?).query(query);+ let endpoint = self.endpoint_with_context(path, context_path)?;+ let mut req = self.http.request(method, endpoint).query(query);if let Some(form) = form {req = req.form(form);}@@ -469,6 +485,29 @@ impl NacosOpenApiAdmin {Ok(parse_namespaces(value))}+ /// The Nacos-compatible discovery endpoint intentionally hides disabled+ /// instances. r-nacos's own management console exposes the complete+ /// administrative view instead, including `enabled = false` instances.+ ///+ /// This requires the separately configured console endpoint and its+ /// session token, so callers retain the compatible OpenAPI fallback when+ /// a console is unavailable. A CAPTCHA requirement is deliberately+ /// propagated for the UI to complete the existing interactive login flow.+ async fn list_rnacos_console_instances(+ &self,+ query: &NacosInstanceQuery,+ namespace: &str,+ requested_clusters: &[String],+ ) -> Result<Vec<NacosInstanceInfo>, String> {+ let mut params = vec![+ ("namespaceId".to_string(), namespace.to_string()),+ ("serviceName".to_string(), query.service_name.clone()),+ ];+ push_optional(&mut params, "groupName", query.group_name.clone());+ let value = self.get_rnacos_console_json("/rnacos/api/console/v2/instance/list", params).await?;+ Ok(filter_instances_by_clusters(parse_instances(value), requested_clusters))+ }+/// Do not let an older in-flight request invalidate a newer session that/// another configuration-history request has already refreshed.async fn clear_rnacos_console_token_if_matches(&self, token: &str) {@@ -590,12 +629,12 @@ impl NacosOpenApiAdmin {// r-nacos implements the Nacos client OpenAPI but not the console state endpoints.// Its documented health endpoint is mounted below the same `/nacos` context path,// so keep it last to preserve the richer official-Nacos state response when available.- let paths = if matches!(self.cfg.implementation, Some(NacosImplementation::RNacos)) {- ["/health", "/v3/console/server/state", "/v1/ns/operator/servers", "/v1/console/server/state"]+ let paths: &[&str] = if matches!(self.cfg.implementation, Some(NacosImplementation::RNacos)) {+ &["/health", "/v3/admin/core/state", "/v1/ns/operator/servers", "/v1/console/server/state"]} else {- ["/v3/console/server/state", "/v1/ns/operator/servers", "/v1/console/server/state", "/health"]+ &["/v3/admin/core/state", "/v1/ns/operator/servers", "/v1/console/server/state", "/health"]};- for path in paths {+ for &path in paths {if !self.api_path_allowed(path) {continue;}@@ -615,12 +654,32 @@ impl NacosOpenApiAdmin {matches!(self.cfg.implementation, Some(NacosImplementation::RNacos))}+ fn is_rnacos_compatible(&self) -> bool {+ self.is_explicit_rnacos() || self.detected_rnacos.load(Ordering::Relaxed)+ }+fn api_path_allowed(&self, path: &str) -> bool {- match self.cfg.version_mode.as_ref() {- Some(NacosVersionMode::V2) => !path.starts_with("/v3/"),- Some(NacosVersionMode::V3) => !path.starts_with("/v1/") && !path.starts_with("/v2/"),- Some(NacosVersionMode::Auto) | None => true,+ // r-nacos implements the Nacos-compatible v1 client OpenAPI, but it+ // does not expose official Nacos v2/v3 console or admin endpoints.+ // Treating its version as auto must not make a v3 probe the first+ // service-management request, because a normal 404 is intentionally+ // not retried across API generations.+ if self.is_rnacos_compatible() {+ return !path.starts_with("/v2/") && !path.starts_with("/v3/");}+ match self.detected_major_version.load(Ordering::Relaxed) {+ 2 => !path.starts_with("/v3/"),+ 3 => !path.starts_with("/v1/") && !path.starts_with("/v2/") && !path.starts_with("/v3/console/"),+ _ => true,+ }+ }++ fn should_try_next_candidate(&self, _error: &str) -> bool {+ // Nacos 2, Nacos 3 and r-nacos are explicitly selected connection+ // profiles. A failed request must remain a failure for that profile;+ // retrying it on a different API generation can mutate the wrong+ // endpoint or hide the real configuration error.+ false}fn namespace(&self, override_ns: Option<&str>) -> String {@@ -641,11 +700,12 @@ impl NacosOpenApiAdmin {("dataId".to_string(), search.to_string()),("groupName".to_string(), group.to_string()),("namespaceId".to_string(), namespace.to_string()),+ ("configDetail".to_string(), String::new()),("pageNo".to_string(), page_no.to_string()),("pageSize".to_string(), page_size.to_string()),];push_optional(&mut v3_params, "appName", Some(app_name.to_string()));- let mut attempts = vec![("/v3/console/cs/config/list", v3_params)];+ let mut attempts = vec![("/v3/admin/cs/config/list", v3_params)];let mut v1_params = vec![("search".to_string(), "blur".to_string()),("dataId".to_string(), search.to_string()),@@ -721,6 +781,150 @@ impl NacosOpenApiAdmin {Err(format!("Failed to {operation}: {}", errors.join("; ")))}+ async fn get_service_json_from_candidates(+ &self,+ operation: &str,+ attempts: Vec<(&str, Vec<(String, String)>)>,+ ) -> Result<Value, String> {+ let mut errors = Vec::new();+ for (path, query) in attempts {+ if !self.api_path_allowed(path) {+ continue;+ }+ match self.get_json(path, query).await {+ Ok(value) => return Ok(value),+ Err(err) => {+ let try_next = self.should_try_next_candidate(&err);+ errors.push(err);+ if !try_next {+ break;+ }+ }+ }+ }+ Err(format!("Failed to {operation}: {}", errors.join("; ")))+ }++ async fn submit_service_form_candidates(+ &self,+ operation: &str,+ method: reqwest::Method,+ attempts: Vec<(&str, Vec<(String, String)>)>,+ ) -> Result<(), String> {+ let mut errors = Vec::new();+ for (path, form) in attempts {+ if !self.api_path_allowed(path) {+ continue;+ }+ let result = match self.request(method.clone(), path, Vec::new(), Some(form), None).await {+ Ok(resp) => error_for_status(resp, path).await.map(|_| ()),+ Err(err) => Err(err),+ };+ match result {+ Ok(()) => return Ok(()),+ Err(err) => {+ let try_next = self.should_try_next_candidate(&err);+ errors.push(err);+ if !try_next {+ break;+ }+ }+ }+ }+ Err(format!("Failed to {operation}: {}", errors.join("; ")))+ }++ async fn submit_service_query_candidates(+ &self,+ operation: &str,+ method: reqwest::Method,+ attempts: Vec<(&str, Vec<(String, String)>)>,+ ) -> Result<(), String> {+ let mut errors = Vec::new();+ for (path, query) in attempts {+ if !self.api_path_allowed(path) {+ continue;+ }+ let result = match self.request(method.clone(), path, query, None, None).await {+ Ok(resp) => error_for_status(resp, path).await.map(|_| ()),+ Err(err) => Err(err),+ };+ match result {+ Ok(()) => return Ok(()),+ Err(err) => {+ let try_next = self.should_try_next_candidate(&err);+ errors.push(err);+ if !try_next {+ break;+ }+ }+ }+ }+ Err(format!("Failed to {operation}: {}", errors.join("; ")))+ }++ async fn submit_service_upsert(+ &self,+ operation: &str,+ req: NacosServiceUpsert,+ method: reqwest::Method,+ ) -> Result<(), String> {+ if req.service_name.trim().is_empty() {+ return Err("Nacos service name is required".to_string());+ }+ let group_name = req+ .group_name+ .as_deref()+ .map(str::trim)+ .filter(|group| !group.is_empty())+ .ok_or_else(|| "Nacos service group name is required".to_string())?+ .to_string();+ let namespace = self.namespace(req.namespace.as_deref());+ let mut form = vec![("namespaceId".to_string(), namespace), ("serviceName".to_string(), req.service_name)];+ form.push(("groupName".to_string(), group_name));+ if let Some(metadata) = req.metadata {+ if !metadata.is_object() {+ return Err("Nacos service metadata must be a JSON object".to_string());+ }+ form.push(("metadata".to_string(), metadata.to_string()));+ }+ if let Some(threshold) = req.protect_threshold {+ if !threshold.is_finite() || !(0.0..=1.0).contains(&threshold) {+ return Err("Nacos service protection threshold must be between 0 and 1".to_string());+ }+ form.push(("protectThreshold".to_string(), threshold.to_string()));+ }+ let selector = req.selector.unwrap_or_else(|| serde_json::json!({ "type": "none", "contextType": "NONE" }));+ if !selector.is_object() {+ return Err("Nacos service selector must be a JSON object".to_string());+ }+ // Both supported Nacos generations reject `{}`. DBX owns the+ // version-neutral "no selector" semantic and sends the canonical+ // none selector instead, which also allows an existing selector to be+ // cleared during an update.+ let selector = if selector.as_object().is_some_and(|object| object.is_empty()) {+ serde_json::json!({ "type": "none", "contextType": "NONE" })+ } else {+ selector+ };+ form.push(("selector".to_string(), selector.to_string()));+ if let Some(ephemeral) = req.ephemeral {+ form.push(("ephemeral".to_string(), ephemeral.to_string()));+ }+ self.submit_service_form_candidates(+ operation,+ method,+ vec![+ ("/v3/admin/ns/service", form.clone()),+ // Nacos 2.x keeps the verified Naming management contract on+ // the v1 endpoint. The v2 compatibility endpoint can accept a+ // request while silently applying defaults to some fields.+ ("/v1/ns/service", form),+ ],+ )+ .await+ }+async fn list_configs_by_client_filter(&self,namespace: String,@@ -851,16 +1055,102 @@ impl NacosOpenApiAdmin {}}- let mut seen = HashSet::new();- instances.retain(|instance| seen.insert((instance.ip.clone(), instance.port, instance.cluster_name.clone())));- Ok(instances)+ Ok(deduplicate_management_instances(instances, namespace, query.group_name.as_deref(), &query.service_name))+ }++ async fn list_v3_admin_instances(+ &self,+ query: &NacosInstanceQuery,+ namespace: &str,+ ) -> Result<Vec<NacosInstanceInfo>, String> {+ // Nacos 3's documentation says omitting `clusterName` lists every+ // cluster. Nacos 3.1.0 can instead resolve that omission to `DEFAULT`,+ // returning an error for services whose only cluster is, for example,+ // `blue` or lowercase `default`. Read the service's cluster map and+ // query every declared cluster explicitly. The same route also keeps+ // disabled instances visible for the management page.+ let requested_clusters = split_nacos_cluster_names(query.clusters.as_deref());+ let cluster_names = if requested_clusters.is_empty() {+ let mut detail_params = vec![+ ("namespaceId".to_string(), namespace.to_string()),+ ("serviceName".to_string(), query.service_name.clone()),+ ];+ push_optional(&mut detail_params, "groupName", query.group_name.clone());+ parse_catalog_cluster_names(&self.get_json("/v3/admin/ns/service", detail_params).await?)+ } else {+ requested_clusters.clone()+ };++ // An empty cluster map is the normal state for an empty service. Do+ // not invent `DEFAULT` (which produces a misleading 404 on Nacos+ // 3.1), but also do not turn a valid zero-instance service into an+ // error: callers must still be able to inspect and delete it.+ if cluster_names.is_empty() {+ return Ok(Vec::new());+ }+ let mut instances = Vec::new();+ for cluster_name in cluster_names {+ let mut params = vec![+ ("namespaceId".to_string(), namespace.to_string()),+ ("serviceName".to_string(), query.service_name.clone()),+ ("clusterName".to_string(), cluster_name),+ ];+ push_optional(&mut params, "groupName", query.group_name.clone());+ instances.extend(parse_instances(self.get_json("/v3/admin/ns/instance/list", params).await?));+ }+ Ok(filter_instances_by_clusters(+ deduplicate_management_instances(instances, namespace, query.group_name.as_deref(), &query.service_name),+ &requested_clusters,+ ))+ }++ async fn verify_v3_naming_admin_api(&self) -> Result<(), String> {+ self.get_json(+ "/v3/admin/ns/service/list",+ vec![+ ("namespaceId".to_string(), self.namespace(None)),+ ("pageNo".to_string(), "1".to_string()),+ ("pageSize".to_string(), "1".to_string()),+ ],+ )+ .await?;+ Ok(())+ }++ async fn verify_v3_admin_config_api(&self) -> Result<(), String> {+ self.get_json(+ "/v3/admin/cs/config/list",+ vec![+ ("namespaceId".to_string(), self.namespace(None)),+ ("dataId".to_string(), String::new()),+ ("groupName".to_string(), String::new()),+ ("configDetail".to_string(), String::new()),+ ("search".to_string(), "blur".to_string()),+ ("pageNo".to_string(), "1".to_string()),+ ("pageSize".to_string(), "1".to_string()),+ ],+ )+ .await?;+ Ok(())+ }++ async fn update_v3_admin_instance(&self, req: NacosInstanceUpdateRequest) -> Result<(), String> {+ let namespace = self.namespace(req.target.namespace.as_deref());+ // Nacos v3 exposes a dedicated partial-update endpoint. Send only the+ // target identity and fields present in the patch so an external+ // console update cannot be overwritten by a stale read-modify-write.+ let form = instance_update_form(namespace, req);+ let response =+ self.request(reqwest::Method::PUT, "/v3/admin/ns/instance/partial", Vec::new(), Some(form), None).await?;+ error_for_status(response, "/v3/admin/ns/instance/partial").await?;+ Ok(())}async fn get_dashboard_nodes(&self) -> Result<Vec<NacosClusterNode>, String> {// r-nacos does not implement the official Nacos cluster-node Admin// APIs. An empty list represents this unsupported optional capability// without turning every dashboard refresh into a false warning.- if self.is_explicit_rnacos() {+ if self.is_rnacos_compatible() {return Ok(Vec::new());}@@ -911,17 +1201,40 @@ fn content_search_endpoint_is_unsupported(error: &str) -> bool {#[async_trait]impl NacosAdmin for NacosOpenApiAdmin {+ fn service_capabilities(&self) -> NacosServiceCapabilities {+ // r-nacos 0.8.x documents the full compatible v1 Naming management+ // surface: service POST/PUT/DELETE and instance POST/PUT/PATCH/DELETE.+ // Its own console exercises the same operations. `api_path_allowed`+ // keeps these calls strictly on `/v1/ns/...`, never on Nacos v3 admin+ // routes, so the shared UI can expose the verified CRUD workflow.+ let mut capabilities = NacosServiceCapabilities::default();+ if self.is_rnacos_compatible() && self.cfg.rnacos_console_addr.trim().is_empty() {+ // r-nacos's compatible discovery API hides disabled instances.+ // Without its console API, DBX cannot safely prove a service is+ // empty before deletion, so keep this destructive action closed.+ capabilities.delete_service =+ NacosOperationCapability::unsupported(NacosCapabilityReason::EndpointUnavailable);+ }+ capabilities+ }+async fn test_connection(&self) -> Result<NacosConnectionInfo, String> {// Server-state endpoints are console APIs and r-nacos deliberately only// guarantees the client OpenAPI. Treat state/health as best-effort;// successful authentication and namespace access below prove that this// connection can perform the DBX operations it exposes.let state = self.get_server_state().await.ok();+ // Namespace discovery must use r-nacos' compatible v1 API as soon as+ // its health response identifies the implementation. Delaying this+ // assignment until after `list_namespaces` made a fresh r-nacos+ // connection first probe official Nacos v3 routes.+ let is_rnacos = self.is_explicit_rnacos() || state.as_ref().is_some_and(|state| state.is_rnacos_compatible);+ self.detected_rnacos.store(is_rnacos, Ordering::Relaxed);let _ = self.access_token().await?;let _ = self.list_namespaces().await?;let mut capabilities = NacosCapabilities::default();- let is_rnacos = self.is_explicit_rnacos() || state.as_ref().is_some_and(|state| state.is_rnacos_compatible);if is_rnacos {+ capabilities.service_management = self.service_capabilities();if !self.cfg.rnacos_history_enabled() {capabilities.supports_config_history = false;capabilities.history_unavailable_reason = Some("historyDisabled".to_string());@@ -933,11 +1246,26 @@ impl NacosAdmin for NacosOpenApiAdmin {capabilities.history_unavailable_reason = Some("consoleCredentialsMissing".to_string());}}+ capabilities.supports_service_management = capabilities.service_management.list_services.supported;+ capabilities.supports_instance_update = capabilities.service_management.update_instance.supported;let server_version = if is_rnacos {self.rnacos_console_version_if_authenticated().await} else {state.as_ref().and_then(|state| extract_server_version(&state.raw))};+ let is_v3 = matches!(self.cfg.version_mode, Some(NacosVersionMode::V3));+ if !is_rnacos && is_v3 {+ self.verify_v3_naming_admin_api().await.map_err(|error| {+ if error.contains("[contextPathMismatch]") || error.contains("[apiVersionMismatch]") {+ format!(+ "NACOS_ERROR[v3AdminEndpointMismatch]: {error}. Nacos 3 服务管理使用 Server / Admin API,通常为 http://主机:8848/nacos;不要使用 8080 Console 端口,并确认上下文路径为 /nacos。"+ )+ } else {+ error+ }+ })?;+ self.verify_v3_admin_config_api().await?;+ }Ok(NacosConnectionInfo {server_addr: self.cfg.server_addr.clone(),display_server_addr: self.cfg.display_server_addr.clone(),@@ -961,7 +1289,7 @@ impl NacosAdmin for NacosOpenApiAdmin {}async fn list_namespaces(&self) -> Result<Vec<NacosNamespaceInfo>, String> {- if self.is_explicit_rnacos() {+ if self.is_rnacos_compatible() {// r-nacos v0.6.12 exposes the Nacos-compatible namespace API on// the main OpenAPI service. This keeps the connection tree usable// without a separately configured console, including consoles@@ -981,7 +1309,7 @@ impl NacosAdmin for NacosOpenApiAdmin {let value = self.get_json_from_candidates("list Nacos namespaces",- vec![("/v3/console/core/namespace/list", Vec::new()), ("/v1/console/namespaces", Vec::new())],+ vec![("/v3/admin/core/namespace/list", Vec::new()), ("/v1/console/namespaces", Vec::new())],).await?;Ok(parse_namespaces(value))@@ -1006,9 +1334,9 @@ impl NacosAdmin for NacosOpenApiAdmin {let mut v1_form =vec![("namespaceName".to_string(), namespace_name), ("namespaceDesc".to_string(), namespace_desc)];if let Some(namespace_id) = namespace_id {- // Nacos 3.x Console API uses `customNamespaceId`; passing only- // `namespaceId` is accepted but ignored and causes a generated UUID.- v3_form.push(("customNamespaceId".to_string(), namespace_id.clone()));+ // Nacos 3's documented Admin API accepts the requested ID as+ // `namespaceId`. The legacy Console route required the extra+ // `customNamespaceId` alias, which remains v1-only below.v3_form.push(("namespaceId".to_string(), namespace_id.clone()));v1_form.push(("customNamespaceId".to_string(), namespace_id.clone()));v1_form.push(("namespaceId".to_string(), namespace_id));@@ -1018,8 +1346,7 @@ impl NacosAdmin for NacosOpenApiAdmin {"create Nacos namespace",reqwest::Method::POST,vec![- ("/v3/console/core/namespace", v3_form.clone()),- ("/v3/console/core/namespace/create", v3_form),+ ("/v3/admin/core/namespace", v3_form),("/v1/console/namespaces", v1_form.clone()),("/v1/console/namespaces/create", v1_form),],@@ -1060,8 +1387,7 @@ impl NacosAdmin for NacosOpenApiAdmin {"update Nacos namespace",reqwest::Method::PUT,vec![- ("/v3/console/core/namespace", v3_form.clone()),- ("/v3/console/core/namespace/update", v3_form),+ ("/v3/admin/core/namespace", v3_form),("/v1/console/namespaces", v1_form.clone()),("/v1/console/namespaces/update", v1_form),],@@ -1122,28 +1448,16 @@ impl NacosAdmin for NacosOpenApiAdmin {// queries, so wrapping the term gives us contains semantics; every// candidate is still fetched and verified with Rust `str::contains`.let config_detail = format!("*{query}*");- let attempts = [- (- "/v3/admin/cs/config/list",- vec![- ("configDetail".to_string(), config_detail.clone()),- ("search".to_string(), "blur".to_string()),- ("namespaceId".to_string(), namespace.to_string()),- ("pageNo".to_string(), page_no.to_string()),- ("pageSize".to_string(), page_size.to_string()),- ],- ),- (- "/v3/console/cs/config/searchDetail",- vec![- ("configDetail".to_string(), config_detail),- ("search".to_string(), "blur".to_string()),- ("namespaceId".to_string(), namespace.to_string()),- ("pageNo".to_string(), page_no.to_string()),- ("pageSize".to_string(), page_size.to_string()),- ],- ),- ];+ let attempts = [(+ "/v3/admin/cs/config/list",+ vec![+ ("configDetail".to_string(), config_detail),+ ("search".to_string(), "blur".to_string()),+ ("namespaceId".to_string(), namespace.to_string()),+ ("pageNo".to_string(), page_no.to_string()),+ ("pageSize".to_string(), page_size.to_string()),+ ],+ )];let mut unsupported = false;for (path, params) in attempts {if !self.api_path_allowed(path) {@@ -1202,12 +1516,9 @@ impl NacosAdmin for NacosOpenApiAdmin {let mut v1_detail_params = v1_params.clone();v1_detail_params.push(("show".to_string(), "all".to_string()));let mut errors = Vec::new();- for (path, query) in [- ("/v3/console/cs/config", v3_params.clone()),- ("/v3/console/cs/config/detail", v3_params),- ("/v1/cs/configs", v1_detail_params),- ("/v1/cs/configs", v1_params),- ] {+ for (path, query) in+ [("/v3/admin/cs/config", v3_params), ("/v1/cs/configs", v1_detail_params), ("/v1/cs/configs", v1_params)]+ {if !self.api_path_allowed(path) {continue;}@@ -1252,11 +1563,7 @@ impl NacosAdmin for NacosOpenApiAdmin {let (v3_form, v1_form) = build_publish_forms(req, namespace);let mut errors = Vec::new();- for (path, form) in [- ("/v3/console/cs/config", v3_form.clone()),- ("/v3/console/cs/config/publish", v3_form.clone()),- ("/v3/console/cs/config/update", v3_form),- ] {+ for (path, form) in [("/v3/admin/cs/config", v3_form)] {if !self.api_path_allowed(path) {continue;}@@ -1301,12 +1608,7 @@ impl NacosAdmin for NacosOpenApiAdmin {self.submit_query_candidates("delete Nacos config",reqwest::Method::DELETE,- vec![- ("/v3/console/cs/config", v3_query.clone()),- ("/v3/console/cs/config/delete", v3_query.clone()),- ("/v3/console/cs/config/remove", v3_query),- ("/v1/cs/configs", v1_query),- ],+ vec![("/v3/admin/cs/config", v3_query), ("/v1/cs/configs", v1_query)],).await}@@ -1335,8 +1637,7 @@ impl NacosAdmin for NacosOpenApiAdmin {.get_json_from_candidates("list Nacos config history",vec![- ("/v3/console/cs/history/list", v3_params.clone()),- ("/v3/console/cs/history", v3_params.clone()),+ ("/v3/admin/cs/history/list", v3_params),("/v1/cs/history/list", v1_params.clone()),("/v1/cs/history", v1_params.clone()),("/v1/cs/history/configs", v1_params),@@ -1390,8 +1691,7 @@ impl NacosAdmin for NacosOpenApiAdmin {.get_json_from_candidates("get Nacos config history",vec![- ("/v3/console/cs/history/detail", v3_params.clone()),- ("/v3/console/cs/history", v3_params.clone()),+ ("/v3/admin/cs/history", v3_params),("/v1/cs/history", v1_params.clone()),("/v1/cs/history/config", v1_params),],@@ -1434,15 +1734,6 @@ impl NacosAdmin for NacosOpenApiAdmin {let data_id = req.data_id.clone();let group = req.group.clone();let history_id = req.history_id.clone();- let mut v3_query = vec![- ("dataId".to_string(), req.data_id.clone()),- ("groupName".to_string(), req.group.clone()),- ("namespaceId".to_string(), namespace.clone()),- ("id".to_string(), req.history_id.clone()),- ];- if let Some(nid) = nid {- v3_query.push(("nid".to_string(), nid.to_string()));- }let mut v1_query = vec![("dataId".to_string(), req.data_id),("group".to_string(), req.group),@@ -1453,18 +1744,20 @@ impl NacosAdmin for NacosOpenApiAdmin {} else {v1_query.push(("id".to_string(), req.history_id));}- let endpoint_result = self- .submit_query_candidates(+ // The Nacos 3 Admin API exposes history reads but no rollback route.+ // Re-publishing the selected revision is the documented, deterministic+ // rollback implementation. Older compatible APIs keep their direct+ // endpoint probes below.+ let endpoint_result = if matches!(self.cfg.version_mode, Some(NacosVersionMode::V3)) {+ Err("Nacos v3 Admin API uses history read and publish for rollback".to_string())+ } else {+ self.submit_query_candidates("rollback Nacos config",reqwest::Method::POST,- vec![- ("/v3/console/cs/history/rollback", v3_query.clone()),- ("/v3/console/cs/config/history/rollback", v3_query),- ("/v1/cs/history/rollback", v1_query.clone()),- ("/v1/cs/history/config/rollback", v1_query),- ],+ vec![("/v1/cs/history/rollback", v1_query.clone()), ("/v1/cs/history/config/rollback", v1_query)],)- .await;+ .await+ };if endpoint_result.is_ok() {return Ok(());}@@ -1520,6 +1813,16 @@ impl NacosAdmin for NacosOpenApiAdmin {];push_optional(&mut v3_params, "groupNameParam", query.group_name.clone());push_optional(&mut v3_params, "serviceNameParam", query.service_name.clone());+ let requested_group = query.group_name.clone();+ let mut v2_params = vec![+ ("namespaceId".to_string(), namespace.clone()),+ ("pageNo".to_string(), page_no.to_string()),+ ("pageSize".to_string(), page_size.to_string()),+ ];+ // Nacos v2 uses the service API's field names rather than the v3+ // console list aliases (`groupNameParam` and `serviceNameParam`).+ push_optional(&mut v2_params, "groupName", query.group_name.clone());+ push_optional(&mut v2_params, "serviceName", query.service_name.clone());let mut v1_catalog_params = vec![("namespaceId".to_string(), namespace.clone()),("pageNo".to_string(), page_no.to_string()),@@ -1534,22 +1837,110 @@ impl NacosAdmin for NacosOpenApiAdmin {];push_optional(&mut v1_legacy_params, "groupName", query.group_name);push_optional(&mut v1_legacy_params, "serviceName", query.service_name);+ if self.is_rnacos_compatible() {+ // r-nacos returns only the default group from the ordinary Naming+ // list endpoint when no group is supplied. Its compatible Catalog+ // service endpoint is the management view that can enumerate+ // services across groups, just as it is for Nacos v2.+ let value = self.get_json("/v1/ns/catalog/services", v1_catalog_params).await?;+ let mut result = parse_service_list(value, page_no, page_size);+ if let Some(group_name) = requested_group.filter(|group| !group.trim().is_empty()) {+ for service in &mut result.items {+ if service.group_name.is_none() {+ service.group_name = Some(group_name.clone());+ }+ }+ }+ return Ok(result);+ }let value = self- .get_json_from_candidates(+ .get_service_json_from_candidates("list Nacos services",vec![- ("/v3/console/ns/service/list", v3_params.clone()),+ ("/v3/admin/ns/service/list", v3_params.clone()),+ // The catalog endpoint is what the Nacos v2 console uses+ // to enumerate services across every group. `/v2/ns/service/list`+ // returns a valid-but-empty response without `groupName`, which+ // must not prevent this cross-group query from being attempted.("/v1/ns/catalog/services", v1_catalog_params.clone()),- ("/v3/console/ns/service", v3_params),+ ("/v2/ns/service/list", v2_params.clone()),("/v1/ns/service/list", v1_legacy_params),],).await?;- Ok(parse_service_list(value, page_no, page_size))+ let mut result = parse_service_list(value, page_no, page_size);+ // Nacos does not include empty services in the v2 catalog response.+ // When a group is explicitly selected, query the direct v2 API as a+ // supplement so manually-created empty services remain manageable.+ if result.items.is_empty()+ && requested_group.as_deref().is_some_and(|group| !group.trim().is_empty())+ && self.api_path_allowed("/v2/ns/service/list")+ {+ if let Ok(value) = self.get_json("/v2/ns/service/list", v2_params).await {+ result = parse_service_list(value, page_no, page_size);+ }+ }+ // The v2 list API returns plain service names and omits the matched+ // group. Preserve the requested group so subsequent detail, update,+ // and instance calls address the same service identity.+ if let Some(group_name) = requested_group.filter(|group| !group.trim().is_empty()) {+ for service in &mut result.items {+ if service.group_name.is_none() {+ service.group_name = Some(group_name.clone());+ }+ }+ }+ Ok(result)+ }++ async fn get_service(&self, query: NacosServiceQuery) -> Result<NacosServiceDetail, String> {+ let namespace = self.namespace(query.namespace.as_deref());+ let service_name = query.service_name.ok_or_else(|| "Nacos service name is required".to_string())?;+ if self.is_rnacos_compatible() {+ // r-nacos reads a grouped service detail through the compatible+ // v1 endpoint, but derives the group from `serviceName` rather+ // than honoring a separate `groupName` parameter.+ let params = vec![+ ("namespaceId".to_string(), namespace),+ ("serviceName".to_string(), qualified_nacos_service_name(&service_name, query.group_name.as_deref())),+ ];+ return self.get_json("/v1/ns/service", params).await.map(parse_service_detail);+ }+ let mut params = vec![("namespaceId".to_string(), namespace), ("serviceName".to_string(), service_name)];+ push_optional(&mut params, "groupName", query.group_name);+ let value = self+ .get_service_json_from_candidates(+ "get Nacos service",+ vec![("/v3/admin/ns/service", params.clone()), ("/v1/ns/service", params)],+ )+ .await?;+ Ok(parse_service_detail(value))+ }++ async fn create_service(&self, req: NacosServiceUpsert) -> Result<(), String> {+ self.submit_service_upsert("create Nacos service", req, reqwest::Method::POST).await+ }++ async fn update_service(&self, req: NacosServiceUpsert) -> Result<(), String> {+ self.submit_service_upsert("update Nacos service", req, reqwest::Method::PUT).await+ }++ async fn delete_service(&self, query: NacosServiceQuery) -> Result<(), String> {+ let namespace = self.namespace(query.namespace.as_deref());+ let service_name = query.service_name.ok_or_else(|| "Nacos service name is required".to_string())?;+ let mut params = vec![("namespaceId".to_string(), namespace), ("serviceName".to_string(), service_name)];+ push_optional(&mut params, "groupName", query.group_name);+ self.submit_service_query_candidates(+ "delete Nacos service",+ reqwest::Method::DELETE,+ vec![("/v3/admin/ns/service", params.clone()), ("/v1/ns/service", params)],+ )+ .await}async fn list_instances(&self, query: NacosInstanceQuery) -> Result<Vec<NacosInstanceInfo>, String> {let namespace = self.namespace(query.namespace.as_deref());+ let requested_clusters = split_nacos_cluster_names(query.clusters.as_deref());let mut params = vec![("serviceName".to_string(), query.service_name.clone()),("namespaceId".to_string(), namespace.clone()),@@ -1557,69 +1948,167 @@ impl NacosAdmin for NacosOpenApiAdmin {push_optional(&mut params, "groupName", query.group_name.clone());push_optional(&mut params, "clusters", query.clusters.clone());- let mut errors = Vec::new();- for path in ["/v3/console/ns/instance/list", "/v3/console/ns/instance"] {- if !self.api_path_allowed(path) {- continue;+ if self.is_rnacos_compatible() {+ // The compatible discovery API only lists enabled instances. When+ // the optional r-nacos console has been configured, prefer its+ // authenticated management endpoint so disabled persistent+ // instances remain operable in DBX as well.+ if !self.cfg.rnacos_console_addr.is_empty() {+ match self.list_rnacos_console_instances(&query, &namespace, &requested_clusters).await {+ Ok(instances) => return Ok(instances),+ Err(error) if error.contains("[rnacosConsoleCaptchaRequired]") => return Err(error),+ // The console is optional for r-nacos. A connection,+ // permission, or version failure must not hide the+ // regular compatible discovery result.+ Err(_) => {}+ }}- match self.get_json(path, params.clone()).await {- Ok(value) => return Ok(parse_instances(value)),- Err(err) => errors.push(err),+ let value = self.get_json("/v1/ns/instance/list", params).await?;+ return Ok(filter_instances_by_clusters(parse_instances(value), &requested_clusters));+ }++ let mut errors = Vec::new();+ if self.api_path_allowed("/v3/admin/ns/instance/list") {+ match self.list_v3_admin_instances(&query, &namespace).await {+ Ok(instances) => return Ok(filter_instances_by_clusters(instances, &requested_clusters)),+ Err(err) => {+ let try_next = self.should_try_next_candidate(&err);+ errors.push(err);+ if !try_next {+ return Err(format!("Failed to list Nacos instances: {}", errors.join("; ")));+ }+ }}}+ // Nacos v2's ordinary Naming list endpoint omits disabled instances.+ // The Catalog controller is the management view and deliberately+ // includes them, so use it before v1/v2 Naming fallbacks.if self.api_path_allowed("/v1/ns/catalog/instances") {match self.list_v1_catalog_instances(&query, &namespace).await {- Ok(instances) => return Ok(instances),- Err(err) => errors.push(err),+ Ok(instances) => return Ok(filter_instances_by_clusters(instances, &requested_clusters)),+ Err(err) => {+ let try_next = self.should_try_next_candidate(&err);+ errors.push(err);+ if !try_next {+ return Err(format!("Failed to list Nacos instances: {}", errors.join("; ")));+ }+ }}}- if !self.api_path_allowed("/v1/ns/instance/list") {- return Err(format!("Failed to list Nacos instances: {}", errors.join("; ")));+ for path in ["/v1/ns/instance/list", "/v2/ns/instance/list"] {+ if !self.api_path_allowed(path) {+ continue;+ }+ match self.get_json(path, params.clone()).await {+ Ok(value) => return Ok(filter_instances_by_clusters(parse_instances(value), &requested_clusters)),+ Err(err) => {+ let try_next = self.should_try_next_candidate(&err);+ errors.push(err);+ if !try_next {+ return Err(format!("Failed to list Nacos instances: {}", errors.join("; ")));+ }+ }+ }}- match self.get_json("/v1/ns/instance/list", params).await {- Ok(value) => Ok(parse_instances(value)),- Err(err) => {- errors.push(err);- Err(format!("Failed to list Nacos instances: {}", errors.join("; ")))+ Err(format!("Failed to list Nacos instances: {}", errors.join("; ")))+ }++ async fn list_instances_for_service_delete(+ &self,+ query: NacosInstanceQuery,+ ) -> Result<Vec<NacosInstanceInfo>, String> {+ if self.is_rnacos_compatible() {+ if self.cfg.rnacos_console_addr.trim().is_empty() {+ return Err(+ "NACOS_ERROR[endpointUnavailable]: r-nacos service deletion requires a configured r-nacos console address so DBX can verify disabled instances"+ .to_string(),+ );}+ let namespace = self.namespace(query.namespace.as_deref());+ let requested_clusters = split_nacos_cluster_names(query.clusters.as_deref());+ return self.list_rnacos_console_instances(&query, &namespace, &requested_clusters).await;}+ self.list_instances(query).await}- async fn update_instance(&self, req: NacosInstanceUpdate) -> Result<(), String> {- let namespace = self.namespace(req.namespace.as_deref());- let mut form = vec![- ("serviceName".to_string(), req.service_name),- ("ip".to_string(), req.ip),- ("port".to_string(), req.port.to_string()),- ("namespaceId".to_string(), namespace),- ];- push_optional(&mut form, "groupName", req.group_name);- push_optional(&mut form, "clusterName", req.cluster_name);- if let Some(value) = req.healthy {- form.push(("healthy".to_string(), value.to_string()));+ async fn update_instance(&self, req: NacosInstanceUpdateRequest) -> Result<(), String> {+ if req.target.service_name.trim().is_empty()+ || req.target.ip.parse::<std::net::IpAddr>().is_err()+ || req.target.port == 0+ {+ return Err("Nacos instance service name, valid IP, and port are required".to_string());}- if let Some(value) = req.enabled {- form.push(("enabled".to_string(), value.to_string()));+ if req.patch.enabled.is_none()+ && req.patch.healthy.is_none()+ && req.patch.weight.is_none()+ && req.patch.metadata.is_none()+ {+ return Err("Nacos instance update patch must contain at least one field".to_string());}- if let Some(value) = req.ephemeral {- form.push(("ephemeral".to_string(), value.to_string()));+ if req.patch.weight.is_some_and(|value| !value.is_finite() || value < 0.0) {+ return Err("Nacos instance weight must be a finite number greater than or equal to 0".to_string());}- if let Some(value) = req.weight {- form.push(("weight".to_string(), value.to_string()));+ if req.patch.metadata.as_ref().is_some_and(|value| !value.is_object()) {+ return Err("Nacos instance metadata must be a JSON object".to_string());}- if let Some(value) = req.metadata {- form.push(("metadata".to_string(), value.to_string()));+ if self.api_path_allowed("/v3/admin/ns/instance/partial") {+ match self.update_v3_admin_instance(req.clone()).await {+ Ok(()) => return Ok(()),+ Err(err) if self.should_try_next_candidate(&err) => {}+ Err(err) => return Err(format!("Failed to update Nacos instance: {err}")),+ }}- self.submit_form_candidates(- "update Nacos instance",- reqwest::Method::PUT,- vec![- ("/v3/console/ns/instance", form.clone()),- ("/v3/console/ns/instance/update", form.clone()),- ("/v1/ns/instance", form),- ],+ if !self.api_path_allowed("/v1/ns/instance") {+ return Err("Failed to update Nacos instance: no compatible management endpoint is available".to_string());+ }+ let namespace = self.namespace(req.target.namespace.as_deref());+ let form = instance_update_form(namespace, req);+ let response = self.request(reqwest::Method::PUT, "/v1/ns/instance", Vec::new(), Some(form), None).await?;+ error_for_status(response, "/v1/ns/instance").await?;+ Ok(())+ }++ async fn register_instance(&self, req: NacosInstanceRegistration) -> Result<(), String> {+ if req.service_name.trim().is_empty() || req.ip.parse::<std::net::IpAddr>().is_err() || req.port == 0 {+ return Err("Nacos instance service name, valid IP, and port are required".to_string());+ }+ if req.weight.is_some_and(|value| !value.is_finite() || value < 0.0) {+ return Err("Nacos instance weight must be a finite number greater than or equal to 0".to_string());+ }+ if req.metadata.as_ref().is_some_and(|value| !value.is_object()) {+ return Err("Nacos instance metadata must be a JSON object".to_string());+ }+ let form = instance_registration_form(self.namespace(req.namespace.as_deref()), req);+ self.submit_service_form_candidates(+ "register Nacos instance",+ reqwest::Method::POST,+ vec![("/v3/admin/ns/instance", form.clone()), ("/v1/ns/instance", form)],+ )+ .await+ }++ async fn deregister_instance(&self, req: NacosInstanceRef) -> Result<(), String> {+ if req.service_name.trim().is_empty() || req.ip.parse::<std::net::IpAddr>().is_err() || req.port == 0 {+ return Err("Nacos instance service name, valid IP, and port are required".to_string());+ }+ let namespace = self.namespace(req.namespace.as_deref());+ let mut params = vec![+ ("namespaceId".to_string(), namespace),+ ("serviceName".to_string(), req.service_name),+ ("ip".to_string(), req.ip),+ ("port".to_string(), req.port.to_string()),+ ];+ push_optional(&mut params, "groupName", req.group_name);+ push_optional(&mut params, "clusterName", req.cluster_name);+ if let Some(ephemeral) = req.ephemeral {+ params.push(("ephemeral".to_string(), ephemeral.to_string()));+ }+ self.submit_service_query_candidates(+ "deregister Nacos instance",+ reqwest::Method::DELETE,+ vec![("/v3/admin/ns/instance", params.clone()), ("/v1/ns/instance", params)],).await}@@ -1794,7 +2283,10 @@ fn parse_namespaces(value: Value) -> Vec<NacosNamespaceInfo> {}}).collect();- if !namespaces.iter().any(|item| item.namespace.is_empty()) {+ // Nacos 3 reports the default namespace with the concrete `public` ID,+ // while older endpoints commonly use an empty ID. Add a synthetic default+ // only when neither representation was returned.+ if !namespaces.iter().any(|item| item.namespace.is_empty() || item.namespace == "public") {namespaces.insert(0,NacosNamespaceInfo {@@ -1943,12 +2435,6 @@ fn admin_endpoint_error(server_addr: &str, errors: &[String]) -> String {),);}- if lower.contains("410 gone") && lower.contains("/v3/console/server/state") {- return classified_error(- "apiVersionMismatch",- "Nacos v1 console API is disabled on this server. DBX already tried the v3 console state API first; please check that Server points to the Nacos console/admin URL and Context Path matches the console mount path.",- );- }classified_error(classify_nacos_error(&joined),&format!("Failed to detect Nacos admin endpoint at {server_addr}: {}", joined.trim()),@@ -2063,7 +2549,11 @@ fn classify_nacos_error(message: &str) -> &'static str {{return "unsupportedConfigHistory";}- if lower.contains("410 gone") || lower.contains("not found") || lower.contains("404") {+ if lower.contains("410 gone")+ || lower.contains("405 method not allowed")+ || lower.contains("not found")+ || lower.contains("404")+ {return "apiVersionMismatch";}if lower.contains("connection refused")@@ -2323,6 +2813,80 @@ fn parse_service_list(value: Value, page_no: u32, page_size: u32) -> NacosServicNacosServiceList { page_no, page_size, total_count, items }}+fn parse_service_detail(value: Value) -> NacosServiceDetail {+ let data = value.get("data").unwrap_or(&value);+ let raw_name = string_field(data, &["name", "serviceName"]);+ let (embedded_group_name, service_name) = split_nacos_service_name(&raw_name);+ NacosServiceDetail {+ service_name,+ group_name: optional_string_field(data, &["groupName"]).or(embedded_group_name),+ metadata: data.get("metadata").cloned().unwrap_or(Value::Null),+ protect_threshold: data.get("protectThreshold").and_then(Value::as_f64),+ selector: data.get("selector").cloned().filter(|value| !value.is_null()),+ ephemeral: data.get("ephemeral").and_then(Value::as_bool),+ }+}++fn instance_ref_form(namespace: String, target: NacosInstanceRef) -> Vec<(String, String)> {+ let mut form = vec![+ ("serviceName".to_string(), target.service_name),+ ("ip".to_string(), target.ip),+ ("port".to_string(), target.port.to_string()),+ ("namespaceId".to_string(), namespace),+ ];+ push_optional(&mut form, "groupName", target.group_name);+ push_optional(&mut form, "clusterName", target.cluster_name);+ if let Some(value) = target.ephemeral {+ form.push(("ephemeral".to_string(), value.to_string()));+ }+ form+}++fn instance_update_form(namespace: String, req: NacosInstanceUpdateRequest) -> Vec<(String, String)> {+ let mut form = instance_ref_form(namespace, req.target);+ if let Some(value) = req.patch.healthy {+ form.push(("healthy".to_string(), value.to_string()));+ }+ if let Some(value) = req.patch.enabled {+ form.push(("enabled".to_string(), value.to_string()));+ }+ if let Some(value) = req.patch.weight {+ if value.is_finite() && value >= 0.0 {+ form.push(("weight".to_string(), value.to_string()));+ }+ }+ if let Some(value) = req.patch.metadata {+ if value.is_object() {+ form.push(("metadata".to_string(), value.to_string()));+ }+ }+ form+}++fn instance_registration_form(namespace: String, req: NacosInstanceRegistration) -> Vec<(String, String)> {+ let target = NacosInstanceRef {+ namespace: req.namespace,+ service_name: req.service_name,+ ip: req.ip,+ port: req.port,+ group_name: req.group_name,+ cluster_name: req.cluster_name,+ ephemeral: Some(false),+ };+ let mut form = instance_ref_form(namespace, target);+ if let Some(value) = req.weight {+ if value.is_finite() && value >= 0.0 {+ form.push(("weight".to_string(), value.to_string()));+ }+ }+ if let Some(value) = req.metadata {+ if value.is_object() {+ form.push(("metadata".to_string(), value.to_string()));+ }+ }+ form+}+fn split_nacos_service_name(value: &str) -> (Option<String>, String) {let trimmed = value.trim();if let Some((group, name)) = trimmed.split_once("@@") {@@ -2347,17 +2911,63 @@ fn split_nacos_cluster_names(value: Option<&str>) -> Vec<String> {.collect()}+fn filter_instances_by_clusters(+ instances: Vec<NacosInstanceInfo>,+ requested_clusters: &[String],+) -> Vec<NacosInstanceInfo> {+ if requested_clusters.is_empty() {+ return instances;+ }+ instances+ .into_iter()+ .filter(|instance| {+ instance+ .cluster_name+ .as_deref()+ .is_some_and(|cluster| requested_clusters.iter().any(|requested| requested == cluster))+ })+ .collect()+}++fn deduplicate_management_instances(+ mut instances: Vec<NacosInstanceInfo>,+ namespace: &str,+ group_name: Option<&str>,+ service_name: &str,+) -> Vec<NacosInstanceInfo> {+ let mut seen = HashSet::new();+ let default_group = group_name.unwrap_or("DEFAULT_GROUP").to_string();+ let service_name = service_name.to_string();+ instances.retain(|instance| {+ seen.insert((+ namespace,+ instance.group_name.clone().unwrap_or_else(|| default_group.clone()),+ instance.service_name.clone().unwrap_or_else(|| service_name.clone()),+ instance.ip.clone(),+ instance.port,+ instance.cluster_name.clone(),+ instance.ephemeral,+ ))+ });+ instances+}+fn parse_catalog_cluster_names(value: &Value) -> Vec<String> {let data = value.get("data").unwrap_or(value);let mut seen = HashSet::new();- data.get("clusters")+ let mut names: Vec<String> = data+ .get("clusters").or_else(|| value.get("clusters")).and_then(Value::as_array).into_iter().flatten().filter_map(|cluster| optional_string_field(cluster, &["name", "clusterName"])).filter(|name| seen.insert(name.clone()))- .collect()+ .collect();+ if let Some(cluster_map) = data.get("clusterMap").and_then(Value::as_object) {+ names.extend(cluster_map.keys().filter(|name| seen.insert((*name).clone())).cloned());+ }+ names}fn catalog_instance_count(value: &Value) -> Option<u64> {@@ -2372,7 +2982,8 @@ fn catalog_instance_count(value: &Value) -> Option<u64> {fn parse_instances(value: Value) -> Vec<NacosInstanceInfo> {let data = value.get("data").unwrap_or(&value);- data.get("hosts")+ let items = data+ .get("hosts").or_else(|| data.get("instances")).or_else(|| data.get("list")).or_else(|| data.get("pageItems"))@@ -2382,23 +2993,33 @@ fn parse_instances(value: Value) -> Vec<NacosInstanceInfo> {.or_else(|| value.get("list")).and_then(Value::as_array).cloned()- .unwrap_or_default()+ // Nacos 3 Naming Admin returns `data` as the instance array directly,+ // unlike the v1/v2 `hosts` and Catalog `list` wrappers.+ .or_else(|| data.as_array().cloned())+ .or_else(|| data.is_object().then(|| vec![data.clone()]))+ .unwrap_or_default();+ items.into_iter()- .map(|item| NacosInstanceInfo {- ip: string_field(&item, &["ip"]),- port: item.get("port").and_then(Value::as_u64).unwrap_or(0) as u16,- service_name: optional_string_field(&item, &["serviceName"]),- cluster_name: optional_string_field(&item, &["clusterName"]),- group_name: optional_string_field(&item, &["groupName"]),- healthy: item.get("healthy").and_then(Value::as_bool),- enabled: item.get("enabled").and_then(Value::as_bool),- ephemeral: item.get("ephemeral").and_then(Value::as_bool),- weight: item.get("weight").and_then(Value::as_f64),- metadata: item.get("metadata").cloned().unwrap_or(Value::Null),- })+ .filter(|item| item.get("ip").is_some() && item.get("port").is_some())+ .map(parse_instance).collect()}+fn parse_instance(item: Value) -> NacosInstanceInfo {+ NacosInstanceInfo {+ ip: string_field(&item, &["ip"]),+ port: item.get("port").and_then(Value::as_u64).unwrap_or(0) as u16,+ service_name: optional_string_field(&item, &["serviceName"]),+ cluster_name: optional_string_field(&item, &["clusterName"]),+ group_name: optional_string_field(&item, &["groupName"]),+ healthy: item.get("healthy").and_then(Value::as_bool),+ enabled: item.get("enabled").and_then(Value::as_bool),+ ephemeral: item.get("ephemeral").and_then(Value::as_bool),+ weight: item.get("weight").and_then(Value::as_f64),+ metadata: item.get("metadata").cloned().unwrap_or(Value::Null),+ }+}+fn string_field(value: &Value, keys: &[&str]) -> String {optional_string_field(value, keys).unwrap_or_default()}@@ -2412,6 +3033,7 @@ fn optional_string_field(value: &Value, keys: &[&str]) -> Option<String> {.map(str::to_string).or_else(|| value.as_i64().map(|v| v.to_string())).or_else(|| value.as_u64().map(|v| v.to_string()))+ .or_else(|| value.as_bool().map(|v| v.to_string()))}).filter(|value| !value.is_empty())}@@ -2625,35 +3247,578 @@ mod tests {}#[tokio::test]- async fn version_mode_v2_uses_only_v1_config_paths() {+ async fn version_mode_v2_uses_only_v1_config_paths() {+ let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();+ let address = listener.local_addr().unwrap();+ let server = tokio::spawn(async move {+ let (mut socket, _) = listener.accept().await.unwrap();+ assert!(read_request_target(&mut socket).await.starts_with("/nacos/v1/cs/configs?"));+ write_json_response(&mut socket, r#"{"totalCount":0,"pageItems":[]}"#).await;+ });+ let mut config = test_admin_config(format!("http://{address}"));+ config.context_path = "/nacos".to_string();+ config.version_mode = Some(NacosVersionMode::V2);+ let admin = NacosOpenApiAdmin::new(config).unwrap();++ admin.get_config_list_value("", "", "", "", 1, 20).await.unwrap();+ server.await.unwrap();+ }++ #[test]+ fn explicit_v3_rejects_legacy_admin_api_paths() {+ let mut config = test_admin_config("http://127.0.0.1:8848".to_string());+ config.version_mode = Some(NacosVersionMode::V3);+ let admin = NacosOpenApiAdmin::new(config).unwrap();++ assert!(admin.api_path_allowed("/v3/admin/ns/ops/metrics"));+ assert!(admin.api_path_allowed("/health"));+ assert!(!admin.api_path_allowed("/v3/console/cs/config/list"));+ assert!(!admin.api_path_allowed("/v2/ns/operator/metrics"));+ assert!(!admin.api_path_allowed("/v1/ns/operator/metrics"));+ }++ #[tokio::test]+ async fn service_upsert_normalizes_empty_selector() {+ let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();+ let address = listener.local_addr().unwrap();+ let server = tokio::spawn(async move {+ let (mut socket, _) = listener.accept().await.unwrap();+ let request = read_http_request(&mut socket).await;+ assert!(request.starts_with("POST /nacos/v1/ns/service HTTP/1.1"));+ assert!(request.contains("selector="));+ assert!(request.contains("%22type%22%3A%22none%22"));+ write_json_response(&mut socket, r#"{"code":200,"message":"ok"}"#).await;+ });+ let mut config = test_admin_config(format!("http://{address}"));+ config.context_path = "/nacos".to_string();+ config.version_mode = Some(NacosVersionMode::V2);+ let admin = NacosOpenApiAdmin::new(config).unwrap();++ admin+ .create_service(NacosServiceUpsert {+ namespace: Some("public".to_string()),+ service_name: "dbx-e2e".to_string(),+ group_name: Some("DEFAULT_GROUP".to_string()),+ metadata: Some(serde_json::json!({})),+ protect_threshold: Some(0.3),+ selector: Some(serde_json::json!({})),+ ephemeral: None,+ })+ .await+ .unwrap();+ server.await.unwrap();+ }++ #[tokio::test]+ async fn v2_instance_update_uses_v1_naming_api() {+ let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();+ let address = listener.local_addr().unwrap();+ let server = tokio::spawn(async move {+ let (mut socket, _) = listener.accept().await.unwrap();+ let request = read_http_request(&mut socket).await;+ assert!(request.starts_with("PUT /nacos/v1/ns/instance HTTP/1.1"));+ assert!(request.contains("weight=2.5"));+ assert!(request.contains("ephemeral=false"));+ write_json_response(&mut socket, r#"{"code":200,"message":"ok"}"#).await;+ });+ let mut config = test_admin_config(format!("http://{address}"));+ config.context_path = "/nacos".to_string();+ config.version_mode = Some(NacosVersionMode::V2);+ let admin = NacosOpenApiAdmin::new(config).unwrap();++ admin+ .update_instance(NacosInstanceUpdateRequest {+ target: NacosInstanceRef {+ namespace: Some("public".to_string()),+ service_name: "dbx-e2e".to_string(),+ ip: "127.0.0.1".to_string(),+ port: 19001,+ group_name: Some("DBX_E2E".to_string()),+ cluster_name: Some("blue".to_string()),+ ephemeral: Some(false),+ },+ patch: NacosInstancePatch { weight: Some(2.5), ..Default::default() },+ })+ .await+ .unwrap();+ server.await.unwrap();+ }++ #[tokio::test]+ async fn v3_instance_update_uses_partial_patch_endpoint() {+ let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();+ let address = listener.local_addr().unwrap();+ let server = tokio::spawn(async move {+ let (mut socket, _) = listener.accept().await.unwrap();+ let request = read_http_request(&mut socket).await;+ assert!(request.starts_with("PUT /nacos/v3/admin/ns/instance/partial HTTP/1.1"));+ assert!(request.contains("serviceName=dbx-e2e"));+ assert!(request.contains("groupName=DBX_E2E"));+ assert!(request.contains("clusterName=blue"));+ assert!(request.contains("ip=127.0.0.1"));+ assert!(request.contains("port=19001"));+ assert!(request.contains("enabled=false"));+ assert!(request.contains("ephemeral=false"));+ assert!(!request.contains("healthy="));+ assert!(!request.contains("weight="));+ assert!(!request.contains("metadata="));+ write_json_response(&mut socket, r#"{"code":0,"message":"success","data":"ok"}"#).await;+ });+ let mut config = test_admin_config(format!("http://{address}"));+ config.context_path = "/nacos".to_string();+ config.version_mode = Some(NacosVersionMode::V3);+ let admin = NacosOpenApiAdmin::new(config).unwrap();++ admin+ .update_instance(NacosInstanceUpdateRequest {+ target: NacosInstanceRef {+ namespace: Some("public".to_string()),+ service_name: "dbx-e2e".to_string(),+ ip: "127.0.0.1".to_string(),+ port: 19001,+ group_name: Some("DBX_E2E".to_string()),+ cluster_name: Some("blue".to_string()),+ ephemeral: Some(false),+ },+ patch: NacosInstancePatch { enabled: Some(false), ..Default::default() },+ })+ .await+ .unwrap();+ server.await.unwrap();+ }++ #[tokio::test]+ async fn v3_service_and_instance_lists_use_documented_naming_admin_routes() {+ let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();+ let address = listener.local_addr().unwrap();+ let server = tokio::spawn(async move {+ let (mut service_socket, _) = listener.accept().await.unwrap();+ let service_target = read_request_target(&mut service_socket).await;+ let service_url = reqwest::Url::parse(&format!("http://localhost{service_target}")).unwrap();+ assert_eq!(service_url.path(), "/nacos/v3/admin/ns/service/list");+ let service_params = service_url.query_pairs().collect::<HashMap<_, _>>();+ assert_eq!(service_params.get("groupNameParam").map(|value| value.as_ref()), Some("DBX_E2E"));+ write_json_response(+ &mut service_socket,+ r#"{"code":0,"message":"success","data":{"totalCount":1,"pageNumber":1,"pagesAvailable":1,"pageItems":[{"name":"dbx-e2e","groupName":"DBX_E2E","clusterCount":1,"ipCount":2,"healthyInstanceCount":1,"triggerFlag":"false"}]}}"#,+ )+ .await;++ let (mut detail_socket, _) = listener.accept().await.unwrap();+ let detail_target = read_request_target(&mut detail_socket).await;+ let detail_url = reqwest::Url::parse(&format!("http://localhost{detail_target}")).unwrap();+ assert_eq!(detail_url.path(), "/nacos/v3/admin/ns/service");+ write_json_response(+ &mut detail_socket,+ r#"{"code":0,"message":"success","data":{"clusterMap":{"blue":{"clusterName":"blue"},"green":{"clusterName":"green"}}}}"#,+ )+ .await;++ let (mut instance_socket, _) = listener.accept().await.unwrap();+ let instance_target = read_request_target(&mut instance_socket).await;+ let instance_url = reqwest::Url::parse(&format!("http://localhost{instance_target}")).unwrap();+ assert_eq!(instance_url.path(), "/nacos/v3/admin/ns/instance/list");+ let instance_params = instance_url.query_pairs().collect::<HashMap<_, _>>();+ assert_eq!(instance_params.get("serviceName").map(|value| value.as_ref()), Some("dbx-e2e"));+ assert_eq!(instance_params.get("clusterName").map(|value| value.as_ref()), Some("blue"));+ write_json_response(+ &mut instance_socket,+ r#"{"code":0,"message":"success","data":[{"ip":"127.0.0.1","port":19001,"clusterName":"blue","ephemeral":false,"enabled":true,"healthy":true,"weight":1.0}]}"#,+ )+ .await;++ let (mut green_socket, _) = listener.accept().await.unwrap();+ let green_target = read_request_target(&mut green_socket).await;+ let green_url = reqwest::Url::parse(&format!("http://localhost{green_target}")).unwrap();+ assert_eq!(green_url.path(), "/nacos/v3/admin/ns/instance/list");+ let green_params = green_url.query_pairs().collect::<HashMap<_, _>>();+ assert_eq!(green_params.get("clusterName").map(|value| value.as_ref()), Some("green"));+ write_json_response(+ &mut green_socket,+ r#"{"code":0,"message":"success","data":[{"ip":"127.0.0.1","port":19002,"clusterName":"green","ephemeral":false,"enabled":false,"healthy":false,"weight":0.5}]}"#,+ )+ .await;+ });+ let mut config = test_admin_config(format!("http://{address}"));+ config.context_path = "/nacos".to_string();+ config.version_mode = Some(NacosVersionMode::V3);+ let admin = NacosOpenApiAdmin::new(config).unwrap();++ let services = admin+ .list_services(NacosServiceQuery {+ namespace: Some("public".to_string()),+ group_name: Some("DBX_E2E".to_string()),+ service_name: None,+ page_no: Some(1),+ page_size: Some(20),+ })+ .await+ .unwrap();+ assert_eq!(services.items.len(), 1);++ let instances = admin+ .list_instances(NacosInstanceQuery {+ namespace: Some("public".to_string()),+ service_name: "dbx-e2e".to_string(),+ group_name: Some("DBX_E2E".to_string()),+ clusters: None,+ })+ .await+ .unwrap();+ assert_eq!(instances.len(), 2);+ assert_eq!(instances[1].enabled, Some(false));+ server.await.unwrap();+ }++ #[tokio::test]+ async fn v3_empty_service_instance_list_returns_empty_without_inventing_a_default_cluster() {+ let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();+ let address = listener.local_addr().unwrap();+ let server = tokio::spawn(async move {+ let (mut socket, _) = listener.accept().await.unwrap();+ let target = read_request_target(&mut socket).await;+ let url = reqwest::Url::parse(&format!("http://localhost{target}")).unwrap();+ assert_eq!(url.path(), "/nacos/v3/admin/ns/service");+ write_json_response(&mut socket, r#"{"code":0,"message":"success","data":{"clusterMap":{}}}"#).await;+ });+ let mut config = test_admin_config(format!("http://{address}"));+ config.context_path = "/nacos".to_string();+ config.version_mode = Some(NacosVersionMode::V3);+ let admin = NacosOpenApiAdmin::new(config).unwrap();++ let instances = admin+ .list_instances(NacosInstanceQuery {+ namespace: Some("public".to_string()),+ service_name: "custom-cluster-service".to_string(),+ group_name: Some("DBX_V3".to_string()),+ clusters: None,+ })+ .await+ .unwrap();+ assert!(instances.is_empty());+ server.await.unwrap();+ }++ #[tokio::test]+ async fn v2_service_list_uses_catalog_to_enumerate_groups() {+ let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();+ let address = listener.local_addr().unwrap();+ let server = tokio::spawn(async move {+ let (mut socket, _) = listener.accept().await.unwrap();+ let target = read_request_target(&mut socket).await;+ let url = reqwest::Url::parse(&format!("http://localhost{target}")).unwrap();+ let params = url.query_pairs().collect::<HashMap<_, _>>();+ assert_eq!(url.path(), "/nacos/v1/ns/catalog/services");+ assert_eq!(params.get("groupNameParam").map(|value| value.as_ref()), Some("DBX_CURL"));+ write_json_response(+ &mut socket,+ r#"{"count":1,"serviceList":[{"name":"dbx-curl-e2e","groupName":"DBX_CURL","clusterCount":1,"ipCount":1}]}"#,+ )+ .await;+ });+ let mut config = test_admin_config(format!("http://{address}"));+ config.context_path = "/nacos".to_string();+ config.version_mode = Some(NacosVersionMode::V2);+ let admin = NacosOpenApiAdmin::new(config).unwrap();++ let result = admin+ .list_services(NacosServiceQuery {+ namespace: Some("public".to_string()),+ service_name: None,+ group_name: Some("DBX_CURL".to_string()),+ page_no: Some(1),+ page_size: Some(100),+ })+ .await+ .unwrap();+ assert_eq!(result.items.len(), 1);+ assert_eq!(result.items[0].service_name, "dbx-curl-e2e");+ assert_eq!(result.items[0].group_name.as_deref(), Some("DBX_CURL"));+ server.await.unwrap();+ }++ #[tokio::test]+ async fn rnacos_service_list_uses_catalog_without_a_v3_admin_probe() {+ let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();+ let address = listener.local_addr().unwrap();+ let server = tokio::spawn(async move {+ let (mut socket, _) = listener.accept().await.unwrap();+ let target = read_request_target(&mut socket).await;+ let url = reqwest::Url::parse(&format!("http://localhost{target}")).unwrap();+ let params = url.query_pairs().collect::<HashMap<_, _>>();+ assert_eq!(url.path(), "/nacos/v1/ns/catalog/services");+ assert_eq!(params.get("groupNameParam").map(|value| value.as_ref()), Some("DBX_RNACOS"));+ write_json_response(+ &mut socket,+ r#"{"count":1,"serviceList":[{"name":"dbx-demo-api","groupName":"DBX_RNACOS"}]}"#,+ )+ .await;+ });+ let mut config = test_admin_config(format!("http://{address}"));+ config.context_path = "/nacos".to_string();+ config.implementation = Some(NacosImplementation::RNacos);+ let admin = NacosOpenApiAdmin::new(config).unwrap();++ let result = admin+ .list_services(NacosServiceQuery {+ namespace: Some("public".to_string()),+ service_name: None,+ group_name: Some("DBX_RNACOS".to_string()),+ page_no: Some(1),+ page_size: Some(100),+ })+ .await+ .unwrap();+ assert_eq!(result.items.len(), 1);+ assert_eq!(result.items[0].service_name, "dbx-demo-api");+ assert_eq!(result.items[0].group_name.as_deref(), Some("DBX_RNACOS"));+ server.await.unwrap();+ }++ #[tokio::test]+ async fn rnacos_instance_list_uses_v1_naming_without_catalog_or_v3_probes() {+ let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();+ let address = listener.local_addr().unwrap();+ let server = tokio::spawn(async move {+ let (mut socket, _) = listener.accept().await.unwrap();+ let target = read_request_target(&mut socket).await;+ let url = reqwest::Url::parse(&format!("http://localhost{target}")).unwrap();+ assert_eq!(url.path(), "/nacos/v1/ns/instance/list");+ write_json_response(+ &mut socket,+ r#"{"hosts":[{"ip":"127.0.0.1","port":19201,"clusterName":"blue","healthy":true,"enabled":true,"ephemeral":false}]}"#,+ )+ .await;+ });+ let mut config = test_admin_config(format!("http://{address}"));+ config.context_path = "/nacos".to_string();+ config.implementation = Some(NacosImplementation::RNacos);+ let admin = NacosOpenApiAdmin::new(config).unwrap();++ let instances = admin+ .list_instances(NacosInstanceQuery {+ namespace: Some("public".to_string()),+ service_name: "dbx-demo-api".to_string(),+ group_name: Some("DBX_RNACOS".to_string()),+ clusters: None,+ })+ .await+ .unwrap();+ assert_eq!(instances.len(), 1);+ assert_eq!(instances[0].port, 19201);+ server.await.unwrap();+ }++ #[tokio::test]+ async fn rnacos_console_instance_list_includes_disabled_instances() {+ let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();+ let address = listener.local_addr().unwrap();+ let server = tokio::spawn(async move {+ let (mut socket, _) = listener.accept().await.unwrap();+ let request = read_http_request(&mut socket).await;+ let target = request.split_whitespace().nth(1).unwrap();+ let url = reqwest::Url::parse(&format!("http://localhost{target}")).unwrap();+ let params = url.query_pairs().collect::<HashMap<_, _>>();+ assert_eq!(url.path(), "/rnacos/api/console/v2/instance/list");+ assert_eq!(params.get("namespaceId").map(|value| value.as_ref()), Some("public"));+ assert_eq!(params.get("groupName").map(|value| value.as_ref()), Some("DBX_RNACOS"));+ assert_eq!(params.get("serviceName").map(|value| value.as_ref()), Some("dbx-demo-api"));+ assert!(request.to_ascii_lowercase().contains("\ntoken: console-token\r"));+ write_json_response(+ &mut socket,+ r#"{"success":true,"data":{"totalCount":3,"list":[{"ip":"127.0.0.1","port":19201,"clusterName":"blue","healthy":true,"enabled":true,"ephemeral":false},{"ip":"127.0.0.1","port":19202,"clusterName":"green","healthy":true,"enabled":true,"ephemeral":false},{"ip":"127.0.0.1","port":19203,"clusterName":"green-shadow","healthy":true,"enabled":false,"ephemeral":false}]}}"#,+ )+ .await;+ });+ let mut config = test_admin_config(format!("http://{address}"));+ config.context_path = "/nacos".to_string();+ config.implementation = Some(NacosImplementation::RNacos);+ config.rnacos_console_addr = format!("http://{address}");+ config.auth =+ NacosAuthConfig::UsernamePassword { username: "admin".to_string(), password: "admin".to_string() };+ let admin = NacosOpenApiAdmin::new(config).unwrap();+ admin.rnacos_console_session.lock().await.token = Some(RNacosConsoleToken {+ token: "console-token".to_string(),+ expires_at: Instant::now() + Duration::from_secs(300),+ });++ let instances = admin+ .list_instances(NacosInstanceQuery {+ namespace: Some("public".to_string()),+ service_name: "dbx-demo-api".to_string(),+ group_name: Some("DBX_RNACOS".to_string()),+ clusters: None,+ })+ .await+ .unwrap();+ assert_eq!(instances.len(), 3);+ assert!(instances.iter().any(|instance| instance.port == 19203 && instance.enabled == Some(false)));+ server.await.unwrap();+ }++ #[tokio::test]+ async fn rnacos_service_and_instance_crud_use_only_compatible_v1_routes() {+ let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();+ let address = listener.local_addr().unwrap();+ let server = tokio::spawn(async move {+ for (method, path) in [+ ("POST", "/nacos/v1/ns/service"),+ ("PUT", "/nacos/v1/ns/service"),+ ("DELETE", "/nacos/v1/ns/service?"),+ ("PUT", "/nacos/v1/ns/instance"),+ ("POST", "/nacos/v1/ns/instance"),+ ("DELETE", "/nacos/v1/ns/instance?"),+ ] {+ let (mut socket, _) = listener.accept().await.unwrap();+ let request = read_http_request(&mut socket).await;+ let request_line = request.lines().next().unwrap();+ assert!(request_line.starts_with(&format!("{method} {path}")), "unexpected request: {request_line}");+ assert!(!request_line.contains("/v3/"));+ write_text_response(&mut socket, "ok").await;+ }+ });+ let mut config = test_admin_config(format!("http://{address}"));+ config.context_path = "/nacos".to_string();+ config.implementation = Some(NacosImplementation::RNacos);+ let admin = NacosOpenApiAdmin::new(config).unwrap();+ let service = NacosServiceUpsert {+ namespace: Some("public".to_string()),+ service_name: "dbx-rnacos-crud".to_string(),+ group_name: Some("DBX_RNACOS".to_string()),+ metadata: Some(serde_json::json!({ "managed-by": "dbx" })),+ protect_threshold: Some(0.2),+ selector: None,+ ephemeral: None,+ };+ admin.create_service(service.clone()).await.unwrap();+ admin.update_service(service.clone()).await.unwrap();+ admin+ .delete_service(NacosServiceQuery {+ namespace: Some("public".to_string()),+ service_name: Some(service.service_name.clone()),+ group_name: service.group_name.clone(),+ page_no: None,+ page_size: None,+ })+ .await+ .unwrap();++ let target = NacosInstanceRef {+ namespace: Some("public".to_string()),+ service_name: service.service_name.clone(),+ group_name: service.group_name.clone(),+ ip: "127.0.0.1".to_string(),+ port: 19299,+ cluster_name: Some("manual".to_string()),+ ephemeral: Some(false),+ };+ admin+ .update_instance(NacosInstanceUpdateRequest {+ target: target.clone(),+ patch: NacosInstancePatch { enabled: Some(false), ..Default::default() },+ })+ .await+ .unwrap();+ admin+ .register_instance(NacosInstanceRegistration {+ namespace: target.namespace.clone(),+ service_name: target.service_name.clone(),+ group_name: target.group_name.clone(),+ ip: target.ip.clone(),+ port: target.port,+ cluster_name: target.cluster_name.clone(),+ weight: Some(1.0),+ metadata: Some(serde_json::json!({ "managed-by": "dbx" })),+ })+ .await+ .unwrap();+ admin.deregister_instance(target).await.unwrap();+ server.await.unwrap();+ }++ #[tokio::test]+ async fn rnacos_service_detail_embeds_the_group_in_the_service_name() {+ let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();+ let address = listener.local_addr().unwrap();+ let server = tokio::spawn(async move {+ let (mut socket, _) = listener.accept().await.unwrap();+ let target = read_request_target(&mut socket).await;+ let url = reqwest::Url::parse(&format!("http://localhost{target}")).unwrap();+ let params = url.query_pairs().collect::<HashMap<_, _>>();+ assert_eq!(url.path(), "/nacos/v1/ns/service");+ assert_eq!(params.get("serviceName").map(|value| value.as_ref()), Some("DBX_RNACOS@@dbx-demo-api"));+ assert!(!params.contains_key("groupName"));+ write_json_response(+ &mut socket,+ r#"{"namespaceId":"public","groupName":"DBX_RNACOS","name":"dbx-demo-api","metadata":{},"selector":{"type":"none","contextType":"NONE"}}"#,+ )+ .await;+ });+ let mut config = test_admin_config(format!("http://{address}"));+ config.context_path = "/nacos".to_string();+ config.implementation = Some(NacosImplementation::RNacos);+ let admin = NacosOpenApiAdmin::new(config).unwrap();++ let detail = admin+ .get_service(NacosServiceQuery {+ namespace: Some("public".to_string()),+ service_name: Some("dbx-demo-api".to_string()),+ group_name: Some("DBX_RNACOS".to_string()),+ page_no: None,+ page_size: None,+ })+ .await+ .unwrap();+ assert_eq!(detail.service_name, "dbx-demo-api");+ assert_eq!(detail.group_name.as_deref(), Some("DBX_RNACOS"));+ server.await.unwrap();+ }++ #[tokio::test]+ async fn v2_service_list_uses_group_api_for_empty_service() {let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();let address = listener.local_addr().unwrap();let server = tokio::spawn(async move {let (mut socket, _) = listener.accept().await.unwrap();- assert!(read_request_target(&mut socket).await.starts_with("/nacos/v1/cs/configs?"));- write_json_response(&mut socket, r#"{"totalCount":0,"pageItems":[]}"#).await;+ let target = read_request_target(&mut socket).await;+ let url = reqwest::Url::parse(&format!("http://localhost{target}")).unwrap();+ assert_eq!(url.path(), "/nacos/v1/ns/catalog/services");+ write_json_response(&mut socket, r#"{"count":0,"serviceList":[]}"#).await;++ let (mut socket, _) = listener.accept().await.unwrap();+ let target = read_request_target(&mut socket).await;+ let url = reqwest::Url::parse(&format!("http://localhost{target}")).unwrap();+ let params = url.query_pairs().collect::<HashMap<_, _>>();+ assert_eq!(url.path(), "/nacos/v2/ns/service/list");+ assert_eq!(params.get("groupName").map(|value| value.as_ref()), Some("DBX_CURL"));+ assert!(!params.contains_key("groupNameParam"));+ write_json_response(+ &mut socket,+ r#"{"code":0,"message":"success","data":{"count":1,"services":["dbx-empty-e2e"]}}"#,+ )+ .await;});let mut config = test_admin_config(format!("http://{address}"));config.context_path = "/nacos".to_string();config.version_mode = Some(NacosVersionMode::V2);let admin = NacosOpenApiAdmin::new(config).unwrap();- admin.get_config_list_value("", "", "", "", 1, 20).await.unwrap();+ let result = admin+ .list_services(NacosServiceQuery {+ namespace: Some("public".to_string()),+ service_name: None,+ group_name: Some("DBX_CURL".to_string()),+ page_no: Some(1),+ page_size: Some(100),+ })+ .await+ .unwrap();+ assert_eq!(result.items.len(), 1);+ assert_eq!(result.items[0].service_name, "dbx-empty-e2e");+ assert_eq!(result.items[0].group_name.as_deref(), Some("DBX_CURL"));server.await.unwrap();}- #[test]- fn explicit_v3_rejects_legacy_admin_api_paths() {- let mut config = test_admin_config("http://127.0.0.1:8848".to_string());- config.version_mode = Some(NacosVersionMode::V3);- let admin = NacosOpenApiAdmin::new(config).unwrap();-- assert!(admin.api_path_allowed("/v3/admin/ns/ops/metrics"));- assert!(admin.api_path_allowed("/health"));- assert!(!admin.api_path_allowed("/v2/ns/operator/metrics"));- assert!(!admin.api_path_allowed("/v1/ns/operator/metrics"));- }-#[test]fn compacts_html_error_pages_in_admin_warnings() {assert_eq!(@@ -2766,7 +3931,7 @@ mod tests {let address = listener.local_addr().unwrap();let server = tokio::spawn(async move {let (mut socket, _) = listener.accept().await.unwrap();- assert!(read_request_target(&mut socket).await.starts_with("/nacos/v3/console/cs/config/list?"));+ assert!(read_request_target(&mut socket).await.starts_with("/nacos/v3/admin/cs/config/list?"));write_json_response(&mut socket, r#"{"totalCount":0,"pageItems":[]}"#).await;});let mut config = test_admin_config(format!("http://{address}"));@@ -2779,15 +3944,16 @@ mod tests {}#[tokio::test]- async fn v3_console_namespace_creation_uses_custom_namespace_id() {+ async fn v3_admin_namespace_creation_uses_namespace_id() {let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();let address = listener.local_addr().unwrap();let server = tokio::spawn(async move {let (mut socket, _) = listener.accept().await.unwrap();let request = read_http_request(&mut socket).await;assert_eq!(request.split_whitespace().next(), Some("POST"));- assert_eq!(request.split_whitespace().nth(1), Some("/nacos/v3/console/core/namespace"));- assert!(request.contains("customNamespaceId=team-dev"));+ assert_eq!(request.split_whitespace().nth(1), Some("/nacos/v3/admin/core/namespace"));+ assert!(request.contains("namespaceId=team-dev"));+ assert!(!request.contains("customNamespaceId="));write_json_response(&mut socket, r#"{"code":0,"message":"success","data":true}"#).await;});let mut config = test_admin_config(format!("http://{address}"));@@ -2806,6 +3972,51 @@ mod tests {server.await.unwrap();}+ #[tokio::test]+ async fn v3_connection_check_uses_only_admin_core_and_naming_endpoints() {+ let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();+ let address = listener.local_addr().unwrap();+ let server = tokio::spawn(async move {+ let (mut state_socket, _) = listener.accept().await.unwrap();+ assert_eq!(read_request_target(&mut state_socket).await, "/nacos/v3/admin/core/state");+ write_json_response(&mut state_socket, r#"{"version":"3.1.0","auth_enabled":"false"}"#).await;++ let (mut namespaces_socket, _) = listener.accept().await.unwrap();+ assert_eq!(read_request_target(&mut namespaces_socket).await, "/nacos/v3/admin/core/namespace/list");+ write_json_response(+ &mut namespaces_socket,+ r#"{"code":0,"message":"success","data":[{"namespace":"public","namespaceShowName":"public"}]}"#,+ )+ .await;++ let (mut services_socket, _) = listener.accept().await.unwrap();+ let target = read_request_target(&mut services_socket).await;+ assert!(target.starts_with("/nacos/v3/admin/ns/service/list?"));+ write_json_response(+ &mut services_socket,+ r#"{"code":0,"message":"success","data":{"totalCount":0,"pageItems":[]}}"#,+ )+ .await;++ let (mut configs_socket, _) = listener.accept().await.unwrap();+ let target = read_request_target(&mut configs_socket).await;+ assert!(target.starts_with("/nacos/v3/admin/cs/config/list?"));+ write_json_response(+ &mut configs_socket,+ r#"{"code":0,"message":"success","data":{"totalCount":0,"pageItems":[]}}"#,+ )+ .await;+ });+ let mut config = test_admin_config(format!("http://{address}"));+ config.context_path = "/nacos".to_string();+ config.version_mode = Some(NacosVersionMode::V3);+ let admin = NacosOpenApiAdmin::new(config).unwrap();++ let info = admin.test_connection().await.unwrap();+ assert_eq!(info.server_version.as_deref(), Some("3.1.0"));+ server.await.unwrap();+ }+#[tokio::test]async fn v2_namespace_creation_uses_legacy_custom_namespace_id() {let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();@@ -2839,13 +4050,6 @@ mod tests {let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();let address = listener.local_addr().unwrap();let server = tokio::spawn(async move {- for expected_path in ["/v3/console/core/namespace", "/v3/console/core/namespace/create"] {- let (mut socket, _) = listener.accept().await.unwrap();- let request = read_http_request(&mut socket).await;- assert_eq!(request.split_whitespace().nth(1), Some(expected_path));- write_not_found_response(&mut socket).await;- }-let (mut socket, _) = listener.accept().await.unwrap();let request = read_http_request(&mut socket).await;assert_eq!(request.split_whitespace().nth(1), Some("/v1/console/namespaces"));@@ -2868,14 +4072,10 @@ mod tests {}#[tokio::test]- async fn version_mode_auto_falls_back_from_v3_to_v1_config_paths() {+ async fn legacy_auto_mode_uses_v1_config_paths_without_cross_version_fallback() {let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();let address = listener.local_addr().unwrap();let server = tokio::spawn(async move {- let (mut socket, _) = listener.accept().await.unwrap();- assert!(read_request_target(&mut socket).await.starts_with("/nacos/v3/console/cs/config/list?"));- write_not_found_response(&mut socket).await;-let (mut socket, _) = listener.accept().await.unwrap();assert!(read_request_target(&mut socket).await.starts_with("/nacos/v1/cs/configs?"));write_json_response(&mut socket, r#"{"totalCount":0,"pageItems":[]}"#).await;@@ -2931,12 +4131,6 @@ mod tests {let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();let address = listener.local_addr().unwrap();let server = tokio::spawn(async move {- for expected_path in ["/v3/console/cs/config", "/v3/console/cs/config/detail"] {- let (mut socket, _) = listener.accept().await.unwrap();- assert!(read_request_target(&mut socket).await.starts_with(expected_path));- write_not_found_response(&mut socket).await;- }-let (mut socket, _) = listener.accept().await.unwrap();assert!(read_request_target(&mut socket).await.starts_with("/v1/cs/configs?"));write_text_response(&mut socket, "cloud_providers: {}\n").await;@@ -2987,12 +4181,6 @@ mod tests {let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();let address = listener.local_addr().unwrap();let server = tokio::spawn(async move {- for expected_path in ["/v3/console/cs/config", "/v3/console/cs/config/detail"] {- let (mut socket, _) = listener.accept().await.unwrap();- assert!(read_request_target(&mut socket).await.starts_with(expected_path));- write_not_found_response(&mut socket).await;- }-let (mut socket, _) = listener.accept().await.unwrap();assert!(read_request_target(&mut socket).await.starts_with("/v1/cs/configs?"));write_text_response(&mut socket, "cloud_providers: {}\n").await;@@ -3030,12 +4218,6 @@ mod tests {let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();let address = listener.local_addr().unwrap();let server = tokio::spawn(async move {- for expected_path in ["/v3/console/cs/config", "/v3/console/cs/config/detail"] {- let (mut socket, _) = listener.accept().await.unwrap();- assert!(read_request_target(&mut socket).await.starts_with(expected_path));- write_not_found_response(&mut socket).await;- }-let (mut socket, _) = listener.accept().await.unwrap();assert!(read_request_target(&mut socket).await.starts_with("/v1/cs/configs?"));write_text_response(&mut socket, "cloud_providers: {}\n").await;@@ -3074,10 +4256,6 @@ mod tests {let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();let address = listener.local_addr().unwrap();let server = tokio::spawn(async move {- let (mut socket, _) = listener.accept().await.unwrap();- assert!(read_request_target(&mut socket).await.starts_with("/v3/console/cs/config/list?"));- write_not_found_response(&mut socket).await;-let (mut socket, _) = listener.accept().await.unwrap();assert!(read_request_target(&mut socket).await.starts_with("/v1/cs/configs?"));write_json_response(@@ -3086,12 +4264,6 @@ mod tests {).await;- for expected_path in ["/v3/console/cs/config", "/v3/console/cs/config/detail"] {- let (mut socket, _) = listener.accept().await.unwrap();- assert!(read_request_target(&mut socket).await.starts_with(expected_path));- write_not_found_response(&mut socket).await;- }-let (mut socket, _) = listener.accept().await.unwrap();assert!(read_request_target(&mut socket).await.starts_with("/v1/cs/configs?"));write_text_response(&mut socket, "cloud_providers: {}\n").await;@@ -3141,10 +4313,6 @@ mod tests {let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();let address = listener.local_addr().unwrap();let server = tokio::spawn(async move {- let (mut socket, _) = listener.accept().await.unwrap();- assert!(read_request_target(&mut socket).await.starts_with("/v3/console/cs/config/list?"));- write_not_found_response(&mut socket).await;-let (mut socket, _) = listener.accept().await.unwrap();assert!(read_request_target(&mut socket).await.starts_with("/v1/cs/configs?"));write_json_response(@@ -3153,12 +4321,6 @@ mod tests {).await;- for expected_path in ["/v3/console/cs/config", "/v3/console/cs/config/detail"] {- let (mut socket, _) = listener.accept().await.unwrap();- assert!(read_request_target(&mut socket).await.starts_with(expected_path));- write_not_found_response(&mut socket).await;- }-let (mut socket, _) = listener.accept().await.unwrap();assert!(read_request_target(&mut socket).await.starts_with("/v1/cs/configs?"));write_text_response(&mut socket, "server:\n port: 8848\n").await;@@ -3201,12 +4363,7 @@ mod tests {let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();let address = listener.local_addr().unwrap();let server = tokio::spawn(async move {- for expected_path in [- "/nacos/health",- "/nacos/v3/console/server/state",- "/nacos/v1/ns/operator/servers",- "/nacos/v1/console/server/state",- ] {+ for expected_path in ["/nacos/health", "/nacos/v1/ns/operator/servers", "/nacos/v1/console/server/state"] {let (mut socket, _) = listener.accept().await.unwrap();assert_eq!(read_request_target(&mut socket).await, expected_path);write_service_unavailable_response(&mut socket).await;@@ -3394,13 +4551,11 @@ mod tests {}#[tokio::test]- async fn uses_health_endpoint_when_console_state_apis_are_unavailable() {+ async fn health_response_identifies_rnacos_when_v3_state_endpoint_is_unavailable() {let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();let address = listener.local_addr().unwrap();let server = tokio::spawn(async move {- for expected_path in- ["/nacos/v3/console/server/state", "/nacos/v1/ns/operator/servers", "/nacos/v1/console/server/state"]- {+ for expected_path in ["/nacos/v3/admin/core/state"] {let (mut socket, _) = listener.accept().await.unwrap();assert_eq!(read_request_target(&mut socket).await, expected_path);write_not_found_response(&mut socket).await;@@ -3413,6 +4568,7 @@ mod tests {let mut config = test_admin_config(format!("http://{address}"));config.context_path = "/nacos".to_string();+ config.version_mode = Some(NacosVersionMode::V3);let admin = NacosOpenApiAdmin::new(config).unwrap();let state = admin.get_server_state().await.unwrap();@@ -3426,22 +4582,10 @@ mod tests {let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();let address = listener.local_addr().unwrap();let server = tokio::spawn(async move {- for expected_path in- ["/nacos/v3/console/server/state", "/nacos/v1/ns/operator/servers", "/nacos/v1/console/server/state"]- {- let (mut socket, _) = listener.accept().await.unwrap();- assert_eq!(read_request_target(&mut socket).await, expected_path);- write_not_found_response(&mut socket).await;- }-let (mut socket, _) = listener.accept().await.unwrap();assert_eq!(read_request_target(&mut socket).await, "/nacos/health");write_json_response(&mut socket, "success").await;- let (mut socket, _) = listener.accept().await.unwrap();- assert_eq!(read_request_target(&mut socket).await, "/nacos/v3/console/core/namespace/list");- write_not_found_response(&mut socket).await;-let (mut socket, _) = listener.accept().await.unwrap();assert_eq!(read_request_target(&mut socket).await, "/nacos/v1/console/namespaces");write_json_response(&mut socket, r#"{"data":[]}"#).await;@@ -3449,6 +4593,7 @@ mod tests {let mut config = test_admin_config(format!("http://{address}"));config.context_path = "/nacos".to_string();+ config.implementation = Some(NacosImplementation::RNacos);let admin = NacosOpenApiAdmin::new(config).unwrap();let info = admin.test_connection().await.unwrap();@@ -3457,25 +4602,19 @@ mod tests {}#[tokio::test]- async fn test_connection_accepts_client_openapi_when_console_state_and_health_are_unavailable() {+ async fn rnacos_connection_accepts_client_openapi_when_state_and_health_are_unavailable() {let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();let address = listener.local_addr().unwrap();let server = tokio::spawn(async move {- for expected_path in- ["/nacos/v3/console/server/state", "/nacos/v1/ns/operator/servers", "/nacos/v1/console/server/state"]- {- let (mut socket, _) = listener.accept().await.unwrap();- assert_eq!(read_request_target(&mut socket).await, expected_path);- write_not_found_response(&mut socket).await;- }-let (mut socket, _) = listener.accept().await.unwrap();assert_eq!(read_request_target(&mut socket).await, "/nacos/health");write_service_unavailable_response(&mut socket).await;- let (mut socket, _) = listener.accept().await.unwrap();- assert_eq!(read_request_target(&mut socket).await, "/nacos/v3/console/core/namespace/list");- write_not_found_response(&mut socket).await;+ for expected_path in ["/nacos/v1/ns/operator/servers", "/nacos/v1/console/server/state"] {+ let (mut socket, _) = listener.accept().await.unwrap();+ assert_eq!(read_request_target(&mut socket).await, expected_path);+ write_not_found_response(&mut socket).await;+ }let (mut socket, _) = listener.accept().await.unwrap();assert_eq!(read_request_target(&mut socket).await, "/nacos/v1/console/namespaces");@@ -3484,12 +4623,13 @@ mod tests {let mut config = test_admin_config(format!("http://{address}"));config.context_path = "/nacos".to_string();+ config.implementation = Some(NacosImplementation::RNacos);let admin = NacosOpenApiAdmin::new(config).unwrap();let info = admin.test_connection().await.unwrap();assert!(info.raw.is_none());assert_eq!(info.auth, "none");- assert!(info.capabilities.supports_config_history);+ assert!(!info.capabilities.supports_config_history);server.await.unwrap();}@@ -3498,13 +4638,7 @@ mod tests {let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();let address = listener.local_addr().unwrap();let server = tokio::spawn(async move {- for expected_path in [- "/nacos/v3/console/cs/history/list",- "/nacos/v3/console/cs/history",- "/nacos/v1/cs/history/list",- "/nacos/v1/cs/history",- "/nacos/v1/cs/history/configs",- ] {+ for expected_path in ["/nacos/v1/cs/history/list", "/nacos/v1/cs/history", "/nacos/v1/cs/history/configs"] {let (mut socket, _) = listener.accept().await.unwrap();assert!(read_request_target(&mut socket).await.starts_with(expected_path));write_not_found_response(&mut socket).await;@@ -3533,6 +4667,7 @@ mod tests {let mut config = test_admin_config(format!("http://{address}"));config.context_path = "/nacos".to_string();+ config.implementation = Some(NacosImplementation::RNacos);config.rnacos_console_addr = format!("http://{address}");config.auth =NacosAuthConfig::UsernamePassword { username: "admin".to_string(), password: "admin".to_string() };@@ -3563,12 +4698,7 @@ mod tests {let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();let address = listener.local_addr().unwrap();let server = tokio::spawn(async move {- for expected_path in [- "/nacos/v3/console/cs/history/detail",- "/nacos/v3/console/cs/history",- "/nacos/v1/cs/history",- "/nacos/v1/cs/history/config",- ] {+ for expected_path in ["/nacos/v1/cs/history", "/nacos/v1/cs/history/config"] {let (mut socket, _) = listener.accept().await.unwrap();assert!(read_request_target(&mut socket).await.starts_with(expected_path));write_not_found_response(&mut socket).await;@@ -3590,6 +4720,7 @@ mod tests {let mut config = test_admin_config(format!("http://{address}"));config.context_path = "/nacos".to_string();+ config.implementation = Some(NacosImplementation::RNacos);config.rnacos_console_addr = format!("http://{address}");config.auth =NacosAuthConfig::UsernamePassword { username: "admin".to_string(), password: "admin".to_string() };@@ -3901,11 +5032,11 @@ mod tests {#[test]fn namespace_list_error_keeps_v3_and_v1_details() {let err = namespace_list_error(- "NACOS_ERROR[authFailed]: Nacos admin /v3/console/core/namespace/list returned 403 Forbidden",+ "NACOS_ERROR[authFailed]: Nacos admin /v3/admin/core/namespace/list returned 403 Forbidden","NACOS_ERROR[apiVersionMismatch]: Nacos admin /v1/console/namespaces returned 410 Gone",);assert!(err.starts_with("NACOS_ERROR[authFailed]:"));- assert!(err.contains("/v3/console/core/namespace/list returned 403 Forbidden"));+ assert!(err.contains("/v3/admin/core/namespace/list returned 403 Forbidden"));assert!(err.contains("/v1/console/namespaces returned 410 Gone"));}@@ -4116,6 +5247,20 @@ mod tests {assert_eq!(parsed[0].enabled, Some(false));}+ #[test]+ fn filters_instance_list_when_nacos_ignores_cluster_parameter() {+ let instances = parse_instances(serde_json::json!({+ "hosts": [+ { "ip": "127.0.0.1", "port": 19001, "clusterName": "blue" },+ { "ip": "127.0.0.1", "port": 19002, "clusterName": "green" }+ ]+ }));++ let filtered = filter_instances_by_clusters(instances, &["blue".to_string()]);+ assert_eq!(filtered.len(), 1);+ assert_eq!(filtered[0].cluster_name.as_deref(), Some("blue"));+ }+#[test]fn parses_v1_catalog_service_clusters_and_requested_cluster_filter() {let clusters = parse_catalog_cluster_names(&serde_json::json!({@@ -4156,7 +5301,9 @@ mod tests {write_json_response(&mut instances_socket, r#"{"list":[],"count":0}"#).await;});- let admin = NacosOpenApiAdmin::new(test_admin_config(format!("http://{address}"))).unwrap();+ let mut config = test_admin_config(format!("http://{address}"));+ config.version_mode = Some(NacosVersionMode::V2);+ let admin = NacosOpenApiAdmin::new(config).unwrap();let instances = admin.list_v1_catalog_instances(&NacosInstanceQuery {@@ -4174,6 +5321,42 @@ mod tests {server.await.unwrap();}+ #[tokio::test]+ async fn v2_instance_list_uses_catalog_and_keeps_disabled_instances() {+ let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();+ let address = listener.local_addr().unwrap();+ let server = tokio::spawn(async move {+ let (mut detail_socket, _) = listener.accept().await.unwrap();+ assert!(read_request_target(&mut detail_socket).await.starts_with("/nacos/v1/ns/catalog/service?"));+ write_json_response(&mut detail_socket, r#"{"clusters":[{"name":"manual"}]}"#).await;++ let (mut instances_socket, _) = listener.accept().await.unwrap();+ assert!(read_request_target(&mut instances_socket).await.starts_with("/nacos/v1/ns/catalog/instances?"));+ write_json_response(+ &mut instances_socket,+ r#"{"list":[{"ip":"127.0.0.1","port":19101,"clusterName":"manual","healthy":false,"enabled":false,"ephemeral":false}],"count":1}"#,+ )+ .await;+ });+ let mut config = test_admin_config(format!("http://{address}"));+ config.context_path = "/nacos".to_string();+ config.version_mode = Some(NacosVersionMode::V2);+ let admin = NacosOpenApiAdmin::new(config).unwrap();++ let instances = admin+ .list_instances(NacosInstanceQuery {+ namespace: Some("public".to_string()),+ service_name: "dbx-ui-crud".to_string(),+ group_name: Some("DBX_E2E".to_string()),+ clusters: None,+ })+ .await+ .unwrap();+ assert_eq!(instances.len(), 1);+ assert_eq!(instances[0].enabled, Some(false));+ server.await.unwrap();+ }+#[tokio::test]async fn dashboard_combines_metrics_nodes_and_namespace_totals() {let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();@@ -4192,11 +5375,11 @@ mod tests {"/v3/admin/core/cluster/node/list" => {r#"{"code":0,"data":[{"address":"127.0.0.1:8848","ip":"127.0.0.1","port":8848,"state":"UP"}]}"#}- "/v3/console/core/namespace/list" => {- r#"{"code":0,"data":{"pageItems":[{"namespaceId":"dev","namespaceName":"Development"}]}}"#+ "/v3/admin/core/namespace/list" => {+ r#"{"code":0,"data":[{"namespace":"dev","namespaceShowName":"Development"}]}"#}- "/v3/console/cs/config/list" => r#"{"code":0,"data":{"totalCount":21,"pageItems":[]}}"#,- "/v3/console/ns/service/list" => r#"{"code":0,"data":{"count":3,"serviceList":[]}}"#,+ "/v3/admin/cs/config/list" => r#"{"code":0,"data":{"totalCount":21,"pageItems":[]}}"#,+ "/v3/admin/ns/service/list" => r#"{"code":0,"data":{"count":3,"serviceList":[]}}"#,"/actuator/prometheus" => {"# TYPE system_cpu_usage gauge\nsystem_cpu_usage 0.25\n# TYPE nacos_monitor gauge\nnacos_monitor{module=\"config\",name=\"configCount\"} 12\nnacos_monitor{module=\"naming\",name=\"serviceCount\"} 4\nnacos_monitor{module=\"naming\",name=\"ipCount\"} 14\n"}@@ -4207,7 +5390,9 @@ mod tests {paths});- let admin = NacosOpenApiAdmin::new(test_admin_config(format!("http://{address}"))).unwrap();+ let mut config = test_admin_config(format!("http://{address}"));+ config.version_mode = Some(NacosVersionMode::V3);+ let admin = NacosOpenApiAdmin::new(config).unwrap();let snapshot = admin.get_dashboard(NacosDashboardQuery { namespace: Some("dev".to_string()) }).await.unwrap();assert_eq!(snapshot.namespace, "dev");@@ -4235,6 +5420,16 @@ mod tests {assert_eq!(parsed[1].namespace_desc.as_deref(), Some("dev ns"));}+ #[test]+ fn does_not_add_a_second_default_namespace_when_v3_returns_public() {+ let parsed = parse_namespaces(serde_json::json!({+ "code": 0,+ "data": [{ "namespace": "public", "namespaceShowName": "public" }]+ }));+ assert_eq!(parsed.len(), 1);+ assert_eq!(parsed[0].namespace, "public");+ }+#[test]fn parses_v3_namespace_page_shape() {let parsed = parse_namespaces(serde_json::json!({@@ -4307,7 +5502,7 @@ mod tests {#[test]fn validates_raw_api_paths() {- for path in ["/v1/cs/configs", "/v2/console/example", "/v3/console/server/state"] {+ for path in ["/v1/cs/configs", "/v2/console/example", "/v3/admin/core/state"] {validate_raw_api_path(path).unwrap();}@@ -4328,7 +5523,7 @@ mod tests {#[test]fn classifies_common_nacos_errors() {assert_eq!(classify_nacos_error("401 Unauthorized invalid access token"), "authFailed");- assert_eq!(classify_nacos_error("No static resource nacos/v3/console/server/state"), "contextPathMismatch");+ assert_eq!(classify_nacos_error("No static resource nacos/v3/admin/core/state"), "contextPathMismatch");assert_eq!(classify_nacos_error(r#"410 Gone {"message":"Current API will be deprecated","path":"/v1/console/namespaces"}"#@@ -4348,4 +5543,197 @@ mod tests {"NACOS_ERROR[requestFailed]: Nacos admin /v3/admin/cs/config/list returned 500 Internal Server Error: database unavailable"));}++ #[test]+ fn instance_update_form_keeps_identity_separate_from_the_patch() {+ let form = instance_update_form(+ "public".to_string(),+ NacosInstanceUpdateRequest {+ target: NacosInstanceRef {+ namespace: Some("public".to_string()),+ service_name: "api".to_string(),+ ip: "127.0.0.1".to_string(),+ port: 8080,+ group_name: Some("DBX_TEST".to_string()),+ cluster_name: Some("blue".to_string()),+ ephemeral: Some(false),+ },+ patch: NacosInstancePatch {+ weight: Some(2.5),+ metadata: Some(serde_json::json!({ "role": "api" })),+ ..Default::default()+ },+ },+ );+ let form = form.into_iter().collect::<HashMap<_, _>>();+ assert_eq!(form.get("ephemeral").map(String::as_str), Some("false"));+ assert_eq!(form.get("weight").map(String::as_str), Some("2.5"));+ assert!(form.contains_key("metadata"));+ assert!(!form.contains_key("enabled"));+ assert!(!form.contains_key("healthy"));+ }++ #[test]+ fn instance_registration_form_is_always_persistent() {+ let form = instance_registration_form(+ "public".to_string(),+ NacosInstanceRegistration {+ namespace: Some("public".to_string()),+ service_name: "api".to_string(),+ ip: "127.0.0.1".to_string(),+ port: 8080,+ group_name: Some("DBX_TEST".to_string()),+ cluster_name: Some("manual".to_string()),+ weight: Some(1.0),+ metadata: Some(serde_json::json!({})),+ },+ );+ let form = form.into_iter().collect::<HashMap<_, _>>();+ assert_eq!(form.get("ephemeral").map(String::as_str), Some("false"));+ }++ #[test]+ fn management_instance_deduplication_includes_full_identity() {+ let instance = NacosInstanceInfo {+ ip: "127.0.0.1".to_string(),+ port: 8080,+ service_name: Some("api".to_string()),+ cluster_name: Some("blue".to_string()),+ group_name: Some("DBX_TEST".to_string()),+ healthy: Some(true),+ enabled: Some(true),+ ephemeral: None,+ weight: Some(1.0),+ metadata: serde_json::json!({}),+ };+ let instances = deduplicate_management_instances(+ vec![+ instance.clone(),+ NacosInstanceInfo { ephemeral: Some(false), ..instance.clone() },+ NacosInstanceInfo { ephemeral: Some(true), ..instance.clone() },+ NacosInstanceInfo { group_name: Some("OTHER_GROUP".to_string()), ..instance.clone() },+ NacosInstanceInfo { service_name: Some("worker".to_string()), ..instance.clone() },+ instance,+ ],+ "public",+ Some("DBX_TEST"),+ "api",+ );+ assert_eq!(instances.len(), 5);+ }++ #[test]+ fn cluster_names_support_catalog_arrays_and_service_detail_maps() {+ assert_eq!(+ parse_catalog_cluster_names(&serde_json::json!({+ "data": {+ "clusters": [{ "clusterName": "blue" }],+ "clusterMap": { "blue": {}, "green": {} }+ }+ })),+ vec!["blue".to_string(), "green".to_string()]+ );+ }++ #[test]+ fn rnacos_requires_console_management_view_for_safe_service_deletion() {+ let mut config = test_admin_config("http://127.0.0.1:8848".to_string());+ config.implementation = Some(NacosImplementation::RNacos);+ let admin = NacosOpenApiAdmin::new(config).unwrap();+ let capabilities = admin.service_capabilities();+ assert!(capabilities.list_services.supported);+ assert!(capabilities.list_instances.supported);+ assert!(capabilities.create_service.supported);+ assert!(capabilities.update_service.supported);+ assert!(!capabilities.delete_service.supported);+ assert_eq!(capabilities.delete_service.reason, Some(NacosCapabilityReason::EndpointUnavailable));+ assert!(capabilities.update_instance.supported);+ assert!(capabilities.register_instance.supported);+ assert!(capabilities.deregister_instance.supported);+ }++ #[tokio::test]+ async fn rnacos_service_delete_guard_does_not_fall_back_to_lossy_discovery() {+ let mut config = test_admin_config("http://127.0.0.1:8848".to_string());+ config.implementation = Some(NacosImplementation::RNacos);+ let admin = NacosOpenApiAdmin::new(config).unwrap();++ let error = admin+ .list_instances_for_service_delete(NacosInstanceQuery {+ namespace: Some("public".to_string()),+ service_name: "orders".to_string(),+ group_name: None,+ clusters: None,+ })+ .await+ .unwrap_err();++ assert!(error.contains("r-nacos service deletion requires a configured r-nacos console address"));+ }++ #[test]+ fn rnacos_console_enables_safe_service_deletion_capability() {+ let mut config = test_admin_config("http://127.0.0.1:8848".to_string());+ config.implementation = Some(NacosImplementation::RNacos);+ config.rnacos_console_addr = "http://127.0.0.1:10848".to_string();+ let capabilities = NacosOpenApiAdmin::new(config).unwrap().service_capabilities();+ assert!(capabilities.delete_service.supported);+ }++ #[test]+ fn official_v2_and_v3_expose_the_verified_management_matrix() {+ for version_mode in [NacosVersionMode::V2, NacosVersionMode::V3] {+ let mut config = test_admin_config("http://127.0.0.1:8848".to_string());+ config.implementation = Some(NacosImplementation::Nacos);+ config.version_mode = Some(version_mode);+ let capabilities = NacosOpenApiAdmin::new(config).unwrap().service_capabilities();+ assert!(capabilities.list_services.supported);+ assert!(capabilities.get_service.supported);+ assert!(capabilities.create_service.supported);+ assert!(capabilities.update_service.supported);+ assert!(capabilities.delete_service.supported);+ assert!(capabilities.list_instances.supported);+ assert!(capabilities.update_instance.supported);+ assert!(capabilities.register_instance.supported);+ assert!(capabilities.deregister_instance.supported);+ }+ }++ #[test]+ fn legacy_auto_mode_never_falls_back_across_api_generations() {+ let mut auto = test_admin_config("http://127.0.0.1:8848".to_string());+ auto.version_mode = Some(NacosVersionMode::Auto);+ let auto = NacosOpenApiAdmin::new(auto).unwrap();+ assert!(!auto.should_try_next_candidate("NACOS_ERROR[apiVersionMismatch]: missing"));+ assert!(!auto.should_try_next_candidate("NACOS_ERROR[contextPathMismatch]: missing"));+ assert!(!auto.should_try_next_candidate("NACOS_ERROR[authFailed]: forbidden"));+ assert!(!auto.should_try_next_candidate("NACOS_ERROR[requestFailed]: selector error"));+ assert!(auto.api_path_allowed("/v1/ns/service"));+ assert!(!auto.api_path_allowed("/v3/admin/ns/service"));++ let mut explicit = test_admin_config("http://127.0.0.1:8848".to_string());+ explicit.version_mode = Some(NacosVersionMode::V3);+ let explicit = NacosOpenApiAdmin::new(explicit).unwrap();+ assert!(!explicit.should_try_next_candidate("NACOS_ERROR[apiVersionMismatch]: missing"));+ }++ #[tokio::test]+ async fn service_creation_requires_an_explicit_group() {+ let mut config = test_admin_config("http://127.0.0.1:9".to_string());+ config.version_mode = Some(NacosVersionMode::V2);+ let admin = NacosOpenApiAdmin::new(config).unwrap();+ let error = admin+ .create_service(NacosServiceUpsert {+ namespace: Some("public".to_string()),+ service_name: "api".to_string(),+ group_name: Some(" ".to_string()),+ metadata: Some(serde_json::json!({})),+ protect_threshold: Some(0.0),+ selector: None,+ ephemeral: None,+ })+ .await+ .unwrap_err();+ assert!(error.contains("group name is required"));+ }}diff --git a/crates/dbx-core/src/nacos/port.rs b/crates/dbx-core/src/nacos/port.rsindex 31baf07b9b..6acfe7f482 100644--- a/crates/dbx-core/src/nacos/port.rs+++ b/crates/dbx-core/src/nacos/port.rs@@ -4,6 +4,10 @@ use crate::nacos::types::*;#[async_trait]pub trait NacosAdmin: Send + Sync {+ fn service_capabilities(&self) -> NacosServiceCapabilities {+ NacosServiceCapabilities::default()+ }+async fn test_connection(&self) -> Result<NacosConnectionInfo, String>;async fn list_namespaces(&self) -> Result<Vec<NacosNamespaceInfo>, String>;async fn create_namespace(&self, req: NacosNamespaceCreate) -> Result<(), String>;@@ -29,8 +33,23 @@ pub trait NacosAdmin: Send + Sync {async fn get_rnacos_console_captcha(&self) -> Result<NacosRNacosConsoleCaptcha, String>;async fn login_rnacos_console(&self, captcha: Option<String>) -> Result<(), String>;async fn list_services(&self, query: NacosServiceQuery) -> Result<NacosServiceList, String>;+ async fn get_service(&self, query: NacosServiceQuery) -> Result<NacosServiceDetail, String>;+ async fn create_service(&self, req: NacosServiceUpsert) -> Result<(), String>;+ async fn update_service(&self, req: NacosServiceUpsert) -> Result<(), String>;+ async fn delete_service(&self, query: NacosServiceQuery) -> Result<(), String>;async fn list_instances(&self, query: NacosInstanceQuery) -> Result<Vec<NacosInstanceInfo>, String>;- async fn update_instance(&self, req: NacosInstanceUpdate) -> Result<(), String>;+ /// Returns the authoritative management view used before deleting a+ /// service. Implementations whose discovery API hides disabled instances+ /// must override this instead of falling back to that lossy view.+ async fn list_instances_for_service_delete(+ &self,+ query: NacosInstanceQuery,+ ) -> Result<Vec<NacosInstanceInfo>, String> {+ self.list_instances(query).await+ }+ async fn update_instance(&self, req: NacosInstanceUpdateRequest) -> Result<(), String>;+ async fn register_instance(&self, req: NacosInstanceRegistration) -> Result<(), String>;+ async fn deregister_instance(&self, req: NacosInstanceRef) -> Result<(), String>;async fn get_dashboard(&self, query: NacosDashboardQuery) -> Result<NacosDashboardSnapshot, String>;async fn raw_request(&self, req: NacosRawRequest) -> Result<NacosRawResponse, String>;}diff --git a/crates/dbx-core/src/nacos/search.rs b/crates/dbx-core/src/nacos/search.rsindex ec42186280..9abda68b29 100644--- a/crates/dbx-core/src/nacos/search.rs+++ b/crates/dbx-core/src/nacos/search.rs@@ -693,10 +693,28 @@ mod tests {async fn list_services(&self, _: NacosServiceQuery) -> Result<NacosServiceList, String> {Err("unused".to_string())}+ async fn get_service(&self, _: NacosServiceQuery) -> Result<NacosServiceDetail, String> {+ Err("unused".to_string())+ }+ async fn create_service(&self, _: NacosServiceUpsert) -> Result<(), String> {+ Err("unused".to_string())+ }+ async fn update_service(&self, _: NacosServiceUpsert) -> Result<(), String> {+ Err("unused".to_string())+ }+ async fn delete_service(&self, _: NacosServiceQuery) -> Result<(), String> {+ Err("unused".to_string())+ }async fn list_instances(&self, _: NacosInstanceQuery) -> Result<Vec<NacosInstanceInfo>, String> {Err("unused".to_string())}- async fn update_instance(&self, _: NacosInstanceUpdate) -> Result<(), String> {+ async fn update_instance(&self, _: NacosInstanceUpdateRequest) -> Result<(), String> {+ Err("unused".to_string())+ }+ async fn register_instance(&self, _: NacosInstanceRegistration) -> Result<(), String> {+ Err("unused".to_string())+ }+ async fn deregister_instance(&self, _: NacosInstanceRef) -> Result<(), String> {Err("unused".to_string())}async fn get_dashboard(&self, _: NacosDashboardQuery) -> Result<NacosDashboardSnapshot, String> {diff --git a/crates/dbx-core/src/nacos/service.rs b/crates/dbx-core/src/nacos/service.rsindex 30adae14e3..47b6671eb2 100644--- a/crates/dbx-core/src/nacos/service.rs+++ b/crates/dbx-core/src/nacos/service.rs@@ -140,6 +140,7 @@ pub async fn nacos_list_services_core(query: NacosServiceQuery,) -> Result<NacosServiceList, String> {let admin = get_admin(state, conn_id).await?;+ ensure_service_operation(admin.as_ref(), NacosServiceOperation::ListServices)?;admin.list_services(query).await}@@ -149,19 +150,100 @@ pub async fn nacos_list_instances_core(query: NacosInstanceQuery,) -> Result<Vec<NacosInstanceInfo>, String> {let admin = get_admin(state, conn_id).await?;+ ensure_service_operation(admin.as_ref(), NacosServiceOperation::ListInstances)?;admin.list_instances(query).await}+pub async fn nacos_get_service_core(+ state: &AppState,+ conn_id: &str,+ query: NacosServiceQuery,+) -> Result<NacosServiceDetail, String> {+ let admin = get_admin(state, conn_id).await?;+ ensure_service_operation(admin.as_ref(), NacosServiceOperation::GetService)?;+ admin.get_service(query).await+}++pub async fn nacos_create_service_core(state: &AppState, conn_id: &str, req: NacosServiceUpsert) -> Result<(), String> {+ ensure_connection_writable(state, conn_id, "Create Nacos service").await?;+ let admin = get_admin(state, conn_id).await?;+ ensure_service_operation(admin.as_ref(), NacosServiceOperation::CreateService)?;+ admin.create_service(req).await+}++pub async fn nacos_update_service_core(state: &AppState, conn_id: &str, req: NacosServiceUpsert) -> Result<(), String> {+ ensure_connection_writable(state, conn_id, "Update Nacos service").await?;+ let admin = get_admin(state, conn_id).await?;+ ensure_service_operation(admin.as_ref(), NacosServiceOperation::UpdateService)?;+ admin.update_service(req).await+}++pub async fn nacos_delete_service_core(+ state: &AppState,+ conn_id: &str,+ query: NacosServiceQuery,+) -> Result<(), String> {+ ensure_connection_writable(state, conn_id, "Delete Nacos service").await?;+ let admin = get_admin(state, conn_id).await?;+ ensure_service_operation(admin.as_ref(), NacosServiceOperation::DeleteService)?;+ ensure_service_operation(admin.as_ref(), NacosServiceOperation::ListInstances)?;+ let service_name = query+ .service_name+ .as_deref()+ .map(str::trim)+ .filter(|name| !name.is_empty())+ .ok_or_else(|| "Nacos service name is required".to_string())?+ .to_string();+ let instances = admin+ .list_instances_for_service_delete(NacosInstanceQuery {+ namespace: query.namespace.clone(),+ service_name,+ group_name: query.group_name.clone(),+ clusters: None,+ })+ .await?;+ if !instances.is_empty() {+ return Err(format!(+ "NACOS_ERROR[serviceNotEmpty]: Nacos service still contains {} instance(s); deregister them before deletion",+ instances.len()+ ));+ }+ admin.delete_service(query).await+}+pub async fn nacos_update_instance_core(state: &AppState,conn_id: &str,- req: NacosInstanceUpdate,+ req: NacosInstanceUpdateRequest,) -> Result<(), String> {ensure_connection_writable(state, conn_id, "Update Nacos instance").await?;let admin = get_admin(state, conn_id).await?;+ ensure_service_operation(admin.as_ref(), NacosServiceOperation::UpdateInstance)?;admin.update_instance(req).await}+pub async fn nacos_register_instance_core(+ state: &AppState,+ conn_id: &str,+ req: NacosInstanceRegistration,+) -> Result<(), String> {+ ensure_connection_writable(state, conn_id, "Register Nacos instance").await?;+ let admin = get_admin(state, conn_id).await?;+ ensure_service_operation(admin.as_ref(), NacosServiceOperation::RegisterInstance)?;+ admin.register_instance(req).await+}++pub async fn nacos_deregister_instance_core(+ state: &AppState,+ conn_id: &str,+ req: NacosInstanceRef,+) -> Result<(), String> {+ ensure_connection_writable(state, conn_id, "Deregister Nacos instance").await?;+ let admin = get_admin(state, conn_id).await?;+ ensure_service_operation(admin.as_ref(), NacosServiceOperation::DeregisterInstance)?;+ admin.deregister_instance(req).await+}+pub async fn nacos_get_dashboard_core(state: &AppState,conn_id: &str,@@ -205,10 +287,65 @@ pub(crate) async fn ensure_connection_writable(state: &AppState, conn_id: &str,}}+fn ensure_service_operation(+ admin: &dyn crate::nacos::port::NacosAdmin,+ operation: NacosServiceOperation,+) -> Result<(), String> {+ let capabilities = admin.service_capabilities();+ let capability = capabilities.operation(operation);+ if capability.supported {+ return Ok(());+ }+ let reason = match capability.reason {+ Some(NacosCapabilityReason::ImplementationReadOnly) => "implementationReadOnly",+ Some(NacosCapabilityReason::VersionUnsupported) => "versionUnsupported",+ Some(NacosCapabilityReason::EndpointUnavailable) => "endpointUnavailable",+ Some(NacosCapabilityReason::NotVerified) => "notVerified",+ Some(NacosCapabilityReason::ConnectionReadOnly) => "connectionReadOnly",+ None => "notVerified",+ };+ Err(format!("NACOS_ERROR[unsupportedOperation]: Nacos service operation {operation:?} is unavailable ({reason})"))+}+#[cfg(test)]mod tests {use super::*;+ #[test]+ fn core_service_operation_guard_allows_documented_rnacos_v1_writes() {+ use crate::nacos::config::{+ NacosAdminConfig, NacosAuthConfig, NacosImplementation, NacosMetricsMode, NacosRNacosConsoleAuth,+ NacosVersionMode,+ };+ use crate::nacos::http::NacosOpenApiAdmin;+ use crate::nacos::port::NacosAdmin;++ let admin = NacosOpenApiAdmin::new(NacosAdminConfig {+ implementation: Some(NacosImplementation::RNacos),+ server_addr: "http://127.0.0.1:3848".to_string(),+ display_server_addr: "http://127.0.0.1:3848".to_string(),+ namespace: "public".to_string(),+ version_mode: Some(NacosVersionMode::Auto),+ context_path: "/nacos".to_string(),+ rnacos_console_addr: String::new(),+ rnacos_history_enabled: Some(false),+ rnacos_console_auth: NacosRNacosConsoleAuth::Inherit,+ auth: NacosAuthConfig::None,+ tls_skip_verify: false,+ metrics_mode: NacosMetricsMode::Disabled,+ metrics_url: String::new(),+ page_size: 20,+ connect_override: None,+ })+ .unwrap();+ assert!(ensure_service_operation(&admin, NacosServiceOperation::ListServices).is_ok());+ assert!(ensure_service_operation(&admin, NacosServiceOperation::CreateService).is_ok());+ assert!(ensure_service_operation(&admin, NacosServiceOperation::UpdateInstance).is_ok());+ assert!(admin.service_capabilities().create_service.supported);+ let error = ensure_service_operation(&admin, NacosServiceOperation::DeleteService).unwrap_err();+ assert!(error.contains("endpointUnavailable"));+ }+#[tokio::test]async fn raw_mutation_requires_writable_connection_before_adapter_build() {let dir = std::env::temp_dir().join(format!("dbx-nacos-service-test-{}", uuid::Uuid::new_v4()));diff --git a/crates/dbx-core/src/nacos/types.rs b/crates/dbx-core/src/nacos/types.rsindex 62c46ed9d2..8f2a121505 100644--- a/crates/dbx-core/src/nacos/types.rs+++ b/crates/dbx-core/src/nacos/types.rs@@ -10,6 +10,99 @@ pub struct NacosCapabilities {pub supports_service_management: bool,pub supports_instance_update: bool,pub supports_raw_api: bool,+ #[serde(default)]+ pub service_management: NacosServiceCapabilities,+}++#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]+#[serde(rename_all = "camelCase")]+pub struct NacosOperationCapability {+ pub supported: bool,+ #[serde(skip_serializing_if = "Option::is_none")]+ pub reason: Option<NacosCapabilityReason>,+}++impl NacosOperationCapability {+ pub fn supported() -> Self {+ Self { supported: true, reason: None }+ }++ pub fn unsupported(reason: NacosCapabilityReason) -> Self {+ Self { supported: false, reason: Some(reason) }+ }+}++impl Default for NacosOperationCapability {+ fn default() -> Self {+ Self::supported()+ }+}++#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)]+#[serde(rename_all = "camelCase")]+pub enum NacosCapabilityReason {+ ImplementationReadOnly,+ VersionUnsupported,+ EndpointUnavailable,+ NotVerified,+ ConnectionReadOnly,+}++#[derive(Debug, Clone, Copy, PartialEq, Eq)]+pub enum NacosServiceOperation {+ ListServices,+ GetService,+ CreateService,+ UpdateService,+ DeleteService,+ ListInstances,+ UpdateInstance,+ RegisterInstance,+ DeregisterInstance,+}++#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq, Default)]+#[serde(rename_all = "camelCase")]+pub struct NacosServiceCapabilities {+ pub list_services: NacosOperationCapability,+ pub get_service: NacosOperationCapability,+ pub create_service: NacosOperationCapability,+ pub update_service: NacosOperationCapability,+ pub delete_service: NacosOperationCapability,+ pub list_instances: NacosOperationCapability,+ pub update_instance: NacosOperationCapability,+ pub register_instance: NacosOperationCapability,+ pub deregister_instance: NacosOperationCapability,+}++impl NacosServiceCapabilities {+ pub fn read_only(reason: NacosCapabilityReason) -> Self {+ Self {+ list_services: NacosOperationCapability::supported(),+ get_service: NacosOperationCapability::supported(),+ create_service: NacosOperationCapability::unsupported(reason),+ update_service: NacosOperationCapability::unsupported(reason),+ delete_service: NacosOperationCapability::unsupported(reason),+ list_instances: NacosOperationCapability::supported(),+ update_instance: NacosOperationCapability::unsupported(reason),+ register_instance: NacosOperationCapability::unsupported(reason),+ deregister_instance: NacosOperationCapability::unsupported(reason),+ }+ }++ pub fn operation(&self, operation: NacosServiceOperation) -> &NacosOperationCapability {+ match operation {+ NacosServiceOperation::ListServices => &self.list_services,+ NacosServiceOperation::GetService => &self.get_service,+ NacosServiceOperation::CreateService => &self.create_service,+ NacosServiceOperation::UpdateService => &self.update_service,+ NacosServiceOperation::DeleteService => &self.delete_service,+ NacosServiceOperation::ListInstances => &self.list_instances,+ NacosServiceOperation::UpdateInstance => &self.update_instance,+ NacosServiceOperation::RegisterInstance => &self.register_instance,+ NacosServiceOperation::DeregisterInstance => &self.deregister_instance,+ }+ }}impl Default for NacosCapabilities {@@ -21,6 +114,7 @@ impl Default for NacosCapabilities {supports_service_management: true,supports_instance_update: true,supports_raw_api: true,+ service_management: NacosServiceCapabilities::default(),}}}@@ -437,6 +531,40 @@ pub struct NacosServiceList {pub items: Vec<NacosServiceInfo>,}+#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]+#[serde(rename_all = "camelCase")]+pub struct NacosServiceDetail {+ pub service_name: String,+ #[serde(default)]+ pub group_name: Option<String>,+ #[serde(default)]+ pub metadata: serde_json::Value,+ #[serde(default)]+ pub protect_threshold: Option<f64>,+ #[serde(default)]+ pub selector: Option<serde_json::Value>,+ #[serde(default)]+ pub ephemeral: Option<bool>,+}++#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]+#[serde(rename_all = "camelCase")]+pub struct NacosServiceUpsert {+ #[serde(default)]+ pub namespace: Option<String>,+ pub service_name: String,+ #[serde(default)]+ pub group_name: Option<String>,+ #[serde(default)]+ pub metadata: Option<serde_json::Value>,+ #[serde(default)]+ pub protect_threshold: Option<f64>,+ #[serde(default)]+ pub selector: Option<serde_json::Value>,+ #[serde(default)]+ pub ephemeral: Option<bool>,+}+#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]#[serde(rename_all = "camelCase")]pub struct NacosInstanceInfo {@@ -474,7 +602,7 @@ pub struct NacosInstanceQuery {#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]#[serde(rename_all = "camelCase")]-pub struct NacosInstanceUpdate {+pub struct NacosInstanceRef {#[serde(default)]pub namespace: Option<String>,pub service_name: String,@@ -484,12 +612,42 @@ pub struct NacosInstanceUpdate {pub group_name: Option<String>,#[serde(default)]pub cluster_name: Option<String>,+ #[serde(default)]+ pub ephemeral: Option<bool>,+}++#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Default)]+#[serde(rename_all = "camelCase")]+pub struct NacosInstancePatch {#[serde(default)]pub healthy: Option<bool>,#[serde(default)]pub enabled: Option<bool>,#[serde(default)]- pub ephemeral: Option<bool>,+ pub weight: Option<f64>,+ #[serde(default)]+ pub metadata: Option<serde_json::Value>,+}++#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]+#[serde(rename_all = "camelCase")]+pub struct NacosInstanceUpdateRequest {+ pub target: NacosInstanceRef,+ pub patch: NacosInstancePatch,+}++#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]+#[serde(rename_all = "camelCase")]+pub struct NacosInstanceRegistration {+ #[serde(default)]+ pub namespace: Option<String>,+ pub service_name: String,+ pub ip: String,+ pub port: u16,+ #[serde(default)]+ pub group_name: Option<String>,+ #[serde(default)]+ pub cluster_name: Option<String>,#[serde(default)]pub weight: Option<f64>,#[serde(default)]@@ -503,6 +661,86 @@ pub struct NacosDashboardQuery {pub namespace: Option<String>,}+#[cfg(test)]+mod service_capability_tests {+ use super::*;++ #[test]+ fn official_nacos_service_capabilities_enable_every_supported_operation() {+ let capabilities = NacosServiceCapabilities::default();+ for operation in [+ NacosServiceOperation::ListServices,+ NacosServiceOperation::GetService,+ NacosServiceOperation::CreateService,+ NacosServiceOperation::UpdateService,+ NacosServiceOperation::DeleteService,+ NacosServiceOperation::ListInstances,+ NacosServiceOperation::UpdateInstance,+ NacosServiceOperation::RegisterInstance,+ NacosServiceOperation::DeregisterInstance,+ ] {+ assert!(capabilities.operation(operation).supported);+ }+ }++ #[test]+ fn read_only_implementation_preserves_reads_and_explains_writes() {+ let capabilities = NacosServiceCapabilities::read_only(NacosCapabilityReason::ImplementationReadOnly);+ assert!(capabilities.list_services.supported);+ assert!(capabilities.get_service.supported);+ assert!(capabilities.list_instances.supported);+ assert_eq!(capabilities.update_instance.reason, Some(NacosCapabilityReason::ImplementationReadOnly));+ assert_eq!(capabilities.create_service.reason, Some(NacosCapabilityReason::ImplementationReadOnly));+ assert_eq!(capabilities.deregister_instance.reason, Some(NacosCapabilityReason::ImplementationReadOnly));+ }++ #[test]+ fn service_capabilities_use_the_tauri_and_web_camel_case_contract() {+ let value =+ serde_json::to_value(NacosServiceCapabilities::read_only(NacosCapabilityReason::NotVerified)).unwrap();+ assert_eq!(value["listServices"]["supported"], true);+ assert_eq!(value["createService"]["supported"], false);+ assert_eq!(value["createService"]["reason"], "notVerified");+ assert!(value.get("manageServices").is_none());+ }++ #[test]+ fn instance_update_uses_nested_target_and_patch_transport_contract() {+ let value = serde_json::to_value(NacosInstanceUpdateRequest {+ target: NacosInstanceRef {+ namespace: Some("public".to_string()),+ service_name: "api".to_string(),+ ip: "127.0.0.1".to_string(),+ port: 8080,+ group_name: Some("DBX_TEST".to_string()),+ cluster_name: Some("blue".to_string()),+ ephemeral: Some(false),+ },+ patch: NacosInstancePatch { enabled: Some(false), ..Default::default() },+ })+ .unwrap();+ assert_eq!(value["target"]["serviceName"], "api");+ assert_eq!(value["target"]["ephemeral"], false);+ assert_eq!(value["patch"]["enabled"], false);+ assert!(value.get("serviceName").is_none());+ assert!(value["patch"].get("weight").is_some_and(serde_json::Value::is_null));+ }++ #[test]+ fn legacy_capabilities_without_the_operation_matrix_remain_readable() {+ let capabilities: NacosCapabilities = serde_json::from_value(serde_json::json!({+ "supportsConfigManagement": true,+ "supportsConfigHistory": true,+ "supportsServiceManagement": true,+ "supportsInstanceUpdate": true,+ "supportsRawApi": true+ }))+ .unwrap();+ assert!(capabilities.service_management.list_services.supported);+ assert!(capabilities.service_management.update_instance.supported);+ }+}+#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Default)]#[serde(rename_all = "camelCase")]pub struct NacosDashboardMetrics {diff --git a/crates/dbx-mcp/src/backend.rs b/crates/dbx-mcp/src/backend.rsindex 239559d84c..ed5d91193a 100644--- a/crates/dbx-mcp/src/backend.rs+++ b/crates/dbx-mcp/src/backend.rs@@ -323,11 +323,8 @@ impl LocalBackend {}}}- let stale_ids: Vec<String> = runtime- .keys()- .filter(|id| !configs.iter().any(|config| &config.id == *id))- .cloned()- .collect();+ let stale_ids: Vec<String> =+ runtime.keys().filter(|id| !configs.iter().any(|config| &config.id == *id)).cloned().collect();for id in stale_ids {runtime.remove(&id);}diff --git a/crates/dbx-mcp/tests/local.rs b/crates/dbx-mcp/tests/local.rsindex 15f605afa9..01ec14a620 100644--- a/crates/dbx-mcp/tests/local.rs+++ b/crates/dbx-mcp/tests/local.rs@@ -1,7 +1,7 @@use std::{ffi::OsString, sync::Arc};use dbx_core::{models::connection::ConnectionConfig, storage::Storage};-use dbx_mcp::{DbxMcpServer, LocalBackend, McpScope};+use dbx_mcp::{DbxBackend, DbxMcpServer, LocalBackend, McpScope};use rmcp::{model::CallToolRequestParams, ServiceExt};use serde_json::{json, Map, Value};use tempfile::tempdir;@@ -111,11 +111,8 @@ async fn local_backend_picks_up_connections_added_after_startup_without_reload()storage.save_connections(&[initial, added.clone()]).await.expect("save added connection");// list_connections reads storage live, so the new connection is already visible.- let list_result = client- .peer()- .call_tool(CallToolRequestParams::new("dbx_list_connections"))- .await- .expect("list connections");+ let list_result =+ client.peer().call_tool(CallToolRequestParams::new("dbx_list_connections")).await.expect("list connections");let list_text = list_result.content[0].as_text().expect("text response").text.clone();assert!(list_text.contains("added-sqlite"), "list should include added connection: {list_text}");diff --git a/crates/dbx-web/src/main.rs b/crates/dbx-web/src/main.rsindex da5ca6d979..bb4d9c84dd 100644--- a/crates/dbx-web/src/main.rs+++ b/crates/dbx-web/src/main.rs@@ -573,8 +573,14 @@ async fn main() {.route("/nacos/rnacos-console/captcha", post(routes::nacos::get_rnacos_console_captcha)).route("/nacos/rnacos-console/login", post(routes::nacos::login_rnacos_console)).route("/nacos/services/list", post(routes::nacos::list_services))+ .route("/nacos/services/get", post(routes::nacos::get_service))+ .route("/nacos/services/create", post(routes::nacos::create_service))+ .route("/nacos/services/update", post(routes::nacos::update_service))+ .route("/nacos/services/delete", post(routes::nacos::delete_service)).route("/nacos/instances/list", post(routes::nacos::list_instances)).route("/nacos/instances/update", post(routes::nacos::update_instance))+ .route("/nacos/instances/register", post(routes::nacos::register_instance))+ .route("/nacos/instances/deregister", post(routes::nacos::deregister_instance)).route("/nacos/dashboard", post(routes::nacos::get_dashboard)).route("/nacos/raw", post(routes::nacos::raw_request)).route("/nacos/configs/search", post(routes::nacos::search_config_content))diff --git a/crates/dbx-web/src/routes/nacos.rs b/crates/dbx-web/src/routes/nacos.rsindex 7ca7e9ff11..29c5921472 100644--- a/crates/dbx-web/src/routes/nacos.rs+++ b/crates/dbx-web/src/routes/nacos.rs@@ -95,6 +95,20 @@ pub(crate) struct ServiceListReq {query: dbx_core::nacos::NacosServiceQuery,}+#[derive(serde::Deserialize)]+#[serde(rename_all = "camelCase")]+pub(crate) struct ServiceQueryReq {+ connection_id: String,+ query: dbx_core::nacos::NacosServiceQuery,+}++#[derive(serde::Deserialize)]+#[serde(rename_all = "camelCase")]+pub(crate) struct ServiceUpsertReq {+ connection_id: String,+ req: dbx_core::nacos::NacosServiceUpsert,+}+#[derive(serde::Deserialize)]#[serde(rename_all = "camelCase")]pub(crate) struct InstanceListReq {@@ -106,7 +120,21 @@ pub(crate) struct InstanceListReq {#[serde(rename_all = "camelCase")]pub(crate) struct InstanceUpdateReq {connection_id: String,- req: dbx_core::nacos::NacosInstanceUpdate,+ req: dbx_core::nacos::NacosInstanceUpdateRequest,+}++#[derive(serde::Deserialize)]+#[serde(rename_all = "camelCase")]+pub(crate) struct InstanceRegistrationReq {+ connection_id: String,+ req: dbx_core::nacos::NacosInstanceRegistration,+}++#[derive(serde::Deserialize)]+#[serde(rename_all = "camelCase")]+pub(crate) struct InstanceRefReq {+ connection_id: String,+ req: dbx_core::nacos::NacosInstanceRef,}#[derive(serde::Deserialize)]@@ -319,6 +347,46 @@ pub async fn list_instances(Ok(Json(result))}+pub async fn get_service(+ State(state): State<Arc<WebState>>,+ Json(req): Json<ServiceQueryReq>,+) -> Result<Json<dbx_core::nacos::NacosServiceDetail>, AppError> {+ let result = dbx_core::nacos::service::nacos_get_service_core(&state.app, &req.connection_id, req.query)+ .await+ .map_err(AppError::from)?;+ Ok(Json(result))+}++pub async fn create_service(+ State(state): State<Arc<WebState>>,+ Json(req): Json<ServiceUpsertReq>,+) -> Result<Json<()>, AppError> {+ dbx_core::nacos::service::nacos_create_service_core(&state.app, &req.connection_id, req.req)+ .await+ .map_err(AppError::from)?;+ Ok(Json(()))+}++pub async fn update_service(+ State(state): State<Arc<WebState>>,+ Json(req): Json<ServiceUpsertReq>,+) -> Result<Json<()>, AppError> {+ dbx_core::nacos::service::nacos_update_service_core(&state.app, &req.connection_id, req.req)+ .await+ .map_err(AppError::from)?;+ Ok(Json(()))+}++pub async fn delete_service(+ State(state): State<Arc<WebState>>,+ Json(req): Json<ServiceQueryReq>,+) -> Result<Json<()>, AppError> {+ dbx_core::nacos::service::nacos_delete_service_core(&state.app, &req.connection_id, req.query)+ .await+ .map_err(AppError::from)?;+ Ok(Json(()))+}+pub async fn update_instance(State(state): State<Arc<WebState>>,Json(req): Json<InstanceUpdateReq>,@@ -329,6 +397,26 @@ pub async fn update_instance(Ok(Json(()))}+pub async fn register_instance(+ State(state): State<Arc<WebState>>,+ Json(req): Json<InstanceRegistrationReq>,+) -> Result<Json<()>, AppError> {+ dbx_core::nacos::service::nacos_register_instance_core(&state.app, &req.connection_id, req.req)+ .await+ .map_err(AppError::from)?;+ Ok(Json(()))+}++pub async fn deregister_instance(+ State(state): State<Arc<WebState>>,+ Json(req): Json<InstanceRefReq>,+) -> Result<Json<()>, AppError> {+ dbx_core::nacos::service::nacos_deregister_instance_core(&state.app, &req.connection_id, req.req)+ .await+ .map_err(AppError::from)?;+ Ok(Json(()))+}+pub async fn get_dashboard(State(state): State<Arc<WebState>>,Json(req): Json<DashboardReq>,@@ -754,4 +842,31 @@ mod batch_tests {request.connection_id = "connection-b".to_string();assert!(validate_nacos_import_context(&context, Some("preview-session"), &request).is_err());}++ #[test]+ fn instance_update_route_uses_target_and_patch_contract() {+ let request: InstanceUpdateReq = serde_json::from_value(serde_json::json!({+ "connectionId": "nacos-v2",+ "req": {+ "target": {+ "namespace": "public",+ "groupName": "DBX_TEST",+ "serviceName": "api",+ "ip": "127.0.0.1",+ "port": 8080,+ "clusterName": "blue",+ "ephemeral": false+ },+ "patch": {+ "weight": 2.5,+ "metadata": { "role": "api" }+ }+ }+ }))+ .unwrap();+ assert_eq!(request.connection_id, "nacos-v2");+ assert_eq!(request.req.target.ephemeral, Some(false));+ assert_eq!(request.req.patch.weight, Some(2.5));+ assert_eq!(request.req.patch.metadata, Some(serde_json::json!({ "role": "api" })));+ }}diff --git a/src-tauri/src/commands/nacos_cmd.rs b/src-tauri/src/commands/nacos_cmd.rsindex 43af958d3e..4761e6eee2 100644--- a/src-tauri/src/commands/nacos_cmd.rs+++ b/src-tauri/src/commands/nacos_cmd.rs@@ -129,6 +129,42 @@ pub async fn nacos_list_services(dbx_core::nacos::service::nacos_list_services_core(&state, &connection_id, query).await}+#[tauri::command]+pub async fn nacos_get_service(+ state: State<'_, Arc<AppState>>,+ connection_id: String,+ query: dbx_core::nacos::NacosServiceQuery,+) -> Result<dbx_core::nacos::NacosServiceDetail, String> {+ dbx_core::nacos::service::nacos_get_service_core(&state, &connection_id, query).await+}++#[tauri::command]+pub async fn nacos_create_service(+ state: State<'_, Arc<AppState>>,+ connection_id: String,+ req: dbx_core::nacos::NacosServiceUpsert,+) -> Result<(), String> {+ dbx_core::nacos::service::nacos_create_service_core(&state, &connection_id, req).await+}++#[tauri::command]+pub async fn nacos_update_service(+ state: State<'_, Arc<AppState>>,+ connection_id: String,+ req: dbx_core::nacos::NacosServiceUpsert,+) -> Result<(), String> {+ dbx_core::nacos::service::nacos_update_service_core(&state, &connection_id, req).await+}++#[tauri::command]+pub async fn nacos_delete_service(+ state: State<'_, Arc<AppState>>,+ connection_id: String,+ query: dbx_core::nacos::NacosServiceQuery,+) -> Result<(), String> {+ dbx_core::nacos::service::nacos_delete_service_core(&state, &connection_id, query).await+}+#[tauri::command]pub async fn nacos_list_instances(state: State<'_, Arc<AppState>>,@@ -142,11 +178,29 @@ pub async fn nacos_list_instances(pub async fn nacos_update_instance(state: State<'_, Arc<AppState>>,connection_id: String,- req: dbx_core::nacos::NacosInstanceUpdate,+ req: dbx_core::nacos::NacosInstanceUpdateRequest,) -> Result<(), String> {dbx_core::nacos::service::nacos_update_instance_core(&state, &connection_id, req).await}+#[tauri::command]+pub async fn nacos_register_instance(+ state: State<'_, Arc<AppState>>,+ connection_id: String,+ req: dbx_core::nacos::NacosInstanceRegistration,+) -> Result<(), String> {+ dbx_core::nacos::service::nacos_register_instance_core(&state, &connection_id, req).await+}++#[tauri::command]+pub async fn nacos_deregister_instance(+ state: State<'_, Arc<AppState>>,+ connection_id: String,+ req: dbx_core::nacos::NacosInstanceRef,+) -> Result<(), String> {+ dbx_core::nacos::service::nacos_deregister_instance_core(&state, &connection_id, req).await+}+#[tauri::command]pub async fn nacos_get_dashboard(state: State<'_, Arc<AppState>>,diff --git a/src-tauri/src/lib.rs b/src-tauri/src/lib.rsindex f2c35b99c0..0e376deb96 100644--- a/src-tauri/src/lib.rs+++ b/src-tauri/src/lib.rs@@ -1755,8 +1755,14 @@ pub fn run() {commands::nacos_cmd::nacos_get_rnacos_console_captcha,commands::nacos_cmd::nacos_login_rnacos_console,commands::nacos_cmd::nacos_list_services,+ commands::nacos_cmd::nacos_get_service,+ commands::nacos_cmd::nacos_create_service,+ commands::nacos_cmd::nacos_update_service,+ commands::nacos_cmd::nacos_delete_service,commands::nacos_cmd::nacos_list_instances,commands::nacos_cmd::nacos_update_instance,+ commands::nacos_cmd::nacos_register_instance,+ commands::nacos_cmd::nacos_deregister_instance,commands::nacos_cmd::nacos_get_dashboard,commands::nacos_cmd::nacos_raw_request,commands::nacos_cmd::nacos_search_config_content,