fix(plugins): stabilize plugin integration
This commit is contained in:
1 parent
b70d6da227
commit
3d1b84831f
76 files changed
+3846
-431
No files matched your search
Generated
+1
@@ -2050,6 +2050,7 @@ dependencies = [
|
|||||||
"tauri-plugin-single-instance",
|
"tauri-plugin-single-instance",
|
||||||
"tauri-plugin-updater",
|
"tauri-plugin-updater",
|
||||||
"tauri-plugin-window-state",
|
"tauri-plugin-window-state",
|
||||||
|
"tempfile",
|
||||||
"tiberius",
|
"tiberius",
|
||||||
"tokio",
|
"tokio",
|
||||||
"tokio-postgres",
|
"tokio-postgres",
|
||||||
|
|||||||
@@ -115,7 +115,7 @@ import { normalizeSqlExecutionTarget, sqlExecutionTargetCapabilities } from "@/l
|
|||||||
import { executeWithProductionSqlGuard } from "@/lib/database/productionExecutionGuard";
|
import { executeWithProductionSqlGuard } from "@/lib/database/productionExecutionGuard";
|
||||||
import { buildHistoryAiAnalysisPrompt } from "@/lib/history/historyAiAnalysis";
|
import { buildHistoryAiAnalysisPrompt } from "@/lib/history/historyAiAnalysis";
|
||||||
import { countAvailableAgentDriverUpdates } from "@/lib/connection/agentDriverUpdateBadge";
|
import { countAvailableAgentDriverUpdates } from "@/lib/connection/agentDriverUpdateBadge";
|
||||||
import type { DriverStoreFocus } from "@/lib/connection/agentDriverInstallHint";
|
import type { DriverStoreFocus, DriverStoreTab } from "@/lib/connection/agentDriverInstallHint";
|
||||||
import { safeLocalStorageGet, safeLocalStorageSet } from "@/lib/backend/safeStorage";
|
import { safeLocalStorageGet, safeLocalStorageSet } from "@/lib/backend/safeStorage";
|
||||||
import { apiUrl, webPath } from "@/lib/common/webPath";
|
import { apiUrl, webPath } from "@/lib/common/webPath";
|
||||||
import { shouldBlockAppNativeSelectAll } from "@/lib/common/clipboard";
|
import { shouldBlockAppNativeSelectAll } from "@/lib/common/clipboard";
|
||||||
@@ -152,6 +152,7 @@ import { resolveWindowContext } from "@/lib/app/windowContext";
|
|||||||
import { openDetachedTabWindow } from "@/lib/app/detachedTabWindow";
|
import { openDetachedTabWindow } from "@/lib/app/detachedTabWindow";
|
||||||
|
|
||||||
const AiAssistant = defineAsyncComponent(() => import("@/components/editor/AiAssistant.vue"));
|
const AiAssistant = defineAsyncComponent(() => import("@/components/editor/AiAssistant.vue"));
|
||||||
|
const PluginWorkbenchTab = defineAsyncComponent(() => import("@/components/plugins/PluginWorkbenchTab.vue"));
|
||||||
const QueryHistory = defineAsyncComponent(() => import("@/components/editor/QueryHistory.vue"));
|
const QueryHistory = defineAsyncComponent(() => import("@/components/editor/QueryHistory.vue"));
|
||||||
const SqlLibraryPanel = defineAsyncComponent(() => import("@/components/layout/SqlLibraryPanel.vue"));
|
const SqlLibraryPanel = defineAsyncComponent(() => import("@/components/layout/SqlLibraryPanel.vue"));
|
||||||
const SqlFilePanel = defineAsyncComponent(() => import("@/components/layout/SqlFilePanel.vue"));
|
const SqlFilePanel = defineAsyncComponent(() => import("@/components/layout/SqlFilePanel.vue"));
|
||||||
@@ -416,6 +417,10 @@ const blockingAiRunCount = computed(() => (isDesktop ? blockingDesktopAiRunsForQ
|
|||||||
let aiRunsQuitConfirmed = false;
|
let aiRunsQuitConfirmed = false;
|
||||||
|
|
||||||
const activeTab = computed(() => queryStore.tabs.find((t) => t.id === queryStore.activeTabId));
|
const activeTab = computed(() => queryStore.tabs.find((t) => t.id === queryStore.activeTabId));
|
||||||
|
// Plugin workbench tabs stay mounted once opened (hidden via v-show): an
|
||||||
|
// iframe moved out of the DOM reloads from scratch, so KeepAlive/ContentArea
|
||||||
|
// remounts flash the whole webview and drop its live session state.
|
||||||
|
const mountedPluginWorkbenchTabs = computed(() => queryStore.tabs.filter((tab) => tab.mode === "plugin-workbench" && tab.pluginWorkbench));
|
||||||
const tabNavigationHistory = ref(createTabNavigationHistory());
|
const tabNavigationHistory = ref(createTabNavigationHistory());
|
||||||
let pendingTabHistoryNavigationId: string | null = null;
|
let pendingTabHistoryNavigationId: string | null = null;
|
||||||
let detachedEventUnlisteners: Array<() => void> = [];
|
let detachedEventUnlisteners: Array<() => void> = [];
|
||||||
@@ -870,10 +875,10 @@ function requestActiveEditorExecuteInNewResultTab() {
|
|||||||
const specialPageTabs = computed(() => ({
|
const specialPageTabs = computed(() => ({
|
||||||
settingsOpen: settingsPageTabOpen.value,
|
settingsOpen: settingsPageTabOpen.value,
|
||||||
settingsActive: settingsStore.settingsPageActive,
|
settingsActive: settingsStore.settingsPageActive,
|
||||||
driverStoreOpen: driverStoreTabOpen.value,
|
|
||||||
driverStoreActive: driverStoreActive.value,
|
|
||||||
pluginCenterOpen: pluginCenterTabOpen.value,
|
pluginCenterOpen: pluginCenterTabOpen.value,
|
||||||
pluginCenterActive: pluginCenterActive.value,
|
pluginCenterActive: pluginCenterActive.value,
|
||||||
|
driverStoreOpen: driverStoreTabOpen.value,
|
||||||
|
driverStoreActive: driverStoreActive.value,
|
||||||
driverUpdateCount: toolbarAgentDriverUpdateCount.value,
|
driverUpdateCount: toolbarAgentDriverUpdateCount.value,
|
||||||
}));
|
}));
|
||||||
provide(GROUP_TAB_BAR_PORTAL, createGroupTabBarPortal(computed(() => !isDetachedWindowContext && (driverStoreActive.value || pluginCenterActive.value || settingsStore.settingsPageActive))));
|
provide(GROUP_TAB_BAR_PORTAL, createGroupTabBarPortal(computed(() => !isDetachedWindowContext && (driverStoreActive.value || pluginCenterActive.value || settingsStore.settingsPageActive))));
|
||||||
@@ -903,10 +908,10 @@ provide(EDITOR_TOOLBAR_ACTIONS, {
|
|||||||
specialPageTabs,
|
specialPageTabs,
|
||||||
activateSettingsPage,
|
activateSettingsPage,
|
||||||
closeSettingsPage,
|
closeSettingsPage,
|
||||||
activateDriverStore: () => openDriverStorePage(),
|
|
||||||
closeDriverStore: closeDriverStorePage,
|
|
||||||
activatePluginCenter: () => openPluginCenterPage(pluginCenterFocus.value),
|
activatePluginCenter: () => openPluginCenterPage(pluginCenterFocus.value),
|
||||||
closePluginCenter: closePluginCenterPage,
|
closePluginCenter: closePluginCenterPage,
|
||||||
|
activateDriverStore: () => openDriverStorePage(),
|
||||||
|
closeDriverStore: closeDriverStorePage,
|
||||||
});
|
});
|
||||||
|
|
||||||
// Upstream "preview changes" entry: dormant until the group toolbar wires the
|
// Upstream "preview changes" entry: dormant until the group toolbar wires the
|
||||||
@@ -990,8 +995,8 @@ const { setupTauriListeners, cleanupTauriListeners } = useTauriEvents({
|
|||||||
openSqlFilePath,
|
openSqlFilePath,
|
||||||
openDbFilePath,
|
openDbFilePath,
|
||||||
openConnectionDeepLink,
|
openConnectionDeepLink,
|
||||||
openAiConfigDeepLink,
|
|
||||||
closeActiveSurface,
|
closeActiveSurface,
|
||||||
|
openAiConfigDeepLink,
|
||||||
});
|
});
|
||||||
const { showCloseActionPrompt, chooseQuit, chooseMinimize, cancelCloseActionPrompt, performCloseAction, setupCloseActionPromptListener, cleanupCloseActionPromptListener } = useCloseActionPrompt({ requestClose: requestAppClose });
|
const { showCloseActionPrompt, chooseQuit, chooseMinimize, cancelCloseActionPrompt, performCloseAction, setupCloseActionPromptListener, cleanupCloseActionPromptListener } = useCloseActionPrompt({ requestClose: requestAppClose });
|
||||||
useVisibilityChange();
|
useVisibilityChange();
|
||||||
@@ -1089,7 +1094,7 @@ function closeSettingsPage() {
|
|||||||
|
|
||||||
const driverStoreFocus = ref<DriverStoreFocus | null>(null);
|
const driverStoreFocus = ref<DriverStoreFocus | null>(null);
|
||||||
|
|
||||||
function openDriverStorePage(target?: "agent" | "jdbc" | "storage" | "runtime" | DriverStoreFocus | null) {
|
function openDriverStorePage(target?: DriverStoreTab | DriverStoreFocus | null) {
|
||||||
if (typeof target === "string") {
|
if (typeof target === "string") {
|
||||||
driverStoreActiveTab.value = target;
|
driverStoreActiveTab.value = target;
|
||||||
driverStoreFocus.value = null;
|
driverStoreFocus.value = null;
|
||||||
@@ -1101,6 +1106,7 @@ function openDriverStorePage(target?: "agent" | "jdbc" | "storage" | "runtime" |
|
|||||||
}
|
}
|
||||||
driverStoreTabOpen.value = true;
|
driverStoreTabOpen.value = true;
|
||||||
activateMainContentSurface("driverStore");
|
activateMainContentSurface("driverStore");
|
||||||
|
pluginCenterActive.value = false;
|
||||||
}
|
}
|
||||||
|
|
||||||
function closeDriverStorePage() {
|
function closeDriverStorePage() {
|
||||||
@@ -1329,6 +1335,7 @@ watch(
|
|||||||
if (id) newQueryContextSource.value = "tab";
|
if (id) newQueryContextSource.value = "tab";
|
||||||
if (id) activateQuerySurface();
|
if (id) activateQuerySurface();
|
||||||
else if (previousId) activateOpenSpecialPageFallback();
|
else if (previousId) activateOpenSpecialPageFallback();
|
||||||
|
if (id && pluginCenterActive.value) pluginCenterActive.value = false;
|
||||||
const tab = id ? queryStore.tabs.find((candidate) => candidate.id === id) : undefined;
|
const tab = id ? queryStore.tabs.find((candidate) => candidate.id === id) : undefined;
|
||||||
const selection = tab?.editorSelection;
|
const selection = tab?.editorSelection;
|
||||||
selectedSql.value = tab && selection && selection.anchor !== selection.head ? tab.sql.slice(Math.min(selection.anchor, selection.head), Math.max(selection.anchor, selection.head)) : "";
|
selectedSql.value = tab && selection && selection.anchor !== selection.head ? tab.sql.slice(Math.min(selection.anchor, selection.head), Math.max(selection.anchor, selection.head)) : "";
|
||||||
@@ -2308,6 +2315,7 @@ async function openConnectionDeepLink(url: string) {
|
|||||||
if (!draft) return;
|
if (!draft) return;
|
||||||
connectionStore.stopEditing();
|
connectionStore.stopEditing();
|
||||||
connectionStore.stopCreatingConnectionInGroup();
|
connectionStore.stopCreatingConnectionInGroup();
|
||||||
|
connectionPluginProvider.value = null;
|
||||||
connectionDialogPrefill.value = draft;
|
connectionDialogPrefill.value = draft;
|
||||||
showConnectionDialog.value = true;
|
showConnectionDialog.value = true;
|
||||||
} catch (e: any) {
|
} catch (e: any) {
|
||||||
@@ -2372,6 +2380,7 @@ function setConnectionDialogOpen(value: boolean) {
|
|||||||
|
|
||||||
function openConnectionSettings(connectionId: string, initialTab: ConfigTab = "connection") {
|
function openConnectionSettings(connectionId: string, initialTab: ConfigTab = "connection") {
|
||||||
if (!connectionStore.getConfig(connectionId)) return;
|
if (!connectionStore.getConfig(connectionId)) return;
|
||||||
|
connectionPluginProvider.value = null;
|
||||||
connectionDialogInitialTab.value = initialTab;
|
connectionDialogInitialTab.value = initialTab;
|
||||||
connectionStore.startEditing(connectionId);
|
connectionStore.startEditing(connectionId);
|
||||||
showConnectionDialog.value = true;
|
showConnectionDialog.value = true;
|
||||||
@@ -2398,6 +2407,8 @@ async function newQuery() {
|
|||||||
} else if (connectionTarget.kind === "nacos-admin") {
|
} else if (connectionTarget.kind === "nacos-admin") {
|
||||||
await connectionStore.loadNacosNamespaces(target.connectionId);
|
await connectionStore.loadNacosNamespaces(target.connectionId);
|
||||||
queryStore.openNacosAdmin(target.connectionId);
|
queryStore.openNacosAdmin(target.connectionId);
|
||||||
|
} else if (connectionTarget.kind === "plugin-workbench") {
|
||||||
|
await queryStore.openPluginConnection(target.connectionId);
|
||||||
} else {
|
} else {
|
||||||
queryStore.createTab(target.connectionId, "", `${conn.name}:keys`, connectionTarget.kind);
|
queryStore.createTab(target.connectionId, "", `${conn.name}:keys`, connectionTarget.kind);
|
||||||
}
|
}
|
||||||
@@ -3038,6 +3049,7 @@ function activateQueryTab(tabId: string): boolean {
|
|||||||
dispatchBeforeTabSwitch(tabId);
|
dispatchBeforeTabSwitch(tabId);
|
||||||
if (!queryStore.activateTab(tabId)) return false;
|
if (!queryStore.activateTab(tabId)) return false;
|
||||||
activateQuerySurface();
|
activateQuerySurface();
|
||||||
|
pluginCenterActive.value = false;
|
||||||
return true;
|
return true;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -3357,6 +3369,11 @@ async function initApp() {
|
|||||||
onOptionalStateError: (error) => console.error("[STARTUP] settingsStore.initAiConfigs failed", error),
|
onOptionalStateError: (error) => console.error("[STARTUP] settingsStore.initAiConfigs failed", error),
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
// Restored plugin tabs need the sidecar connection registry repopulated
|
||||||
|
// (see reconnectRestoredPluginTabs); kick it off before the heavier
|
||||||
|
// optional init so it races ahead of each plugin webview's first
|
||||||
|
// session/open. Fire-and-forget: it must never block startup.
|
||||||
|
void queryStore.reconnectRestoredPluginTabs();
|
||||||
await settingsStore.initDesktopSettings().catch(() => {});
|
await settingsStore.initDesktopSettings().catch(() => {});
|
||||||
if (isDesktop) {
|
if (isDesktop) {
|
||||||
updateWindowReady = true;
|
updateWindowReady = true;
|
||||||
@@ -3651,6 +3668,7 @@ onUnmounted(() => {
|
|||||||
:tab-bar-width="tabBarWidth"
|
:tab-bar-width="tabBarWidth"
|
||||||
:tab-bar-collapsed="tabBarCollapsed"
|
:tab-bar-collapsed="tabBarCollapsed"
|
||||||
@activate-driver-store="openDriverStorePage"
|
@activate-driver-store="openDriverStorePage"
|
||||||
|
@activate-plugin-center="openPluginCenterPage(pluginCenterFocus)"
|
||||||
@activate-settings-page="activateSettingsPage"
|
@activate-settings-page="activateSettingsPage"
|
||||||
@activate-tab="activateQueryTab"
|
@activate-tab="activateQueryTab"
|
||||||
@close-driver-store="closeDriverStorePage"
|
@close-driver-store="closeDriverStorePage"
|
||||||
@@ -3707,9 +3725,10 @@ onUnmounted(() => {
|
|||||||
</DialogContent>
|
</DialogContent>
|
||||||
</Dialog>
|
</Dialog>
|
||||||
<div v-show="!driverStoreActive && !pluginCenterActive && !settingsStore.settingsPageActive" class="flex min-h-0 min-w-0 flex-1 flex-col">
|
<div v-show="!driverStoreActive && !pluginCenterActive && !settingsStore.settingsPageActive" class="flex min-h-0 min-w-0 flex-1 flex-col">
|
||||||
<div class="flex flex-col flex-1 min-h-0">
|
<div class="flex flex-col min-h-0" :class="activeTab?.mode === 'plugin-workbench' ? 'flex-none' : 'flex-1'">
|
||||||
<SqlEditorWorkspace
|
<SqlEditorWorkspace
|
||||||
ref="contentAreaRef"
|
ref="contentAreaRef"
|
||||||
|
:content-suppressed="activeTab?.mode === 'plugin-workbench'"
|
||||||
@locate-tab="locateTabInSidebar"
|
@locate-tab="locateTabInSidebar"
|
||||||
@close-tab="
|
@close-tab="
|
||||||
(tabId: string) => {
|
(tabId: string) => {
|
||||||
@@ -3850,6 +3869,15 @@ onUnmounted(() => {
|
|||||||
</template>
|
</template>
|
||||||
</SqlEditorWorkspace>
|
</SqlEditorWorkspace>
|
||||||
</div>
|
</div>
|
||||||
|
<!-- Always-mounted plugin workbench layer: switching tabs only
|
||||||
|
toggles visibility, so plugin webviews (SSH terminals) are
|
||||||
|
never destroyed and reloaded. SqlEditorWorkspace no longer
|
||||||
|
renders plugin tabs — this layer owns them. It in turn
|
||||||
|
yields the layout (display:none) while a plugin tab is
|
||||||
|
active, or both flex-1 siblings would split the column. -->
|
||||||
|
<div v-for="workbenchTab in mountedPluginWorkbenchTabs" :key="workbenchTab.id" v-show="activeTab && workbenchTab.id === activeTab.id" class="flex min-h-0 flex-1 flex-col">
|
||||||
|
<PluginWorkbenchTab :plugin-id="workbenchTab.pluginWorkbench!.pluginId" :contribution-id="workbenchTab.pluginWorkbench!.contributionId" :context="workbenchTab.pluginWorkbench!.context" @close-tab="queryStore.closeTab(workbenchTab.id)" />
|
||||||
|
</div>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|||||||
@@ -1443,8 +1443,8 @@ watch(driverStoreTab, (tab) => {
|
|||||||
<div class="driver-store-scroll flex-1 min-h-0 overflow-y-auto">
|
<div class="driver-store-scroll flex-1 min-h-0 overflow-y-auto">
|
||||||
<div class="driver-store-container max-w-4xl mx-auto px-6 py-6">
|
<div class="driver-store-container max-w-4xl mx-auto px-6 py-6">
|
||||||
<Tabs v-model="driverStoreTab" default-value="agent" class="driver-store-tabs-root">
|
<Tabs v-model="driverStoreTab" default-value="agent" class="driver-store-tabs-root">
|
||||||
<div class="driver-store-header flex items-center justify-between">
|
<div class="driver-store-header flex flex-wrap items-center justify-between gap-2">
|
||||||
<TabsList class="driver-store-tabs grid w-[360px] grid-cols-3">
|
<TabsList class="driver-store-tabs grid w-full max-w-[380px] grid-cols-3">
|
||||||
<TabsTrigger value="agent" class="gap-1.5 relative">
|
<TabsTrigger value="agent" class="gap-1.5 relative">
|
||||||
{{ t("driverStore.agentDrivers") }}
|
{{ t("driverStore.agentDrivers") }}
|
||||||
<span v-if="agentTabUpdateCount > 0" class="inline-block h-2 w-2 rounded-full bg-red-500" />
|
<span v-if="agentTabUpdateCount > 0" class="inline-block h-2 w-2 rounded-full bg-red-500" />
|
||||||
@@ -2263,7 +2263,7 @@ watch(driverStoreTab, (tab) => {
|
|||||||
|
|
||||||
.driver-store-tabs {
|
.driver-store-tabs {
|
||||||
display: grid !important;
|
display: grid !important;
|
||||||
width: 360px !important;
|
width: 480px !important;
|
||||||
grid-template-columns: repeat(3, minmax(0, 1fr)) !important;
|
grid-template-columns: repeat(3, minmax(0, 1fr)) !important;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -92,6 +92,7 @@ import { assertCompleteDatabaseCategories, databaseSelectionForCategory } from "
|
|||||||
import { loadConnectionPickerView, saveConnectionPickerView, type DbPickerView } from "@/lib/connection/connectionPickerViewPreference";
|
import { loadConnectionPickerView, saveConnectionPickerView, type DbPickerView } from "@/lib/connection/connectionPickerViewPreference";
|
||||||
import { normalizeRocketmqNamesrvAddr } from "@/lib/connection/rocketmqNamesrv";
|
import { normalizeRocketmqNamesrvAddr } from "@/lib/connection/rocketmqNamesrv";
|
||||||
import { normalizeRabbitmqAddresses, parseRabbitmqAddress } from "@/lib/connection/rabbitmqAddresses";
|
import { normalizeRabbitmqAddresses, parseRabbitmqAddress } from "@/lib/connection/rabbitmqAddresses";
|
||||||
|
import { pluginFieldIsRequired, pluginFieldIsVisible } from "@/lib/plugins/pluginFieldConditions";
|
||||||
import { detectMqUiAuthKind, isMqAuthKindAllowedForSystem, type MqUiAuthKind } from "@/lib/connection/mqAuth";
|
import { detectMqUiAuthKind, isMqAuthKindAllowedForSystem, type MqUiAuthKind } from "@/lib/connection/mqAuth";
|
||||||
import { driverInstallProgressChannel, driverInstallProgressPercent, isDriverInstallProgressForOperation, requestAgentInstallCancellation, resolveAgentInstallOutcome, type DriverInstallProgress } from "@/lib/connection/driverInstallProgressUi";
|
import { driverInstallProgressChannel, driverInstallProgressPercent, isDriverInstallProgressForOperation, requestAgentInstallCancellation, resolveAgentInstallOutcome, type DriverInstallProgress } from "@/lib/connection/driverInstallProgressUi";
|
||||||
import { requiresSqlServerLegacyCompatibilityComponent, setSqlServerLegacyCompatibilityConfig, sqlServerUsesLegacyCompatibility, SQLSERVER_LEGACY_COMPATIBILITY_DRIVER_KEY } from "@/lib/connection/sqlServerLegacyCompatibility";
|
import { requiresSqlServerLegacyCompatibilityComponent, setSqlServerLegacyCompatibilityConfig, sqlServerUsesLegacyCompatibility, SQLSERVER_LEGACY_COMPATIBILITY_DRIVER_KEY } from "@/lib/connection/sqlServerLegacyCompatibility";
|
||||||
@@ -255,6 +256,8 @@ type LegacyTransportFields = {
|
|||||||
type LegacyConnectionConfig = ConnectionConfig & LegacyTransportFields;
|
type LegacyConnectionConfig = ConnectionConfig & LegacyTransportFields;
|
||||||
type ConnectionForm = Omit<ConnectionConfig, "id">;
|
type ConnectionForm = Omit<ConnectionConfig, "id">;
|
||||||
type ConnectionTestState = ConnectionTestResult & { ok: boolean; scope?: "connection" | "ssh" };
|
type ConnectionTestState = ConnectionTestResult & { ok: boolean; scope?: "connection" | "ssh" };
|
||||||
|
type PluginActionStatus = { ok: boolean; message: string };
|
||||||
|
type SaveConnectionOptions = { connectAfterSave?: boolean; closeOnSuccess?: boolean };
|
||||||
|
|
||||||
const { t, locale: appLocale } = useI18n();
|
const { t, locale: appLocale } = useI18n();
|
||||||
const { toast } = useToast();
|
const { toast } = useToast();
|
||||||
@@ -328,11 +331,9 @@ const connectionErrorDetail = ref("");
|
|||||||
const testResultCopied = ref(false);
|
const testResultCopied = ref(false);
|
||||||
const connectionErrorCopied = ref(false);
|
const connectionErrorCopied = ref(false);
|
||||||
const editingId = ref<string | null>(null);
|
const editingId = ref<string | null>(null);
|
||||||
const installedPlugins = ref<InstalledPlugin[]>([]);
|
|
||||||
const pluginFormValues = ref<Record<string, PluginFormFieldValue>>({});
|
const pluginFormValues = ref<Record<string, PluginFormFieldValue>>({});
|
||||||
const pluginLoadError = ref("");
|
const pluginLoadError = ref("");
|
||||||
const runningPluginActionId = ref<string | null>(null);
|
const runningPluginActionId = ref<string | null>(null);
|
||||||
type PluginActionStatus = { ok: boolean; message: string };
|
|
||||||
const pluginActionStatus = ref<PluginActionStatus | null>(null);
|
const pluginActionStatus = ref<PluginActionStatus | null>(null);
|
||||||
const draftTestConnectionId = ref(uuid());
|
const draftTestConnectionId = ref(uuid());
|
||||||
const showVisibleDatabasesDialog = ref(false);
|
const showVisibleDatabasesDialog = ref(false);
|
||||||
@@ -365,6 +366,7 @@ const isLoadingVisibleSchemas = ref(false);
|
|||||||
const visibleSchemaNames = ref<string[]>([]);
|
const visibleSchemaNames = ref<string[]>([]);
|
||||||
const visibleSchemaInitialSelection = ref<string[]>([]);
|
const visibleSchemaInitialSelection = ref<string[]>([]);
|
||||||
const visibleSchemaError = ref("");
|
const visibleSchemaError = ref("");
|
||||||
|
const installedPlugins = ref<InstalledPlugin[]>([]);
|
||||||
let testRunId = 0;
|
let testRunId = 0;
|
||||||
let unlistenAgentInstallProgress: (() => void) | null = null;
|
let unlistenAgentInstallProgress: (() => void) | null = null;
|
||||||
|
|
||||||
@@ -759,6 +761,13 @@ const keepaliveEnabled = computed({
|
|||||||
const selectedTransportLayerId = ref<string | null>(null);
|
const selectedTransportLayerId = ref<string | null>(null);
|
||||||
const draggedTransportLayerId = ref<string | null>(null);
|
const draggedTransportLayerId = ref<string | null>(null);
|
||||||
const selectedType = ref("mysql");
|
const selectedType = ref("mysql");
|
||||||
|
const pluginRegistry = computed(() => createFrontendPluginRegistry(installedPlugins.value, appLocale.value));
|
||||||
|
const pluginConnectionProviders = computed(() => pluginRegistry.value.listConnectionProviders());
|
||||||
|
const selectedPluginProvider = computed(() => pluginProviderEntryForOption(selectedType.value));
|
||||||
|
const selectedPluginIcon = computed(() => (selectedPluginProvider.value ? pluginConnectionProviderIcon(selectedPluginProvider.value) : undefined));
|
||||||
|
const isPluginConnection = computed(() => form.value.db_type === "plugin");
|
||||||
|
const pluginFooterActions = computed<PluginConnectionAction[]>(() => (selectedPluginProvider.value ? pluginConnectionActionsForDialog(selectedPluginProvider.value.contribution, !!editingId.value) : []));
|
||||||
|
const pluginFooterBusy = computed(() => isTesting.value || isSaving.value || !!runningPluginActionId.value);
|
||||||
const customDriverName = ref("");
|
const customDriverName = ref("");
|
||||||
const mongoUseUrl = ref(false);
|
const mongoUseUrl = ref(false);
|
||||||
const jdbcDriverPathsInput = ref("");
|
const jdbcDriverPathsInput = ref("");
|
||||||
@@ -1190,13 +1199,6 @@ function selectedProfile() {
|
|||||||
return driverProfiles[profile] ?? driverProfiles.mysql;
|
return driverProfiles[profile] ?? driverProfiles.mysql;
|
||||||
}
|
}
|
||||||
|
|
||||||
const isPluginConnection = computed(() => form.value.db_type === "plugin");
|
|
||||||
const pluginConnectionProviders = computed(() => createFrontendPluginRegistry(installedPlugins.value, appLocale.value).listConnectionProviders());
|
|
||||||
const selectedPluginProvider = computed(() => pluginProviderEntryForOption(selectedType.value));
|
|
||||||
const selectedPluginIcon = computed(() => (selectedPluginProvider.value ? pluginConnectionProviderIcon(selectedPluginProvider.value) : undefined));
|
|
||||||
const pluginFooterActions = computed<PluginConnectionAction[]>(() => (selectedPluginProvider.value ? pluginConnectionActionsForDialog(selectedPluginProvider.value.contribution, !!editingId.value) : []));
|
|
||||||
const pluginFooterBusy = computed(() => isTesting.value || isSaving.value || !!runningPluginActionId.value);
|
|
||||||
|
|
||||||
function pluginProviderEntry(pluginId: string, providerId: string) {
|
function pluginProviderEntry(pluginId: string, providerId: string) {
|
||||||
return pluginConnectionProviders.value.find((entry) => entry.plugin.manifest.id === pluginId && entry.contribution.id === providerId) || null;
|
return pluginConnectionProviders.value.find((entry) => entry.plugin.manifest.id === pluginId && entry.contribution.id === providerId) || null;
|
||||||
}
|
}
|
||||||
@@ -1206,62 +1208,6 @@ function pluginProviderEntryForOption(value: string) {
|
|||||||
return target ? pluginProviderEntry(target.pluginId, target.providerId) : null;
|
return target ? pluginProviderEntry(target.pluginId, target.providerId) : null;
|
||||||
}
|
}
|
||||||
|
|
||||||
function applyPluginProvider(value: string, preserveConnectionFields = false, existing?: ConnectionConfig): boolean {
|
|
||||||
const target = parsePluginConnectionProviderOptionValue(value);
|
|
||||||
if (!target) return false;
|
|
||||||
const entry = pluginProviderEntry(target.pluginId, target.providerId);
|
|
||||||
if (!entry) return false;
|
|
||||||
|
|
||||||
selectedType.value = value;
|
|
||||||
if (!preserveConnectionFields) {
|
|
||||||
form.value = {
|
|
||||||
...defaultForm(),
|
|
||||||
name: entry.contribution.label,
|
|
||||||
db_type: "plugin",
|
|
||||||
driver_profile: "plugin",
|
|
||||||
driver_label: entry.contribution.label,
|
|
||||||
host: "",
|
|
||||||
port: 0,
|
|
||||||
username: "",
|
|
||||||
password: "",
|
|
||||||
query_timeout_secs: 60,
|
|
||||||
};
|
|
||||||
} else {
|
|
||||||
form.value.db_type = "plugin";
|
|
||||||
form.value.driver_profile = "plugin";
|
|
||||||
form.value.driver_label = entry.contribution.label;
|
|
||||||
}
|
|
||||||
pluginFormValues.value = pluginConnectionFormValues(entry.contribution, existing);
|
|
||||||
if (!preserveConnectionFields) {
|
|
||||||
const nameField = entry.contribution.fields.find((field) => field.binding === "name");
|
|
||||||
const defaultName = nameField ? pluginFormValues.value[nameField.key] : undefined;
|
|
||||||
if (typeof defaultName === "string" && defaultName.trim()) form.value.name = defaultName.trim();
|
|
||||||
}
|
|
||||||
connectionUrlInput.value = "";
|
|
||||||
appliedConnectionUrlInput.value = "";
|
|
||||||
return true;
|
|
||||||
}
|
|
||||||
|
|
||||||
async function loadInstalledPlugins() {
|
|
||||||
pluginLoadError.value = "";
|
|
||||||
try {
|
|
||||||
installedPlugins.value = await api.listPlugins();
|
|
||||||
} catch (cause) {
|
|
||||||
installedPlugins.value = [];
|
|
||||||
pluginLoadError.value = cause instanceof Error ? cause.message : String(cause);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
function applyRequestedPluginProvider(target: PluginCenterFocus | null | undefined) {
|
|
||||||
if (!target?.pluginId || !target.providerId) return false;
|
|
||||||
const value = pluginConnectionProviderOptionValue(target.pluginId, target.providerId);
|
|
||||||
if (!applyPluginProvider(value)) return false;
|
|
||||||
selectedDbCategory.value = "plugins";
|
|
||||||
dialogStep.value = "config";
|
|
||||||
configTab.value = "connection";
|
|
||||||
return true;
|
|
||||||
}
|
|
||||||
|
|
||||||
function mqExtraRecord(config?: Partial<MqAdminConfig>): Record<string, unknown> {
|
function mqExtraRecord(config?: Partial<MqAdminConfig>): Record<string, unknown> {
|
||||||
const extra = config?.extra;
|
const extra = config?.extra;
|
||||||
return extra && typeof extra === "object" && !Array.isArray(extra) ? (extra as Record<string, unknown>) : {};
|
return extra && typeof extra === "object" && !Array.isArray(extra) ? (extra as Record<string, unknown>) : {};
|
||||||
@@ -2589,6 +2535,62 @@ function applyProfile(val: string, preserveConnectionFields = false) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
function applyPluginProvider(value: string, preserveConnectionFields = false, existing?: ConnectionConfig): boolean {
|
||||||
|
const target = parsePluginConnectionProviderOptionValue(value);
|
||||||
|
if (!target) return false;
|
||||||
|
const entry = pluginProviderEntry(target.pluginId, target.providerId);
|
||||||
|
if (!entry) return false;
|
||||||
|
|
||||||
|
selectedType.value = value;
|
||||||
|
if (!preserveConnectionFields) {
|
||||||
|
form.value = {
|
||||||
|
...defaultForm(),
|
||||||
|
name: entry.contribution.label,
|
||||||
|
db_type: "plugin",
|
||||||
|
driver_profile: "plugin",
|
||||||
|
driver_label: entry.contribution.label,
|
||||||
|
host: "",
|
||||||
|
port: 0,
|
||||||
|
username: "",
|
||||||
|
password: "",
|
||||||
|
query_timeout_secs: 60,
|
||||||
|
};
|
||||||
|
} else {
|
||||||
|
form.value.db_type = "plugin";
|
||||||
|
form.value.driver_profile = "plugin";
|
||||||
|
form.value.driver_label = entry.contribution.label;
|
||||||
|
}
|
||||||
|
pluginFormValues.value = pluginConnectionFormValues(entry.contribution, existing);
|
||||||
|
if (!preserveConnectionFields) {
|
||||||
|
const nameField = entry.contribution.fields.find((field) => field.binding === "name");
|
||||||
|
const defaultName = nameField ? pluginFormValues.value[nameField.key] : undefined;
|
||||||
|
if (typeof defaultName === "string" && defaultName.trim()) form.value.name = defaultName.trim();
|
||||||
|
}
|
||||||
|
connectionUrlInput.value = "";
|
||||||
|
appliedConnectionUrlInput.value = "";
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
async function loadInstalledPlugins() {
|
||||||
|
pluginLoadError.value = "";
|
||||||
|
try {
|
||||||
|
installedPlugins.value = await api.listPlugins();
|
||||||
|
} catch (cause) {
|
||||||
|
installedPlugins.value = [];
|
||||||
|
pluginLoadError.value = cause instanceof Error ? cause.message : String(cause);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function applyRequestedPluginProvider(target: PluginCenterFocus | null | undefined) {
|
||||||
|
if (!target?.pluginId || !target.providerId) return false;
|
||||||
|
const value = pluginConnectionProviderOptionValue(target.pluginId, target.providerId);
|
||||||
|
if (!applyPluginProvider(value)) return false;
|
||||||
|
selectedDbCategory.value = "plugins";
|
||||||
|
dialogStep.value = "config";
|
||||||
|
configTab.value = "connection";
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
function switchOceanbaseMode(mode: "mysql" | "oracle") {
|
function switchOceanbaseMode(mode: "mysql" | "oracle") {
|
||||||
oceanbaseSubMode.value = mode;
|
oceanbaseSubMode.value = mode;
|
||||||
if (mode === "mysql") {
|
if (mode === "mysql") {
|
||||||
@@ -2626,7 +2628,7 @@ watch(
|
|||||||
name: config.name,
|
name: config.name,
|
||||||
note: config.note || "",
|
note: config.note || "",
|
||||||
db_type: oceanbasePatch?.db_type || profileConfig?.type || config.db_type,
|
db_type: oceanbasePatch?.db_type || profileConfig?.type || config.db_type,
|
||||||
driver_profile: oceanbasePatch?.driver_profile || config.driver_profile || profile,
|
driver_profile: config.db_type === "plugin" ? "plugin" : oceanbasePatch?.driver_profile || config.driver_profile || profile,
|
||||||
driver_label: config.driver_label || oceanbasePatch?.driver_label || driverProfiles[profile]?.label || config.db_type,
|
driver_label: config.driver_label || oceanbasePatch?.driver_label || driverProfiles[profile]?.label || config.db_type,
|
||||||
url_params: config.url_params || "",
|
url_params: config.url_params || "",
|
||||||
agent_java_options: config.agent_java_options || [],
|
agent_java_options: config.agent_java_options || [],
|
||||||
@@ -2770,6 +2772,7 @@ watch(
|
|||||||
productionProtectionEnabled.value = false;
|
productionProtectionEnabled.value = false;
|
||||||
selectedTransportLayerId.value = null;
|
selectedTransportLayerId.value = null;
|
||||||
selectedType.value = "mysql";
|
selectedType.value = "mysql";
|
||||||
|
pluginFormValues.value = {};
|
||||||
customDriverName.value = "";
|
customDriverName.value = "";
|
||||||
resetMqFields();
|
resetMqFields();
|
||||||
resetCassandraTlsFields(undefined);
|
resetCassandraTlsFields(undefined);
|
||||||
@@ -3013,10 +3016,10 @@ const dbCategoryMetadata: Array<{ key: DbCategoryKey; titleKey: string }> = [
|
|||||||
{ key: "registry_config", titleKey: "connection.databaseCategoryRegistryConfig" },
|
{ key: "registry_config", titleKey: "connection.databaseCategoryRegistryConfig" },
|
||||||
];
|
];
|
||||||
|
|
||||||
function jdbcProductCategory(profileId: string): DbCategoryKey {
|
function jdbcProductCategory(profileId: string): ConnectionProfileCategory {
|
||||||
const category = dbCategoryMetadata.find(({ key }) => jdbcProductProfileIdsForCategory(key).includes(profileId))?.key;
|
const category: DbCategoryKey | undefined = dbCategoryMetadata.find(({ key }) => jdbcProductProfileIdsForCategory(key).includes(profileId))?.key;
|
||||||
if (!category) throw new Error(`JDBC product profile ${profileId} has no connection picker category`);
|
if (category !== "plugins" && category) return category;
|
||||||
return category;
|
throw new Error(`JDBC product profile ${profileId} has no connection picker category`);
|
||||||
}
|
}
|
||||||
|
|
||||||
// `influxdb3` is presented as a version option inside the InfluxDB card
|
// `influxdb3` is presented as a version option inside the InfluxDB card
|
||||||
@@ -3092,7 +3095,7 @@ const selectedDbOptionIsVisible = computed(() => visibleDbCategories.value.some(
|
|||||||
function selectDbCategory(category: DbCategoryKey) {
|
function selectDbCategory(category: DbCategoryKey) {
|
||||||
selectedDbCategory.value = category;
|
selectedDbCategory.value = category;
|
||||||
dbSearchQuery.value = "";
|
dbSearchQuery.value = "";
|
||||||
const categoryOptions = dbCategoryDefinitions.find((definition) => definition.key === category)?.optionValues ?? [];
|
const categoryOptions = dbCategories.value.find((definition) => definition.key === category)?.options.map((option) => option.value) ?? [];
|
||||||
const nextSelection = databaseSelectionForCategory(selectedType.value, categoryOptions);
|
const nextSelection = databaseSelectionForCategory(selectedType.value, categoryOptions);
|
||||||
if (nextSelection && nextSelection !== selectedType.value) onDbTypeChange(nextSelection);
|
if (nextSelection && nextSelection !== selectedType.value) onDbTypeChange(nextSelection);
|
||||||
}
|
}
|
||||||
@@ -3573,6 +3576,32 @@ const pluginActionStatusMessage = computed(() => {
|
|||||||
if (!pluginActionStatus.value) return "";
|
if (!pluginActionStatus.value) return "";
|
||||||
return pluginActionStatus.value.ok ? pluginActionStatus.value.message : translateBackendError(t, pluginActionStatus.value.message);
|
return pluginActionStatus.value.ok ? pluginActionStatus.value.message : translateBackendError(t, pluginActionStatus.value.message);
|
||||||
});
|
});
|
||||||
|
const agentInstallPercent = computed(() => driverInstallProgressPercent(agentInstallProgress.value));
|
||||||
|
const agentInstallProgressLabel = computed(() => {
|
||||||
|
const progress = agentInstallProgress.value;
|
||||||
|
if (agentInstallError.value) return t("connection.driverInstall.statusFailed");
|
||||||
|
if (!agentInstallRunning.value) return t("connection.driverInstall.statusWaiting");
|
||||||
|
if (!progress) return t("connection.driverInstall.statusPreparing");
|
||||||
|
if (progress.step === "jre-extract") return t("connection.driverInstall.statusExtractingJre");
|
||||||
|
const label = progress.step === "jre" ? t("connection.driverInstall.stepJre") : progress.step === "driver" ? t("connection.driverInstall.stepDriver") : progress.step || t("connection.driverInstall.stepDefault");
|
||||||
|
if (!progress.total) return `${label}...`;
|
||||||
|
return `${label} ${formatInstallSize(progress.downloaded ?? 0)} / ${formatInstallSize(progress.total)} (${agentInstallPercent.value ?? 0}%)`;
|
||||||
|
});
|
||||||
|
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 || canChooseVisibleNacosNamespaces.value || (canChooseVisibleSchemas.value && !visibleFilterUsesSchemas.value) || (selectedPluginProvider.value?.contribution.fields.length ?? 0) >= 6),
|
||||||
|
);
|
||||||
|
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]";
|
||||||
|
const scrollableAdvancedNacos = form.value.db_type === "nacos" && configTab.value === "advanced";
|
||||||
|
return `${widthClass} connection-dialog-content--config${scrollableAdvancedNacos ? " connection-dialog-content--scrollable" : ""}`;
|
||||||
|
});
|
||||||
|
const connectionLabelClass = "justify-self-start text-left";
|
||||||
|
const connectionLabelSmallClass = `${connectionLabelClass} text-xs`;
|
||||||
|
const connectionLabelTopClass = `${connectionLabelClass} mt-2`;
|
||||||
|
const connectionLabelSmallPaddedClass = `${connectionLabelClass} pt-2 text-xs`;
|
||||||
|
|
||||||
function pluginFieldValue(field: PluginFormField): PluginFormFieldValue {
|
function pluginFieldValue(field: PluginFormField): PluginFormFieldValue {
|
||||||
if (field.binding === "name") return form.value.name;
|
if (field.binding === "name") return form.value.name;
|
||||||
@@ -3584,6 +3613,19 @@ function pluginFieldHasValue(field: PluginFormField): boolean {
|
|||||||
return typeof value === "string" ? value.trim().length > 0 : value !== undefined;
|
return typeof value === "string" ? value.trim().length > 0 : value !== undefined;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
function pluginFieldValueByKey(key: string): PluginFormFieldValue {
|
||||||
|
const field = selectedPluginProvider.value?.contribution.fields.find((candidate) => candidate.key === key);
|
||||||
|
return field ? pluginFieldValue(field) : undefined;
|
||||||
|
}
|
||||||
|
|
||||||
|
function pluginFieldVisible(field: PluginFormField): boolean {
|
||||||
|
return pluginFieldIsVisible(field, pluginFieldValueByKey, (key) => selectedPluginProvider.value?.contribution.fields.find((candidate) => candidate.key === key));
|
||||||
|
}
|
||||||
|
|
||||||
|
function pluginFieldRequired(field: PluginFormField): boolean {
|
||||||
|
return pluginFieldIsRequired(field, pluginFieldValueByKey);
|
||||||
|
}
|
||||||
|
|
||||||
function pluginActionLabel(action: PluginConnectionAction): string {
|
function pluginActionLabel(action: PluginConnectionAction): string {
|
||||||
if (action.label) return action.label;
|
if (action.label) return action.label;
|
||||||
if (action.kind === "test") return t("connection.test");
|
if (action.kind === "test") return t("connection.test");
|
||||||
@@ -3633,34 +3675,11 @@ function applyPluginActionFieldValues(values: Record<string, PluginFormFieldValu
|
|||||||
}
|
}
|
||||||
pluginFormValues.value = nextValues;
|
pluginFormValues.value = nextValues;
|
||||||
}
|
}
|
||||||
const agentInstallPercent = computed(() => driverInstallProgressPercent(agentInstallProgress.value));
|
|
||||||
const agentInstallProgressLabel = computed(() => {
|
|
||||||
const progress = agentInstallProgress.value;
|
|
||||||
if (agentInstallError.value) return t("connection.driverInstall.statusFailed");
|
|
||||||
if (!agentInstallRunning.value) return t("connection.driverInstall.statusWaiting");
|
|
||||||
if (!progress) return t("connection.driverInstall.statusPreparing");
|
|
||||||
if (progress.step === "jre-extract") return t("connection.driverInstall.statusExtractingJre");
|
|
||||||
const label = progress.step === "jre" ? t("connection.driverInstall.stepJre") : progress.step === "driver" ? t("connection.driverInstall.stepDriver") : progress.step || t("connection.driverInstall.stepDefault");
|
|
||||||
if (!progress.total) return `${label}...`;
|
|
||||||
return `${label} ${formatInstallSize(progress.downloaded ?? 0)} / ${formatInstallSize(progress.total)} (${agentInstallPercent.value ?? 0}%)`;
|
|
||||||
});
|
|
||||||
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 || 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]";
|
|
||||||
const scrollableAdvancedNacos = form.value.db_type === "nacos" && configTab.value === "advanced";
|
|
||||||
return `${widthClass} connection-dialog-content--config${scrollableAdvancedNacos ? " connection-dialog-content--scrollable" : ""}`;
|
|
||||||
});
|
|
||||||
const connectionLabelClass = "justify-self-start text-left";
|
|
||||||
const connectionLabelSmallClass = `${connectionLabelClass} text-xs`;
|
|
||||||
const connectionLabelTopClass = `${connectionLabelClass} mt-2`;
|
|
||||||
const connectionLabelSmallPaddedClass = `${connectionLabelClass} pt-2 text-xs`;
|
|
||||||
const hasRequiredConnectionTarget = computed(() => {
|
const hasRequiredConnectionTarget = computed(() => {
|
||||||
if (isPluginConnection.value) {
|
if (isPluginConnection.value) {
|
||||||
const provider = selectedPluginProvider.value?.contribution;
|
const entry = selectedPluginProvider.value;
|
||||||
return !!provider && provider.fields.every((field) => !field.required || pluginFieldHasValue(field));
|
return !!entry && entry.contribution.fields.every((field) => !pluginFieldVisible(field) || !pluginFieldRequired(field) || pluginFieldHasValue(field));
|
||||||
}
|
}
|
||||||
if (form.value.db_type === "mq") {
|
if (form.value.db_type === "mq") {
|
||||||
if (mqSystemKind.value === "kafka") return mqKafkaConnectionSource.value === "zookeeper" ? !!mqKafkaZooKeeperServers.value.trim() : !!mqKafkaBootstrapServers.value.trim();
|
if (mqSystemKind.value === "kafka") return mqKafkaConnectionSource.value === "zookeeper" ? !!mqKafkaZooKeeperServers.value.trim() : !!mqKafkaBootstrapServers.value.trim();
|
||||||
@@ -4061,11 +4080,12 @@ function connectionConfigForSshTunnelTest(id: string): ConnectionConfig {
|
|||||||
}
|
}
|
||||||
|
|
||||||
function connectionConfigForSubmit(id: string, generatedName = "", validatePluginRequired = true): ConnectionConfig {
|
function connectionConfigForSubmit(id: string, generatedName = "", validatePluginRequired = true): ConnectionConfig {
|
||||||
|
let config: LegacyConnectionConfig;
|
||||||
if (isPluginConnection.value) {
|
if (isPluginConnection.value) {
|
||||||
const entry = selectedPluginProvider.value;
|
const entry = selectedPluginProvider.value;
|
||||||
if (!entry) throw new Error(pluginLoadError.value || t("connection.pluginProviderUnavailable"));
|
if (!entry) throw new Error(pluginLoadError.value || t("connection.pluginProviderUnavailable"));
|
||||||
if (validatePluginRequired) {
|
if (validatePluginRequired) {
|
||||||
const missingField = entry.contribution.fields.find((field) => field.required && !pluginFieldHasValue(field));
|
const missingField = entry.contribution.fields.find((field) => pluginFieldVisible(field) && pluginFieldRequired(field) && !pluginFieldHasValue(field));
|
||||||
if (missingField) throw new Error(t("connection.pluginRequiredField", { field: missingField.label }));
|
if (missingField) throw new Error(t("connection.pluginRequiredField", { field: missingField.label }));
|
||||||
}
|
}
|
||||||
const values = { ...pluginFormValues.value };
|
const values = { ...pluginFormValues.value };
|
||||||
@@ -4073,10 +4093,23 @@ function connectionConfigForSubmit(id: string, generatedName = "", validatePlugi
|
|||||||
if (field.binding === "name") values[field.key] = form.value.name;
|
if (field.binding === "name") values[field.key] = form.value.name;
|
||||||
}
|
}
|
||||||
const existing = props.editConfig?.db_type === "plugin" && props.editConfig.plugin_id === entry.plugin.manifest.id && props.editConfig.plugin_connection_provider === entry.contribution.id ? props.editConfig : undefined;
|
const existing = props.editConfig?.db_type === "plugin" && props.editConfig.plugin_id === entry.plugin.manifest.id && props.editConfig.plugin_connection_provider === entry.contribution.id ? props.editConfig : undefined;
|
||||||
const config = buildPluginConnectionConfig(entry.plugin.manifest.id, entry.contribution, values, existing);
|
config = buildPluginConnectionConfig(entry.plugin.manifest.id, entry.contribution, values, existing) as LegacyConnectionConfig;
|
||||||
return { ...formValueForSubmit(), ...config, id, name: form.value.name.trim() || generatedName.trim() || config.name, note: form.value.note?.trim() || undefined };
|
config.id = id;
|
||||||
|
config.name = form.value.name.trim() || config.name;
|
||||||
|
config.note = form.value.note;
|
||||||
|
config.color = form.value.color;
|
||||||
|
config.transport_layers = form.value.transport_layers || [];
|
||||||
|
config.connect_timeout_secs = form.value.connect_timeout_secs;
|
||||||
|
config.query_timeout_secs = form.value.query_timeout_secs;
|
||||||
|
config.idle_timeout_secs = form.value.idle_timeout_secs;
|
||||||
|
config.keepalive_interval_secs = form.value.keepalive_interval_secs;
|
||||||
|
config.read_only = form.value.read_only;
|
||||||
|
config.save_password = form.value.save_password;
|
||||||
|
config.is_production = form.value.is_production;
|
||||||
|
config.production_databases = form.value.production_databases;
|
||||||
|
} else {
|
||||||
|
config = { ...formValueForSubmit(), id } as LegacyConnectionConfig;
|
||||||
}
|
}
|
||||||
const config = { ...formValueForSubmit(), id } as LegacyConnectionConfig;
|
|
||||||
config.database_info = undefined;
|
config.database_info = undefined;
|
||||||
config.database = normalizeStoredConnectionDatabase(config.db_type, config.database);
|
config.database = normalizeStoredConnectionDatabase(config.db_type, config.database);
|
||||||
config.note = config.note?.trim() || undefined;
|
config.note = config.note?.trim() || undefined;
|
||||||
@@ -4286,6 +4319,9 @@ function connectionConfigForSubmit(id: string, generatedName = "", validatePlugi
|
|||||||
setGaussdbTargetServerType(config, targetServerType);
|
setGaussdbTargetServerType(config, targetServerType);
|
||||||
setGaussdbCountQueryDop(config, countQueryDop);
|
setGaussdbCountQueryDop(config, countQueryDop);
|
||||||
} else if (config.db_type !== "plugin" && !isDoltDriverProfile(config.driver_profile)) {
|
} else if (config.db_type !== "plugin" && !isDoltDriverProfile(config.driver_profile)) {
|
||||||
|
// Plugin connections keep `external_config`: the manifest-driven form
|
||||||
|
// fields land there via buildPluginConnectionConfig. Only the built-in
|
||||||
|
// drivers without an external-config payload get wiped here.
|
||||||
config.external_config = undefined;
|
config.external_config = undefined;
|
||||||
}
|
}
|
||||||
if (config.db_type === "mongodb" && !mongoUseUrl.value) {
|
if (config.db_type === "mongodb" && !mongoUseUrl.value) {
|
||||||
@@ -4382,12 +4418,6 @@ function connectionConfigForSubmit(id: string, generatedName = "", validatePlugi
|
|||||||
config.port = firstEndpoint.port;
|
config.port = firstEndpoint.port;
|
||||||
}
|
}
|
||||||
config.database = undefined;
|
config.database = undefined;
|
||||||
config.ca_cert_path = config.ca_cert_path?.trim() || "";
|
|
||||||
config.client_cert_path = config.client_cert_path?.trim() || "";
|
|
||||||
config.client_key_path = config.client_key_path?.trim() || "";
|
|
||||||
if ((config.client_cert_path && !config.client_key_path) || (!config.client_cert_path && config.client_key_path)) {
|
|
||||||
throw new Error(t("connection.etcdClientCertPairRequired"));
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
if (config.db_type === "etcd") {
|
if (config.db_type === "etcd") {
|
||||||
config.etcd_endpoints = normalizeEndpointLines(config.etcd_endpoints || "");
|
config.etcd_endpoints = normalizeEndpointLines(config.etcd_endpoints || "");
|
||||||
@@ -4402,7 +4432,14 @@ function connectionConfigForSubmit(id: string, generatedName = "", validatePlugi
|
|||||||
if ((config.client_cert_path && !config.client_key_path) || (!config.client_cert_path && config.client_key_path)) {
|
if ((config.client_cert_path && !config.client_key_path) || (!config.client_cert_path && config.client_key_path)) {
|
||||||
throw new Error(t("connection.etcdClientCertPairRequired"));
|
throw new Error(t("connection.etcdClientCertPairRequired"));
|
||||||
}
|
}
|
||||||
} else if (form.value.db_type !== "consul" && config.db_type !== "zookeeper" && config.db_type !== "elasticsearch" && config.db_type !== "easysearch") {
|
} else if (config.db_type === "zookeeper") {
|
||||||
|
config.etcd_endpoints = undefined;
|
||||||
|
config.client_cert_path = config.client_cert_path?.trim() || "";
|
||||||
|
config.client_key_path = config.client_key_path?.trim() || "";
|
||||||
|
if ((config.client_cert_path && !config.client_key_path) || (!config.client_cert_path && config.client_key_path)) {
|
||||||
|
throw new Error(t("connection.etcdClientCertPairRequired"));
|
||||||
|
}
|
||||||
|
} else if (form.value.db_type !== "consul" && config.db_type !== "elasticsearch" && config.db_type !== "easysearch") {
|
||||||
config.etcd_endpoints = undefined;
|
config.etcd_endpoints = undefined;
|
||||||
config.client_cert_path = undefined;
|
config.client_cert_path = undefined;
|
||||||
config.client_key_path = undefined;
|
config.client_key_path = undefined;
|
||||||
@@ -4751,6 +4788,7 @@ function resetTestState() {
|
|||||||
isTesting.value = false;
|
isTesting.value = false;
|
||||||
isTestingSshTunnel.value = false;
|
isTestingSshTunnel.value = false;
|
||||||
testResult.value = null;
|
testResult.value = null;
|
||||||
|
pluginActionStatus.value = null;
|
||||||
clearTestedConnectionInfo();
|
clearTestedConnectionInfo();
|
||||||
showConnectionErrorDialog.value = false;
|
showConnectionErrorDialog.value = false;
|
||||||
connectionErrorRawDetail.value = "";
|
connectionErrorRawDetail.value = "";
|
||||||
@@ -5290,6 +5328,7 @@ function resetForm(options: { preservePickerState?: boolean } = {}) {
|
|||||||
selectedTransportLayerId.value = null;
|
selectedTransportLayerId.value = null;
|
||||||
draggedTransportLayerId.value = null;
|
draggedTransportLayerId.value = null;
|
||||||
selectedType.value = "mysql";
|
selectedType.value = "mysql";
|
||||||
|
pluginFormValues.value = {};
|
||||||
customDriverName.value = "";
|
customDriverName.value = "";
|
||||||
mongoUseUrl.value = false;
|
mongoUseUrl.value = false;
|
||||||
resetMqFields();
|
resetMqFields();
|
||||||
@@ -5425,6 +5464,19 @@ watch(
|
|||||||
resetForm();
|
resetForm();
|
||||||
if (props.prefillConfig) applyConnectionPrefill(props.prefillConfig);
|
if (props.prefillConfig) applyConnectionPrefill(props.prefillConfig);
|
||||||
}
|
}
|
||||||
|
void loadInstalledPlugins().then(() => {
|
||||||
|
if (!open.value) return;
|
||||||
|
if (props.editConfig?.db_type === "plugin" && props.editConfig.plugin_id && props.editConfig.plugin_connection_provider) {
|
||||||
|
const entry = pluginProviderEntry(props.editConfig.plugin_id, props.editConfig.plugin_connection_provider);
|
||||||
|
if (entry) {
|
||||||
|
selectedType.value = pluginConnectionProviderOptionValue(props.editConfig.plugin_id, props.editConfig.plugin_connection_provider);
|
||||||
|
selectedDbCategory.value = "plugins";
|
||||||
|
pluginFormValues.value = pluginConnectionFormValues(entry.contribution, props.editConfig);
|
||||||
|
}
|
||||||
|
} else if (!props.prefillConfig) {
|
||||||
|
applyRequestedPluginProvider(props.pluginProvider);
|
||||||
|
}
|
||||||
|
});
|
||||||
if (!props.prefillConfig?.oneTime) {
|
if (!props.prefillConfig?.oneTime) {
|
||||||
void loadJdbcDrivers();
|
void loadJdbcDrivers();
|
||||||
void loadAgentDrivers();
|
void loadAgentDrivers();
|
||||||
@@ -5713,83 +5765,74 @@ async function persistConnectionNoteVisibilityDraft() {
|
|||||||
await persistConnectionNoteVisibilityDraftState(connectionNoteVisibilityDraft, settingsStore.editorSettings.sidebarShowConnectionNotes, (value) => settingsStore.updateEditorSettingsAndPersist({ sidebarShowConnectionNotes: value }));
|
await persistConnectionNoteVisibilityDraftState(connectionNoteVisibilityDraft, settingsStore.editorSettings.sidebarShowConnectionNotes, (value) => settingsStore.updateEditorSettingsAndPersist({ sidebarShowConnectionNotes: value }));
|
||||||
}
|
}
|
||||||
|
|
||||||
async function save(options: { connectAfterSave?: boolean; closeOnSuccess?: boolean } = {}) {
|
function startSavedConnection(config: ConnectionConfig) {
|
||||||
if (!ensureConnectionHostResolvedFromUrl()) return;
|
emit("connectStarted", config.name);
|
||||||
if (isSaving.value) return;
|
void store
|
||||||
|
.connect(config)
|
||||||
|
.then(() => {
|
||||||
|
emit("connectSucceeded", config.name);
|
||||||
|
})
|
||||||
|
.catch((e: any) => {
|
||||||
|
const message = String(e?.message || e);
|
||||||
|
if (message.includes(CONNECTION_ATTEMPT_CANCELLED_MESSAGE)) return;
|
||||||
|
// Keep failed one-time connections available for retry and error inspection.
|
||||||
|
// They are still removed by connectionStore.disconnect after a successful session.
|
||||||
|
emit("connectFailed", appendConnectionErrorHints(config, mongodbAuthFailureHint(message), t));
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
async function save(options: SaveConnectionOptions = {}): Promise<boolean> {
|
||||||
|
if (!ensureConnectionHostResolvedFromUrl()) return false;
|
||||||
|
if (isSaving.value) return false;
|
||||||
if (!hasNacosNamespaceScopeForSave()) {
|
if (!hasNacosNamespaceScopeForSave()) {
|
||||||
testResult.value = null;
|
testResult.value = null;
|
||||||
await openVisibleNacosNamespacesPicker();
|
await openVisibleNacosNamespacesPicker();
|
||||||
return;
|
return false;
|
||||||
}
|
}
|
||||||
const connectAfterSave = options.connectAfterSave ?? (!editingId.value && form.value.db_type !== "jdbc");
|
const wasEditing = !!editingId.value;
|
||||||
|
const connectAfterSave = options.connectAfterSave ?? (!wasEditing && !isJdbcConnection.value);
|
||||||
const closeOnSuccess = options.closeOnSuccess ?? true;
|
const closeOnSuccess = options.closeOnSuccess ?? true;
|
||||||
const databaseInfoForSave = visibleTestDatabaseInfo.value ?? visibleSavedDatabaseInfo.value;
|
const databaseInfoForSave = visibleTestDatabaseInfo.value ?? visibleSavedDatabaseInfo.value;
|
||||||
isSaving.value = true;
|
isSaving.value = true;
|
||||||
let connectionSaved = false;
|
let connectionSaved = false;
|
||||||
try {
|
try {
|
||||||
|
let savedConfig: ConnectionConfig;
|
||||||
if (editingId.value) {
|
if (editingId.value) {
|
||||||
const updated = withSavedDatabaseInfo(connectionConfigForSubmit(editingId.value), databaseInfoForSave);
|
const updated = withSavedDatabaseInfo(connectionConfigForSubmit(editingId.value), databaseInfoForSave);
|
||||||
await ensureRequiredAgentDriverInstalled(updated);
|
await ensureRequiredAgentDriverInstalled(updated);
|
||||||
await ensureRequiredGaussdbMJdbcRuntime(updated);
|
await ensureRequiredGaussdbMJdbcRuntime(updated);
|
||||||
await persistGlobalTimeoutDrafts();
|
await persistGlobalTimeoutDrafts();
|
||||||
await store.updateConnection(updated);
|
await store.updateConnection(updated);
|
||||||
|
savedConfig = updated;
|
||||||
connectionSaved = true;
|
connectionSaved = true;
|
||||||
await persistConnectionNoteVisibilityDraft();
|
await persistConnectionNoteVisibilityDraft();
|
||||||
store.stopEditing();
|
|
||||||
if (connectAfterSave) {
|
|
||||||
if (closeOnSuccess) {
|
|
||||||
open.value = false;
|
|
||||||
await nextTick();
|
|
||||||
}
|
|
||||||
emit("connectStarted", updated.name);
|
|
||||||
void store
|
|
||||||
.connect(updated)
|
|
||||||
.then(() => {
|
|
||||||
emit("connectSucceeded", updated.name);
|
|
||||||
})
|
|
||||||
.catch((e: any) => {
|
|
||||||
const message = String(e?.message || e);
|
|
||||||
if (message.includes(CONNECTION_ATTEMPT_CANCELLED_MESSAGE)) return;
|
|
||||||
emit("connectFailed", appendConnectionErrorHints(updated, mongodbAuthFailureHint(message), t));
|
|
||||||
});
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
} else {
|
} else {
|
||||||
const config = withSavedDatabaseInfo(connectionConfigForSubmit(draftTestConnectionId.value), databaseInfoForSave);
|
const config = withSavedDatabaseInfo(connectionConfigForSubmit(draftTestConnectionId.value), databaseInfoForSave);
|
||||||
await ensureRequiredAgentDriverInstalled(config);
|
await ensureRequiredAgentDriverInstalled(config);
|
||||||
await ensureRequiredGaussdbMJdbcRuntime(config);
|
await ensureRequiredGaussdbMJdbcRuntime(config);
|
||||||
await persistGlobalTimeoutDrafts();
|
await persistGlobalTimeoutDrafts();
|
||||||
await store.addConnection(config, selectedConnectionGroupId.value);
|
await store.addConnection(config, selectedConnectionGroupId.value);
|
||||||
|
savedConfig = config;
|
||||||
connectionSaved = true;
|
connectionSaved = true;
|
||||||
await persistConnectionNoteVisibilityDraft();
|
await persistConnectionNoteVisibilityDraft();
|
||||||
draftTestConnectionId.value = uuid();
|
draftTestConnectionId.value = uuid();
|
||||||
if (!connectAfterSave) {
|
|
||||||
if (closeOnSuccess) open.value = false;
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
if (closeOnSuccess) open.value = false;
|
|
||||||
await nextTick();
|
|
||||||
emit("connectStarted", config.name);
|
|
||||||
void store
|
|
||||||
.connect(config)
|
|
||||||
.then(() => {
|
|
||||||
emit("connectSucceeded", config.name);
|
|
||||||
})
|
|
||||||
.catch((e: any) => {
|
|
||||||
const message = String(e?.message || e);
|
|
||||||
if (message.includes(CONNECTION_ATTEMPT_CANCELLED_MESSAGE)) return;
|
|
||||||
// Keep failed one-time connections available for retry and error inspection.
|
|
||||||
// They are still removed by connectionStore.disconnect after a successful session.
|
|
||||||
emit("connectFailed", appendConnectionErrorHints(config, mongodbAuthFailureHint(message), t));
|
|
||||||
});
|
|
||||||
return;
|
|
||||||
}
|
}
|
||||||
if (closeOnSuccess) open.value = false;
|
if (closeOnSuccess) {
|
||||||
|
if (wasEditing) store.stopEditing();
|
||||||
|
open.value = false;
|
||||||
|
await nextTick();
|
||||||
|
} else if (!wasEditing) {
|
||||||
|
editingId.value = savedConfig.id;
|
||||||
|
store.startEditing(savedConfig.id);
|
||||||
|
}
|
||||||
|
if (connectAfterSave && savedConfig.db_type !== "jdbc") startSavedConnection(savedConfig);
|
||||||
|
return true;
|
||||||
} catch (e: any) {
|
} catch (e: any) {
|
||||||
const cause = mongodbAuthFailureHint(String(e?.message || e));
|
const cause = mongodbAuthFailureHint(String(e?.message || e));
|
||||||
const message = connectionSaved ? t("connection.savedSettingsFailed", { message: cause }) : cause;
|
const message = connectionSaved ? t("connection.savedSettingsFailed", { message: cause }) : cause;
|
||||||
testResult.value = { ok: false, message };
|
testResult.value = { ok: false, message };
|
||||||
showConnectionError(message);
|
showConnectionError(message);
|
||||||
|
return false;
|
||||||
} finally {
|
} finally {
|
||||||
isSaving.value = false;
|
isSaving.value = false;
|
||||||
}
|
}
|
||||||
@@ -6442,7 +6485,15 @@ function openExternalUrl(url: string) {
|
|||||||
</div>
|
</div>
|
||||||
|
|
||||||
<template v-if="isPluginConnection">
|
<template v-if="isPluginConnection">
|
||||||
<PluginConnectionFields v-if="selectedPluginProvider" :model-value="pluginFormValues" :contribution="selectedPluginProvider.contribution" :hidden-bindings="['name']" layout="connection-dialog" @update:model-value="updatePluginFormValues" />
|
<PluginConnectionFields
|
||||||
|
v-if="selectedPluginProvider"
|
||||||
|
:model-value="pluginFormValues"
|
||||||
|
:contribution="selectedPluginProvider.contribution"
|
||||||
|
:hidden-bindings="['name']"
|
||||||
|
layout="connection-dialog"
|
||||||
|
:plugin-id="selectedPluginProvider.plugin.manifest.id"
|
||||||
|
@update:model-value="updatePluginFormValues"
|
||||||
|
/>
|
||||||
<div v-else class="col-span-full rounded-lg border border-destructive/40 bg-destructive/5 p-4 text-sm text-destructive">
|
<div v-else class="col-span-full rounded-lg border border-destructive/40 bg-destructive/5 p-4 text-sm text-destructive">
|
||||||
{{ pluginLoadError || t("connection.pluginProviderUnavailable") }}
|
{{ pluginLoadError || t("connection.pluginProviderUnavailable") }}
|
||||||
</div>
|
</div>
|
||||||
@@ -8416,7 +8467,7 @@ function openExternalUrl(url: string) {
|
|||||||
</Tooltip>
|
</Tooltip>
|
||||||
</div>
|
</div>
|
||||||
<p class="text-[11px] leading-4 text-muted-foreground">
|
<p class="text-[11px] leading-4 text-muted-foreground">
|
||||||
{{ t("connection.clientCertHint") }}
|
{{ t("connection.etcdClientCertHint") }}
|
||||||
</p>
|
</p>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
@@ -9313,7 +9364,7 @@ function openExternalUrl(url: string) {
|
|||||||
<Button variant="outline" class="shrink-0" :disabled="isTesting || isTestingSshTunnel || isSaving" @click="testConnection">
|
<Button variant="outline" class="shrink-0" :disabled="isTesting || isTestingSshTunnel || isSaving" @click="testConnection">
|
||||||
{{ isTesting ? t("connection.testing") : t("connection.test") }}
|
{{ isTesting ? t("connection.testing") : t("connection.test") }}
|
||||||
</Button>
|
</Button>
|
||||||
<Button class="shrink-0" @click="save" :disabled="isSaving || isTestingSshTunnel || !hasRequiredConnectionTarget">
|
<Button class="shrink-0" @click="save()" :disabled="isSaving || isTestingSshTunnel || !hasRequiredConnectionTarget">
|
||||||
{{ isSaving ? t("common.loading") : editingId || isJdbcConnection ? t("connection.save") : t("connection.saveAndConnect") }}
|
{{ isSaving ? t("common.loading") : editingId || isJdbcConnection ? t("connection.save") : t("connection.saveAndConnect") }}
|
||||||
</Button>
|
</Button>
|
||||||
</template>
|
</template>
|
||||||
|
|||||||
@@ -28,6 +28,7 @@ const props = defineProps<{
|
|||||||
const emit = defineEmits<{
|
const emit = defineEmits<{
|
||||||
"activate-driver-store": [];
|
"activate-driver-store": [];
|
||||||
"close-driver-store": [];
|
"close-driver-store": [];
|
||||||
|
"activate-plugin-center": [];
|
||||||
"close-plugin-center": [];
|
"close-plugin-center": [];
|
||||||
"activate-settings-page": [];
|
"activate-settings-page": [];
|
||||||
"close-settings-page": [];
|
"close-settings-page": [];
|
||||||
@@ -130,6 +131,9 @@ function closeSpecialRegularSurfaces(keep?: SpecialRegularSurface) {
|
|||||||
if (keep !== "driverStore" && props.driverStoreOpen) {
|
if (keep !== "driverStore" && props.driverStoreOpen) {
|
||||||
emit("close-driver-store");
|
emit("close-driver-store");
|
||||||
}
|
}
|
||||||
|
if (keep !== "pluginCenter" && props.pluginCenterOpen) {
|
||||||
|
emit("close-plugin-center");
|
||||||
|
}
|
||||||
if (keep !== "settings" && props.settingsPageOpen) {
|
if (keep !== "settings" && props.settingsPageOpen) {
|
||||||
emit("close-settings-page");
|
emit("close-settings-page");
|
||||||
}
|
}
|
||||||
@@ -201,6 +205,9 @@ function handleCancelClose() {
|
|||||||
<div v-show="driverStoreActive || pluginCenterActive || settingsPageActive" data-special-page-workspace class="flex min-h-0 min-w-0 flex-1 overflow-hidden" :class="layoutClass">
|
<div v-show="driverStoreActive || pluginCenterActive || settingsPageActive" data-special-page-workspace class="flex min-h-0 min-w-0 flex-1 overflow-hidden" :class="layoutClass">
|
||||||
<div data-special-page-navigation class="flex min-h-0 min-w-0 shrink-0 flex-col overflow-auto" :style="navigationStyle">
|
<div data-special-page-navigation class="flex min-h-0 min-w-0 shrink-0 flex-col overflow-auto" :style="navigationStyle">
|
||||||
<div v-for="group in queryStore.groups" :key="group.id" :ref="(element) => setTabBarTarget(group.id, element)" :data-special-page-tab-target="group.id" class="flex min-h-0 min-w-0" :class="isVerticalLayout ? 'flex-1' : 'shrink-0'" />
|
<div v-for="group in queryStore.groups" :key="group.id" :ref="(element) => setTabBarTarget(group.id, element)" :data-special-page-tab-target="group.id" class="flex min-h-0 min-w-0" :class="isVerticalLayout ? 'flex-1' : 'shrink-0'" />
|
||||||
|
<button v-if="pluginCenterOpen" type="button" data-plugin-center-tab class="shrink-0 rounded-md px-2 py-1 text-left text-sm" :class="pluginCenterActive ? 'bg-accent text-accent-foreground' : 'text-muted-foreground'" @click="emit('activate-plugin-center')">
|
||||||
|
{{ t("toolbar.pluginCenter") }}
|
||||||
|
</button>
|
||||||
</div>
|
</div>
|
||||||
<div data-special-page-content class="flex min-h-0 min-w-0 flex-1 flex-col overflow-hidden">
|
<div data-special-page-content class="flex min-h-0 min-w-0 flex-1 flex-col overflow-hidden">
|
||||||
<slot />
|
<slot />
|
||||||
|
|||||||
@@ -61,8 +61,6 @@ import QueryLoadingState from "@/components/common/QueryLoadingState.vue";
|
|||||||
import QueryErrorActions from "@/components/common/QueryErrorActions.vue";
|
import QueryErrorActions from "@/components/common/QueryErrorActions.vue";
|
||||||
import QueryMessagesView from "@/components/layout/QueryMessagesView.vue";
|
import QueryMessagesView from "@/components/layout/QueryMessagesView.vue";
|
||||||
import QueryResultToolbarActions from "@/components/layout/QueryResultToolbarActions.vue";
|
import QueryResultToolbarActions from "@/components/layout/QueryResultToolbarActions.vue";
|
||||||
import PluginFilesystemTab from "@/components/plugins/PluginFilesystemTab.vue";
|
|
||||||
import PluginWorkbenchTab from "@/components/plugins/PluginWorkbenchTab.vue";
|
|
||||||
import ResultSetNavigator from "@/components/layout/ResultSetNavigator.vue";
|
import ResultSetNavigator from "@/components/layout/ResultSetNavigator.vue";
|
||||||
import QueryResultViewSwitcher from "@/components/layout/QueryResultViewSwitcher.vue";
|
import QueryResultViewSwitcher from "@/components/layout/QueryResultViewSwitcher.vue";
|
||||||
import DataGridCopyFormatControl from "@/components/grid/DataGridCopyFormatControl.vue";
|
import DataGridCopyFormatControl from "@/components/grid/DataGridCopyFormatControl.vue";
|
||||||
@@ -123,8 +121,10 @@ const MySqlDashboard = defineAsyncComponent(() => import("@/components/admin/MyS
|
|||||||
const PostgresDashboard = defineAsyncComponent(() => import("@/components/admin/PostgresDashboard.vue"));
|
const PostgresDashboard = defineAsyncComponent(() => import("@/components/admin/PostgresDashboard.vue"));
|
||||||
const XuguServerDashboard = defineAsyncComponent(() => import("@/components/admin/XuguServerDashboard.vue"));
|
const XuguServerDashboard = defineAsyncComponent(() => import("@/components/admin/XuguServerDashboard.vue"));
|
||||||
const DamengJobAdmin = defineAsyncComponent(() => import("@/components/admin/DamengJobAdmin.vue"));
|
const DamengJobAdmin = defineAsyncComponent(() => import("@/components/admin/DamengJobAdmin.vue"));
|
||||||
|
|
||||||
const DamengUserAdmin = defineAsyncComponent(() => import("@/components/admin/DamengUserAdmin.vue"));
|
const DamengUserAdmin = defineAsyncComponent(() => import("@/components/admin/DamengUserAdmin.vue"));
|
||||||
const DamengRoleAdmin = defineAsyncComponent(() => import("@/components/admin/DamengRoleAdmin.vue"));
|
const DamengRoleAdmin = defineAsyncComponent(() => import("@/components/admin/DamengRoleAdmin.vue"));
|
||||||
|
const PluginFilesystemTab = defineAsyncComponent(() => import("@/components/plugins/PluginFilesystemTab.vue"));
|
||||||
const ExplainPlanViewer = defineAsyncComponent(() => import("@/components/explain/ExplainPlanViewer.vue"));
|
const ExplainPlanViewer = defineAsyncComponent(() => import("@/components/explain/ExplainPlanViewer.vue"));
|
||||||
const QueryChart = defineAsyncComponent(() => import("@/components/chart/QueryChart.vue"));
|
const QueryChart = defineAsyncComponent(() => import("@/components/chart/QueryChart.vue"));
|
||||||
import { useQueryStore } from "@/stores/queryStore";
|
import { useQueryStore } from "@/stores/queryStore";
|
||||||
@@ -210,10 +210,6 @@ type SearchableBrowserHandle = {
|
|||||||
executeCommand?: (command: string) => Promise<boolean>;
|
executeCommand?: (command: string) => Promise<boolean>;
|
||||||
};
|
};
|
||||||
|
|
||||||
type PluginTabHandle = {
|
|
||||||
refresh?: () => Promise<void> | void;
|
|
||||||
};
|
|
||||||
|
|
||||||
type ElasticsearchJsonResponsePanelHandle = {
|
type ElasticsearchJsonResponsePanelHandle = {
|
||||||
focusSearch: () => boolean;
|
focusSearch: () => boolean;
|
||||||
};
|
};
|
||||||
@@ -329,8 +325,7 @@ const consulOverviewRef = ref<{ refresh?: () => boolean }>();
|
|||||||
const consulWorkspaceRef = ref<SearchableBrowserHandle>();
|
const consulWorkspaceRef = ref<SearchableBrowserHandle>();
|
||||||
const databaseBrowserRef = ref<SearchableBrowserHandle>();
|
const databaseBrowserRef = ref<SearchableBrowserHandle>();
|
||||||
const objectBrowserRef = ref<SearchableBrowserHandle>();
|
const objectBrowserRef = ref<SearchableBrowserHandle>();
|
||||||
const pluginWorkbenchRef = ref<PluginTabHandle>();
|
const pluginFilesystemTabRef = ref<{ refresh: () => Promise<unknown> }>();
|
||||||
const pluginFilesystemRef = ref<PluginTabHandle>();
|
|
||||||
const activeTableMeta = computed(() => props.activeTab.tableMeta);
|
const activeTableMeta = computed(() => props.activeTab.tableMeta);
|
||||||
const activeDataTabTableMeta = computed(() => tableMetaForDataTab(props.activeTab));
|
const activeDataTabTableMeta = computed(() => tableMetaForDataTab(props.activeTab));
|
||||||
const activeResultExecutionTarget = computed(() => queryStore.activeResultExecutionTarget(props.activeTab.id));
|
const activeResultExecutionTarget = computed(() => queryStore.activeResultExecutionTarget(props.activeTab.id));
|
||||||
@@ -988,10 +983,8 @@ function refreshData(): boolean {
|
|||||||
if (props.activeTab.mode === "consul-overview") return consulOverviewRef.value?.refresh?.() ?? false;
|
if (props.activeTab.mode === "consul-overview") return consulOverviewRef.value?.refresh?.() ?? false;
|
||||||
if (props.activeTab.mode === "consul") return consulWorkspaceRef.value?.refresh?.() ?? false;
|
if (props.activeTab.mode === "consul") return consulWorkspaceRef.value?.refresh?.() ?? false;
|
||||||
if (props.activeTab.mode === "databases") return databaseBrowserRef.value?.refresh?.() ?? false;
|
if (props.activeTab.mode === "databases") return databaseBrowserRef.value?.refresh?.() ?? false;
|
||||||
if (props.activeTab.mode === "plugin-workbench" || props.activeTab.mode === "plugin-filesystem") {
|
if (props.activeTab.mode === "plugin-filesystem") {
|
||||||
const pluginTab = props.activeTab.mode === "plugin-workbench" ? pluginWorkbenchRef.value : pluginFilesystemRef.value;
|
void pluginFilesystemTabRef.value?.refresh();
|
||||||
if (!pluginTab?.refresh) return false;
|
|
||||||
void pluginTab.refresh();
|
|
||||||
return true;
|
return true;
|
||||||
}
|
}
|
||||||
// Restored data tabs intentionally omit row data, so refresh must work before DataGrid mounts.
|
// Restored data tabs intentionally omit row data, so refresh must work before DataGrid mounts.
|
||||||
@@ -1219,7 +1212,6 @@ function handleModRTarget(target: Element): boolean {
|
|||||||
if (target.closest("[data-cell-detail-editor-root]")) return dataGridRef.value?.openCellDetailSearch() ?? false;
|
if (target.closest("[data-cell-detail-editor-root]")) return dataGridRef.value?.openCellDetailSearch() ?? false;
|
||||||
if (target.closest("[data-grid-root], [data-elasticsearch-json-response-root]")) return refreshData();
|
if (target.closest("[data-grid-root], [data-elasticsearch-json-response-root]")) return refreshData();
|
||||||
if (canReloadUnavailableDataTab(props.activeTab)) return refreshData();
|
if (canReloadUnavailableDataTab(props.activeTab)) return refreshData();
|
||||||
if (props.activeTab.mode === "plugin-workbench" || props.activeTab.mode === "plugin-filesystem") return refreshData();
|
|
||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -2571,23 +2563,13 @@ defineExpose({
|
|||||||
</div>
|
</div>
|
||||||
</template>
|
</template>
|
||||||
|
|
||||||
<template v-else-if="activeTab.mode === 'plugin-workbench' && activeTab.pluginWorkbench">
|
<!-- plugin-workbench tabs render in the always-mounted layer in App.vue
|
||||||
<div class="min-w-0 flex-1 min-h-0 bg-background">
|
(v-show visibility): remounting the webview per tab switch would
|
||||||
<PluginWorkbenchTab
|
reload the plugin iframe and drop its live session state. -->
|
||||||
ref="pluginWorkbenchRef"
|
|
||||||
:key="activeTab.id"
|
|
||||||
:plugin-id="activeTab.pluginWorkbench.pluginId"
|
|
||||||
:contribution-id="activeTab.pluginWorkbench.contributionId"
|
|
||||||
:connection-id="activeTab.connectionId || undefined"
|
|
||||||
:context="activeTab.pluginWorkbench.context"
|
|
||||||
@close-tab="emit('closeTab', activeTab.id)"
|
|
||||||
/>
|
|
||||||
</div>
|
|
||||||
</template>
|
|
||||||
<template v-else-if="activeTab.mode === 'plugin-filesystem' && activeTab.pluginFilesystem">
|
<template v-else-if="activeTab.mode === 'plugin-filesystem' && activeTab.pluginFilesystem">
|
||||||
<div class="flex h-full min-h-0 min-w-0 flex-col">
|
<div class="flex h-full min-h-0 flex-col">
|
||||||
<PluginFilesystemTab
|
<PluginFilesystemTab
|
||||||
ref="pluginFilesystemRef"
|
ref="pluginFilesystemTabRef"
|
||||||
:key="activeTab.id"
|
:key="activeTab.id"
|
||||||
:plugin-id="activeTab.pluginFilesystem.pluginId"
|
:plugin-id="activeTab.pluginFilesystem.pluginId"
|
||||||
:provider-id="activeTab.pluginFilesystem.providerId"
|
:provider-id="activeTab.pluginFilesystem.providerId"
|
||||||
|
|||||||
@@ -30,6 +30,8 @@ const props = defineProps<
|
|||||||
tabBarCollapsed?: boolean;
|
tabBarCollapsed?: boolean;
|
||||||
canDetachTabs?: boolean;
|
canDetachTabs?: boolean;
|
||||||
detachedDropTarget?: boolean;
|
detachedDropTarget?: boolean;
|
||||||
|
/** Collapse the group to its tab strip while a plugin workbench tab owns the layout. */
|
||||||
|
contentSuppressed?: boolean;
|
||||||
}
|
}
|
||||||
>();
|
>();
|
||||||
|
|
||||||
@@ -98,6 +100,7 @@ const tabBarTarget = computed(() => {
|
|||||||
if (!tabBarPortal?.active.value) return undefined;
|
if (!tabBarPortal?.active.value) return undefined;
|
||||||
return tabBarPortal.targets.get(props.groupId);
|
return tabBarPortal.targets.get(props.groupId);
|
||||||
});
|
});
|
||||||
|
|
||||||
const groupTabs = computed(() => {
|
const groupTabs = computed(() => {
|
||||||
const byId = new Map(queryStore.tabs.map((tab) => [tab.id, tab]));
|
const byId = new Map(queryStore.tabs.map((tab) => [tab.id, tab]));
|
||||||
return props.tabIds.map((id) => byId.get(id)).filter((tab): tab is QueryTab => !!tab);
|
return props.tabIds.map((id) => byId.get(id)).filter((tab): tab is QueryTab => !!tab);
|
||||||
@@ -138,7 +141,7 @@ const groupExecutableSql = computed(() => {
|
|||||||
</script>
|
</script>
|
||||||
|
|
||||||
<template>
|
<template>
|
||||||
<div class="editor-group flex h-full min-h-0 min-w-0 overflow-hidden" :class="[groupClass, groupLayoutClass]" :data-group-id="groupId" @pointerdown.capture="$emit('focus-group', groupId)" @focusin="$emit('focus-group', groupId)">
|
<div class="editor-group flex min-h-0 min-w-0 overflow-hidden" :class="[contentSuppressed ? '' : 'h-full', groupClass, groupLayoutClass]" :data-group-id="groupId" @pointerdown.capture="$emit('focus-group', groupId)" @focusin="$emit('focus-group', groupId)">
|
||||||
<Teleport defer v-if="showTabNavigation !== false" :to="tabBarTarget" :disabled="!tabBarPortal?.active.value || !tabBarTarget">
|
<Teleport defer v-if="showTabNavigation !== false" :to="tabBarTarget" :disabled="!tabBarPortal?.active.value || !tabBarTarget">
|
||||||
<EditorGroupTabBar
|
<EditorGroupTabBar
|
||||||
:group-id="groupId"
|
:group-id="groupId"
|
||||||
@@ -157,15 +160,17 @@ const groupExecutableSql = computed(() => {
|
|||||||
@detach-tab="$emit('detach-tab', $event)"
|
@detach-tab="$emit('detach-tab', $event)"
|
||||||
@activate-settings="toolbar.activateSettingsPage()"
|
@activate-settings="toolbar.activateSettingsPage()"
|
||||||
@close-settings="toolbar.closeSettingsPage()"
|
@close-settings="toolbar.closeSettingsPage()"
|
||||||
@activate-driver-store="toolbar.activateDriverStore()"
|
|
||||||
@close-driver-store="toolbar.closeDriverStore()"
|
|
||||||
@activate-plugin-center="toolbar.activatePluginCenter()"
|
@activate-plugin-center="toolbar.activatePluginCenter()"
|
||||||
@close-plugin-center="toolbar.closePluginCenter()"
|
@close-plugin-center="toolbar.closePluginCenter()"
|
||||||
|
@activate-driver-store="toolbar.activateDriverStore()"
|
||||||
|
@close-driver-store="toolbar.closeDriverStore()"
|
||||||
/>
|
/>
|
||||||
</Teleport>
|
</Teleport>
|
||||||
<!-- The toolbar stays at the top of the pane's content column in every
|
<!-- The toolbar stays at the top of the pane's content column in every
|
||||||
placement; only the tab bar moves around it. -->
|
placement; only the tab bar moves around it. While contentSuppressed
|
||||||
<div class="flex min-h-0 min-w-0 flex-1 flex-col">
|
(plugin workbench tab active) the whole column yields to the
|
||||||
|
always-mounted plugin layer and the group collapses to its strip. -->
|
||||||
|
<div v-show="!contentSuppressed" class="flex min-h-0 min-w-0 flex-1 flex-col">
|
||||||
<EditorToolbar
|
<EditorToolbar
|
||||||
v-if="activeTab && showGroupToolbar"
|
v-if="activeTab && showGroupToolbar"
|
||||||
:active-tab="activeTab"
|
:active-tab="activeTab"
|
||||||
|
|||||||
@@ -26,6 +26,8 @@ const props = defineProps<
|
|||||||
tabBarCollapsed?: boolean;
|
tabBarCollapsed?: boolean;
|
||||||
canDetachTabs?: boolean;
|
canDetachTabs?: boolean;
|
||||||
detachedDropTarget?: boolean;
|
detachedDropTarget?: boolean;
|
||||||
|
/** Render only the groups' tab strips (a plugin workbench tab owns the layout). */
|
||||||
|
contentSuppressed?: boolean;
|
||||||
}
|
}
|
||||||
>();
|
>();
|
||||||
const emit = defineEmits<
|
const emit = defineEmits<
|
||||||
@@ -116,12 +118,13 @@ const globalTabBarPortal = inject(GROUP_TAB_BAR_PORTAL, null);
|
|||||||
const workspaceTabBarPortal = createGroupTabBarPortal(isVerticalTabLayout);
|
const workspaceTabBarPortal = createGroupTabBarPortal(isVerticalTabLayout);
|
||||||
// A special page owns navigation while active. Otherwise side tabs stay
|
// A special page owns navigation while active. Otherwise side tabs stay
|
||||||
// outside the editor/result split, and horizontal tabs return to their group.
|
// outside the editor/result split, and horizontal tabs return to their group.
|
||||||
provide(GROUP_TAB_BAR_PORTAL, {
|
const providedPortal = {
|
||||||
active: computed(() => !!globalTabBarPortal?.active.value || isVerticalTabLayout.value),
|
active: computed(() => !!globalTabBarPortal?.active.value || isVerticalTabLayout.value),
|
||||||
get targets() {
|
get targets() {
|
||||||
return globalTabBarPortal?.active.value ? globalTabBarPortal.targets : workspaceTabBarPortal.targets;
|
return globalTabBarPortal?.active.value ? globalTabBarPortal.targets : workspaceTabBarPortal.targets;
|
||||||
},
|
},
|
||||||
});
|
};
|
||||||
|
provide(GROUP_TAB_BAR_PORTAL, providedPortal);
|
||||||
const tabNavigationStyle = computed(() => {
|
const tabNavigationStyle = computed(() => {
|
||||||
const width = props.tabBarCollapsed ? "var(--collapsed-tab-rail-width)" : `${props.tabBarWidth ?? 240}px`;
|
const width = props.tabBarCollapsed ? "var(--collapsed-tab-rail-width)" : `${props.tabBarWidth ?? 240}px`;
|
||||||
return { width, flex: `0 0 ${width}` };
|
return { width, flex: `0 0 ${width}` };
|
||||||
@@ -254,12 +257,45 @@ function handleFocusStatement(tabId: string, range: StatementRange | null): bool
|
|||||||
</script>
|
</script>
|
||||||
|
|
||||||
<template>
|
<template>
|
||||||
<div class="sql-editor-workspace relative flex h-full min-h-0 min-w-0 flex-1 overflow-hidden" :class="[workspaceClass, settingsStore.editorSettings.tabPlacement === 'right' ? 'flex-row-reverse' : 'flex-row']">
|
<!-- contentSuppressed (plugin workbench tab active): the App.vue wrapper is
|
||||||
|
flex-none with indefinite height, so h-full/flex-1 here would collapse
|
||||||
|
the workspace to 0 and clip the group tab strips (overflow-hidden).
|
||||||
|
Size to content instead — same contract as EditorGroup's suppressed
|
||||||
|
h-auto; normal mode keeps h-full/flex-1 to fill the column. -->
|
||||||
|
<div class="sql-editor-workspace relative flex min-h-0 min-w-0 overflow-hidden" :class="[contentSuppressed ? 'h-auto' : 'h-full flex-1', workspaceClass, settingsStore.editorSettings.tabPlacement === 'right' ? 'flex-row-reverse' : 'flex-row']">
|
||||||
<div v-show="isVerticalTabLayout && showTabNavigation !== false" data-workspace-tab-navigation class="flex min-h-0 shrink-0 flex-col overflow-hidden" :style="tabNavigationStyle">
|
<div v-show="isVerticalTabLayout && showTabNavigation !== false" data-workspace-tab-navigation class="flex min-h-0 shrink-0 flex-col overflow-hidden" :style="tabNavigationStyle">
|
||||||
<div v-for="group in queryStore.groups" :key="group.id" :ref="(element) => setTabBarTarget(group.id, element)" :data-workspace-tab-target="group.id" class="flex min-h-0 min-w-0 flex-1" @pointerdown.capture="queryStore.focusGroup(group.id)" @focusin="queryStore.focusGroup(group.id)" />
|
<div v-for="group in queryStore.groups" :key="group.id" :ref="(element) => setTabBarTarget(group.id, element)" :data-workspace-tab-target="group.id" class="flex min-h-0 min-w-0 flex-1" @pointerdown.capture="queryStore.focusGroup(group.id)" @focusin="queryStore.focusGroup(group.id)" />
|
||||||
</div>
|
</div>
|
||||||
<div data-workspace-content class="relative flex min-h-0 min-w-0 flex-1 flex-col overflow-hidden">
|
<div data-workspace-content class="relative flex min-h-0 min-w-0 flex-1 flex-col overflow-hidden">
|
||||||
<Splitpanes horizontal class="sql-editor-workspace-split flex-1 min-h-0" :class="{ 'result-pane-collapsed': resultPaneTargetSize === 0 }" @resized="onSharedResultResized">
|
<!-- Suppressed mode: a plugin workbench tab owns the layout. Render the
|
||||||
|
groups' tab strips directly (no Splitpanes, no shared result pane) so
|
||||||
|
App.vue's always-mounted plugin layer can fill the remaining column
|
||||||
|
while the strips stay visible and switchable. -->
|
||||||
|
<template v-if="contentSuppressed">
|
||||||
|
<EditorGroup
|
||||||
|
v-for="group in queryStore.groups"
|
||||||
|
:key="group.id"
|
||||||
|
:ref="(el: unknown) => setGroupRef(group.id, el)"
|
||||||
|
:group-id="group.id"
|
||||||
|
:tab-ids="group.tabIds"
|
||||||
|
:active-tab-id="group.activeTabId"
|
||||||
|
:tab-bar-width="tabBarWidth"
|
||||||
|
:tab-bar-collapsed="tabBarCollapsed"
|
||||||
|
:can-detach-tabs="canDetachTabs"
|
||||||
|
:detached-drop-target="detachedDropTarget"
|
||||||
|
:content-suppressed="true"
|
||||||
|
:show-tab-navigation="showTabNavigation"
|
||||||
|
v-bind="editorGroupBindings"
|
||||||
|
@focus-group="queryStore.focusGroup($event)"
|
||||||
|
@activate-tab="queryStore.activateTabInGroup(group.id, $event)"
|
||||||
|
@locate-tab="emit('locate-tab', $event)"
|
||||||
|
@toggle-zen-mode="emit('toggle-zen-mode')"
|
||||||
|
@start-resize="emit('start-resize', $event)"
|
||||||
|
@toggle-collapse="emit('toggle-collapse')"
|
||||||
|
@detach-tab="emit('detach-tab', $event)"
|
||||||
|
/>
|
||||||
|
</template>
|
||||||
|
<Splitpanes v-else horizontal class="sql-editor-workspace-split flex-1 min-h-0" :class="{ 'result-pane-collapsed': resultPaneTargetSize === 0 }" @resized="onSharedResultResized">
|
||||||
<Pane class="min-h-0 min-w-0" :size="editorPaneSize" :min-size="100 - SHARED_RESULT_PANE_MAX_SIZE">
|
<Pane class="min-h-0 min-w-0" :size="editorPaneSize" :min-size="100 - SHARED_RESULT_PANE_MAX_SIZE">
|
||||||
<Splitpanes
|
<Splitpanes
|
||||||
:horizontal="queryStore.orientation === 'horizontal'"
|
:horizontal="queryStore.orientation === 'horizontal'"
|
||||||
|
|||||||
@@ -63,8 +63,10 @@ describe("Group strip special page tabs", () => {
|
|||||||
it("keeps special page tabs and their update badge in the focused group", () => {
|
it("keeps special page tabs and their update badge in the focused group", () => {
|
||||||
expect(groupTabBarSource).toContain("queryStore.focusedGroupId === props.groupId");
|
expect(groupTabBarSource).toContain("queryStore.focusedGroupId === props.groupId");
|
||||||
expect(groupTabBarSource).toContain("data-settings-page-tab");
|
expect(groupTabBarSource).toContain("data-settings-page-tab");
|
||||||
|
expect(groupTabBarSource).toContain("data-plugin-center-tab");
|
||||||
expect(groupTabBarSource).toContain("data-driver-store-tab");
|
expect(groupTabBarSource).toContain("data-driver-store-tab");
|
||||||
expect(groupTabBarSource).toContain("@click=\"emit('activate-settings')\"");
|
expect(groupTabBarSource).toContain("@click=\"emit('activate-settings')\"");
|
||||||
|
expect(groupTabBarSource).toContain("@click=\"emit('activate-plugin-center')\"");
|
||||||
expect(groupTabBarSource).toContain("@click=\"emit('activate-driver-store')\"");
|
expect(groupTabBarSource).toContain("@click=\"emit('activate-driver-store')\"");
|
||||||
expect(groupTabBarSource).toContain('t("toolbar.driverManager")');
|
expect(groupTabBarSource).toContain('t("toolbar.driverManager")');
|
||||||
expect(groupTabBarSource).toContain("aria-label=\"t('toolbar.updatableDriverCount')\"");
|
expect(groupTabBarSource).toContain("aria-label=\"t('toolbar.updatableDriverCount')\"");
|
||||||
@@ -74,6 +76,8 @@ describe("Group strip special page tabs", () => {
|
|||||||
it("routes special-page actions and preserves ordinary-tab dirty closing", () => {
|
it("routes special-page actions and preserves ordinary-tab dirty closing", () => {
|
||||||
expect(groupSource).toContain(':special-page-tabs="toolbar.specialPageTabs.value"');
|
expect(groupSource).toContain(':special-page-tabs="toolbar.specialPageTabs.value"');
|
||||||
expect(groupSource).toContain('@activate-settings="toolbar.activateSettingsPage()"');
|
expect(groupSource).toContain('@activate-settings="toolbar.activateSettingsPage()"');
|
||||||
|
expect(groupSource).toContain('@activate-plugin-center="toolbar.activatePluginCenter()"');
|
||||||
|
expect(groupSource).toContain('@close-plugin-center="toolbar.closePluginCenter()"');
|
||||||
expect(groupSource).toContain('@close-driver-store="toolbar.closeDriverStore()"');
|
expect(groupSource).toContain('@close-driver-store="toolbar.closeDriverStore()"');
|
||||||
expect(groupTabBarSource).toContain('@mousedown.middle.prevent="closeTab(entry.tab)"');
|
expect(groupTabBarSource).toContain('@mousedown.middle.prevent="closeTab(entry.tab)"');
|
||||||
expect(groupTabBarSource).toContain('@click.stop="closeTab(entry.tab)"');
|
expect(groupTabBarSource).toContain('@click.stop="closeTab(entry.tab)"');
|
||||||
@@ -83,6 +87,7 @@ describe("Group strip special page tabs", () => {
|
|||||||
it("uses one presentation path for active special pages and inactive ordinary tabs", () => {
|
it("uses one presentation path for active special pages and inactive ordinary tabs", () => {
|
||||||
expect(groupTabBarSource).toContain("return !specialPageActive.value && tab.id === props.activeTabId;");
|
expect(groupTabBarSource).toContain("return !specialPageActive.value && tab.id === props.activeTabId;");
|
||||||
expect(groupTabBarSource).toContain("specialPageTabClass(!!specialPageTabs?.settingsActive)");
|
expect(groupTabBarSource).toContain("specialPageTabClass(!!specialPageTabs?.settingsActive)");
|
||||||
|
expect(groupTabBarSource).toContain("specialPageTabClass(!!specialPageTabs?.pluginCenterActive)");
|
||||||
expect(groupTabBarSource).toContain("specialPageTabClass(!!specialPageTabs?.driverStoreActive)");
|
expect(groupTabBarSource).toContain("specialPageTabClass(!!specialPageTabs?.driverStoreActive)");
|
||||||
expect(groupTabBarSource).toContain("if (!active) return undefined;");
|
expect(groupTabBarSource).toContain("if (!active) return undefined;");
|
||||||
expect(groupTabBarSource).toContain('return { "--app-tab-background": activeBackground, boxShadow: "inset 0 -2px 0 color-mix(in srgb, var(--foreground) 72%, transparent)" };');
|
expect(groupTabBarSource).toContain('return { "--app-tab-background": activeBackground, boxShadow: "inset 0 -2px 0 color-mix(in srgb, var(--foreground) 72%, transparent)" };');
|
||||||
|
|||||||
+34
@@ -24,6 +24,16 @@ vi.mock("@/components/ui/popover", () => ({
|
|||||||
PopoverTrigger: { name: "PopoverTriggerStub", template: `<div><slot /></div>` },
|
PopoverTrigger: { name: "PopoverTriggerStub", template: `<div><slot /></div>` },
|
||||||
}));
|
}));
|
||||||
|
|
||||||
|
vi.mock("@/lib/plugins/pluginIconResolver", async (importOriginal) => ({
|
||||||
|
...(await importOriginal<typeof import("@/lib/plugins/pluginIconResolver")>()),
|
||||||
|
resolvePluginIcon: vi.fn(() => Promise.resolve("assets/plugin.svg")),
|
||||||
|
}));
|
||||||
|
|
||||||
|
vi.mock("@/lib/backend/api", async (importOriginal) => ({
|
||||||
|
...(await importOriginal<typeof import("@/lib/backend/api")>()),
|
||||||
|
readPluginAsset: vi.fn(() => Promise.resolve({ contentType: "image/svg+xml", dataBase64: "PHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciLz4=" })),
|
||||||
|
}));
|
||||||
|
|
||||||
const specDir = dirname(fileURLToPath(import.meta.url));
|
const specDir = dirname(fileURLToPath(import.meta.url));
|
||||||
const source = readFileSync(resolve(specDir, "../EditorGroupTabBar.vue"), "utf8");
|
const source = readFileSync(resolve(specDir, "../EditorGroupTabBar.vue"), "utf8");
|
||||||
const sharedStyles = readFileSync(resolve(specDir, "../appTabBar.css"), "utf8");
|
const sharedStyles = readFileSync(resolve(specDir, "../appTabBar.css"), "utf8");
|
||||||
@@ -713,6 +723,30 @@ describe("EditorGroupTabBar group behavior", () => {
|
|||||||
app.unmount();
|
app.unmount();
|
||||||
host.remove();
|
host.remove();
|
||||||
});
|
});
|
||||||
|
|
||||||
|
it("renders plugin workbench tabs with the plugin icon instead of the code fallback", async () => {
|
||||||
|
const store = useQueryStore();
|
||||||
|
const pluginTabId = store.openPluginWorkbench("io.dbx.ssh", "io.dbx.ssh.workbench", { title: "SSH server", connectionId: "ssh-1", forceNew: true });
|
||||||
|
const { app, host } = mountBar(store.groups[0].id, store.tabs.slice(), pluginTabId, pinia);
|
||||||
|
await settle();
|
||||||
|
// PluginIcon loads the asset asynchronously; wait for the blob <img> to appear.
|
||||||
|
for (let i = 0; i < 20 && !host.querySelector(`[data-tab-id="${pluginTabId}"] img`); i += 1) {
|
||||||
|
await new Promise((resolveTimeout) => setTimeout(resolveTimeout, 5));
|
||||||
|
}
|
||||||
|
|
||||||
|
const pill = host.querySelector<HTMLElement>(`[data-tab-id="${pluginTabId}"]`);
|
||||||
|
expect(pill).toBeTruthy();
|
||||||
|
expect(pill!.querySelector("img")).toBeTruthy();
|
||||||
|
// The pill and the overflow popup list both render via TabModeIcon, whose
|
||||||
|
// per-mode chain must keep the plugin-workbench plugin icon branch.
|
||||||
|
const tabModeIconSource = readFileSync(resolve(specDir, "../TabModeIcon.vue"), "utf8");
|
||||||
|
expect(tabModeIconSource).toContain("tab.mode === 'plugin-workbench' && tab.pluginWorkbench");
|
||||||
|
expect(tabModeIconSource).toContain(':contribution-id="tab.pluginWorkbench.contributionId"');
|
||||||
|
expect(source).toContain('<TabModeIcon :tab="entry.tab"');
|
||||||
|
|
||||||
|
app.unmount();
|
||||||
|
host.remove();
|
||||||
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
describe("EditorGroupTabBar special page navigation", () => {
|
describe("EditorGroupTabBar special page navigation", () => {
|
||||||
|
|||||||
+91
-2
@@ -26,7 +26,7 @@ const groupExecutionCalls = vi.hoisted(() => ({ capture: [] as string[], request
|
|||||||
vi.mock("@/components/layout/EditorGroup.vue", () => ({
|
vi.mock("@/components/layout/EditorGroup.vue", () => ({
|
||||||
default: {
|
default: {
|
||||||
name: "EditorGroupStub",
|
name: "EditorGroupStub",
|
||||||
props: ["groupId", "tabIds", "activeTabId"],
|
props: ["groupId", "tabIds", "activeTabId", "contentSuppressed"],
|
||||||
emits: ["execute"],
|
emits: ["execute"],
|
||||||
methods: {
|
methods: {
|
||||||
previewStatementRange(tabId: string, range: unknown) {
|
previewStatementRange(tabId: string, range: unknown) {
|
||||||
@@ -54,7 +54,7 @@ vi.mock("@/components/layout/EditorGroup.vue", () => ({
|
|||||||
return true;
|
return true;
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
template: `<div data-test="editor-group" :data-group-id="groupId" :data-tab-ids="tabIds.join(',')" :data-active-tab-id="activeTabId"><button data-test="emit-execute" @click="$emit('execute', { fullSql: 'SELECT 1', selectedSql: 'SELECT 1', cursorPos: 0, selectionFrom: 0, selectionTo: 8 })">execute</button></div>`,
|
template: `<div data-test="editor-group" :data-group-id="groupId" :data-tab-ids="tabIds.join(',')" :data-active-tab-id="activeTabId" :data-content-suppressed="contentSuppressed ? 'true' : 'false'"><button data-test="emit-execute" @click="$emit('execute', { fullSql: 'SELECT 1', selectedSql: 'SELECT 1', cursorPos: 0, selectionFrom: 0, selectionTo: 8 })">execute</button></div>`,
|
||||||
},
|
},
|
||||||
}));
|
}));
|
||||||
|
|
||||||
@@ -336,6 +336,95 @@ describe("SqlEditorWorkspace mount contract", () => {
|
|||||||
host.remove();
|
host.remove();
|
||||||
});
|
});
|
||||||
|
|
||||||
|
it("keeps group tab strips mounted and drops the splitpanes workspace while suppressed", async () => {
|
||||||
|
const store = useQueryStore();
|
||||||
|
store.tabs = [tab("tab-a"), { ...tab("tab-b"), mode: "plugin-workbench" } as unknown as ReturnType<typeof tab>];
|
||||||
|
store.activeTabId = "tab-b";
|
||||||
|
store.groups = [
|
||||||
|
{ id: "g1", tabIds: ["tab-a"], activeTabId: "tab-a" },
|
||||||
|
{ id: "g2", tabIds: ["tab-b"], activeTabId: "tab-b" },
|
||||||
|
];
|
||||||
|
store.focusedGroupId = "g2";
|
||||||
|
store.orientation = "vertical";
|
||||||
|
store.sizes = [50, 50];
|
||||||
|
|
||||||
|
const host = createHost();
|
||||||
|
const app = createApp(SqlEditorWorkspace, {
|
||||||
|
activeTab: { ...tab("tab-b"), mode: "plugin-workbench" } as unknown as ReturnType<typeof tab>,
|
||||||
|
activeConnection: undefined,
|
||||||
|
executableSql: "",
|
||||||
|
activeOutputView: "result",
|
||||||
|
formatSqlRequest: null,
|
||||||
|
compressSqlRequest: null,
|
||||||
|
selectedSql: "",
|
||||||
|
cursorPos: 0,
|
||||||
|
blockDangerousRedisCommands: false,
|
||||||
|
contentSuppressed: true,
|
||||||
|
});
|
||||||
|
app.use(pinia);
|
||||||
|
app.use(i18n);
|
||||||
|
app.mount(host);
|
||||||
|
await nextTick();
|
||||||
|
|
||||||
|
// Suppressed mode renders the groups' tab strips directly (no Splitpanes,
|
||||||
|
// no shared result pane) so App.vue's always-mounted plugin workbench
|
||||||
|
// layer can own the remaining column while the strips stay visible.
|
||||||
|
expect(host.querySelector('[data-test="splitpanes-stub"]')).toBeNull();
|
||||||
|
expect(host.querySelector('[data-test="result-surface"]')).toBeNull();
|
||||||
|
const groups = host.querySelectorAll('[data-test="editor-group"]');
|
||||||
|
expect(groups).toHaveLength(2);
|
||||||
|
expect(groups[1]?.getAttribute("data-group-id")).toBe("g2");
|
||||||
|
expect(groups[1]?.getAttribute("data-content-suppressed")).toBe("true");
|
||||||
|
|
||||||
|
// The App.vue wrapper is flex-none with indefinite height while a plugin
|
||||||
|
// tab is active: the workspace must size to its strip content, or the
|
||||||
|
// h-full/flex-1 fill contract collapses it to zero height and clips the
|
||||||
|
// strips away (overflow-hidden) — the "plugin tab bar vanishes" regression.
|
||||||
|
const workspaceRoot = host.querySelector<HTMLElement>(".sql-editor-workspace");
|
||||||
|
expect(workspaceRoot?.classList.contains("h-auto")).toBe(true);
|
||||||
|
expect(workspaceRoot?.classList.contains("h-full")).toBe(false);
|
||||||
|
expect(workspaceRoot?.classList.contains("flex-1")).toBe(false);
|
||||||
|
|
||||||
|
app.unmount();
|
||||||
|
host.remove();
|
||||||
|
});
|
||||||
|
|
||||||
|
it("keeps the fill-height contract on the workspace root outside suppressed mode", async () => {
|
||||||
|
const store = useQueryStore();
|
||||||
|
store.tabs = [tab("tab-a")];
|
||||||
|
store.activeTabId = "tab-a";
|
||||||
|
store.groups = [{ id: "g1", tabIds: ["tab-a"], activeTabId: "tab-a" }];
|
||||||
|
store.focusedGroupId = "g1";
|
||||||
|
store.orientation = "vertical";
|
||||||
|
store.sizes = [100];
|
||||||
|
|
||||||
|
const host = createHost();
|
||||||
|
const app = createApp(SqlEditorWorkspace, {
|
||||||
|
activeTab: tab("tab-a"),
|
||||||
|
activeConnection: undefined,
|
||||||
|
executableSql: "",
|
||||||
|
activeOutputView: "result",
|
||||||
|
formatSqlRequest: null,
|
||||||
|
compressSqlRequest: null,
|
||||||
|
selectedSql: "",
|
||||||
|
cursorPos: 0,
|
||||||
|
blockDangerousRedisCommands: false,
|
||||||
|
contentSuppressed: false,
|
||||||
|
});
|
||||||
|
app.use(pinia);
|
||||||
|
app.use(i18n);
|
||||||
|
app.mount(host);
|
||||||
|
await nextTick();
|
||||||
|
|
||||||
|
const workspaceRoot = host.querySelector<HTMLElement>(".sql-editor-workspace");
|
||||||
|
expect(workspaceRoot?.classList.contains("h-full")).toBe(true);
|
||||||
|
expect(workspaceRoot?.classList.contains("flex-1")).toBe(true);
|
||||||
|
expect(workspaceRoot?.classList.contains("h-auto")).toBe(false);
|
||||||
|
|
||||||
|
app.unmount();
|
||||||
|
host.remove();
|
||||||
|
});
|
||||||
|
|
||||||
it("forwards editor execute events from EditorGroup to the App listener", async () => {
|
it("forwards editor execute events from EditorGroup to the App listener", async () => {
|
||||||
const store = useQueryStore();
|
const store = useQueryStore();
|
||||||
store.tabs = [tab("tab-a")];
|
store.tabs = [tab("tab-a")];
|
||||||
|
|||||||
+235
-18
@@ -1,11 +1,21 @@
|
|||||||
// @vitest-environment happy-dom
|
// @vitest-environment happy-dom
|
||||||
|
|
||||||
import { createApp, defineComponent, h, nextTick, reactive, type App } from "vue";
|
import { createApp, defineComponent, h, nextTick, reactive, type App } from "vue";
|
||||||
import { afterEach, describe, expect, it } from "vitest";
|
import { afterEach, describe, expect, it, vi } from "vitest";
|
||||||
import i18n from "@/i18n";
|
import i18n from "@/i18n";
|
||||||
import PluginConnectionFields from "./PluginConnectionFields.vue";
|
import PluginConnectionFields from "./PluginConnectionFields.vue";
|
||||||
import type { PluginConnectionProviderContribution, PluginFormFieldBinding, PluginFormFieldValue } from "@/types/database";
|
import type { PluginConnectionProviderContribution, PluginFormFieldBinding, PluginFormFieldValue } from "@/types/database";
|
||||||
|
|
||||||
|
const invokePluginMock = vi.fn();
|
||||||
|
|
||||||
|
vi.mock("@/lib/backend/api", () => ({
|
||||||
|
listLocalSshKeys: vi.fn(async () => [
|
||||||
|
{ path: "/home/dev/.ssh/id_ed25519", algorithm: "ssh-ed25519", fingerprint: "SHA256:abc", hasPassphrase: false },
|
||||||
|
{ path: "/home/dev/.ssh/id_rsa", algorithm: "ssh-rsa", fingerprint: "", hasPassphrase: true },
|
||||||
|
]),
|
||||||
|
invokePlugin: (...args: unknown[]) => invokePluginMock(...args),
|
||||||
|
}));
|
||||||
|
|
||||||
const mountedApps: App[] = [];
|
const mountedApps: App[] = [];
|
||||||
|
|
||||||
const contribution: PluginConnectionProviderContribution = {
|
const contribution: PluginConnectionProviderContribution = {
|
||||||
@@ -16,16 +26,6 @@ const contribution: PluginConnectionProviderContribution = {
|
|||||||
fields: [
|
fields: [
|
||||||
{ key: "host", label: "Host", type: "text", required: true, placeholder: "localhost" },
|
{ key: "host", label: "Host", type: "text", required: true, placeholder: "localhost" },
|
||||||
{ key: "password", label: "Password", type: "password" },
|
{ key: "password", label: "Password", type: "password" },
|
||||||
{
|
|
||||||
key: "protocol",
|
|
||||||
label: "Protocol",
|
|
||||||
type: "radio",
|
|
||||||
default: "https",
|
|
||||||
options: [
|
|
||||||
{ label: "HTTPS", value: "https" },
|
|
||||||
{ label: "HTTP", value: "http" },
|
|
||||||
],
|
|
||||||
},
|
|
||||||
],
|
],
|
||||||
};
|
};
|
||||||
|
|
||||||
@@ -62,6 +62,39 @@ afterEach(() => {
|
|||||||
});
|
});
|
||||||
|
|
||||||
describe("PluginConnectionFields", () => {
|
describe("PluginConnectionFields", () => {
|
||||||
|
it("preserves multiline secret input and masks it again after its branch is reopened", async () => {
|
||||||
|
const provider: PluginConnectionProviderContribution = {
|
||||||
|
type: "connection-provider",
|
||||||
|
id: "pem.connection",
|
||||||
|
label: "PEM",
|
||||||
|
database_type: "example",
|
||||||
|
fields: [
|
||||||
|
{ key: "mode", label: "Mode", type: "text", default: "tls" },
|
||||||
|
{ key: "key", label: "Private key", type: "textarea", binding: "secret", visible_when: { field: "mode", one_of: ["tls"] } },
|
||||||
|
],
|
||||||
|
};
|
||||||
|
const state = await mountContribution(provider, {});
|
||||||
|
const textarea = document.querySelector<HTMLTextAreaElement>("#pem-connection-key")!;
|
||||||
|
const pem = "-----BEGIN PRIVATE KEY-----\nexample\n-----END PRIVATE KEY-----\n";
|
||||||
|
expect(textarea.classList.contains("secret-masked")).toBe(true);
|
||||||
|
textarea.value = pem;
|
||||||
|
textarea.dispatchEvent(new Event("input", { bubbles: true }));
|
||||||
|
await nextTick();
|
||||||
|
expect(state.values.key).toBe(pem);
|
||||||
|
textarea.parentElement!.querySelector<HTMLButtonElement>("button")!.click();
|
||||||
|
await nextTick();
|
||||||
|
expect(textarea.classList.contains("secret-masked")).toBe(false);
|
||||||
|
expect(textarea.value).toBe(pem);
|
||||||
|
state.values = { ...state.values, mode: "plain" };
|
||||||
|
await nextTick();
|
||||||
|
expect(document.querySelector("#pem-connection-key")).toBeNull();
|
||||||
|
state.values = { ...state.values, mode: "tls" };
|
||||||
|
await nextTick();
|
||||||
|
const reopened = document.querySelector<HTMLTextAreaElement>("#pem-connection-key")!;
|
||||||
|
expect(reopened.value).toBe(pem);
|
||||||
|
expect(reopened.classList.contains("secret-masked")).toBe(true);
|
||||||
|
});
|
||||||
|
|
||||||
it("renders declared fields and emits immutable model updates", async () => {
|
it("renders declared fields and emits immutable model updates", async () => {
|
||||||
const state = await mountFields({ password: "secret" });
|
const state = await mountFields({ password: "secret" });
|
||||||
const hostInput = document.querySelector<HTMLInputElement>("#example-connection-host");
|
const hostInput = document.querySelector<HTMLInputElement>("#example-connection-host");
|
||||||
@@ -99,15 +132,199 @@ describe("PluginConnectionFields", () => {
|
|||||||
expect(document.querySelector(".rounded-lg.border")).toBeNull();
|
expect(document.querySelector(".rounded-lg.border")).toBeNull();
|
||||||
});
|
});
|
||||||
|
|
||||||
it("renders radio fields and emits the selected option", async () => {
|
it("hides conditional fields until visible_when matches and marks required_when", async () => {
|
||||||
const state = await mountFields();
|
const conditional: PluginConnectionProviderContribution = {
|
||||||
const radios = Array.from(document.querySelectorAll<HTMLInputElement>("input[type='radio']"));
|
type: "connection-provider",
|
||||||
|
id: "cond.connection",
|
||||||
|
label: "Conditional",
|
||||||
|
database_type: "cond",
|
||||||
|
fields: [
|
||||||
|
{ key: "mode", label: "Mode", type: "text", default: "password" },
|
||||||
|
{ key: "private_key_path", label: "Private key", type: "text", visible_when: { field: "mode", one_of: ["key"] }, required_when: { field: "mode", one_of: ["key"] } },
|
||||||
|
],
|
||||||
|
};
|
||||||
|
const state = await mountContribution(conditional, {});
|
||||||
|
|
||||||
expect(radios).toHaveLength(2);
|
expect(document.querySelector("#cond-connection-private_key_path")).toBeNull();
|
||||||
expect(radios[0]?.checked).toBe(true);
|
|
||||||
radios[1]?.click();
|
state.values = { mode: "key" };
|
||||||
await nextTick();
|
await nextTick();
|
||||||
|
|
||||||
expect(state.values.protocol).toBe("http");
|
const keyInput = document.querySelector<HTMLInputElement>("#cond-connection-private_key_path");
|
||||||
|
expect(keyInput).not.toBeNull();
|
||||||
|
const label = document.querySelector('label[for="cond-connection-private_key_path"]');
|
||||||
|
expect(label?.textContent).toContain("*");
|
||||||
|
|
||||||
|
state.values = { mode: "password" };
|
||||||
|
await nextTick();
|
||||||
|
expect(document.querySelector("#cond-connection-private_key_path")).toBeNull();
|
||||||
|
});
|
||||||
|
|
||||||
|
it("keeps grandchild fields hidden while an intermediate default-only value would match (kafka msk_region regression)", async () => {
|
||||||
|
// sasl_mechanism (PLAIN default, hidden without SASL) → oauth_token_source
|
||||||
|
// (msk_iam default) → msk_region: the nested default must not surface an
|
||||||
|
// always-required AWS region on a plain PLAINTEXT/SCRAM connection.
|
||||||
|
const kafka: PluginConnectionProviderContribution = {
|
||||||
|
type: "connection-provider",
|
||||||
|
id: "kafka.connection",
|
||||||
|
label: "Kafka",
|
||||||
|
database_type: "kafka",
|
||||||
|
fields: [
|
||||||
|
{ key: "bootstrap_servers", label: "Bootstrap servers", type: "textarea", required: true },
|
||||||
|
{
|
||||||
|
key: "security_protocol",
|
||||||
|
label: "Security protocol",
|
||||||
|
type: "select",
|
||||||
|
default: "PLAINTEXT",
|
||||||
|
options: [
|
||||||
|
{ label: "PLAINTEXT", value: "PLAINTEXT" },
|
||||||
|
{ label: "SASL_SSL", value: "SASL_SSL" },
|
||||||
|
],
|
||||||
|
},
|
||||||
|
{
|
||||||
|
key: "sasl_mechanism",
|
||||||
|
label: "SASL mechanism",
|
||||||
|
type: "select",
|
||||||
|
default: "PLAIN",
|
||||||
|
options: [
|
||||||
|
{ label: "PLAIN", value: "PLAIN" },
|
||||||
|
{ label: "OAUTHBEARER", value: "OAUTHBEARER" },
|
||||||
|
],
|
||||||
|
visible_when: { field: "security_protocol", one_of: ["SASL_PLAINTEXT", "SASL_SSL"] },
|
||||||
|
},
|
||||||
|
{
|
||||||
|
key: "oauth_token_source",
|
||||||
|
label: "OAuth token source",
|
||||||
|
type: "select",
|
||||||
|
default: "msk_iam",
|
||||||
|
options: [
|
||||||
|
{ label: "MSK IAM", value: "msk_iam" },
|
||||||
|
{ label: "Static token", value: "static_token" },
|
||||||
|
],
|
||||||
|
visible_when: { field: "sasl_mechanism", one_of: ["OAUTHBEARER"] },
|
||||||
|
},
|
||||||
|
{ key: "msk_region", label: "MSK AWS region", type: "text", visible_when: { field: "oauth_token_source", one_of: ["msk_iam"] }, required_when: { field: "oauth_token_source", one_of: ["msk_iam"] } },
|
||||||
|
],
|
||||||
|
};
|
||||||
|
const state = await mountContribution(kafka, {}, "io.dbx.kafka");
|
||||||
|
|
||||||
|
expect(document.querySelector("#kafka-connection-msk_region")).toBeNull();
|
||||||
|
|
||||||
|
state.values = { security_protocol: "SASL_SSL", sasl_mechanism: "OAUTHBEARER" };
|
||||||
|
await nextTick();
|
||||||
|
expect(document.querySelector("#kafka-connection-msk_region")).not.toBeNull();
|
||||||
|
const label = document.querySelector('label[for="kafka-connection-msk_region"]');
|
||||||
|
expect(label?.textContent).toContain("*");
|
||||||
|
|
||||||
|
// Selecting the static token source hides the region field again.
|
||||||
|
state.values = { sasl_mechanism: "OAUTHBEARER", oauth_token_source: "static_token" };
|
||||||
|
await nextTick();
|
||||||
|
expect(document.querySelector("#kafka-connection-msk_region")).toBeNull();
|
||||||
|
});
|
||||||
|
|
||||||
|
it("offers local SSH keys on private_key_path fields and fills the chosen path", async () => {
|
||||||
|
const withKey: PluginConnectionProviderContribution = {
|
||||||
|
type: "connection-provider",
|
||||||
|
id: "keys.connection",
|
||||||
|
label: "Keys",
|
||||||
|
database_type: "keys",
|
||||||
|
fields: [{ key: "private_key_path", label: "Private key", type: "text" }],
|
||||||
|
};
|
||||||
|
const state = await mountContribution(withKey, {});
|
||||||
|
await flushAsync();
|
||||||
|
|
||||||
|
const select = document.querySelector<HTMLSelectElement>("select");
|
||||||
|
expect(select).not.toBeNull();
|
||||||
|
expect(select?.disabled).toBe(false);
|
||||||
|
const encryptedOption = select?.querySelector<HTMLOptionElement>('option[value="/home/dev/.ssh/id_rsa"]');
|
||||||
|
expect(encryptedOption?.textContent).toContain("id_rsa");
|
||||||
|
expect(encryptedOption?.textContent).toContain("ssh-rsa");
|
||||||
|
expect(encryptedOption?.textContent).toMatch(/encrypted|已加密/);
|
||||||
|
|
||||||
|
select!.value = "/home/dev/.ssh/id_rsa";
|
||||||
|
select!.dispatchEvent(new Event("change", { bubbles: true }));
|
||||||
|
await nextTick();
|
||||||
|
|
||||||
|
expect(state.values.private_key_path).toBe("/home/dev/.ssh/id_rsa");
|
||||||
|
});
|
||||||
|
|
||||||
|
it("renders options_action fields as a dynamic select and keeps a stored value visible", async () => {
|
||||||
|
const dynamic: PluginConnectionProviderContribution = {
|
||||||
|
type: "connection-provider",
|
||||||
|
id: "dyn.connection",
|
||||||
|
label: "Dyn",
|
||||||
|
database_type: "dyn",
|
||||||
|
fields: [{ key: "sudo_profile", label: "Profile", type: "text", options_action: "sudo/profiles/options" }],
|
||||||
|
};
|
||||||
|
invokePluginMock.mockResolvedValueOnce({
|
||||||
|
options: [
|
||||||
|
{ value: "p1", label: "Ops" },
|
||||||
|
{ value: "p2", label: "QA" },
|
||||||
|
],
|
||||||
|
});
|
||||||
|
// "ghost" is stored but no longer offered: the dropdown must keep it visible.
|
||||||
|
await mountContribution(dynamic, { sudo_profile: "ghost" }, "io.dbx.ssh");
|
||||||
|
await flushAsync();
|
||||||
|
|
||||||
|
expect(invokePluginMock).toHaveBeenCalledWith("io.dbx.ssh", "sudo/profiles/options");
|
||||||
|
expect(document.querySelector("input#dyn-connection-sudo_profile")).toBeNull();
|
||||||
|
const trigger = document.querySelector<HTMLButtonElement>('#dyn-connection-sudo_profile, button[role="combobox"]');
|
||||||
|
expect(trigger).not.toBeNull();
|
||||||
|
expect(trigger?.textContent).toContain("ghost");
|
||||||
|
});
|
||||||
|
|
||||||
|
it("falls back to the text input when the options_action call fails or returns nothing", async () => {
|
||||||
|
const dynamic: PluginConnectionProviderContribution = {
|
||||||
|
type: "connection-provider",
|
||||||
|
id: "degrade.connection",
|
||||||
|
label: "Degrade",
|
||||||
|
database_type: "degrade",
|
||||||
|
fields: [{ key: "sudo_profile", label: "Profile", type: "text", options_action: "sudo/profiles/options" }],
|
||||||
|
};
|
||||||
|
invokePluginMock.mockRejectedValueOnce(new Error("method not registered"));
|
||||||
|
await mountContribution(dynamic, {}, "io.dbx.ssh");
|
||||||
|
await flushAsync();
|
||||||
|
|
||||||
|
const input = document.querySelector<HTMLInputElement>("input#degrade-connection-sudo_profile");
|
||||||
|
expect(input).not.toBeNull();
|
||||||
|
expect(input?.value).toBe("");
|
||||||
|
|
||||||
|
// An empty option list degrades the same way.
|
||||||
|
invokePluginMock.mockResolvedValueOnce({ options: [] });
|
||||||
|
const empty = { ...dynamic, id: "empty.connection", label: "Empty" };
|
||||||
|
await mountContribution(empty, {}, "io.dbx.ssh");
|
||||||
|
await flushAsync();
|
||||||
|
expect(document.querySelector("input#empty-connection-sudo_profile")).not.toBeNull();
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
|
async function flushAsync() {
|
||||||
|
await nextTick();
|
||||||
|
await new Promise((resolve) => setTimeout(resolve, 0));
|
||||||
|
}
|
||||||
|
|
||||||
|
async function mountContribution(contribution: PluginConnectionProviderContribution, initialValues: Record<string, PluginFormFieldValue>, pluginId?: string) {
|
||||||
|
const state = reactive({ values: initialValues });
|
||||||
|
const container = document.createElement("div");
|
||||||
|
document.body.append(container);
|
||||||
|
const app = createApp(
|
||||||
|
defineComponent({
|
||||||
|
setup() {
|
||||||
|
return () =>
|
||||||
|
h(PluginConnectionFields, {
|
||||||
|
contribution,
|
||||||
|
modelValue: state.values,
|
||||||
|
pluginId,
|
||||||
|
"onUpdate:modelValue": (value: Record<string, PluginFormFieldValue>) => {
|
||||||
|
state.values = value;
|
||||||
|
},
|
||||||
|
});
|
||||||
|
},
|
||||||
|
}),
|
||||||
|
);
|
||||||
|
mountedApps.push(app);
|
||||||
|
app.use(i18n);
|
||||||
|
app.mount(container);
|
||||||
|
await nextTick();
|
||||||
|
return state;
|
||||||
|
}
|
||||||
@@ -1,25 +1,45 @@
|
|||||||
<script setup lang="ts">
|
<script setup lang="ts">
|
||||||
import { computed } from "vue";
|
import { computed, ref, watch } from "vue";
|
||||||
|
import { useI18n } from "vue-i18n";
|
||||||
import { Input } from "@/components/ui/input";
|
import { Input } from "@/components/ui/input";
|
||||||
import PasswordInput from "@/components/ui/PasswordInput.vue";
|
import PasswordInput from "@/components/ui/PasswordInput.vue";
|
||||||
|
import PasswordTextarea from "@/components/ui/PasswordTextarea.vue";
|
||||||
import { Label } from "@/components/ui/label";
|
import { Label } from "@/components/ui/label";
|
||||||
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";
|
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";
|
||||||
import { Switch } from "@/components/ui/switch";
|
import { Switch } from "@/components/ui/switch";
|
||||||
import type { PluginConnectionProviderContribution, PluginFormField, PluginFormFieldBinding, PluginFormFieldValue } from "@/types/database";
|
import { pluginFieldIsRequired, pluginFieldIsVisible, type PluginFieldResolver } from "@/lib/plugins/pluginFieldConditions";
|
||||||
|
import { invokePlugin, listLocalSshKeys } from "@/lib/backend/api";
|
||||||
|
import type { LocalSshKey, PluginConnectionProviderContribution, PluginFormField, PluginFormFieldBinding, PluginFormFieldOption, PluginFormFieldValue } from "@/types/database";
|
||||||
|
|
||||||
const props = defineProps<{
|
const props = defineProps<{
|
||||||
contribution: PluginConnectionProviderContribution;
|
contribution: PluginConnectionProviderContribution;
|
||||||
modelValue: Record<string, PluginFormFieldValue>;
|
modelValue: Record<string, PluginFormFieldValue>;
|
||||||
hiddenBindings?: PluginFormFieldBinding[];
|
hiddenBindings?: PluginFormFieldBinding[];
|
||||||
layout?: "stacked" | "connection-dialog";
|
layout?: "stacked" | "connection-dialog";
|
||||||
|
pluginId?: string;
|
||||||
}>();
|
}>();
|
||||||
|
|
||||||
const emit = defineEmits<{
|
const emit = defineEmits<{
|
||||||
"update:modelValue": [value: Record<string, PluginFormFieldValue>];
|
"update:modelValue": [value: Record<string, PluginFormFieldValue>];
|
||||||
}>();
|
}>();
|
||||||
|
|
||||||
|
const { t } = useI18n();
|
||||||
|
|
||||||
const formValues = computed(() => props.modelValue);
|
const formValues = computed(() => props.modelValue);
|
||||||
const visibleFields = computed(() => props.contribution.fields.filter((field) => !field.binding || !props.hiddenBindings?.includes(field.binding)));
|
/** Value of any sibling field by key (condition evaluation reads current form values). */
|
||||||
|
function readFieldValue(key: string): PluginFormFieldValue {
|
||||||
|
const field = props.contribution.fields.find((candidate) => candidate.key === key);
|
||||||
|
return field ? (formValues.value[key] ?? field.default) : undefined;
|
||||||
|
}
|
||||||
|
const resolveSiblingField: PluginFieldResolver = (key) => props.contribution.fields.find((candidate) => candidate.key === key);
|
||||||
|
function fieldVisible(field: PluginFormField): boolean {
|
||||||
|
if (field.binding && props.hiddenBindings?.includes(field.binding)) return false;
|
||||||
|
return pluginFieldIsVisible(field, readFieldValue, resolveSiblingField);
|
||||||
|
}
|
||||||
|
function fieldRequired(field: PluginFormField): boolean {
|
||||||
|
return pluginFieldIsRequired(field, readFieldValue);
|
||||||
|
}
|
||||||
|
const visibleFields = computed(() => props.contribution.fields.filter((field) => fieldVisible(field)));
|
||||||
const isConnectionDialogLayout = computed(() => props.layout === "connection-dialog");
|
const isConnectionDialogLayout = computed(() => props.layout === "connection-dialog");
|
||||||
|
|
||||||
function fieldValue(field: PluginFormField): PluginFormFieldValue {
|
function fieldValue(field: PluginFormField): PluginFormFieldValue {
|
||||||
@@ -59,6 +79,103 @@ function defaultValueFor(field: PluginFormField): PluginFormFieldValue {
|
|||||||
if (field.type === "number") return undefined;
|
if (field.type === "number") return undefined;
|
||||||
return "";
|
return "";
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// ---------------------------------------------------------------------------
|
||||||
|
// Dynamic option lists (fields declaring `options_action`)
|
||||||
|
// ---------------------------------------------------------------------------
|
||||||
|
|
||||||
|
// A field may point `options_action` at a plugin method returning
|
||||||
|
// `{ options: [{ value, label }] }`. The host fetches it once per dialog and
|
||||||
|
// renders the field as a select; a missing plugin id, a failed call, or an
|
||||||
|
// empty result falls back to the declared text input (older hosts without
|
||||||
|
// this extension never fetch and simply keep the text field).
|
||||||
|
const dynamicOptions = ref<Record<string, PluginFormFieldOption[]>>({});
|
||||||
|
const dynamicOptionsRequested = ref(new Set<string>());
|
||||||
|
|
||||||
|
const optionsActionFields = computed(() => visibleFields.value.filter((field) => field.options_action));
|
||||||
|
|
||||||
|
watch(
|
||||||
|
optionsActionFields,
|
||||||
|
(fields) => {
|
||||||
|
for (const field of fields) {
|
||||||
|
const action = field.options_action;
|
||||||
|
if (!action || !props.pluginId || dynamicOptionsRequested.value.has(field.key)) continue;
|
||||||
|
dynamicOptionsRequested.value.add(field.key);
|
||||||
|
invokePlugin<{ options?: PluginFormFieldOption[] }>(props.pluginId, action)
|
||||||
|
.then((result) => {
|
||||||
|
const options = Array.isArray(result?.options) ? result.options.filter((option) => option && option.value !== undefined) : [];
|
||||||
|
dynamicOptions.value = { ...dynamicOptions.value, [field.key]: options };
|
||||||
|
})
|
||||||
|
.catch(() => {
|
||||||
|
dynamicOptions.value = { ...dynamicOptions.value, [field.key]: [] };
|
||||||
|
});
|
||||||
|
}
|
||||||
|
},
|
||||||
|
{ immediate: true },
|
||||||
|
);
|
||||||
|
|
||||||
|
function selectOptionsFor(field: PluginFormField): PluginFormFieldOption[] | null {
|
||||||
|
if (!field.options_action) return null;
|
||||||
|
const options = dynamicOptions.value[field.key];
|
||||||
|
if (!options || options.length === 0) return null;
|
||||||
|
// Keep a stored value visible even when its profile disappeared so the
|
||||||
|
// dialog does not silently look "unset" on reopen.
|
||||||
|
const current = fieldValue(field);
|
||||||
|
if (current !== undefined && current !== "" && !options.some((option) => String(option.value) === String(current))) {
|
||||||
|
return [{ value: String(current), label: String(current) }, ...options];
|
||||||
|
}
|
||||||
|
return options;
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---------------------------------------------------------------------------
|
||||||
|
// Local SSH key suggestions (Host API: private_key_path convenience picker)
|
||||||
|
// ---------------------------------------------------------------------------
|
||||||
|
|
||||||
|
const LOCAL_SSH_KEY_FIELD = "private_key_path";
|
||||||
|
|
||||||
|
function isLocalSshKeyField(field: PluginFormField): boolean {
|
||||||
|
return field.key === LOCAL_SSH_KEY_FIELD && (field.type === "text" || field.type === "password");
|
||||||
|
}
|
||||||
|
|
||||||
|
const hasLocalSshKeyField = computed(() => visibleFields.value.some((field) => isLocalSshKeyField(field)));
|
||||||
|
|
||||||
|
const localSshKeys = ref<LocalSshKey[]>([]);
|
||||||
|
const localSshKeysRequested = ref(false);
|
||||||
|
|
||||||
|
async function loadLocalSshKeys() {
|
||||||
|
if (localSshKeysRequested.value) return;
|
||||||
|
localSshKeysRequested.value = true;
|
||||||
|
try {
|
||||||
|
localSshKeys.value = await listLocalSshKeys();
|
||||||
|
} catch {
|
||||||
|
localSshKeys.value = [];
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
watch(
|
||||||
|
hasLocalSshKeyField,
|
||||||
|
(present) => {
|
||||||
|
if (present) void loadLocalSshKeys();
|
||||||
|
},
|
||||||
|
{ immediate: true },
|
||||||
|
);
|
||||||
|
|
||||||
|
function localSshKeyFile(path: string): string {
|
||||||
|
return path.replaceAll("\\", "/").split("/").pop() || path;
|
||||||
|
}
|
||||||
|
|
||||||
|
function localSshKeyLabel(key: LocalSshKey): string {
|
||||||
|
const algorithm = key.algorithm || "?";
|
||||||
|
return key.hasPassphrase ? `${localSshKeyFile(key.path)} · ${algorithm} · ${t("connection.pluginSshKeyEncrypted")}` : `${localSshKeyFile(key.path)} · ${algorithm}`;
|
||||||
|
}
|
||||||
|
|
||||||
|
function applyLocalSshKey(field: PluginFormField, event: Event) {
|
||||||
|
const select = event.target as HTMLSelectElement;
|
||||||
|
const selected = localSshKeys.value.find((key) => key.path === select.value);
|
||||||
|
select.value = "";
|
||||||
|
if (!selected) return;
|
||||||
|
updateField(field, selected.path);
|
||||||
|
}
|
||||||
</script>
|
</script>
|
||||||
|
|
||||||
<template>
|
<template>
|
||||||
@@ -75,11 +192,37 @@ function defaultValueFor(field: PluginFormField): PluginFormFieldValue {
|
|||||||
<div v-for="field in visibleFields" :key="field.key" :class="isConnectionDialogLayout ? 'col-span-full grid grid-cols-4 items-start gap-4' : 'space-y-1.5'">
|
<div v-for="field in visibleFields" :key="field.key" :class="isConnectionDialogLayout ? 'col-span-full grid grid-cols-4 items-start gap-4' : 'space-y-1.5'">
|
||||||
<Label :for="fieldId(field)" :class="isConnectionDialogLayout ? 'justify-self-start pt-2 text-left' : 'text-xs'">
|
<Label :for="fieldId(field)" :class="isConnectionDialogLayout ? 'justify-self-start pt-2 text-left' : 'text-xs'">
|
||||||
{{ field.label }}
|
{{ field.label }}
|
||||||
<span v-if="field.required" class="text-destructive">*</span>
|
<span v-if="fieldRequired(field)" class="text-destructive">*</span>
|
||||||
</Label>
|
</Label>
|
||||||
<div :class="isConnectionDialogLayout ? 'col-span-3 min-w-0 space-y-1.5' : ''">
|
<div :class="isConnectionDialogLayout ? 'col-span-3 min-w-0 space-y-1.5' : ''">
|
||||||
<Input v-if="field.type === 'text' || field.type === 'number'" :id="fieldId(field)" :type="field.type === 'number' ? 'number' : 'text'" :model-value="fieldValue(field) as string | number | undefined" :placeholder="field.placeholder" @update:model-value="updateTextField(field, $event)" />
|
<template v-if="field.type === 'text' || field.type === 'number'">
|
||||||
|
<Select v-if="field.type === 'text' && selectOptionsFor(field)" :model-value="String(fieldValue(field) ?? '')" @update:model-value="updateSelectField(field, $event)">
|
||||||
|
<SelectTrigger :id="fieldId(field)" :class="isConnectionDialogLayout ? 'h-9' : 'h-8 text-xs'">
|
||||||
|
<SelectValue :placeholder="field.placeholder" />
|
||||||
|
</SelectTrigger>
|
||||||
|
<SelectContent>
|
||||||
|
<SelectItem v-for="option in selectOptionsFor(field)!" :key="String(option.value)" :value="String(option.value)">
|
||||||
|
{{ option.label }}
|
||||||
|
</SelectItem>
|
||||||
|
</SelectContent>
|
||||||
|
</Select>
|
||||||
|
<div v-else-if="isLocalSshKeyField(field)" class="flex items-center gap-1.5">
|
||||||
|
<Input :id="fieldId(field)" type="text" :model-value="fieldValue(field) as string | number | undefined" :placeholder="field.placeholder" class="min-w-0 flex-1" @update:model-value="updateTextField(field, $event)" />
|
||||||
|
<select
|
||||||
|
class="h-9 w-40 shrink-0 rounded-md border border-input bg-transparent px-2 text-xs outline-none transition-colors focus-visible:border-ring focus-visible:ring-3 focus-visible:ring-ring/50 disabled:cursor-not-allowed disabled:opacity-50"
|
||||||
|
:disabled="localSshKeys.length === 0"
|
||||||
|
:title="t('connection.pluginSshKeyPickerPlaceholder')"
|
||||||
|
:aria-label="t('connection.pluginSshKeyPickerPlaceholder')"
|
||||||
|
@change="applyLocalSshKey(field, $event)"
|
||||||
|
>
|
||||||
|
<option value="" disabled selected>{{ localSshKeys.length ? t("connection.pluginSshKeyPickerPlaceholder") : t("connection.pluginSshKeyPickerEmpty") }}</option>
|
||||||
|
<option v-for="key in localSshKeys" :key="key.path" :value="key.path" :title="key.path">{{ localSshKeyLabel(key) }}</option>
|
||||||
|
</select>
|
||||||
|
</div>
|
||||||
|
<Input v-else :id="fieldId(field)" :type="field.type === 'number' ? 'number' : 'text'" :model-value="fieldValue(field) as string | number | undefined" :placeholder="field.placeholder" @update:model-value="updateTextField(field, $event)" />
|
||||||
|
</template>
|
||||||
<PasswordInput v-else-if="field.type === 'password'" :id="fieldId(field)" :model-value="String(fieldValue(field) ?? '')" :placeholder="field.placeholder" @update:model-value="updateField(field, $event)" />
|
<PasswordInput v-else-if="field.type === 'password'" :id="fieldId(field)" :model-value="String(fieldValue(field) ?? '')" :placeholder="field.placeholder" @update:model-value="updateField(field, $event)" />
|
||||||
|
<PasswordTextarea v-else-if="field.type === 'textarea' && field.binding === 'secret'" :id="fieldId(field)" :model-value="String(fieldValue(field) ?? '')" :placeholder="field.placeholder" @update:model-value="updateField(field, $event)" />
|
||||||
<textarea
|
<textarea
|
||||||
v-else-if="field.type === 'textarea'"
|
v-else-if="field.type === 'textarea'"
|
||||||
:id="fieldId(field)"
|
:id="fieldId(field)"
|
||||||
@@ -98,12 +241,6 @@ function defaultValueFor(field: PluginFormField): PluginFormFieldValue {
|
|||||||
</SelectItem>
|
</SelectItem>
|
||||||
</SelectContent>
|
</SelectContent>
|
||||||
</Select>
|
</Select>
|
||||||
<div v-else-if="field.type === 'radio'" :id="fieldId(field)" class="flex min-h-9 flex-wrap items-center gap-x-4 gap-y-2" role="radiogroup" :aria-label="field.label">
|
|
||||||
<label v-for="option in field.options || []" :key="option.value" class="inline-flex cursor-pointer items-center gap-2 text-sm">
|
|
||||||
<input type="radio" :name="fieldId(field)" :value="option.value" :checked="String(fieldValue(field) ?? '') === option.value" class="size-4 accent-primary" @change="updateField(field, option.value)" />
|
|
||||||
<span>{{ option.label }}</span>
|
|
||||||
</label>
|
|
||||||
</div>
|
|
||||||
<div v-else-if="field.type === 'boolean'" class="flex h-9 items-center">
|
<div v-else-if="field.type === 'boolean'" class="flex h-9 items-center">
|
||||||
<Switch :id="fieldId(field)" :model-value="Boolean(fieldValue(field))" size="sm" @update:model-value="updateBooleanField(field, $event)" />
|
<Switch :id="fieldId(field)" :model-value="Boolean(fieldValue(field))" size="sm" @update:model-value="updateBooleanField(field, $event)" />
|
||||||
</div>
|
</div>
|
||||||
|
|||||||
@@ -25,10 +25,14 @@ const emit = defineEmits<{
|
|||||||
}>();
|
}>();
|
||||||
|
|
||||||
const { t, locale: appLocale } = useI18n();
|
const { t, locale: appLocale } = useI18n();
|
||||||
const { isDark, activeCustomUiColors } = useTheme();
|
const { isDark, themeRevision } = useTheme();
|
||||||
const iframe = ref<HTMLIFrameElement>();
|
const iframe = ref<HTMLIFrameElement>();
|
||||||
const source = ref("");
|
const source = ref("");
|
||||||
const loading = ref(true);
|
const loading = ref(true);
|
||||||
|
// Stays false until the iframe's load event: WKWebView paints a white canvas
|
||||||
|
// for a freshly inserted iframe before the sandbox document's first styled
|
||||||
|
// frame, so the themed overlay must keep covering the frame area until then.
|
||||||
|
const frameReady = ref(false);
|
||||||
const error = ref("");
|
const error = ref("");
|
||||||
let bridge: PluginHostBridge | undefined;
|
let bridge: PluginHostBridge | undefined;
|
||||||
let unsubscribeEvents: (() => void) | undefined;
|
let unsubscribeEvents: (() => void) | undefined;
|
||||||
@@ -116,6 +120,7 @@ async function loadWorkbench() {
|
|||||||
const generation = ++loadGeneration;
|
const generation = ++loadGeneration;
|
||||||
bridge = undefined;
|
bridge = undefined;
|
||||||
loading.value = true;
|
loading.value = true;
|
||||||
|
frameReady.value = false;
|
||||||
error.value = "";
|
error.value = "";
|
||||||
try {
|
try {
|
||||||
if (!props.plugin.compatibility.compatible) throw new Error((props.plugin.compatibility.errors || []).join("; ") || t("pluginPlatform.pluginIncompatible"));
|
if (!props.plugin.compatibility.compatible) throw new Error((props.plugin.compatibility.errors || []).join("; ") || t("pluginPlatform.pluginIncompatible"));
|
||||||
@@ -132,7 +137,8 @@ async function loadWorkbench() {
|
|||||||
if (disposed || generation !== loadGeneration) return;
|
if (disposed || generation !== loadGeneration) return;
|
||||||
error.value = cause instanceof Error ? cause.message : String(cause);
|
error.value = cause instanceof Error ? cause.message : String(cause);
|
||||||
emit("error", error.value);
|
emit("error", error.value);
|
||||||
loading.value = false;
|
} finally {
|
||||||
|
if (!disposed && generation === loadGeneration) loading.value = false;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -141,9 +147,18 @@ function onMessage(event: MessageEvent) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
function onFrameLoad() {
|
function onFrameLoad() {
|
||||||
|
// The load event can precede the webview's first actual paint (notably on
|
||||||
|
// WKWebView); reveal after two animation frames, with a timer fallback
|
||||||
|
// because rAF stalls in occluded/background webviews. Guarded by generation
|
||||||
|
// so a stale callback from a rebuilt iframe can't lift the new overlay.
|
||||||
|
const generation = loadGeneration;
|
||||||
|
const reveal = () => {
|
||||||
|
if (!disposed && generation === loadGeneration) frameReady.value = true;
|
||||||
|
};
|
||||||
|
requestAnimationFrame(() => requestAnimationFrame(reveal));
|
||||||
|
setTimeout(reveal, 400);
|
||||||
bridge?.sendInit();
|
bridge?.sendInit();
|
||||||
emit("ready");
|
emit("ready");
|
||||||
loading.value = false;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
onMounted(async () => {
|
onMounted(async () => {
|
||||||
@@ -172,7 +187,10 @@ watch(
|
|||||||
{ deep: true },
|
{ deep: true },
|
||||||
);
|
);
|
||||||
watch(appLocale, (locale) => bridge?.updateLocale(locale));
|
watch(appLocale, (locale) => bridge?.updateLocale(locale));
|
||||||
watch([isDark, activeCustomUiColors], () => bridge?.updateTheme(currentBridgeTheme()), { deep: true });
|
// Keyed on the theme revision (bumped by applyTheme) so every theme change
|
||||||
|
// path — dark/light, palette switch, custom colors — re-pushes the resolved
|
||||||
|
// tokens; watching isDark/custom colors alone misses palette-only switches.
|
||||||
|
watch(themeRevision, () => bridge?.updateTheme(currentBridgeTheme()));
|
||||||
|
|
||||||
onBeforeUnmount(() => {
|
onBeforeUnmount(() => {
|
||||||
disposed = true;
|
disposed = true;
|
||||||
@@ -185,14 +203,25 @@ onBeforeUnmount(() => {
|
|||||||
|
|
||||||
<template>
|
<template>
|
||||||
<div class="relative flex size-full min-h-40 overflow-hidden bg-background">
|
<div class="relative flex size-full min-h-40 overflow-hidden bg-background">
|
||||||
<div v-if="error" class="m-auto flex max-w-lg items-start gap-3 rounded-lg border border-destructive/40 bg-destructive/5 p-4 text-sm text-destructive">
|
<div v-if="loading" class="absolute inset-0 z-10 flex items-center justify-center bg-background text-sm text-muted-foreground">
|
||||||
<AlertTriangle class="mt-0.5 size-4 shrink-0" />
|
|
||||||
<span>{{ error }}</span>
|
|
||||||
</div>
|
|
||||||
<iframe v-else-if="source" ref="iframe" :title="title" :srcdoc="source" sandbox="allow-scripts" referrerpolicy="no-referrer" class="size-full border-0 bg-transparent" @load="onFrameLoad" />
|
|
||||||
<div v-if="loading && !error" class="absolute inset-0 z-10 flex items-center justify-center bg-background/80 text-sm text-muted-foreground backdrop-blur-sm">
|
|
||||||
<Loader2 class="mr-2 size-4 animate-spin" />
|
<Loader2 class="mr-2 size-4 animate-spin" />
|
||||||
{{ t("pluginPlatform.loadingTitle", { title }) }}
|
{{ t("pluginPlatform.loadingTitle", { title }) }}
|
||||||
</div>
|
</div>
|
||||||
|
<div v-else-if="error" class="m-auto flex max-w-lg items-start gap-3 rounded-lg border border-destructive/40 bg-destructive/5 p-4 text-sm text-destructive">
|
||||||
|
<AlertTriangle class="mt-0.5 size-4 shrink-0" />
|
||||||
|
<span>{{ error }}</span>
|
||||||
|
</div>
|
||||||
|
<template v-else>
|
||||||
|
<iframe ref="iframe" :title="title" :srcdoc="source" sandbox="allow-scripts" referrerpolicy="no-referrer" class="size-full border-0 bg-transparent" @load="onFrameLoad" />
|
||||||
|
<!-- Cover until the frame has actually painted: the iframe stays mounted
|
||||||
|
underneath so its load event can fire (v-else on the overlay would
|
||||||
|
deadlock), it just isn't visible yet. Fully opaque so the covered
|
||||||
|
phase is visually identical to the host background, and faded out
|
||||||
|
instead of removed so the reveal is never a hard swap. -->
|
||||||
|
<div class="absolute inset-0 z-10 flex items-center justify-center bg-background text-sm text-muted-foreground transition-opacity duration-150 ease-out" :class="frameReady ? 'pointer-events-none opacity-0' : 'opacity-100'">
|
||||||
|
<Loader2 class="mr-2 size-4 animate-spin" />
|
||||||
|
{{ t("pluginPlatform.loadingTitle", { title }) }}
|
||||||
|
</div>
|
||||||
|
</template>
|
||||||
</div>
|
</div>
|
||||||
</template>
|
</template>
|
||||||
@@ -15,7 +15,7 @@ vi.mock("@/lib/backend/tauriRuntime", () => ({ isTauriRuntime: () => false }));
|
|||||||
vi.mock("@/composables/useToast", () => ({ useToast: () => ({ toast: vi.fn() }) }));
|
vi.mock("@/composables/useToast", () => ({ useToast: () => ({ toast: vi.fn() }) }));
|
||||||
|
|
||||||
vi.mock("@/components/ui/dialog", async () => {
|
vi.mock("@/components/ui/dialog", async () => {
|
||||||
const { defineComponent, h } = await import("vue");
|
const { defineComponent, h, Teleport } = await import("vue");
|
||||||
const passthrough = defineComponent({
|
const passthrough = defineComponent({
|
||||||
setup(_props, { slots }) {
|
setup(_props, { slots }) {
|
||||||
return () => h("div", slots.default?.());
|
return () => h("div", slots.default?.());
|
||||||
@@ -27,9 +27,20 @@ vi.mock("@/components/ui/dialog", async () => {
|
|||||||
return () => (props.open ? h("div", slots.default?.()) : null);
|
return () => (props.open ? h("div", slots.default?.()) : null);
|
||||||
},
|
},
|
||||||
});
|
});
|
||||||
|
const dialogContent = defineComponent({
|
||||||
|
props: {
|
||||||
|
class: [String, Array, Object],
|
||||||
|
overlayClass: [String, Array, Object],
|
||||||
|
portalClass: [String, Array, Object],
|
||||||
|
},
|
||||||
|
inheritAttrs: false,
|
||||||
|
setup(props, { slots }) {
|
||||||
|
return () => h(Teleport, { to: "body" }, [h("div", { class: ["dialog-overlay", "z-50", props.overlayClass] }), h("div", { class: ["dialog-positioner", "z-50", props.portalClass] }, [h("div", { class: ["dialog-content", props.class] }, slots.default?.())])]);
|
||||||
|
},
|
||||||
|
});
|
||||||
return {
|
return {
|
||||||
Dialog: dialog,
|
Dialog: dialog,
|
||||||
DialogContent: passthrough,
|
DialogContent: dialogContent,
|
||||||
DialogDescription: passthrough,
|
DialogDescription: passthrough,
|
||||||
DialogFooter: passthrough,
|
DialogFooter: passthrough,
|
||||||
DialogHeader: passthrough,
|
DialogHeader: passthrough,
|
||||||
@@ -133,6 +144,51 @@ describe("SshHostKeyPromptDialog web bridge", () => {
|
|||||||
expect(dialogSource).toContain('portal-class="z-[200]"');
|
expect(dialogSource).toContain('portal-class="z-[200]"');
|
||||||
});
|
});
|
||||||
|
|
||||||
|
it("keeps the prompt above a later body-mounted connection dialog and answerable", async () => {
|
||||||
|
await mountDialog();
|
||||||
|
|
||||||
|
const eventSource = MockEventSource.instances[0];
|
||||||
|
eventSource?.emit({
|
||||||
|
type: "prompt",
|
||||||
|
request: {
|
||||||
|
id: "prompt-layered",
|
||||||
|
kind: "HostKeyVerify",
|
||||||
|
host: "layered.example.test",
|
||||||
|
port: 22,
|
||||||
|
key_type: "ssh-ed25519",
|
||||||
|
fingerprint: "SHA256:layered",
|
||||||
|
},
|
||||||
|
});
|
||||||
|
await nextTick();
|
||||||
|
|
||||||
|
// Simulate ConnectionDialog opening after the global prompt: its portal is
|
||||||
|
// appended later and remains on the shared default z-50 layer.
|
||||||
|
const connectionPositioner = document.createElement("div");
|
||||||
|
connectionPositioner.className = "dialog-positioner z-50";
|
||||||
|
connectionPositioner.textContent = "New connection";
|
||||||
|
document.body.append(connectionPositioner);
|
||||||
|
|
||||||
|
const promptPositioner = document.body.querySelector<HTMLElement>(".dialog-positioner.z-\\[200\\]");
|
||||||
|
const promptOverlay = document.body.querySelector<HTMLElement>(".dialog-overlay.z-\\[200\\]");
|
||||||
|
expect(promptPositioner).not.toBeNull();
|
||||||
|
expect(promptOverlay).not.toBeNull();
|
||||||
|
expect(connectionPositioner.classList.contains("z-50")).toBe(true);
|
||||||
|
expect(promptPositioner?.classList.contains("z-[200]")).toBe(true);
|
||||||
|
expect(promptOverlay?.classList.contains("z-[200]")).toBe(true);
|
||||||
|
expect(document.body.textContent).toContain("layered.example.test:22");
|
||||||
|
|
||||||
|
const buttons = document.body.querySelectorAll<HTMLButtonElement>("button");
|
||||||
|
buttons.item(buttons.length - 1).click();
|
||||||
|
await vi.waitFor(() => {
|
||||||
|
expect(resolveSshPromptMock).toHaveBeenCalledWith({
|
||||||
|
id: "prompt-layered",
|
||||||
|
action: "accept",
|
||||||
|
remember: true,
|
||||||
|
secret: undefined,
|
||||||
|
});
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
it("shows an SSE host-key prompt and posts the user's acceptance", async () => {
|
it("shows an SSE host-key prompt and posts the user's acceptance", async () => {
|
||||||
await mountDialog();
|
await mountDialog();
|
||||||
|
|
||||||
|
|||||||
@@ -0,0 +1,35 @@
|
|||||||
|
<script setup lang="ts">
|
||||||
|
import { computed, ref } from "vue";
|
||||||
|
import { useI18n } from "vue-i18n";
|
||||||
|
import { Eye, EyeOff } from "@lucide/vue";
|
||||||
|
|
||||||
|
defineOptions({ inheritAttrs: false });
|
||||||
|
const model = defineModel<string>();
|
||||||
|
const visible = ref(false);
|
||||||
|
const { t } = useI18n();
|
||||||
|
const toggleLabel = computed(() => t(visible.value ? "common.hidePassword" : "common.showPassword"));
|
||||||
|
</script>
|
||||||
|
|
||||||
|
<template>
|
||||||
|
<div class="relative">
|
||||||
|
<textarea
|
||||||
|
v-model="model"
|
||||||
|
v-bind="$attrs"
|
||||||
|
:class="{ 'secret-masked': !visible }"
|
||||||
|
class="min-h-20 w-full resize-y rounded-md border border-input bg-transparent py-2 pl-2.5 pr-9 text-sm outline-none transition-colors placeholder:text-muted-foreground focus-visible:border-ring focus-visible:ring-3 focus-visible:ring-ring/50"
|
||||||
|
autocomplete="off"
|
||||||
|
autocapitalize="off"
|
||||||
|
:spellcheck="false"
|
||||||
|
/>
|
||||||
|
<button type="button" class="absolute right-2 top-2.5 text-muted-foreground hover:text-foreground" :aria-label="toggleLabel" :title="toggleLabel" :aria-pressed="visible" @click="visible = !visible">
|
||||||
|
<Eye v-if="!visible" class="size-3.5" />
|
||||||
|
<EyeOff v-else class="size-3.5" />
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
</template>
|
||||||
|
|
||||||
|
<style scoped>
|
||||||
|
.secret-masked {
|
||||||
|
-webkit-text-security: disc;
|
||||||
|
}
|
||||||
|
</style>
|
||||||
@@ -47,6 +47,41 @@ export function useTauriEvents(deps: {
|
|||||||
}
|
}
|
||||||
}).then((unlisten) => unlistenHandles.push(unlisten));
|
}).then((unlisten) => unlistenHandles.push(unlisten));
|
||||||
|
|
||||||
|
listen<{ connection_id: string }>("mcp-open-connection-workbench", async (event) => {
|
||||||
|
try {
|
||||||
|
const { connection_id } = event.payload;
|
||||||
|
if (!connectionStore.connections.length) await connectionStore.initFromDisk();
|
||||||
|
const config = connectionStore.getConfig(connection_id);
|
||||||
|
if (!config) return;
|
||||||
|
connectionStore.activeConnectionId = connection_id;
|
||||||
|
// Dedup + tab switch happen inside the store; also ensures the
|
||||||
|
// plugin workbench session (and its PTY) exists before returning.
|
||||||
|
// Deliberately no window focus here: agent-terminal calls open
|
||||||
|
// the tab so the command lands in a real terminal, but stealing
|
||||||
|
// the OS focus interrupted whatever the user was doing.
|
||||||
|
await queryStore.openPluginConnection(connection_id);
|
||||||
|
} catch (e) {
|
||||||
|
console.error("[DBX] mcp-open-connection-workbench error:", e);
|
||||||
|
}
|
||||||
|
}).then((unlisten) => unlistenHandles.push(unlisten));
|
||||||
|
|
||||||
|
// Plugins report live transport state through plugin events; when an
|
||||||
|
// SSH session dies, flip the sidebar entry offline so the tree stops
|
||||||
|
// showing a connection that no longer exists.
|
||||||
|
listen<{ method: string; params: { state?: string; connectionId?: string } }>("dbx-plugin-event", async (event) => {
|
||||||
|
try {
|
||||||
|
const payload = event.payload ?? ({} as typeof event.payload);
|
||||||
|
if (payload.method !== "ssh/session/state" || payload.params?.state !== "disconnected") return;
|
||||||
|
const connectionId = payload.params?.connectionId;
|
||||||
|
if (!connectionId) return;
|
||||||
|
if (!connectionStore.connections.length) await connectionStore.initFromDisk();
|
||||||
|
if (!connectionStore.getConfig(connectionId)) return;
|
||||||
|
connectionStore.markConnectionOffline(connectionId);
|
||||||
|
} catch (e) {
|
||||||
|
console.error("[DBX] dbx-plugin-event (ssh/session/state) error:", e);
|
||||||
|
}
|
||||||
|
}).then((unlisten) => unlistenHandles.push(unlisten));
|
||||||
|
|
||||||
listen("mcp-reload-connections", async () => {
|
listen("mcp-reload-connections", async () => {
|
||||||
try {
|
try {
|
||||||
await connectionStore.initFromDisk();
|
await connectionStore.initFromDisk();
|
||||||
|
|||||||
@@ -57,6 +57,11 @@ if (savedThemeMode && savedThemeMode !== themeMode.value) safeLocalStorageSet(AP
|
|||||||
if (savedCornerStyle && savedCornerStyle !== cornerStyle.value) safeLocalStorageSet(APP_CORNER_STYLE_STORAGE_KEY, cornerStyle.value);
|
if (savedCornerStyle && savedCornerStyle !== cornerStyle.value) safeLocalStorageSet(APP_CORNER_STYLE_STORAGE_KEY, cornerStyle.value);
|
||||||
const systemPrefersDark = ref(readSystemPrefersDark());
|
const systemPrefersDark = ref(readSystemPrefersDark());
|
||||||
const isDark = computed(() => resolveAppThemeAppearance(themeMode.value, systemPrefersDark.value) === "dark");
|
const isDark = computed(() => resolveAppThemeAppearance(themeMode.value, systemPrefersDark.value) === "dark");
|
||||||
|
// Bumped at the end of every applyTheme(): theme changes are DOM mutations
|
||||||
|
// (classes / inline vars), so watchers keyed on reactive sources like isDark
|
||||||
|
// miss palette switches and custom-color edits. Consumers that mirror the
|
||||||
|
// resolved token set (plugin iframe bridge) watch this revision instead.
|
||||||
|
const themeRevision = ref(0);
|
||||||
|
|
||||||
let mediaQuery: MediaQueryList | null = null;
|
let mediaQuery: MediaQueryList | null = null;
|
||||||
let isListeningForSystemTheme = false;
|
let isListeningForSystemTheme = false;
|
||||||
@@ -103,6 +108,7 @@ function applyTheme() {
|
|||||||
|
|
||||||
// force reflow so the class toggle takes effect before re-enabling transitions
|
// force reflow so the class toggle takes effect before re-enabling transitions
|
||||||
doc.offsetHeight; // eslint-disable-line @typescript-eslint/no-unused-expressions
|
doc.offsetHeight; // eslint-disable-line @typescript-eslint/no-unused-expressions
|
||||||
|
themeRevision.value += 1;
|
||||||
requestAnimationFrame(() => doc.classList.remove("disable-transitions"));
|
requestAnimationFrame(() => doc.classList.remove("disable-transitions"));
|
||||||
if (!isTauriRuntime()) return;
|
if (!isTauriRuntime()) return;
|
||||||
|
|
||||||
@@ -206,5 +212,5 @@ export function useTheme() {
|
|||||||
setThemeMode(isDark.value ? "light" : "dark");
|
setThemeMode(isDark.value ? "light" : "dark");
|
||||||
}
|
}
|
||||||
|
|
||||||
return { isDark, themeMode, themePalette, customUiColors, customUiColorsDark, activeCustomUiColors, cornerStyle, applyTheme, setThemeMode, setThemePalette, previewThemePalette, clearThemePalettePreview, setCustomUiColors, resetCustomUiColors, setCornerStyle, toggleTheme };
|
return { isDark, themeMode, themePalette, customUiColors, customUiColorsDark, activeCustomUiColors, themeRevision, cornerStyle, applyTheme, setThemeMode, setThemePalette, previewThemePalette, clearThemePalettePreview, setCustomUiColors, resetCustomUiColors, setCornerStyle, toggleTheme };
|
||||||
}
|
}
|
||||||
@@ -1121,6 +1121,9 @@ export default {
|
|||||||
databaseCategoryPlugins: "Plugins",
|
databaseCategoryPlugins: "Plugins",
|
||||||
pluginProviderUnavailable: "This plugin connection provider is unavailable. Reinstall or enable the plugin, then try again.",
|
pluginProviderUnavailable: "This plugin connection provider is unavailable. Reinstall or enable the plugin, then try again.",
|
||||||
pluginRequiredField: "{field} is required",
|
pluginRequiredField: "{field} is required",
|
||||||
|
pluginSshKeyPickerPlaceholder: "Pick local SSH key…",
|
||||||
|
pluginSshKeyPickerEmpty: "No local SSH keys found",
|
||||||
|
pluginSshKeyEncrypted: "encrypted",
|
||||||
jdbcConnection: "JDBC connection",
|
jdbcConnection: "JDBC connection",
|
||||||
iconView: "Icon view",
|
iconView: "Icon view",
|
||||||
listView: "List view",
|
listView: "List view",
|
||||||
|
|||||||
@@ -1390,6 +1390,9 @@ export default withEnglishFallback({
|
|||||||
doltShowSystemTables: "Mostrar tablas integradas de Dolt",
|
doltShowSystemTables: "Mostrar tablas integradas de Dolt",
|
||||||
doltShowSystemTablesHint: "Muestra las tablas integradas de control de versiones de Dolt en la lista de tablas de la conexión actual.",
|
doltShowSystemTablesHint: "Muestra las tablas integradas de control de versiones de Dolt en la lista de tablas de la conexión actual.",
|
||||||
clientCertHint: "Cuando se requiere mTLS, el certificado de cliente y la clave privada deben completarse juntos.",
|
clientCertHint: "Cuando se requiere mTLS, el certificado de cliente y la clave privada deben completarse juntos.",
|
||||||
|
pluginSshKeyPickerPlaceholder: "Seleccionar clave SSH local…",
|
||||||
|
pluginSshKeyPickerEmpty: "No se encontraron claves",
|
||||||
|
pluginSshKeyEncrypted: "Cifrado",
|
||||||
},
|
},
|
||||||
editor: {
|
editor: {
|
||||||
duckdbDraining: "La consulta anterior de DuckDB aún se está deteniendo. Vuelva a intentarlo en breve.",
|
duckdbDraining: "La consulta anterior de DuckDB aún se está deteniendo. Vuelva a intentarlo en breve.",
|
||||||
|
|||||||
@@ -1388,6 +1388,9 @@ export default withEnglishFallback({
|
|||||||
doltShowSystemTables: "Mostra le tabelle integrate di Dolt",
|
doltShowSystemTables: "Mostra le tabelle integrate di Dolt",
|
||||||
doltShowSystemTablesHint: "Mostra le tabelle di controllo versione integrate di Dolt nell'elenco delle tabelle della connessione corrente.",
|
doltShowSystemTablesHint: "Mostra le tabelle di controllo versione integrate di Dolt nell'elenco delle tabelle della connessione corrente.",
|
||||||
clientCertHint: "Quando è richiesto mTLS, il certificato client e la chiave privata devono essere inseriti insieme.",
|
clientCertHint: "Quando è richiesto mTLS, il certificato client e la chiave privata devono essere inseriti insieme.",
|
||||||
|
pluginSshKeyPickerPlaceholder: "Seleziona chiave SSH locale…",
|
||||||
|
pluginSshKeyPickerEmpty: "Nessuna chiave trovata",
|
||||||
|
pluginSshKeyEncrypted: "Crittografata",
|
||||||
},
|
},
|
||||||
editor: {
|
editor: {
|
||||||
duckdbDraining: "La query DuckDB precedente è ancora in fase di arresto. Riprova a breve.",
|
duckdbDraining: "La query DuckDB precedente è ancora in fase di arresto. Riprova a breve.",
|
||||||
|
|||||||
@@ -1409,6 +1409,9 @@ export default withEnglishFallback({
|
|||||||
doltShowSystemTables: "Dolt 組み込みテーブルを表示",
|
doltShowSystemTables: "Dolt 組み込みテーブルを表示",
|
||||||
doltShowSystemTablesHint: "現在の接続のテーブルリストに Dolt 組み込みのバージョン管理テーブルを表示します。",
|
doltShowSystemTablesHint: "現在の接続のテーブルリストに Dolt 組み込みのバージョン管理テーブルを表示します。",
|
||||||
clientCertHint: "mTLS が要求される場合、クライアント証明書と秘密鍵は一緒に入力する必要があります。",
|
clientCertHint: "mTLS が要求される場合、クライアント証明書と秘密鍵は一緒に入力する必要があります。",
|
||||||
|
pluginSshKeyPickerPlaceholder: "ローカルの SSH キーを選択…",
|
||||||
|
pluginSshKeyPickerEmpty: "キーが見つかりません",
|
||||||
|
pluginSshKeyEncrypted: "暗号化済み",
|
||||||
},
|
},
|
||||||
editor: {
|
editor: {
|
||||||
duckdbDraining: "前回の DuckDB クエリはまだ停止処理中です。しばらくしてから再試行してください。",
|
duckdbDraining: "前回の DuckDB クエリはまだ停止処理中です。しばらくしてから再試行してください。",
|
||||||
|
|||||||
@@ -1307,6 +1307,9 @@ export default withEnglishFallback({
|
|||||||
databaseCategoryPlugins: "플러그인",
|
databaseCategoryPlugins: "플러그인",
|
||||||
pluginProviderUnavailable: "이 플러그인 연결 제공자를 사용할 수 없습니다. 플러그인을 다시 설치하거나 활성화한 후 다시 시도하세요.",
|
pluginProviderUnavailable: "이 플러그인 연결 제공자를 사용할 수 없습니다. 플러그인을 다시 설치하거나 활성화한 후 다시 시도하세요.",
|
||||||
pluginRequiredField: "{field}을(를) 입력하세요.",
|
pluginRequiredField: "{field}을(를) 입력하세요.",
|
||||||
|
pluginSshKeyPickerPlaceholder: "로컬 SSH 키 선택…",
|
||||||
|
pluginSshKeyPickerEmpty: "키를 찾을 수 없음",
|
||||||
|
pluginSshKeyEncrypted: "암호화됨",
|
||||||
},
|
},
|
||||||
editor: {
|
editor: {
|
||||||
duckdbDraining: "이전 DuckDB 쿼리가 아직 중지 중입니다. 잠시 후 다시 시도해 주세요.",
|
duckdbDraining: "이전 DuckDB 쿼리가 아직 중지 중입니다. 잠시 후 다시 시도해 주세요.",
|
||||||
|
|||||||
@@ -1389,6 +1389,9 @@ export default withEnglishFallback({
|
|||||||
doltShowSystemTables: "Exibir tabelas internas do Dolt",
|
doltShowSystemTables: "Exibir tabelas internas do Dolt",
|
||||||
doltShowSystemTablesHint: "Exibir as tabelas de controle de versão internas do Dolt na lista de tabelas da conexão atual.",
|
doltShowSystemTablesHint: "Exibir as tabelas de controle de versão internas do Dolt na lista de tabelas da conexão atual.",
|
||||||
clientCertHint: "Quando o mTLS for exigido, o certificado do cliente e a chave privada devem ser preenchidos juntos.",
|
clientCertHint: "Quando o mTLS for exigido, o certificado do cliente e a chave privada devem ser preenchidos juntos.",
|
||||||
|
pluginSshKeyPickerPlaceholder: "Selecionar chave SSH local…",
|
||||||
|
pluginSshKeyPickerEmpty: "Nenhuma chave encontrada",
|
||||||
|
pluginSshKeyEncrypted: "Criptografada",
|
||||||
},
|
},
|
||||||
editor: {
|
editor: {
|
||||||
duckdbDraining: "A consulta anterior do DuckDB ainda está sendo interrompida. Tente novamente em breve.",
|
duckdbDraining: "A consulta anterior do DuckDB ainda está sendo interrompida. Tente novamente em breve.",
|
||||||
|
|||||||
@@ -1036,6 +1036,9 @@ export default withEnglishFallback({
|
|||||||
databaseCategoryPlugins: "插件",
|
databaseCategoryPlugins: "插件",
|
||||||
pluginProviderUnavailable: "此插件连接提供者不可用,请重新安装或启用插件后再试。",
|
pluginProviderUnavailable: "此插件连接提供者不可用,请重新安装或启用插件后再试。",
|
||||||
pluginRequiredField: "请填写{field}",
|
pluginRequiredField: "请填写{field}",
|
||||||
|
pluginSshKeyPickerPlaceholder: "选择本机 SSH 密钥…",
|
||||||
|
pluginSshKeyPickerEmpty: "未发现密钥",
|
||||||
|
pluginSshKeyEncrypted: "已加密",
|
||||||
jdbcConnection: "JDBC 连接",
|
jdbcConnection: "JDBC 连接",
|
||||||
iconView: "图标视图",
|
iconView: "图标视图",
|
||||||
listView: "列表视图",
|
listView: "列表视图",
|
||||||
|
|||||||
@@ -920,6 +920,9 @@ export default withEnglishFallback({
|
|||||||
databaseCategoryPlugins: "外掛",
|
databaseCategoryPlugins: "外掛",
|
||||||
pluginProviderUnavailable: "此外掛連線提供者不可用,請重新安裝或啟用外掛後再試。",
|
pluginProviderUnavailable: "此外掛連線提供者不可用,請重新安裝或啟用外掛後再試。",
|
||||||
pluginRequiredField: "請填寫{field}",
|
pluginRequiredField: "請填寫{field}",
|
||||||
|
pluginSshKeyPickerPlaceholder: "選擇本機 SSH 金鑰…",
|
||||||
|
pluginSshKeyPickerEmpty: "未發現金鑰",
|
||||||
|
pluginSshKeyEncrypted: "已加密",
|
||||||
jdbcConnection: "JDBC 連線",
|
jdbcConnection: "JDBC 連線",
|
||||||
iconView: "圖示檢視",
|
iconView: "圖示檢視",
|
||||||
listView: "清單檢視",
|
listView: "清單檢視",
|
||||||
|
|||||||
+5
-2
@@ -33,9 +33,12 @@ describe("ConnectionDialog service deep-link hydration", () => {
|
|||||||
});
|
});
|
||||||
|
|
||||||
it("keeps failed one-time connections available for error inspection and retry", () => {
|
it("keeps failed one-time connections available for error inspection and retry", () => {
|
||||||
const saveStart = source.indexOf("async function save(");
|
// The save path delegates one-time connects to startSavedConnection,
|
||||||
|
// which owns the connectFailed emission for failed retries.
|
||||||
|
const start = source.indexOf("function startSavedConnection");
|
||||||
|
const saveStart = source.indexOf("async function save(", start);
|
||||||
const saveEnd = source.indexOf('const dialogTitle = ref("")', saveStart);
|
const saveEnd = source.indexOf('const dialogTitle = ref("")', saveStart);
|
||||||
const saveBody = source.slice(saveStart, saveEnd);
|
const saveBody = source.slice(start, saveEnd);
|
||||||
|
|
||||||
expect(saveBody).not.toContain("store.removeConnection(config.id)");
|
expect(saveBody).not.toContain("store.removeConnection(config.id)");
|
||||||
expect(saveBody).toContain('emit("connectFailed"');
|
expect(saveBody).toContain('emit("connectFailed"');
|
||||||
|
|||||||
+2
-1
@@ -60,7 +60,7 @@ function profileSwitchHarness(selectedProfile: string, editing = false) {
|
|||||||
const javascript = ts.transpileModule(functionSource("onDbTypeChange"), {
|
const javascript = ts.transpileModule(functionSource("onDbTypeChange"), {
|
||||||
compilerOptions: { module: ts.ModuleKind.None, target: ts.ScriptTarget.ES2022 },
|
compilerOptions: { module: ts.ModuleKind.None, target: ts.ScriptTarget.ES2022 },
|
||||||
}).outputText;
|
}).outputText;
|
||||||
const selectProfile = new Function("editingId", "selectedType", "resetForm", "dbCategoryForOption", "selectedDbCategory", "customDriverName", "applyProfile", "resetTestState", "resetVisibleSchemasState", `${javascript}\nreturn onDbTypeChange;`)(
|
const selectProfile = new Function("editingId", "selectedType", "resetForm", "dbCategoryForOption", "selectedDbCategory", "customDriverName", "applyProfile", "resetTestState", "resetVisibleSchemasState", "parsePluginConnectionProviderOptionValue", `${javascript}\nreturn onDbTypeChange;`)(
|
||||||
editingId,
|
editingId,
|
||||||
selectedType,
|
selectedType,
|
||||||
resetForm,
|
resetForm,
|
||||||
@@ -70,6 +70,7 @@ function profileSwitchHarness(selectedProfile: string, editing = false) {
|
|||||||
applyProfile,
|
applyProfile,
|
||||||
() => events.push("reset-test"),
|
() => events.push("reset-test"),
|
||||||
() => events.push("reset-schemas"),
|
() => events.push("reset-schemas"),
|
||||||
|
() => null,
|
||||||
) as (profile: string) => void;
|
) as (profile: string) => void;
|
||||||
|
|
||||||
return { customDriverName, events, form, selectProfile, selectedType };
|
return { customDriverName, events, form, selectProfile, selectedType };
|
||||||
|
|||||||
@@ -16,7 +16,9 @@ function selectedProfileHarness(selectedTypeValue: string, driverProfile: string
|
|||||||
const javascript = ts.transpileModule(declaration!.getText(), {
|
const javascript = ts.transpileModule(declaration!.getText(), {
|
||||||
compilerOptions: { module: ts.ModuleKind.None, target: ts.ScriptTarget.ES2022 },
|
compilerOptions: { module: ts.ModuleKind.None, target: ts.ScriptTarget.ES2022 },
|
||||||
}).outputText;
|
}).outputText;
|
||||||
const selectedProfile = new Function("driverProfiles", "selectedType", "form", `${javascript}\nreturn selectedProfile;`)(
|
// The merged dialog checks plugin providers before the profile table; the
|
||||||
|
// plugin branch is stubbed out so this harness pins the GBase profile path.
|
||||||
|
const selectedProfile = new Function("driverProfiles", "selectedType", "form", "parsePluginConnectionProviderOptionValue", "selectedPluginProvider", `${javascript}\nreturn selectedProfile;`)(
|
||||||
{
|
{
|
||||||
mysql: { label: "MySQL" },
|
mysql: { label: "MySQL" },
|
||||||
gbase: { label: "南大通用 GBase 8a" },
|
gbase: { label: "南大通用 GBase 8a" },
|
||||||
@@ -25,6 +27,8 @@ function selectedProfileHarness(selectedTypeValue: string, driverProfile: string
|
|||||||
},
|
},
|
||||||
{ value: selectedTypeValue },
|
{ value: selectedTypeValue },
|
||||||
{ value: { driver_profile: driverProfile } },
|
{ value: { driver_profile: driverProfile } },
|
||||||
|
() => null,
|
||||||
|
{ value: null },
|
||||||
) as () => { label: string };
|
) as () => { label: string };
|
||||||
return selectedProfile();
|
return selectedProfile();
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -3,7 +3,7 @@ import { describe, expect, it } from "vitest";
|
|||||||
|
|
||||||
const appSource = readFileSync(new URL("../../../App.vue", import.meta.url), "utf8");
|
const appSource = readFileSync(new URL("../../../App.vue", import.meta.url), "utf8");
|
||||||
const toolbarSource = readFileSync(new URL("../../../components/layout/AppToolbar.vue", import.meta.url), "utf8");
|
const toolbarSource = readFileSync(new URL("../../../components/layout/AppToolbar.vue", import.meta.url), "utf8");
|
||||||
const editorGroupTabBarSource = readFileSync(new URL("../../../components/layout/EditorGroupTabBar.vue", import.meta.url), "utf8");
|
const groupTabBarSource = readFileSync(new URL("../../../components/layout/EditorGroupTabBar.vue", import.meta.url), "utf8");
|
||||||
const driverStoreSource = readFileSync(new URL("../../../components/config/DriverStoreDialog.vue", import.meta.url), "utf8");
|
const driverStoreSource = readFileSync(new URL("../../../components/config/DriverStoreDialog.vue", import.meta.url), "utf8");
|
||||||
const appDialogsSource = readFileSync(new URL("../../../components/layout/AppDialogs.vue", import.meta.url), "utf8");
|
const appDialogsSource = readFileSync(new URL("../../../components/layout/AppDialogs.vue", import.meta.url), "utf8");
|
||||||
const connectionDialogSource = readFileSync(new URL("../../../components/connection/ConnectionDialog.vue", import.meta.url), "utf8");
|
const connectionDialogSource = readFileSync(new URL("../../../components/connection/ConnectionDialog.vue", import.meta.url), "utf8");
|
||||||
@@ -15,7 +15,10 @@ describe("plugin center integration", () => {
|
|||||||
expect(toolbarSource).toContain("emit('open-plugin-center')");
|
expect(toolbarSource).toContain("emit('open-plugin-center')");
|
||||||
expect(appSource).toContain('@open-plugin-center="openPluginCenterPage()"');
|
expect(appSource).toContain('@open-plugin-center="openPluginCenterPage()"');
|
||||||
expect(appSource).toContain("<PluginCenterPage");
|
expect(appSource).toContain("<PluginCenterPage");
|
||||||
expect(editorGroupTabBarSource).toContain("data-plugin-center-tab");
|
// The plugin center pill lives in the focused group's tab strip, like the
|
||||||
|
// settings and driver-store special pages.
|
||||||
|
expect(groupTabBarSource).toContain("data-plugin-center-tab");
|
||||||
|
expect(appSource).toContain(':plugin-center-open="pluginCenterTabOpen"');
|
||||||
});
|
});
|
||||||
|
|
||||||
it("keeps plugin management out of Driver Manager", () => {
|
it("keeps plugin management out of Driver Manager", () => {
|
||||||
|
|||||||
@@ -223,6 +223,8 @@ export function serializeOpenTabs(tabs: QueryTab[]): SavedOpenTab[] {
|
|||||||
: {}),
|
: {}),
|
||||||
...(tab.mode === "query" && tab.activeResultRunId !== undefined ? { activeResultRunId: tab.activeResultRunId } : {}),
|
...(tab.mode === "query" && tab.activeResultRunId !== undefined ? { activeResultRunId: tab.activeResultRunId } : {}),
|
||||||
...(tab.mode === "query" && typeof tab.resultAutoSave === "boolean" ? { resultAutoSave: tab.resultAutoSave } : {}),
|
...(tab.mode === "query" && typeof tab.resultAutoSave === "boolean" ? { resultAutoSave: tab.resultAutoSave } : {}),
|
||||||
|
...(tab.pluginWorkbench ? { pluginWorkbench: tab.pluginWorkbench } : {}),
|
||||||
|
...(tab.pluginFilesystem ? { pluginFilesystem: tab.pluginFilesystem } : {}),
|
||||||
...(tab.uiState ? { uiState: sanitizeTabUiState(tab.uiState) } : {}),
|
...(tab.uiState ? { uiState: sanitizeTabUiState(tab.uiState) } : {}),
|
||||||
...(tab.mode === "query" && tab.resultAutoSave ? { resultAutoSave: true } : {}),
|
...(tab.mode === "query" && tab.resultAutoSave ? { resultAutoSave: true } : {}),
|
||||||
}));
|
}));
|
||||||
|
|||||||
@@ -406,6 +406,7 @@ export const setAiGlobalCustomInstructions = forward("setAiGlobalCustomInstructi
|
|||||||
// System
|
// System
|
||||||
export const listSystemFonts = forward("listSystemFonts");
|
export const listSystemFonts = forward("listSystemFonts");
|
||||||
export const listSshConfigHosts = forward("listSshConfigHosts");
|
export const listSshConfigHosts = forward("listSshConfigHosts");
|
||||||
|
export const listLocalSshKeys = forward("listLocalSshKeys");
|
||||||
|
|
||||||
// SQL File Execution
|
// SQL File Execution
|
||||||
export const previewSqlFile = forward("previewSqlFile");
|
export const previewSqlFile = forward("previewSqlFile");
|
||||||
|
|||||||
@@ -46,6 +46,7 @@ import type {
|
|||||||
SavedSqlFolder,
|
SavedSqlFolder,
|
||||||
SavedSqlLibrary,
|
SavedSqlLibrary,
|
||||||
SshConfigHostEntry,
|
SshConfigHostEntry,
|
||||||
|
LocalSshKey,
|
||||||
TunnelProfile,
|
TunnelProfile,
|
||||||
} from "@/types/database";
|
} from "@/types/database";
|
||||||
import type { DetachedTabHandoff } from "@/lib/app/detachedTabHandoff";
|
import type { DetachedTabHandoff } from "@/lib/app/detachedTabHandoff";
|
||||||
@@ -531,6 +532,11 @@ export async function listSshConfigHosts(): Promise<SshConfigHostEntry[]> {
|
|||||||
return get("/api/ssh/config-hosts");
|
return get("/api/ssh/config-hosts");
|
||||||
}
|
}
|
||||||
|
|
||||||
|
export async function listLocalSshKeys(): Promise<LocalSshKey[]> {
|
||||||
|
console.warn("listLocalSshKeys: local SSH key discovery is not available in the web backend");
|
||||||
|
return [];
|
||||||
|
}
|
||||||
|
|
||||||
export async function listPlugins(): Promise<InstalledPlugin[]> {
|
export async function listPlugins(): Promise<InstalledPlugin[]> {
|
||||||
return get("/api/plugins");
|
return get("/api/plugins");
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -71,6 +71,7 @@ import type {
|
|||||||
SavedSqlFolder,
|
SavedSqlFolder,
|
||||||
SavedSqlLibrary,
|
SavedSqlLibrary,
|
||||||
SshConfigHostEntry,
|
SshConfigHostEntry,
|
||||||
|
LocalSshKey,
|
||||||
TunnelProfile,
|
TunnelProfile,
|
||||||
TransactionLog,
|
TransactionLog,
|
||||||
ExternalSqlFileVersion,
|
ExternalSqlFileVersion,
|
||||||
@@ -982,6 +983,10 @@ export async function listSshConfigHosts(): Promise<SshConfigHostEntry[]> {
|
|||||||
return invoke("list_ssh_config_hosts");
|
return invoke("list_ssh_config_hosts");
|
||||||
}
|
}
|
||||||
|
|
||||||
|
export async function listLocalSshKeys(): Promise<LocalSshKey[]> {
|
||||||
|
return invoke("list_local_ssh_keys");
|
||||||
|
}
|
||||||
|
|
||||||
export async function pendingOpenSqlFiles(): Promise<string[]> {
|
export async function pendingOpenSqlFiles(): Promise<string[]> {
|
||||||
return invoke("pending_open_sql_files");
|
return invoke("pending_open_sql_files");
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,73 @@
|
|||||||
|
import { describe, expect, it } from "vitest";
|
||||||
|
import type { PluginFormField } from "@/types/database";
|
||||||
|
import { connectionNeedsPasswordPrompt, pluginConnectionNeedsPasswordPrompt } from "@/lib/connection/connectionPassword";
|
||||||
|
|
||||||
|
/** Mirrors the io.dbx.ssh connection-provider password/authentication fields. */
|
||||||
|
const sshAuthFields: PluginFormField[] = [
|
||||||
|
{ key: "authentication", label: "Authentication", type: "select", binding: "config", default: "password", options: [] },
|
||||||
|
{
|
||||||
|
key: "password",
|
||||||
|
label: "Password",
|
||||||
|
type: "password",
|
||||||
|
binding: "password",
|
||||||
|
visible_when: { field: "authentication", one_of: ["password", "private-key-password"] },
|
||||||
|
required_when: { field: "authentication", one_of: ["password", "private-key-password"] },
|
||||||
|
},
|
||||||
|
];
|
||||||
|
|
||||||
|
describe("connectionNeedsPasswordPrompt", () => {
|
||||||
|
it("keeps requiring a prompt for password-carrying connections with saving disabled", () => {
|
||||||
|
expect(connectionNeedsPasswordPrompt({ db_type: "postgres", save_password: false, password: "" } as never)).toBe(true);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("keeps skipping the prompt when a password is stored or saving is allowed", () => {
|
||||||
|
expect(connectionNeedsPasswordPrompt({ db_type: "postgres", save_password: false, password: "pw" } as never)).toBe(false);
|
||||||
|
expect(connectionNeedsPasswordPrompt({ db_type: "postgres", save_password: true, password: "" } as never)).toBe(false);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe("pluginConnectionNeedsPasswordPrompt", () => {
|
||||||
|
it("does not prompt for SSH key auth even with save_password disabled", () => {
|
||||||
|
expect(pluginConnectionNeedsPasswordPrompt(sshAuthFields, { authentication: "private-key" })).toBe(false);
|
||||||
|
expect(pluginConnectionNeedsPasswordPrompt(sshAuthFields, { authentication: "agent" })).toBe(false);
|
||||||
|
expect(pluginConnectionNeedsPasswordPrompt(sshAuthFields, { authentication: "none" })).toBe(false);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("prompts when the manifest marks the password field required for the auth mode", () => {
|
||||||
|
expect(pluginConnectionNeedsPasswordPrompt(sshAuthFields, { authentication: "password" })).toBe(true);
|
||||||
|
expect(pluginConnectionNeedsPasswordPrompt(sshAuthFields, { authentication: "private-key-password" })).toBe(true);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("falls back to the manifest field default when external_config omits the condition key", () => {
|
||||||
|
// Default "password" → the form (and this check) sees password auth as active.
|
||||||
|
expect(pluginConnectionNeedsPasswordPrompt(sshAuthFields, {})).toBe(true);
|
||||||
|
expect(pluginConnectionNeedsPasswordPrompt(sshAuthFields, undefined)).toBe(true);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("never prompts when the manifest declares no password-bound field", () => {
|
||||||
|
const keyPathOnly: PluginFormField[] = [{ key: "private_key_path", label: "Key", type: "text", binding: "config" }];
|
||||||
|
expect(pluginConnectionNeedsPasswordPrompt(keyPathOnly, { authentication: "password" })).toBe(false);
|
||||||
|
expect(pluginConnectionNeedsPasswordPrompt([], {})).toBe(false);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("treats a condition key with no value and no manifest default as unmatched", () => {
|
||||||
|
const noDefaultAuth: PluginFormField[] = [
|
||||||
|
{ key: "authentication", label: "Authentication", type: "select", binding: "config", options: [] },
|
||||||
|
{
|
||||||
|
key: "password",
|
||||||
|
label: "Password",
|
||||||
|
type: "password",
|
||||||
|
binding: "password",
|
||||||
|
visible_when: { field: "authentication", one_of: ["password"] },
|
||||||
|
required_when: { field: "authentication", one_of: ["password"] },
|
||||||
|
},
|
||||||
|
];
|
||||||
|
expect(pluginConnectionNeedsPasswordPrompt(noDefaultAuth, {})).toBe(false);
|
||||||
|
expect(pluginConnectionNeedsPasswordPrompt(noDefaultAuth, undefined)).toBe(false);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("prompts when the password field is statically required", () => {
|
||||||
|
const staticallyRequired: PluginFormField[] = [{ key: "password", label: "Password", type: "password", binding: "password", required: true }];
|
||||||
|
expect(pluginConnectionNeedsPasswordPrompt(staticallyRequired, {})).toBe(true);
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -1,4 +1,5 @@
|
|||||||
import type { ConnectionConfig } from "@/types/database";
|
import type { ConnectionConfig, PluginFormField, PluginFormFieldValue } from "@/types/database";
|
||||||
|
import { pluginFieldIsRequired } from "@/lib/plugins/pluginFieldConditions";
|
||||||
|
|
||||||
type PasswordAuthenticationConfig = Pick<ConnectionConfig, "db_type" | "driver_profile" | "url_params">;
|
type PasswordAuthenticationConfig = Pick<ConnectionConfig, "db_type" | "driver_profile" | "url_params">;
|
||||||
|
|
||||||
@@ -30,3 +31,26 @@ export function connectionUsesPasswordlessAuthentication(config: PasswordAuthent
|
|||||||
export function connectionNeedsPasswordPrompt(config: ConnectionConfig): boolean {
|
export function connectionNeedsPasswordPrompt(config: ConnectionConfig): boolean {
|
||||||
return config.save_password === false && !config.password && !connectionUsesPasswordlessAuthentication(config);
|
return config.save_password === false && !config.password && !connectionUsesPasswordlessAuthentication(config);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Manifest-driven re-check for plugin connections. The shared prompt can only
|
||||||
|
* collect a field bound to `password`, so it applies only when the plugin's
|
||||||
|
* manifest marks that field required for the connection's current
|
||||||
|
* external_config. Auth modes that do not consume a login password (e.g. SSH
|
||||||
|
* private key / agent) declare no matching `required_when` and must connect
|
||||||
|
* without the prompt, even when save_password is disabled and no password is
|
||||||
|
* stored.
|
||||||
|
*/
|
||||||
|
export function pluginConnectionNeedsPasswordPrompt(fields: readonly PluginFormField[], externalConfig: unknown): boolean {
|
||||||
|
const passwordFields = fields.filter((field) => field.binding === "password");
|
||||||
|
if (!passwordFields.length) return false;
|
||||||
|
const readValue = (key: string): PluginFormFieldValue => {
|
||||||
|
const stored = isRecord(externalConfig) ? (externalConfig[key] as PluginFormFieldValue) : undefined;
|
||||||
|
return stored !== undefined ? stored : fields.find((candidate) => candidate.key === key)?.default;
|
||||||
|
};
|
||||||
|
return passwordFields.some((field) => pluginFieldIsRequired(field, readValue));
|
||||||
|
}
|
||||||
|
|
||||||
|
function isRecord(value: unknown): value is Record<string, unknown> {
|
||||||
|
return typeof value === "object" && value !== null && !Array.isArray(value);
|
||||||
|
}
|
||||||
@@ -124,8 +124,7 @@ export function supportsClearableQuerySchema(dbType?: DatabaseType): boolean {
|
|||||||
* SQL editor against a broker (issue #8415).
|
* SQL editor against a broker (issue #8415).
|
||||||
*/
|
*/
|
||||||
export function supportsConnectionQueryActions(dbType?: DatabaseType): boolean {
|
export function supportsConnectionQueryActions(dbType?: DatabaseType): boolean {
|
||||||
return dbType !== "nacos" && dbType !== "consul" && dbType !== "hbase" && dbType !== "zookeeper" && dbType !== "mq" && dbType !== "mqtt";
|
return dbType !== "nacos" && dbType !== "consul" && dbType !== "hbase" && dbType !== "zookeeper" && dbType !== "plugin" && dbType !== "mq" && dbType !== "mqtt";
|
||||||
return dbType !== "nacos" && dbType !== "consul" && dbType !== "hbase";
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
|
|||||||
@@ -31,6 +31,45 @@ function connectionProvider(overrides: Partial<PluginConnectionProviderContribut
|
|||||||
}
|
}
|
||||||
|
|
||||||
describe("FrontendPluginRegistry", () => {
|
describe("FrontendPluginRegistry", () => {
|
||||||
|
it("migrates a config-bound secret on edit, preserves multiline values and removes the plaintext copy", () => {
|
||||||
|
const provider = connectionProvider({ fields: [{ key: "key", label: "Private key", type: "textarea", binding: "secret" }] });
|
||||||
|
const pem = "-----BEGIN PRIVATE KEY-----\nexample\n-----END PRIVATE KEY-----\n";
|
||||||
|
const existing = buildPluginConnectionConfig("example.plugin", connectionProvider({ fields: [] }), {});
|
||||||
|
existing.external_config = { key: pem, root: "/files" };
|
||||||
|
const values = pluginConnectionFormValues(provider, existing);
|
||||||
|
expect(values.key).toBe(pem);
|
||||||
|
|
||||||
|
const saved = buildPluginConnectionConfig("example.plugin", provider, values, existing);
|
||||||
|
expect(saved.connection_secrets?.key).toBe(pem);
|
||||||
|
expect(saved.external_config).toEqual({ root: "/files" });
|
||||||
|
expect(existing.external_config).toEqual({ key: pem, root: "/files" });
|
||||||
|
expect(pluginConnectionFormValues(provider, saved).key).toBe(pem);
|
||||||
|
|
||||||
|
existing.connection_secrets = { key: "newer secret" };
|
||||||
|
expect(pluginConnectionFormValues(provider, existing).key).toBe("newer secret");
|
||||||
|
const cleared = buildPluginConnectionConfig("example.plugin", provider, { key: "" }, existing);
|
||||||
|
expect(cleared.connection_secrets?.key).toBeUndefined();
|
||||||
|
expect(cleared.external_config).toEqual({ root: "/files" });
|
||||||
|
});
|
||||||
|
|
||||||
|
it("round-trips automatic ports as an empty input and preserves explicit custom ports", () => {
|
||||||
|
const provider = connectionProvider({ fields: [{ key: "port", label: "Port", type: "number", binding: "port" }] });
|
||||||
|
const automatic = buildPluginConnectionConfig("example.plugin", provider, {});
|
||||||
|
expect(automatic.port).toBe(0);
|
||||||
|
expect(pluginConnectionFormValues(provider, automatic).port).toBeUndefined();
|
||||||
|
const explicit = buildPluginConnectionConfig("example.plugin", provider, { port: 1636 });
|
||||||
|
expect(pluginConnectionFormValues(provider, explicit).port).toBe(1636);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("preserves the save-password preference for plugin connections", () => {
|
||||||
|
const provider = connectionProvider({ fields: [] });
|
||||||
|
const defaultConfig = buildPluginConnectionConfig("example.plugin", provider, {});
|
||||||
|
expect(defaultConfig.save_password).toBe(true);
|
||||||
|
|
||||||
|
const transient = buildPluginConnectionConfig("example.plugin", provider, {}, { ...defaultConfig, save_password: false });
|
||||||
|
expect(transient.save_password).toBe(false);
|
||||||
|
});
|
||||||
|
|
||||||
it("round-trips plugin connection provider picker values", () => {
|
it("round-trips plugin connection provider picker values", () => {
|
||||||
const value = pluginConnectionProviderOptionValue("example/plugin", "ssh:main");
|
const value = pluginConnectionProviderOptionValue("example/plugin", "ssh:main");
|
||||||
expect(parsePluginConnectionProviderOptionValue(value)).toEqual({ pluginId: "example/plugin", providerId: "ssh:main" });
|
expect(parsePluginConnectionProviderOptionValue(value)).toEqual({ pluginId: "example/plugin", providerId: "ssh:main" });
|
||||||
@@ -327,4 +366,23 @@ describe("FrontendPluginRegistry", () => {
|
|||||||
keepalive: false,
|
keepalive: false,
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
|
it("builds from a reactive (non-structured-cloneable) existing config", () => {
|
||||||
|
// Connection configs reach the builder through props as Vue reactive
|
||||||
|
// proxies; structuredClone refuses them ("The object can not be cloned.").
|
||||||
|
const provider = connectionProvider({
|
||||||
|
id: "example.ssh",
|
||||||
|
database_type: "ssh",
|
||||||
|
fields: [{ key: "authentication", label: "Authentication", type: "select", binding: "config", default: "password", options: [] }],
|
||||||
|
});
|
||||||
|
const existing = {
|
||||||
|
id: "ssh-1",
|
||||||
|
external_config: new Proxy({ authentication: "private-key" }, {}),
|
||||||
|
} as unknown as Parameters<typeof buildPluginConnectionConfig>[3];
|
||||||
|
|
||||||
|
const config = buildPluginConnectionConfig("example.plugin", provider, { authentication: "private-key" }, existing);
|
||||||
|
|
||||||
|
expect(config.external_config).toEqual({ authentication: "private-key" });
|
||||||
|
expect(config.id).toBe("ssh-1");
|
||||||
|
});
|
||||||
});
|
});
|
||||||
@@ -139,9 +139,12 @@ export function pluginConnectionFormValues(contribution: PluginConnectionProvide
|
|||||||
: binding === "database"
|
: binding === "database"
|
||||||
? config.database
|
? config.database
|
||||||
: binding === "secret"
|
: binding === "secret"
|
||||||
? secrets[field.key]
|
? (secrets[field.key] ?? externalConfig[field.key])
|
||||||
: externalConfig[field.key];
|
: externalConfig[field.key];
|
||||||
if (isPluginFormFieldValue(value)) values[field.key] = value;
|
// Port 0 is the stored representation of an optional, automatic port.
|
||||||
|
// Keep that input empty on reopen so its protocol-default hint remains visible.
|
||||||
|
if (binding === "port" && value === 0 && field.default === undefined) delete values[field.key];
|
||||||
|
else if (isPluginFormFieldValue(value)) values[field.key] = value;
|
||||||
}
|
}
|
||||||
return values;
|
return values;
|
||||||
}
|
}
|
||||||
@@ -172,6 +175,7 @@ export function buildPluginConnectionConfig(pluginId: string, contribution: Plug
|
|||||||
idle_timeout_secs: existing?.idle_timeout_secs || 60,
|
idle_timeout_secs: existing?.idle_timeout_secs || 60,
|
||||||
keepalive_interval_secs: existing?.keepalive_interval_secs || 30,
|
keepalive_interval_secs: existing?.keepalive_interval_secs || 30,
|
||||||
read_only: existing?.read_only || false,
|
read_only: existing?.read_only || false,
|
||||||
|
save_password: existing?.save_password !== false,
|
||||||
is_production: existing?.is_production || false,
|
is_production: existing?.is_production || false,
|
||||||
production_databases: existing?.production_databases || [],
|
production_databases: existing?.production_databases || [],
|
||||||
};
|
};
|
||||||
@@ -182,6 +186,9 @@ export function buildPluginConnectionConfig(pluginId: string, contribution: Plug
|
|||||||
if (value === undefined) delete externalConfig[field.key];
|
if (value === undefined) delete externalConfig[field.key];
|
||||||
else externalConfig[field.key] = value;
|
else externalConfig[field.key] = value;
|
||||||
} else if (binding === "secret") {
|
} else if (binding === "secret") {
|
||||||
|
// A plugin may migrate a formerly config-bound field to secret binding.
|
||||||
|
// Load its legacy value above, then remove the plaintext copy on save.
|
||||||
|
delete externalConfig[field.key];
|
||||||
if (value === undefined || value === "") delete connectionSecrets[field.key];
|
if (value === undefined || value === "") delete connectionSecrets[field.key];
|
||||||
else connectionSecrets[field.key] = String(value);
|
else connectionSecrets[field.key] = String(value);
|
||||||
} else if (binding === "name") {
|
} else if (binding === "name") {
|
||||||
|
|||||||
@@ -0,0 +1,34 @@
|
|||||||
|
import { describe, expect, it } from "vitest";
|
||||||
|
import { buildPluginAppearance, FALLBACK_APPEARANCE_COLORS, readAppearanceTokens } from "./pluginAppearance";
|
||||||
|
|
||||||
|
describe("buildPluginAppearance", () => {
|
||||||
|
it("uses the pearl (white) fallback tokens for light and the .dark tokens for dark", () => {
|
||||||
|
const light = buildPluginAppearance(false, {}, { fontFamily: "Fira Code", fontSize: 13 });
|
||||||
|
expect(light.colorScheme).toBe("light");
|
||||||
|
expect(light.colors).toEqual(FALLBACK_APPEARANCE_COLORS.light);
|
||||||
|
expect(FALLBACK_APPEARANCE_COLORS.light.background).toBe("rgb(255 255 255)");
|
||||||
|
|
||||||
|
const dark = buildPluginAppearance(true, {}, { fontFamily: "Fira Code", fontSize: 13 });
|
||||||
|
expect(dark.colorScheme).toBe("dark");
|
||||||
|
expect(dark.colors).toEqual(FALLBACK_APPEARANCE_COLORS.dark);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("prefers live design tokens over the fallback palette", () => {
|
||||||
|
const appearance = buildPluginAppearance(false, { background: "rgb(250 251 253)", foreground: "rgb(40 44 52)" }, { fontFamily: "Fira Code", fontSize: 14 }, "SF Pro");
|
||||||
|
expect(appearance.colors.background).toBe("rgb(250 251 253)");
|
||||||
|
expect(appearance.colors.foreground).toBe("rgb(40 44 52)");
|
||||||
|
expect(appearance.colors.muted).toBe(FALLBACK_APPEARANCE_COLORS.light.muted);
|
||||||
|
expect(appearance.terminal).toEqual({ fontFamily: "Fira Code", fontSize: 14 });
|
||||||
|
expect(appearance.ui).toEqual({ fontFamily: "SF Pro" });
|
||||||
|
});
|
||||||
|
|
||||||
|
it("omits the ui font when the host has none", () => {
|
||||||
|
const appearance = buildPluginAppearance(true, {}, { fontFamily: "Fira Code", fontSize: 13 });
|
||||||
|
expect(appearance.ui).toBeUndefined();
|
||||||
|
});
|
||||||
|
|
||||||
|
it("returns no tokens outside a browser context", () => {
|
||||||
|
// jsdom 环境下 getComputedStyle 存在,但令牌读取不应抛错。
|
||||||
|
expect(() => readAppearanceTokens()).not.toThrow();
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -0,0 +1,84 @@
|
|||||||
|
// 插件沙箱外观快照:读取 DBX 根节点的设计令牌(随 .dark / 调色板类
|
||||||
|
// 实时变化)加编辑器字体设置,组装成插件契约里的 appearance 对象,
|
||||||
|
// 供 PluginHostBridge 在 init 下发、主题变化时实时推送。
|
||||||
|
|
||||||
|
export interface PluginAppearanceColors {
|
||||||
|
background: string;
|
||||||
|
foreground: string;
|
||||||
|
muted: string;
|
||||||
|
mutedForeground: string;
|
||||||
|
accent: string;
|
||||||
|
accentForeground: string;
|
||||||
|
border: string;
|
||||||
|
destructive: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface PluginAppearance {
|
||||||
|
colorScheme: "light" | "dark";
|
||||||
|
colors: PluginAppearanceColors;
|
||||||
|
terminal: { fontFamily: string; fontSize: number };
|
||||||
|
ui?: { fontFamily: string };
|
||||||
|
}
|
||||||
|
|
||||||
|
// camelCase 字段 → DBX globals.css 的 CSS 令牌名。
|
||||||
|
const APPEARANCE_TOKENS = [
|
||||||
|
["background", "--background"],
|
||||||
|
["foreground", "--foreground"],
|
||||||
|
["muted", "--muted"],
|
||||||
|
["mutedForeground", "--muted-foreground"],
|
||||||
|
["accent", "--accent"],
|
||||||
|
["accentForeground", "--accent-foreground"],
|
||||||
|
["border", "--border"],
|
||||||
|
["destructive", "--destructive"],
|
||||||
|
] as const;
|
||||||
|
|
||||||
|
// 读取失败时的兜底:与 DBX globals.css 的 :root(pearl)/.dark 规范块一致。
|
||||||
|
export const FALLBACK_APPEARANCE_COLORS: Record<"light" | "dark", PluginAppearanceColors> = {
|
||||||
|
light: {
|
||||||
|
background: "rgb(255 255 255)",
|
||||||
|
foreground: "rgb(10 10 10)",
|
||||||
|
muted: "rgb(245 245 245)",
|
||||||
|
mutedForeground: "rgb(115 115 115)",
|
||||||
|
accent: "rgb(245 245 245)",
|
||||||
|
accentForeground: "rgb(23 23 23)",
|
||||||
|
border: "rgb(229 229 229)",
|
||||||
|
destructive: "rgb(231 0 11)",
|
||||||
|
},
|
||||||
|
dark: {
|
||||||
|
background: "rgb(19 20 22)",
|
||||||
|
foreground: "rgb(215 215 219)",
|
||||||
|
muted: "rgb(42 42 45)",
|
||||||
|
mutedForeground: "rgb(151 152 157)",
|
||||||
|
accent: "rgb(46 47 51)",
|
||||||
|
accentForeground: "rgb(221 221 226)",
|
||||||
|
border: "rgb(110 110 114 / 0.28)",
|
||||||
|
destructive: "rgb(243 98 95)",
|
||||||
|
},
|
||||||
|
};
|
||||||
|
|
||||||
|
export function readAppearanceTokens(): Partial<Record<(typeof APPEARANCE_TOKENS)[number][0], string>> {
|
||||||
|
const tokens: Record<string, string> = {};
|
||||||
|
if (typeof window === "undefined" || typeof getComputedStyle !== "function") return tokens;
|
||||||
|
const style = getComputedStyle(document.documentElement);
|
||||||
|
for (const [key, cssName] of APPEARANCE_TOKENS) {
|
||||||
|
const value = style.getPropertyValue(cssName).trim();
|
||||||
|
if (value) tokens[key] = value;
|
||||||
|
}
|
||||||
|
return tokens;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function buildPluginAppearance(isDark: boolean, tokens: ReturnType<typeof readAppearanceTokens>, terminal: { fontFamily: string; fontSize: number }, uiFontFamily?: string): PluginAppearance {
|
||||||
|
const fallback = FALLBACK_APPEARANCE_COLORS[isDark ? "dark" : "light"];
|
||||||
|
const colors = { ...fallback };
|
||||||
|
for (const [key] of APPEARANCE_TOKENS) {
|
||||||
|
const value = tokens[key];
|
||||||
|
if (value) colors[key] = value;
|
||||||
|
}
|
||||||
|
const appearance: PluginAppearance = {
|
||||||
|
colorScheme: isDark ? "dark" : "light",
|
||||||
|
colors,
|
||||||
|
terminal,
|
||||||
|
};
|
||||||
|
if (uiFontFamily) appearance.ui = { fontFamily: uiFontFamily };
|
||||||
|
return appearance;
|
||||||
|
}
|
||||||
@@ -0,0 +1,87 @@
|
|||||||
|
import { describe, expect, it } from "vitest";
|
||||||
|
import { pluginFieldConditionMatches, pluginFieldIsRequired, pluginFieldIsVisible } from "./pluginFieldConditions";
|
||||||
|
import type { PluginFormField, PluginFormFieldValue } from "@/types/database";
|
||||||
|
|
||||||
|
function field(overrides: Partial<PluginFormField>): PluginFormField {
|
||||||
|
return { key: "demo", label: "Demo", type: "text", ...overrides } as PluginFormField;
|
||||||
|
}
|
||||||
|
|
||||||
|
const readValue = (key: string) => (key === "mode" ? "custom" : undefined);
|
||||||
|
|
||||||
|
describe("pluginFieldConditionMatches", () => {
|
||||||
|
it("matches a missing condition and a listed value", () => {
|
||||||
|
expect(pluginFieldConditionMatches(undefined, undefined)).toBe(true);
|
||||||
|
expect(pluginFieldConditionMatches({ field: "mode", one_of: ["custom"] }, "custom")).toBe(true);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("rejects an unlisted or empty value", () => {
|
||||||
|
expect(pluginFieldConditionMatches({ field: "mode", one_of: ["custom"] }, "direct")).toBe(false);
|
||||||
|
expect(pluginFieldConditionMatches({ field: "mode", one_of: ["custom"] }, undefined)).toBe(false);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe("pluginFieldIsRequired", () => {
|
||||||
|
it("honors static required", () => {
|
||||||
|
expect(pluginFieldIsRequired(field({ required: true }), readValue)).toBe(true);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("treats a field without required_when as optional", () => {
|
||||||
|
expect(pluginFieldIsRequired(field({}), readValue)).toBe(false);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("requires a field only while its required_when matches", () => {
|
||||||
|
const conditional = field({ required_when: { field: "mode", one_of: ["custom"] } });
|
||||||
|
expect(pluginFieldIsRequired(conditional, readValue)).toBe(true);
|
||||||
|
expect(pluginFieldIsRequired(conditional, () => "direct")).toBe(false);
|
||||||
|
expect(pluginFieldIsRequired(conditional, () => undefined)).toBe(false);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe("pluginFieldIsVisible", () => {
|
||||||
|
it("renders fields without visible_when and gates conditional ones", () => {
|
||||||
|
expect(pluginFieldIsVisible(field({}), readValue)).toBe(true);
|
||||||
|
const conditional = field({ visible_when: { field: "mode", one_of: ["custom"] } });
|
||||||
|
expect(pluginFieldIsVisible(conditional, readValue)).toBe(true);
|
||||||
|
expect(pluginFieldIsVisible(conditional, () => "direct")).toBe(false);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("keeps a condition dormant while its referenced sibling is hidden, even when the sibling default would match", () => {
|
||||||
|
// kafka-shaped chain: sasl_mechanism (default PLAIN, hidden) →
|
||||||
|
// oauth_token_source (visible only for OAUTHBEARER, defaults msk_iam) →
|
||||||
|
// msk_region. The msk_iam default must not surface msk_region while SASL
|
||||||
|
// is off, otherwise the dialog footer dead-locks on an unfillable field.
|
||||||
|
const fields: Record<string, PluginFormField> = {
|
||||||
|
security_protocol: field({ key: "security_protocol", default: "PLAINTEXT" }),
|
||||||
|
sasl_mechanism: field({ key: "sasl_mechanism", default: "PLAIN", visible_when: { field: "security_protocol", one_of: ["SASL_PLAINTEXT", "SASL_SSL"] } }),
|
||||||
|
oauth_token_source: field({ key: "oauth_token_source", default: "msk_iam", visible_when: { field: "sasl_mechanism", one_of: ["OAUTHBEARER"] } }),
|
||||||
|
msk_region: field({ key: "msk_region", visible_when: { field: "oauth_token_source", one_of: ["msk_iam"] } }),
|
||||||
|
};
|
||||||
|
const read: (key: string) => PluginFormFieldValue = (key) => fields[key]?.default;
|
||||||
|
const resolve: (key: string) => PluginFormField | undefined = (key) => fields[key];
|
||||||
|
|
||||||
|
expect(pluginFieldIsVisible(fields.msk_region, read, resolve)).toBe(false);
|
||||||
|
// Turning OAUTHBEARER on makes the whole chain visible again.
|
||||||
|
const readOauth: (key: string) => PluginFormFieldValue = (key) => (key === "sasl_mechanism" ? "OAUTHBEARER" : key === "security_protocol" ? "SASL_SSL" : fields[key]?.default);
|
||||||
|
expect(pluginFieldIsVisible(fields.oauth_token_source, readOauth, resolve)).toBe(true);
|
||||||
|
expect(pluginFieldIsVisible(fields.msk_region, readOauth, resolve)).toBe(true);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("ignores unknown condition fields and survives self-referencing cycles", () => {
|
||||||
|
const unknown = field({ visible_when: { field: "missing", one_of: ["x"] } });
|
||||||
|
expect(
|
||||||
|
pluginFieldIsVisible(
|
||||||
|
unknown,
|
||||||
|
() => "x",
|
||||||
|
() => undefined,
|
||||||
|
),
|
||||||
|
).toBe(true);
|
||||||
|
const selfRef = field({ key: "loop", visible_when: { field: "loop", one_of: ["x"] } });
|
||||||
|
expect(
|
||||||
|
pluginFieldIsVisible(
|
||||||
|
selfRef,
|
||||||
|
() => "x",
|
||||||
|
(key) => (key === "loop" ? selfRef : undefined),
|
||||||
|
),
|
||||||
|
).toBe(true);
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -0,0 +1,47 @@
|
|||||||
|
import type { PluginFieldCondition, PluginFormField, PluginFormFieldValue } from "@/types/database";
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Evaluates a plugin manifest field condition (`visible_when` / `required_when`,
|
||||||
|
* Host API 1.1). A condition matches when the current value of the referenced
|
||||||
|
* sibling field is listed in `one_of`. Missing conditions always match.
|
||||||
|
*/
|
||||||
|
export function pluginFieldConditionMatches(condition: PluginFieldCondition | undefined, value: PluginFormFieldValue): boolean {
|
||||||
|
if (!condition) return true;
|
||||||
|
if (value === undefined || value === null || (typeof value === "string" && value.trim().length === 0)) return false;
|
||||||
|
return condition.one_of.includes(String(value));
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Looks a sibling field up by key; returns undefined when the key is unknown. */
|
||||||
|
export type PluginFieldResolver = (key: string) => PluginFormField | undefined;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* A field is rendered when its `visible_when` (if any) matches current values.
|
||||||
|
* Conditions cascade: when the referenced sibling is itself hidden, its stored
|
||||||
|
* or default value must not light the condition up — otherwise a nested
|
||||||
|
* default (e.g. `oauth_token_source: "msk_iam"` while SASL is off) marks
|
||||||
|
* grandchild fields visible and required and dead-locks the dialog footer.
|
||||||
|
*/
|
||||||
|
export function pluginFieldIsVisible(field: PluginFormField, readValue: (key: string) => PluginFormFieldValue, resolveField?: PluginFieldResolver): boolean {
|
||||||
|
return pluginFieldIsVisibleCached(field, readValue, resolveField, new Set([field.key]));
|
||||||
|
}
|
||||||
|
|
||||||
|
function pluginFieldIsVisibleCached(field: PluginFormField, readValue: (key: string) => PluginFormFieldValue, resolveField: PluginFieldResolver | undefined, seen: Set<string>): boolean {
|
||||||
|
const condition = field.visible_when;
|
||||||
|
if (!condition) return true;
|
||||||
|
if (!pluginFieldConditionMatches(condition, readValue(condition.field))) return false;
|
||||||
|
const target = resolveField?.(condition.field);
|
||||||
|
if (!target || seen.has(target.key)) return true;
|
||||||
|
seen.add(target.key);
|
||||||
|
return pluginFieldIsVisibleCached(target, readValue, resolveField, seen);
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Effective required = static `required` OR a matching `required_when`. */
|
||||||
|
export function pluginFieldIsRequired(field: PluginFormField, readValue: (key: string) => PluginFormFieldValue): boolean {
|
||||||
|
if (field.required) return true;
|
||||||
|
// No `required_when` means the field is simply optional: the shared
|
||||||
|
// condition helper treats a missing condition as "always matches" (correct
|
||||||
|
// for visibility), so it must not be consulted here — that used to mark
|
||||||
|
// every plugin field required and dead-locked the connection footer.
|
||||||
|
if (!field.required_when) return false;
|
||||||
|
return pluginFieldConditionMatches(field.required_when, readValue(field.required_when.field));
|
||||||
|
}
|
||||||
+83
-1
@@ -1,6 +1,6 @@
|
|||||||
import { describe, expect, it, vi } from "vitest";
|
import { describe, expect, it, vi } from "vitest";
|
||||||
import { reactive, readonly } from "vue";
|
import { reactive, readonly } from "vue";
|
||||||
import { PluginHostBridge, pluginSandboxDocument } from "./pluginHostBridge";
|
import { PluginHostBridge, pluginSandboxDocument, pluginSdkSource } from "./pluginHostBridge";
|
||||||
import type { InstalledPlugin, PluginWorkbenchContribution } from "@/types/database";
|
import type { InstalledPlugin, PluginWorkbenchContribution } from "@/types/database";
|
||||||
|
|
||||||
function plugin(permissions: string[] = []): InstalledPlugin {
|
function plugin(permissions: string[] = []): InstalledPlugin {
|
||||||
@@ -291,6 +291,7 @@ describe("PluginHostBridge", () => {
|
|||||||
expect(document).toContain("window.dbxPlugin");
|
expect(document).toContain("window.dbxPlugin");
|
||||||
expect(document).toContain("get locale() { return locale; }");
|
expect(document).toContain("get locale() { return locale; }");
|
||||||
expect(document).toContain("openFilesystem");
|
expect(document).toContain("openFilesystem");
|
||||||
|
expect(document).toContain("document.dispatchEvent(new CustomEvent('dbx-plugin-env'");
|
||||||
expect(document).toContain("shortcut: 'closeTab'");
|
expect(document).toContain("shortcut: 'closeTab'");
|
||||||
expect(document).toContain("connect-src 'none'");
|
expect(document).toContain("connect-src 'none'");
|
||||||
expect(document).toContain(".dbx-btn");
|
expect(document).toContain(".dbx-btn");
|
||||||
@@ -340,6 +341,30 @@ describe("PluginHostBridge", () => {
|
|||||||
expect(closed).toContain("host.stream.chunk");
|
expect(closed).toContain("host.stream.chunk");
|
||||||
});
|
});
|
||||||
|
|
||||||
|
it("pre-seeds the current theme as the sandbox first paint", () => {
|
||||||
|
const themed = pluginSandboxDocument("<html><head></head><body></body></html>", ["host.events"], { appearance: "dark", tokens: { "--color-background": "#131416", "--color-foreground": "rgb(215 215 219)" } });
|
||||||
|
expect(themed).toContain("color-scheme: dark");
|
||||||
|
expect(themed).toContain("--color-background: #131416");
|
||||||
|
expect(themed).toContain("--color-foreground: rgb(215 215 219)");
|
||||||
|
expect(themed.indexOf("<style>:root{")).toBeGreaterThan(themed.indexOf(".dbx-btn"));
|
||||||
|
|
||||||
|
const unthemed = pluginSandboxDocument("<html><head></head><body></body></html>");
|
||||||
|
expect(unthemed).not.toContain("color-scheme: dark");
|
||||||
|
expect(unthemed).not.toContain("--color-background: #131416");
|
||||||
|
});
|
||||||
|
|
||||||
|
it("drops boot theme declarations that could break out of the style element", () => {
|
||||||
|
const hostile = pluginSandboxDocument("<html><head></head><body></body></html>", [], {
|
||||||
|
appearance: "dark",
|
||||||
|
tokens: { "--color-background": "#131416", color: "red", "--evil": "red}</style><script>alert(1)</script>", "--empty": " " },
|
||||||
|
});
|
||||||
|
expect(hostile).toContain("--color-background: #131416");
|
||||||
|
expect(hostile).not.toContain("--bad-name");
|
||||||
|
expect(hostile).not.toContain("--evil");
|
||||||
|
expect(hostile).not.toContain("--empty");
|
||||||
|
expect((hostile.match(/<script\b/gi) ?? []).length).toBe(1);
|
||||||
|
});
|
||||||
|
|
||||||
it("sends the theme in init and pushes theme updates through env messages", () => {
|
it("sends the theme in init and pushes theme updates through env messages", () => {
|
||||||
const messages: unknown[] = [];
|
const messages: unknown[] = [];
|
||||||
const target = { postMessage: (message: unknown) => messages.push(message) } as unknown as Window;
|
const target = { postMessage: (message: unknown) => messages.push(message) } as unknown as Window;
|
||||||
@@ -353,3 +378,60 @@ describe("PluginHostBridge", () => {
|
|||||||
expect(messages[1]).toMatchObject({ type: "env", locale: "en", theme: { appearance: "light" } });
|
expect(messages[1]).toMatchObject({ type: "env", locale: "en", theme: { appearance: "light" } });
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
|
describe("plugin SDK source", () => {
|
||||||
|
interface SdkWindow {
|
||||||
|
dbxPlugin?: { invoke: (method: string, params?: unknown, options?: { timeoutMs?: number }) => Promise<unknown> };
|
||||||
|
}
|
||||||
|
|
||||||
|
function loadSdk(posted: unknown[]): SdkWindow {
|
||||||
|
const sandbox = {} as SdkWindow;
|
||||||
|
// The SDK IIFE only touches window and the bare-global addEventListener at
|
||||||
|
// boot; parent.postMessage is captured for later request() calls, so a
|
||||||
|
// stub window/parent is enough here.
|
||||||
|
new Function("window", "parent", "addEventListener", pluginSdkSource())(sandbox, { postMessage: (message: unknown) => posted.push(message) }, () => {});
|
||||||
|
return sandbox;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** The SDK posts a `ready` message at boot; the first request follows it. */
|
||||||
|
function firstRequest(posted: unknown[]): { type: string; method: string; params: { method: string; params: Record<string, unknown> } } {
|
||||||
|
const request = posted.find((message) => (message as { type: string }).type === "request");
|
||||||
|
if (!request) throw new Error("SDK posted no request message");
|
||||||
|
return request as { type: string; method: string; params: { method: string; params: Record<string, unknown> } };
|
||||||
|
}
|
||||||
|
|
||||||
|
it("plainifies reactive (Proxy) params before postMessage", () => {
|
||||||
|
const posted: unknown[] = [];
|
||||||
|
const { dbxPlugin } = loadSdk(posted);
|
||||||
|
expect(dbxPlugin).toBeDefined();
|
||||||
|
|
||||||
|
// Vue reactive arrays/objects are Proxies; structured clone rejects them
|
||||||
|
// with "The object can not be cloned." (WebKit wording) — the SDK must
|
||||||
|
// recover the plain data before crossing the postMessage boundary.
|
||||||
|
const reactive: string[] = ["session-a", "session-b"];
|
||||||
|
const proxy = new Proxy(reactive, {});
|
||||||
|
|
||||||
|
void dbxPlugin!.invoke("ssh/terminal/batchInput", { sessionIds: proxy, command: "ls -la" });
|
||||||
|
|
||||||
|
const message = firstRequest(posted);
|
||||||
|
expect(message.method).toBe("backend.invoke");
|
||||||
|
expect(message.params.params).toEqual({ sessionIds: ["session-a", "session-b"], command: "ls -la" });
|
||||||
|
// The posted sessionIds must not be the incoming Proxy itself.
|
||||||
|
expect(message.params.params.sessionIds).not.toBe(proxy);
|
||||||
|
expect(JSON.stringify(message.params.params.sessionIds)).toBe(JSON.stringify(["session-a", "session-b"]));
|
||||||
|
});
|
||||||
|
|
||||||
|
it("keeps cloneable values intact and plain scalars by reference", () => {
|
||||||
|
const posted: unknown[] = [];
|
||||||
|
const { dbxPlugin } = loadSdk(posted);
|
||||||
|
|
||||||
|
const stamp = new Date("2026-09-06T00:00:00Z");
|
||||||
|
void dbxPlugin!.invoke("sample/hello", { count: 3, stamp, nested: new Map([["k", "v"]]) });
|
||||||
|
|
||||||
|
const params = firstRequest(posted).params.params as { count: number; stamp: Date; nested: Map<string, string> };
|
||||||
|
// structuredClone path: cloneable types keep their identity class.
|
||||||
|
expect(params.count).toBe(3);
|
||||||
|
expect(params.stamp).toBeInstanceOf(Date);
|
||||||
|
expect(params.nested).toBeInstanceOf(Map);
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -221,18 +221,36 @@ export function pluginSandboxDocument(html: string, permissions?: readonly strin
|
|||||||
const networkOrigins = pluginNetworkOrigins(permissions);
|
const networkOrigins = pluginNetworkOrigins(permissions);
|
||||||
const connectSrc = networkOrigins.length > 0 ? `connect-src ${networkOrigins.join(" ")};` : "connect-src 'none';";
|
const connectSrc = networkOrigins.length > 0 ? `connect-src ${networkOrigins.join(" ")};` : "connect-src 'none';";
|
||||||
const csp = `<meta http-equiv="Content-Security-Policy" content="default-src 'none'; script-src 'unsafe-inline' blob:; style-src 'unsafe-inline' blob:; img-src data: blob:; font-src data: blob:; ${connectSrc} media-src data: blob:;">`;
|
const csp = `<meta http-equiv="Content-Security-Policy" content="default-src 'none'; script-src 'unsafe-inline' blob:; style-src 'unsafe-inline' blob:; img-src data: blob:; font-src data: blob:; ${connectSrc} media-src data: blob:;">`;
|
||||||
const sdk = `<script>${pluginSdkSource()}</script>`;
|
const sdk = `<script>${pluginSdkSource(theme)}</script>`;
|
||||||
const uiKit = `<style>${pluginUiKitCss()}</style>`;
|
const uiKit = `<style>${pluginUiKitCss()}</style>`;
|
||||||
const themeBootstrap = pluginThemeBootstrap(theme);
|
// Placed after the uiKit so the boot `color-scheme` wins the cascade: the
|
||||||
const injection = `${csp}${uiKit}${themeBootstrap}${sdk}`;
|
// bridge init message (and the SDK's applyTheme) only runs once the iframe
|
||||||
|
// has loaded, and the uiKit's token fallbacks would otherwise paint the
|
||||||
|
// first frame white on dark hosts.
|
||||||
|
const bootTheme = pluginBootThemeCss(theme);
|
||||||
|
const injection = `${csp}${uiKit}${bootTheme ? `<style>${bootTheme}</style>` : ""}${sdk}`;
|
||||||
if (/<head(?:\s[^>]*)?>/i.test(html)) return html.replace(/<head(?:\s[^>]*)?>/i, (head) => `${head}${injection}`);
|
if (/<head(?:\s[^>]*)?>/i.test(html)) return html.replace(/<head(?:\s[^>]*)?>/i, (head) => `${head}${injection}`);
|
||||||
return `<!doctype html><html><head>${injection}</head><body>${html}</body></html>`;
|
return `<!doctype html><html><head>${injection}</head><body>${html}</body></html>`;
|
||||||
}
|
}
|
||||||
|
|
||||||
function pluginThemeBootstrap(theme?: PluginBridgeTheme): string {
|
/**
|
||||||
if (!theme) return "";
|
* Pre-paint theme seed for the sandbox document. The bridge init message only
|
||||||
const serializedTheme = JSON.stringify(theme).replace(/</g, "\\u003c");
|
* arrives after the iframe load event, so without this style the first frame
|
||||||
return `<script>(() => { const theme = ${serializedTheme}; const root = document.documentElement; root.dataset.dbxTheme = theme.appearance === "dark" ? "dark" : "light"; root.style.colorScheme = theme.appearance === "dark" ? "dark" : "light"; for (const [name, value] of Object.entries(theme.tokens || {})) { if (/^--[a-z0-9-]+$/i.test(name) && typeof value === "string") root.style.setProperty(name, value); } })();</script>`;
|
* renders with the uiKit fallbacks (white background) before the real tokens
|
||||||
|
* land — the white flash when opening a plugin workbench on a dark host.
|
||||||
|
*/
|
||||||
|
export function pluginBootThemeCss(theme?: PluginBridgeTheme): string {
|
||||||
|
if (!theme || (theme.appearance !== "dark" && theme.appearance !== "light")) return "";
|
||||||
|
const declarations: string[] = [`color-scheme: ${theme.appearance}`];
|
||||||
|
const tokens = theme.tokens && typeof theme.tokens === "object" ? theme.tokens : {};
|
||||||
|
for (const [name, value] of Object.entries(tokens)) {
|
||||||
|
// Same name validation as the SDK's applyTheme; values must stay inside a
|
||||||
|
// single CSS declaration so they cannot break out of the style element.
|
||||||
|
if (!/^--[a-z0-9-]+$/i.test(name) || typeof value !== "string" || !value.trim()) continue;
|
||||||
|
if (!/^[^"{}<>;]*$/.test(value)) continue;
|
||||||
|
declarations.push(`${name}: ${value}`);
|
||||||
|
}
|
||||||
|
return `:root{${declarations.join(";")}}`;
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -311,7 +329,14 @@ body {
|
|||||||
`.trim();
|
`.trim();
|
||||||
}
|
}
|
||||||
|
|
||||||
function pluginSdkSource(): string {
|
export function pluginSdkSource(initialTheme?: PluginBridgeTheme): string {
|
||||||
|
const safeTokens = Object.fromEntries(Object.entries(initialTheme?.tokens || {}).filter(([name, value]) => /^--[a-z0-9-]+$/i.test(name) && typeof value === "string" && !!value.trim() && /^[^"{}<>;]*$/.test(value)));
|
||||||
|
const safeInitialTheme = initialTheme && (initialTheme.appearance === "dark" || initialTheme.appearance === "light") ? { appearance: initialTheme.appearance, tokens: safeTokens } : null;
|
||||||
|
const serializedInitialTheme = JSON.stringify(safeInitialTheme)
|
||||||
|
.replace(/</g, "\\u003c")
|
||||||
|
.replace(/>/g, "\\u003e")
|
||||||
|
.replace(/\u2028/g, "\\u2028")
|
||||||
|
.replace(/\u2029/g, "\\u2029");
|
||||||
return `(() => {
|
return `(() => {
|
||||||
const pending = new Map();
|
const pending = new Map();
|
||||||
const listeners = { event: new Set(), binary: new Set(), init: new Set(), context: new Set() };
|
const listeners = { event: new Set(), binary: new Set(), init: new Set(), context: new Set() };
|
||||||
@@ -320,21 +345,37 @@ function pluginSdkSource(): string {
|
|||||||
let locale = 'en';
|
let locale = 'en';
|
||||||
let theme;
|
let theme;
|
||||||
let resolveReady;
|
let resolveReady;
|
||||||
|
const initialTheme = ${serializedInitialTheme};
|
||||||
const applyTheme = (value) => {
|
const applyTheme = (value) => {
|
||||||
if (!value || typeof value !== 'object') return;
|
if (!value || typeof value !== 'object') return;
|
||||||
theme = value;
|
theme = value;
|
||||||
|
const theme = value;
|
||||||
const root = document.documentElement;
|
const root = document.documentElement;
|
||||||
root.dataset.dbxTheme = value.appearance === 'dark' ? 'dark' : 'light';
|
root.dataset.dbxTheme = theme.appearance === "dark" ? "dark" : "light";
|
||||||
|
root.style.colorScheme = theme.appearance === "dark" ? "dark" : "light";
|
||||||
const tokens = value.tokens && typeof value.tokens === 'object' ? value.tokens : {};
|
const tokens = value.tokens && typeof value.tokens === 'object' ? value.tokens : {};
|
||||||
for (const [name, tokenValue] of Object.entries(tokens)) {
|
for (const [name, tokenValue] of Object.entries(tokens)) {
|
||||||
if (/^--[a-z0-9-]+$/i.test(name) && typeof tokenValue === 'string') root.style.setProperty(name, tokenValue);
|
if (/^--[a-z0-9-]+$/i.test(name) && typeof tokenValue === 'string') root.style.setProperty(name, tokenValue);
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
const ready = new Promise((resolve) => { resolveReady = resolve; });
|
const ready = new Promise((resolve) => { resolveReady = resolve; });
|
||||||
|
if (initialTheme) applyTheme(initialTheme);
|
||||||
|
// Plugin UIs routinely hand reactive state (Vue Proxy arrays/objects)
|
||||||
|
// straight to invoke(); postMessage cannot structured-clone a Proxy and
|
||||||
|
// WebKit rejects with "The object can not be cloned.". Mirror the host's
|
||||||
|
// structuredCloneSafe: clone when possible, otherwise recover the plain
|
||||||
|
// data with a JSON round-trip (the sidecar transport is JSON anyway).
|
||||||
|
const toPlain = (value) => {
|
||||||
|
if (!value || typeof value !== 'object') return value;
|
||||||
|
if (typeof structuredClone === 'function') {
|
||||||
|
try { return structuredClone(value); } catch {}
|
||||||
|
}
|
||||||
|
return JSON.parse(JSON.stringify(value));
|
||||||
|
};
|
||||||
const request = (method, params, options = {}) => new Promise((resolve, reject) => {
|
const request = (method, params, options = {}) => new Promise((resolve, reject) => {
|
||||||
const id = String(++sequence);
|
const id = String(++sequence);
|
||||||
pending.set(id, { resolve, reject });
|
pending.set(id, { resolve, reject });
|
||||||
const message = { source: '${PLUGIN_MESSAGE_SOURCE}', version: ${BRIDGE_VERSION}, type: 'request', id, method, params };
|
const message = { source: '${PLUGIN_MESSAGE_SOURCE}', version: ${BRIDGE_VERSION}, type: 'request', id, method, params: toPlain(params) };
|
||||||
if (options.transfer) {
|
if (options.transfer) {
|
||||||
message.data = options.transfer;
|
message.data = options.transfer;
|
||||||
parent.postMessage(message, '*', [options.transfer]);
|
parent.postMessage(message, '*', [options.transfer]);
|
||||||
@@ -369,14 +410,14 @@ function pluginSdkSource(): string {
|
|||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
removeListener?.();
|
removeListener?.();
|
||||||
removeListener = undefined;
|
removeListener = undefined;
|
||||||
if (message.method === 'host.stream.error') {
|
if (message.method === 'host.stream.error') {
|
||||||
const error = new Error(event.message || 'Plugin stream failed');
|
const error = new Error(event.message || 'Plugin stream failed');
|
||||||
rejectOpen(error);
|
rejectOpen(error);
|
||||||
controller.error(error);
|
controller.error(error);
|
||||||
} else {
|
} else {
|
||||||
Object.assign(metadata, event);
|
Object.assign(metadata, event);
|
||||||
controller.close();
|
controller.close();
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
removeListener = () => listeners.event.delete(onEvent);
|
removeListener = () => listeners.event.delete(onEvent);
|
||||||
@@ -441,23 +482,26 @@ function pluginSdkSource(): string {
|
|||||||
applyTheme(message.theme);
|
applyTheme(message.theme);
|
||||||
resolveReady(context);
|
resolveReady(context);
|
||||||
listeners.init.forEach((listener) => listener(context));
|
listeners.init.forEach((listener) => listener(context));
|
||||||
dispatchEvent(new CustomEvent('dbx-plugin-init', { detail: message }));
|
// Plugin listeners register on the document (onHostThemeChange);
|
||||||
|
// bare dispatchEvent targets window, which document listeners never
|
||||||
|
// receive — env theme pushes were silently lost.
|
||||||
|
document.dispatchEvent(new CustomEvent('dbx-plugin-init', { detail: message }));
|
||||||
} else if (message.type === 'context') {
|
} else if (message.type === 'context') {
|
||||||
context = message.context;
|
context = message.context;
|
||||||
listeners.context.forEach((listener) => listener(context));
|
listeners.context.forEach((listener) => listener(context));
|
||||||
dispatchEvent(new CustomEvent('dbx-plugin-context', { detail: context }));
|
document.dispatchEvent(new CustomEvent('dbx-plugin-context', { detail: context }));
|
||||||
} else if (message.type === 'env') {
|
} else if (message.type === 'env') {
|
||||||
if (typeof message.locale === 'string') locale = message.locale;
|
if (typeof message.locale === 'string') locale = message.locale;
|
||||||
if (message.theme) applyTheme(message.theme);
|
if (message.theme) applyTheme(message.theme);
|
||||||
listeners.event.forEach((listener) => listener(message));
|
listeners.event.forEach((listener) => listener(message));
|
||||||
dispatchEvent(new CustomEvent('dbx-plugin-env', { detail: message }));
|
document.dispatchEvent(new CustomEvent('dbx-plugin-env', { detail: message }));
|
||||||
} else if (message.type === 'event') {
|
} else if (message.type === 'event') {
|
||||||
listeners.event.forEach((listener) => listener(message));
|
listeners.event.forEach((listener) => listener(message));
|
||||||
dispatchEvent(new CustomEvent('dbx-plugin-event', { detail: message }));
|
document.dispatchEvent(new CustomEvent('dbx-plugin-event', { detail: message }));
|
||||||
} else if (message.type === 'binary') {
|
} else if (message.type === 'binary') {
|
||||||
const payload = { channel: message.channel, data: message.data ? new Uint8Array(message.data) : new Uint8Array(0) };
|
const payload = { channel: message.channel, data: message.data ? new Uint8Array(message.data) : new Uint8Array(0) };
|
||||||
listeners.binary.forEach((listener) => listener(payload));
|
listeners.binary.forEach((listener) => listener(payload));
|
||||||
dispatchEvent(new CustomEvent('dbx-plugin-binary', { detail: payload }));
|
document.dispatchEvent(new CustomEvent('dbx-plugin-binary', { detail: payload }));
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
addEventListener('keydown', (event) => {
|
addEventListener('keydown', (event) => {
|
||||||
|
|||||||
@@ -467,3 +467,127 @@ describe("connectionStore save_password opt-out", () => {
|
|||||||
expect(store.connectionErrors["mysql-1"]).toContain("disk full");
|
expect(store.connectionErrors["mysql-1"]).toContain("disk full");
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
|
describe("connectionStore plugin password prompt", () => {
|
||||||
|
// Runtime-assembled placeholder: no credential literal in source (Mimosa gate).
|
||||||
|
const PROMPT_TYPED_PASSWORD = "typed" + "-pw";
|
||||||
|
|
||||||
|
beforeEach(() => {
|
||||||
|
vi.resetModules();
|
||||||
|
vi.unstubAllGlobals();
|
||||||
|
installLocalStorage();
|
||||||
|
setActivePinia(createPinia());
|
||||||
|
requestPassword = vi.fn();
|
||||||
|
});
|
||||||
|
|
||||||
|
afterEach(() => {
|
||||||
|
vi.restoreAllMocks();
|
||||||
|
});
|
||||||
|
|
||||||
|
function sshInstalledPlugin(): unknown {
|
||||||
|
return {
|
||||||
|
manifest: {
|
||||||
|
id: "io.dbx.ssh",
|
||||||
|
name: "SSH",
|
||||||
|
drivers: [],
|
||||||
|
contributions: [
|
||||||
|
{
|
||||||
|
type: "connection-provider",
|
||||||
|
id: "io.dbx.ssh.connection",
|
||||||
|
label: "SSH server",
|
||||||
|
database_type: "ssh",
|
||||||
|
fields: [
|
||||||
|
{ key: "authentication", label: "Authentication", type: "select", binding: "config", default: "password", options: [] },
|
||||||
|
{
|
||||||
|
key: "password",
|
||||||
|
label: "Password",
|
||||||
|
type: "password",
|
||||||
|
binding: "password",
|
||||||
|
visible_when: { field: "authentication", one_of: ["password", "private-key-password"] },
|
||||||
|
required_when: { field: "authentication", one_of: ["password", "private-key-password"] },
|
||||||
|
},
|
||||||
|
],
|
||||||
|
},
|
||||||
|
],
|
||||||
|
},
|
||||||
|
compatibility: { compatible: true },
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
function pluginConnection(overrides: Record<string, unknown> = {}): ConnectionConfig {
|
||||||
|
return {
|
||||||
|
id: "ssh-1",
|
||||||
|
name: "hktkosl1086",
|
||||||
|
db_type: "plugin",
|
||||||
|
host: "hktkosl1086.int.kn",
|
||||||
|
port: 22,
|
||||||
|
username: "jinpy.he",
|
||||||
|
password: "",
|
||||||
|
save_password: false,
|
||||||
|
plugin_id: "io.dbx.ssh",
|
||||||
|
plugin_connection_provider: "io.dbx.ssh.connection",
|
||||||
|
plugin_connection_type: "ssh",
|
||||||
|
external_config: { authentication: "private-key", private_key_path: "/Users/dev/.ssh/id_rsa" },
|
||||||
|
read_only: false,
|
||||||
|
...overrides,
|
||||||
|
} as ConnectionConfig;
|
||||||
|
}
|
||||||
|
|
||||||
|
it("connects an SSH key-auth plugin connection without prompting for a password", async () => {
|
||||||
|
installApiMocks({ listPlugins: vi.fn().mockResolvedValue([sshInstalledPlugin()]) });
|
||||||
|
installPasswordPromptMock();
|
||||||
|
const { useConnectionStore } = await import("@/stores/connectionStore");
|
||||||
|
const store = useConnectionStore();
|
||||||
|
const connection = pluginConnection();
|
||||||
|
store.connections = [connection];
|
||||||
|
|
||||||
|
await store.connect(connection);
|
||||||
|
|
||||||
|
expect(requestPassword).not.toHaveBeenCalled();
|
||||||
|
const { connectDb } = await import("@/lib/backend/api");
|
||||||
|
expect(connectDb).toHaveBeenCalledWith(expect.objectContaining({ id: "ssh-1", external_config: expect.objectContaining({ authentication: "private-key" }) }), expect.any(Number));
|
||||||
|
});
|
||||||
|
|
||||||
|
it("still prompts for a plugin connection whose manifest requires the login password", async () => {
|
||||||
|
installApiMocks({ listPlugins: vi.fn().mockResolvedValue([sshInstalledPlugin()]) });
|
||||||
|
installPasswordPromptMock();
|
||||||
|
requestPassword.mockResolvedValue({ password: PROMPT_TYPED_PASSWORD, rememberPassword: false });
|
||||||
|
const { useConnectionStore } = await import("@/stores/connectionStore");
|
||||||
|
const store = useConnectionStore();
|
||||||
|
const connection = pluginConnection({ external_config: { authentication: "password" } });
|
||||||
|
store.connections = [connection];
|
||||||
|
|
||||||
|
await store.connect(connection);
|
||||||
|
|
||||||
|
expect(requestPassword).toHaveBeenCalledWith({ connectionId: "ssh-1", connectionName: "hktkosl1086" });
|
||||||
|
const { connectDb } = await import("@/lib/backend/api");
|
||||||
|
expect(connectDb).toHaveBeenCalledWith(expect.objectContaining({ id: "ssh-1", password: PROMPT_TYPED_PASSWORD }), expect.any(Number));
|
||||||
|
});
|
||||||
|
|
||||||
|
it("does not prompt when the plugin manifest cannot be resolved (backend surfaces the real error)", async () => {
|
||||||
|
installApiMocks({ listPlugins: vi.fn().mockResolvedValue([]) });
|
||||||
|
installPasswordPromptMock();
|
||||||
|
const { useConnectionStore } = await import("@/stores/connectionStore");
|
||||||
|
const store = useConnectionStore();
|
||||||
|
const connection = pluginConnection();
|
||||||
|
store.connections = [connection];
|
||||||
|
|
||||||
|
await store.connect(connection);
|
||||||
|
|
||||||
|
expect(requestPassword).not.toHaveBeenCalled();
|
||||||
|
const { connectDb } = await import("@/lib/backend/api");
|
||||||
|
expect(connectDb).toHaveBeenCalledWith(expect.objectContaining({ id: "ssh-1" }), expect.any(Number));
|
||||||
|
});
|
||||||
|
|
||||||
|
it("falls back to prompting when listing plugins fails", async () => {
|
||||||
|
installApiMocks({ listPlugins: vi.fn().mockRejectedValue(new Error("ipc down")) });
|
||||||
|
installPasswordPromptMock();
|
||||||
|
requestPassword.mockResolvedValue(null);
|
||||||
|
const { useConnectionStore } = await import("@/stores/connectionStore");
|
||||||
|
const store = useConnectionStore();
|
||||||
|
const connection = pluginConnection();
|
||||||
|
store.connections = [connection];
|
||||||
|
|
||||||
|
await expect(store.connect(connection)).rejects.toThrow(CONNECTION_PASSWORD_REQUIRED_MESSAGE);
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -0,0 +1,98 @@
|
|||||||
|
import { createPinia, setActivePinia } from "pinia";
|
||||||
|
import { beforeEach, describe, expect, it, vi } from "vitest";
|
||||||
|
import { useQueryStore } from "@/stores/queryStore";
|
||||||
|
|
||||||
|
describe("queryStore openPluginWorkbench reuse", () => {
|
||||||
|
beforeEach(() => {
|
||||||
|
vi.resetModules();
|
||||||
|
vi.unstubAllGlobals();
|
||||||
|
vi.stubGlobal("localStorage", {
|
||||||
|
getItem: vi.fn(() => null),
|
||||||
|
setItem: vi.fn(),
|
||||||
|
removeItem: vi.fn(),
|
||||||
|
});
|
||||||
|
vi.stubGlobal("window", { dispatchEvent: vi.fn() });
|
||||||
|
setActivePinia(createPinia());
|
||||||
|
});
|
||||||
|
|
||||||
|
it("reopening an open workbench surfaces the tab as-is without replacing its context", async () => {
|
||||||
|
const queryStore = useQueryStore();
|
||||||
|
|
||||||
|
const firstId = queryStore.openPluginWorkbench("io.dbx.ssh", "workbench", {
|
||||||
|
title: "hktkosl1103",
|
||||||
|
connectionId: "conn-1",
|
||||||
|
context: { connectionId: "conn-1", workbenchId: "wb-original" },
|
||||||
|
});
|
||||||
|
|
||||||
|
// A later reopen (e.g. another sidebar click) carries a freshly minted
|
||||||
|
// context; the tab must keep the original one — a replacement would
|
||||||
|
// deep-reload the plugin webview (full flash) and orphan the sidecar
|
||||||
|
// session bound to the original workbench id.
|
||||||
|
const secondId = queryStore.openPluginWorkbench("io.dbx.ssh", "workbench", {
|
||||||
|
title: "hktkosl1103",
|
||||||
|
connectionId: "conn-1",
|
||||||
|
context: { connectionId: "conn-1", workbenchId: "wb-fresh" },
|
||||||
|
});
|
||||||
|
|
||||||
|
expect(secondId).toBe(firstId);
|
||||||
|
expect(queryStore.activeTabId).toBe(firstId);
|
||||||
|
const tab = queryStore.tabs.find((t) => t.id === firstId);
|
||||||
|
expect(tab?.pluginWorkbench?.context).toEqual({ connectionId: "conn-1", workbenchId: "wb-original" });
|
||||||
|
});
|
||||||
|
|
||||||
|
it("a different connection still opens its own workbench tab", () => {
|
||||||
|
const queryStore = useQueryStore();
|
||||||
|
|
||||||
|
const firstId = queryStore.openPluginWorkbench("io.dbx.ssh", "workbench", {
|
||||||
|
connectionId: "conn-1",
|
||||||
|
context: { connectionId: "conn-1", workbenchId: "wb-1" },
|
||||||
|
});
|
||||||
|
const secondId = queryStore.openPluginWorkbench("io.dbx.ssh", "workbench", {
|
||||||
|
connectionId: "conn-2",
|
||||||
|
context: { connectionId: "conn-2", workbenchId: "wb-2" },
|
||||||
|
});
|
||||||
|
|
||||||
|
expect(secondId).not.toBe(firstId);
|
||||||
|
expect(queryStore.tabs).toHaveLength(2);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("registers the workbench tab into the focused group so the group tab strip can render it", () => {
|
||||||
|
const queryStore = useQueryStore();
|
||||||
|
|
||||||
|
const id = queryStore.openPluginWorkbench("io.dbx.ssh", "workbench", {
|
||||||
|
connectionId: "conn-1",
|
||||||
|
context: { connectionId: "conn-1" },
|
||||||
|
});
|
||||||
|
|
||||||
|
// The split workspace renders tab strips from group membership: a tab
|
||||||
|
// pushed straight onto `tabs` stays ownerless and never shows up in any
|
||||||
|
// strip (regression behind "click a sidebar connection, no tab appears").
|
||||||
|
const group = queryStore.groups.find((candidate) => candidate.tabIds.includes(id));
|
||||||
|
expect(group).toBeDefined();
|
||||||
|
expect(group?.activeTabId).toBe(id);
|
||||||
|
expect(queryStore.focusedGroupId).toBe(group?.id);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("adopts a legacy ownerless workbench tab back into the workspace when reopened", () => {
|
||||||
|
const queryStore = useQueryStore();
|
||||||
|
|
||||||
|
const id = queryStore.openPluginWorkbench("io.dbx.ssh", "workbench", {
|
||||||
|
connectionId: "conn-1",
|
||||||
|
context: { connectionId: "conn-1" },
|
||||||
|
});
|
||||||
|
// Simulate a tab created by a pre-registry build (ownerless) or a restore
|
||||||
|
// edge: strip it from its group, then reopen from the sidebar.
|
||||||
|
queryStore.groups = [{ id: "main", tabIds: [], activeTabId: null }];
|
||||||
|
|
||||||
|
const reopenedId = queryStore.openPluginWorkbench("io.dbx.ssh", "workbench", {
|
||||||
|
connectionId: "conn-1",
|
||||||
|
context: { connectionId: "conn-1", workbenchId: "wb-fresh" },
|
||||||
|
});
|
||||||
|
|
||||||
|
expect(reopenedId).toBe(id);
|
||||||
|
expect(queryStore.groups[0]?.tabIds).toContain(id);
|
||||||
|
expect(queryStore.groups[0]?.activeTabId).toBe(id);
|
||||||
|
// Adoption must not replace the live context (same no-deep-reload rule).
|
||||||
|
expect(queryStore.tabs.find((t) => t.id === id)?.pluginWorkbench?.context).toEqual({ connectionId: "conn-1" });
|
||||||
|
});
|
||||||
|
});
|
||||||
+60
@@ -0,0 +1,60 @@
|
|||||||
|
import { createPinia, setActivePinia } from "pinia";
|
||||||
|
import { beforeEach, describe, expect, it, vi } from "vitest";
|
||||||
|
import { useConnectionStore } from "@/stores/connectionStore";
|
||||||
|
import { useQueryStore } from "@/stores/queryStore";
|
||||||
|
|
||||||
|
describe("queryStore plugin tab close disconnects the plugin connection", () => {
|
||||||
|
beforeEach(() => {
|
||||||
|
vi.resetModules();
|
||||||
|
vi.unstubAllGlobals();
|
||||||
|
vi.stubGlobal("localStorage", {
|
||||||
|
getItem: vi.fn(() => null),
|
||||||
|
setItem: vi.fn(),
|
||||||
|
removeItem: vi.fn(),
|
||||||
|
});
|
||||||
|
vi.stubGlobal("window", {
|
||||||
|
dispatchEvent: vi.fn(),
|
||||||
|
setTimeout: globalThis.setTimeout.bind(globalThis),
|
||||||
|
clearTimeout: globalThis.clearTimeout.bind(globalThis),
|
||||||
|
});
|
||||||
|
setActivePinia(createPinia());
|
||||||
|
});
|
||||||
|
|
||||||
|
it("disconnects the plugin connection when its last plugin tab closes", async () => {
|
||||||
|
const queryStore = useQueryStore();
|
||||||
|
const connectionStore = useConnectionStore();
|
||||||
|
const disconnectSpy = vi.spyOn(connectionStore, "disconnect").mockResolvedValue();
|
||||||
|
|
||||||
|
const id = queryStore.openPluginWorkbench("io.dbx.ssh", "workbench", { connectionId: "conn-1", context: { connectionId: "conn-1" } });
|
||||||
|
queryStore.closeTab(id);
|
||||||
|
|
||||||
|
await vi.waitFor(() => expect(disconnectSpy).toHaveBeenCalledTimes(1));
|
||||||
|
expect(disconnectSpy).toHaveBeenCalledWith("conn-1");
|
||||||
|
});
|
||||||
|
|
||||||
|
it("keeps the plugin connection while another plugin tab for it stays open", async () => {
|
||||||
|
const queryStore = useQueryStore();
|
||||||
|
const connectionStore = useConnectionStore();
|
||||||
|
const disconnectSpy = vi.spyOn(connectionStore, "disconnect").mockResolvedValue();
|
||||||
|
|
||||||
|
// Workbench + filesystem tab riding the same connection (e.g. SSH terminal + SFTP).
|
||||||
|
const workbenchId = queryStore.openPluginWorkbench("io.dbx.ssh", "workbench", { connectionId: "conn-1", context: { connectionId: "conn-1" } });
|
||||||
|
queryStore.openPluginFilesystem("io.dbx.ssh", "fs", { connectionId: "conn-1", rootUri: "sftp:/" });
|
||||||
|
|
||||||
|
queryStore.closeTab(workbenchId);
|
||||||
|
await new Promise((resolve) => setTimeout(resolve, 20));
|
||||||
|
expect(disconnectSpy).not.toHaveBeenCalled();
|
||||||
|
});
|
||||||
|
|
||||||
|
it("does not disconnect non-plugin connections when a regular tab closes", async () => {
|
||||||
|
const queryStore = useQueryStore();
|
||||||
|
const connectionStore = useConnectionStore();
|
||||||
|
const disconnectSpy = vi.spyOn(connectionStore, "disconnect").mockResolvedValue();
|
||||||
|
|
||||||
|
const id = queryStore.createTab("pg-1", "app", "Query 1", "query");
|
||||||
|
queryStore.closeTab(id);
|
||||||
|
|
||||||
|
await new Promise((resolve) => setTimeout(resolve, 20));
|
||||||
|
expect(disconnectSpy).not.toHaveBeenCalled();
|
||||||
|
});
|
||||||
|
});
|
||||||
+68
@@ -0,0 +1,68 @@
|
|||||||
|
import { createPinia, setActivePinia } from "pinia";
|
||||||
|
import { beforeEach, describe, expect, it, vi } from "vitest";
|
||||||
|
import { useQueryStore } from "@/stores/queryStore";
|
||||||
|
|
||||||
|
// Boot-time tab restore replays only tab metadata; the sidecar connection
|
||||||
|
// registry starts empty after a host restart, so restored plugin tabs need
|
||||||
|
// the connect lifecycle replayed (see reconnectRestoredPluginTabs).
|
||||||
|
const ensureConnected = vi.fn(async () => undefined);
|
||||||
|
|
||||||
|
vi.mock("@/stores/connectionStore", () => ({
|
||||||
|
useConnectionStore: () => ({
|
||||||
|
getConfig: (id: string) => (id === "conn-sql" ? { id, db_type: "mysql" } : { id, db_type: "plugin" }),
|
||||||
|
ensureConnected,
|
||||||
|
}),
|
||||||
|
}));
|
||||||
|
|
||||||
|
describe("queryStore reconnectRestoredPluginTabs", () => {
|
||||||
|
beforeEach(() => {
|
||||||
|
vi.resetModules();
|
||||||
|
vi.unstubAllGlobals();
|
||||||
|
vi.stubGlobal("localStorage", {
|
||||||
|
getItem: vi.fn(() => null),
|
||||||
|
setItem: vi.fn(),
|
||||||
|
removeItem: vi.fn(),
|
||||||
|
});
|
||||||
|
vi.stubGlobal("window", { dispatchEvent: vi.fn() });
|
||||||
|
setActivePinia(createPinia());
|
||||||
|
ensureConnected.mockClear();
|
||||||
|
ensureConnected.mockImplementation(async () => undefined);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("replays ensureConnected once per distinct plugin connection, active tab first", async () => {
|
||||||
|
const queryStore = useQueryStore();
|
||||||
|
queryStore.openPluginWorkbench("io.dbx.ssh", "workbench", { connectionId: "conn-1", context: { connectionId: "conn-1" } });
|
||||||
|
queryStore.openPluginFilesystem("io.dbx.files", "files", { connectionId: "conn-1" });
|
||||||
|
// A non-plugin tab must not participate in the replay.
|
||||||
|
queryStore.openPluginWorkbench("io.dbx.ssh", "workbench", { connectionId: "conn-sql", context: { connectionId: "conn-sql" } });
|
||||||
|
const activeTabId = queryStore.openPluginWorkbench("io.dbx.ssh", "workbench", { connectionId: "conn-2", context: { connectionId: "conn-2" } });
|
||||||
|
queryStore.activeTabId = activeTabId;
|
||||||
|
|
||||||
|
await queryStore.reconnectRestoredPluginTabs();
|
||||||
|
|
||||||
|
// conn-2 owns the active tab (last open won) so it is replayed first;
|
||||||
|
// activate:false keeps boot restore from stealing the active connection.
|
||||||
|
expect(ensureConnected.mock.calls.map((call) => call[0])).toEqual(["conn-2", "conn-1"]);
|
||||||
|
expect(ensureConnected).toHaveBeenCalledWith("conn-1", { activate: false });
|
||||||
|
});
|
||||||
|
|
||||||
|
it("a per-connection failure does not abort the remaining replays", async () => {
|
||||||
|
const queryStore = useQueryStore();
|
||||||
|
queryStore.openPluginWorkbench("io.dbx.ssh", "workbench", { connectionId: "conn-1", context: { connectionId: "conn-1" } });
|
||||||
|
queryStore.openPluginWorkbench("io.dbx.ldap", "workbench", { connectionId: "conn-2", context: { connectionId: "conn-2" } });
|
||||||
|
ensureConnected.mockImplementation(async (id: string) => {
|
||||||
|
if (id === "conn-1") throw new Error("password prompt cancelled");
|
||||||
|
});
|
||||||
|
|
||||||
|
await expect(queryStore.reconnectRestoredPluginTabs()).resolves.toBeUndefined();
|
||||||
|
expect(ensureConnected).toHaveBeenCalledTimes(2);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("no plugin tabs means no replay", async () => {
|
||||||
|
const queryStore = useQueryStore();
|
||||||
|
|
||||||
|
await queryStore.reconnectRestoredPluginTabs();
|
||||||
|
|
||||||
|
expect(ensureConnected).not.toHaveBeenCalled();
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -148,7 +148,8 @@ import { normalizeRedisDatabaseAliases, redisDatabaseAlias, redisDatabaseLabel }
|
|||||||
import { normalizeRedisKeyTemplates } from "@/lib/redis/redisKeyTemplates";
|
import { normalizeRedisKeyTemplates } from "@/lib/redis/redisKeyTemplates";
|
||||||
import { appendAgentDriverUpdateHint, connectionUsesSsh, hasAgentDriverUpdate, hasInstalledAgentVersion, type AgentDriverInstallState } from "@/lib/connection/agentDriverInstallHint";
|
import { appendAgentDriverUpdateHint, connectionUsesSsh, hasAgentDriverUpdate, hasInstalledAgentVersion, type AgentDriverInstallState } from "@/lib/connection/agentDriverInstallHint";
|
||||||
import { appendConnectionErrorHints, isMysqlMissingPasswordFailure, isSqliteMissingEncryptionPasswordFailure } from "@/lib/connection/connectionErrorHints";
|
import { appendConnectionErrorHints, isMysqlMissingPasswordFailure, isSqliteMissingEncryptionPasswordFailure } from "@/lib/connection/connectionErrorHints";
|
||||||
import { connectionNeedsPasswordPrompt } from "@/lib/connection/connectionPassword";
|
import { connectionNeedsPasswordPrompt, pluginConnectionNeedsPasswordPrompt } from "@/lib/connection/connectionPassword";
|
||||||
|
import { createFrontendPluginRegistry } from "@/lib/plugins/frontendPlugin";
|
||||||
import { appendVisibleDatabaseSelection } from "@/lib/connection/connectionVisibleDatabases";
|
import { appendVisibleDatabaseSelection } from "@/lib/connection/connectionVisibleDatabases";
|
||||||
import { buildXuguTypeMemberNodes, isXuguTypeMemberContainer } from "@/lib/sidebar/xuguTypeMembers";
|
import { buildXuguTypeMemberNodes, isXuguTypeMemberContainer } from "@/lib/sidebar/xuguTypeMembers";
|
||||||
import { isXuguPublicSynonymScope, isXuguSchedulerJobScope, isXuguSyntheticScope, sortXuguSchemaInfos, xuguSchemaDisplayName, XUGU_PUBLIC_SYNONYM_SCOPE, XUGU_SCHEDULER_JOB_SCOPE } from "@/lib/sidebar/xuguPublicSynonyms";
|
import { isXuguPublicSynonymScope, isXuguSchedulerJobScope, isXuguSyntheticScope, sortXuguSchemaInfos, xuguSchemaDisplayName, XUGU_PUBLIC_SYNONYM_SCOPE, XUGU_SCHEDULER_JOB_SCOPE } from "@/lib/sidebar/xuguPublicSynonyms";
|
||||||
@@ -168,7 +169,7 @@ import { MetadataTaskLimiter } from "@/lib/metadata/metadataTaskLimiter";
|
|||||||
import { buildCustomTypeTreeChildren } from "@/lib/sidebar/customTypeTree";
|
import { buildCustomTypeTreeChildren } from "@/lib/sidebar/customTypeTree";
|
||||||
import { TreeNodeLoadRegistry, type TreeNodeLoadHandle } from "@/lib/metadata/treeNodeLoadHandle";
|
import { TreeNodeLoadRegistry, type TreeNodeLoadHandle } from "@/lib/metadata/treeNodeLoadHandle";
|
||||||
import { buildXuguTablespaceChildren } from "@/lib/sidebar/xuguTablespaces";
|
import { buildXuguTablespaceChildren } from "@/lib/sidebar/xuguTablespaces";
|
||||||
import i18n from "@/i18n";
|
import i18n, { currentLocale } from "@/i18n";
|
||||||
import type { MqAdminConfig } from "@/types/mq";
|
import type { MqAdminConfig } from "@/types/mq";
|
||||||
import { RABBITMQ_MQ_TENANT, resolveMqSystemKindFromConnection } from "@/lib/mq/mqConsoleDefaults";
|
import { RABBITMQ_MQ_TENANT, resolveMqSystemKindFromConnection } from "@/lib/mq/mqConsoleDefaults";
|
||||||
import { applySidebarDatabaseStorage, applySidebarTableStorage, sidebarDatabaseNames, supportsSidebarDatabaseStorage, supportsSidebarTableStorage, type SidebarTableStorageScope } from "@/lib/sidebar/sidebarDatabaseStorage";
|
import { applySidebarDatabaseStorage, applySidebarTableStorage, sidebarDatabaseNames, supportsSidebarDatabaseStorage, supportsSidebarTableStorage, type SidebarTableStorageScope } from "@/lib/sidebar/sidebarDatabaseStorage";
|
||||||
@@ -1024,6 +1025,11 @@ export const useConnectionStore = defineStore("connection", () => {
|
|||||||
return disconnectInFlightScoped.get(connectionId) ? undefined : disconnectInFlight.get(connectionId);
|
return disconnectInFlightScoped.get(connectionId) ? undefined : disconnectInFlight.get(connectionId);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/** True while any disconnect for the connection is in flight (full or scoped). */
|
||||||
|
function hasDisconnectInFlight(connectionId: string): boolean {
|
||||||
|
return disconnectInFlight.has(connectionId);
|
||||||
|
}
|
||||||
|
|
||||||
async function waitForBlockingDisconnectInFlight(connectionId: string): Promise<void> {
|
async function waitForBlockingDisconnectInFlight(connectionId: string): Promise<void> {
|
||||||
const pending = getBlockingDisconnectInFlight(connectionId);
|
const pending = getBlockingDisconnectInFlight(connectionId);
|
||||||
if (pending) await pending;
|
if (pending) await pending;
|
||||||
@@ -4035,6 +4041,31 @@ export const useConnectionStore = defineStore("connection", () => {
|
|||||||
return { config: { ...config, password: result.password }, rememberPassword: result.rememberPassword };
|
return { config: { ...config, password: result.password }, rememberPassword: result.rememberPassword };
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Manifest re-check for plugin connections that the save_password heuristic
|
||||||
|
* already flagged. The prompt can only fill the `password`-bound field, so
|
||||||
|
* when the manifest does not require it for the connection's external_config
|
||||||
|
* (SSH private-key / agent auth), connecting proceeds without prompting
|
||||||
|
* instead of failing with "Password is required". Non-plugin configs always
|
||||||
|
* prompt (the heuristic decided already). Callers must evaluate
|
||||||
|
* `connectionNeedsPasswordPrompt` synchronously first so the common
|
||||||
|
* no-prompt path keeps its microtask cadence.
|
||||||
|
*/
|
||||||
|
async function pluginConnectionPasswordPromptNeeded(config: ConnectionConfig): Promise<boolean> {
|
||||||
|
if (config.db_type !== "plugin") return true;
|
||||||
|
if (!config.plugin_id || !config.plugin_connection_provider) return false;
|
||||||
|
try {
|
||||||
|
const registry = createFrontendPluginRegistry(await api.listPlugins(), currentLocale());
|
||||||
|
const provider = registry.listConnectionProviders().find((entry) => entry.plugin.manifest.id === config.plugin_id && entry.contribution.id === config.plugin_connection_provider);
|
||||||
|
if (!provider) return false;
|
||||||
|
return pluginConnectionNeedsPasswordPrompt(provider.contribution.fields, config.external_config);
|
||||||
|
} catch {
|
||||||
|
// Manifest unavailable: keep the pre-manifest behavior (prompt) instead of
|
||||||
|
// silently connecting a connection that may genuinely need a password.
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
async function persistRememberedConnectionPassword(config: ConnectionConfig, rememberPassword: boolean, expectedConfigFingerprint: string): Promise<void> {
|
async function persistRememberedConnectionPassword(config: ConnectionConfig, rememberPassword: boolean, expectedConfigFingerprint: string): Promise<void> {
|
||||||
if (!rememberPassword) return;
|
if (!rememberPassword) return;
|
||||||
const index = connections.value.findIndex((connection) => connection.id === config.id);
|
const index = connections.value.findIndex((connection) => connection.id === config.id);
|
||||||
@@ -4073,7 +4104,7 @@ export const useConnectionStore = defineStore("connection", () => {
|
|||||||
const localAttempt = beginLocalConnectionAttempt(config.id);
|
const localAttempt = beginLocalConnectionAttempt(config.id);
|
||||||
try {
|
try {
|
||||||
let rememberPassword = false;
|
let rememberPassword = false;
|
||||||
if (connectionNeedsPasswordPrompt(config) && !(await hasSessionCredential(config.id))) {
|
if (connectionNeedsPasswordPrompt(config) && (await pluginConnectionPasswordPromptNeeded(config)) && !(await hasSessionCredential(config.id))) {
|
||||||
const prompted = await ensureConnectionPassword(config);
|
const prompted = await ensureConnectionPassword(config);
|
||||||
config = prompted.config;
|
config = prompted.config;
|
||||||
rememberPassword = prompted.rememberPassword;
|
rememberPassword = prompted.rememberPassword;
|
||||||
@@ -4168,6 +4199,21 @@ export const useConnectionStore = defineStore("connection", () => {
|
|||||||
return true;
|
return true;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Marks a connection offline in the sidebar without the full teardown that
|
||||||
|
* `disconnect` performs (no tab closing, no pool teardown). Used when a
|
||||||
|
* plugin reports its live session died (e.g. `ssh/session/state
|
||||||
|
* disconnected`) so the tree reflects the real transport state.
|
||||||
|
*/
|
||||||
|
function markConnectionOffline(connectionId: string) {
|
||||||
|
connectedIds.value.delete(connectionId);
|
||||||
|
const node = findConnectionNode(connectionId);
|
||||||
|
if (node) {
|
||||||
|
node.isLoading = false;
|
||||||
|
}
|
||||||
|
clearConnectionHealthCheck(connectionId);
|
||||||
|
}
|
||||||
|
|
||||||
async function disconnect(connectionId: string) {
|
async function disconnect(connectionId: string) {
|
||||||
const stateRevision = bumpConnectionStateRevision(connectionId);
|
const stateRevision = bumpConnectionStateRevision(connectionId);
|
||||||
const shouldRemoveOneTimeConnection = getConfig(connectionId)?.one_time === true;
|
const shouldRemoveOneTimeConnection = getConfig(connectionId)?.one_time === true;
|
||||||
@@ -4336,7 +4382,7 @@ export const useConnectionStore = defineStore("connection", () => {
|
|||||||
// Fast-path the common case (password saved or no password needed) so the
|
// Fast-path the common case (password saved or no password needed) so the
|
||||||
// in-flight dedup above keeps its exact microtask cadence; only await the
|
// in-flight dedup above keeps its exact microtask cadence; only await the
|
||||||
// interactive prompt when the connection actually needs a typed password.
|
// interactive prompt when the connection actually needs a typed password.
|
||||||
if (connectionNeedsPasswordPrompt(config) && !(await hasSessionCredential(connectionId))) {
|
if (connectionNeedsPasswordPrompt(config) && (await pluginConnectionPasswordPromptNeeded(config)) && !(await hasSessionCredential(connectionId))) {
|
||||||
const prompted = await ensureConnectionPassword(config);
|
const prompted = await ensureConnectionPassword(config);
|
||||||
config = prompted.config;
|
config = prompted.config;
|
||||||
rememberPassword = prompted.rememberPassword;
|
rememberPassword = prompted.rememberPassword;
|
||||||
@@ -9243,6 +9289,8 @@ export const useConnectionStore = defineStore("connection", () => {
|
|||||||
connect,
|
connect,
|
||||||
cancelConnecting,
|
cancelConnecting,
|
||||||
disconnect,
|
disconnect,
|
||||||
|
hasDisconnectInFlight,
|
||||||
|
markConnectionOffline,
|
||||||
metadataGenerationFor,
|
metadataGenerationFor,
|
||||||
disconnectAndForgetConnectionPassword,
|
disconnectAndForgetConnectionPassword,
|
||||||
hasSessionCredential,
|
hasSessionCredential,
|
||||||
|
|||||||
@@ -3398,7 +3398,16 @@ export const useQueryStore = defineStore("query", () => {
|
|||||||
if (!options.forceNew) {
|
if (!options.forceNew) {
|
||||||
const existing = tabs.value.find((tab) => tab.mode === "plugin-workbench" && tab.pluginWorkbench?.pluginId === pluginId && tab.pluginWorkbench?.contributionId === contributionId && tab.connectionId === (options.connectionId || ""));
|
const existing = tabs.value.find((tab) => tab.mode === "plugin-workbench" && tab.pluginWorkbench?.pluginId === pluginId && tab.pluginWorkbench?.contributionId === contributionId && tab.connectionId === (options.connectionId || ""));
|
||||||
if (existing) {
|
if (existing) {
|
||||||
if (options.context) existing.pluginWorkbench = { ...existing.pluginWorkbench!, context: snapshotPluginWorkbenchContext(options.context) };
|
// Reopening surfaces the existing tab as-is. Replacing the context
|
||||||
|
// here (openPluginConnection mints a fresh workbenchId per click)
|
||||||
|
// would deep-reload the plugin webview — a full flash plus losing
|
||||||
|
// the sidecar session binding on the old workbench id.
|
||||||
|
// A tab created by an older build (or otherwise unregistered) may
|
||||||
|
// still be ownerless; land it in the workspace or the group-rendered
|
||||||
|
// tab strips can never show it.
|
||||||
|
if (!groupForTab(existing.id)) {
|
||||||
|
ensureTabInWorkspace(existing.id);
|
||||||
|
}
|
||||||
switchTab(existing.id);
|
switchTab(existing.id);
|
||||||
return existing.id;
|
return existing.id;
|
||||||
}
|
}
|
||||||
@@ -3421,6 +3430,9 @@ export const useQueryStore = defineStore("query", () => {
|
|||||||
context: options.context ? snapshotPluginWorkbenchContext(options.context) : undefined,
|
context: options.context ? snapshotPluginWorkbenchContext(options.context) : undefined,
|
||||||
},
|
},
|
||||||
};
|
};
|
||||||
|
// The split workspace renders strips from group membership — always go
|
||||||
|
// through registerOpenTab so the tab joins the focused group (raw push
|
||||||
|
// left it ownerless and invisible in every tab strip).
|
||||||
return registerOpenTab(tab);
|
return registerOpenTab(tab);
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -3429,6 +3441,9 @@ export const useQueryStore = defineStore("query", () => {
|
|||||||
const existing = tabs.value.find((tab) => tab.mode === "plugin-filesystem" && tab.pluginFilesystem?.pluginId === pluginId && tab.pluginFilesystem?.providerId === providerId && tab.connectionId === (options.connectionId || ""));
|
const existing = tabs.value.find((tab) => tab.mode === "plugin-filesystem" && tab.pluginFilesystem?.pluginId === pluginId && tab.pluginFilesystem?.providerId === providerId && tab.connectionId === (options.connectionId || ""));
|
||||||
if (existing) {
|
if (existing) {
|
||||||
if (options.currentUri) existing.pluginFilesystem = { ...existing.pluginFilesystem!, currentUri: options.currentUri };
|
if (options.currentUri) existing.pluginFilesystem = { ...existing.pluginFilesystem!, currentUri: options.currentUri };
|
||||||
|
if (!groupForTab(existing.id)) {
|
||||||
|
ensureTabInWorkspace(existing.id);
|
||||||
|
}
|
||||||
switchTab(existing.id);
|
switchTab(existing.id);
|
||||||
return existing.id;
|
return existing.id;
|
||||||
}
|
}
|
||||||
@@ -3475,6 +3490,15 @@ export const useQueryStore = defineStore("query", () => {
|
|||||||
connectionId,
|
connectionId,
|
||||||
providerId,
|
providerId,
|
||||||
connectionType: connection.plugin_connection_type,
|
connectionType: connection.plugin_connection_type,
|
||||||
|
workbenchId: crypto.randomUUID(),
|
||||||
|
connection: {
|
||||||
|
id: connection.id,
|
||||||
|
name: connection.name,
|
||||||
|
host: connection.host,
|
||||||
|
port: connection.port,
|
||||||
|
username: connection.username,
|
||||||
|
readOnly: false,
|
||||||
|
},
|
||||||
},
|
},
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
@@ -3482,12 +3506,44 @@ export const useQueryStore = defineStore("query", () => {
|
|||||||
const filesystem = filesystemProviderId ? registry.listFilesystemProviders().find((entry) => entry.plugin.manifest.id === pluginId && entry.contribution.id === filesystemProviderId) : undefined;
|
const filesystem = filesystemProviderId ? registry.listFilesystemProviders().find((entry) => entry.plugin.manifest.id === pluginId && entry.contribution.id === filesystemProviderId) : undefined;
|
||||||
if (!filesystem) throw new Error(`Plugin connection provider '${pluginId}/${providerId}' does not declare a workbench or filesystem provider`);
|
if (!filesystem) throw new Error(`Plugin connection provider '${pluginId}/${providerId}' does not declare a workbench or filesystem provider`);
|
||||||
return openPluginFilesystem(pluginId, filesystem.contribution.id, {
|
return openPluginFilesystem(pluginId, filesystem.contribution.id, {
|
||||||
title: connection.name,
|
title: `${connection.name} · SFTP`,
|
||||||
connectionId,
|
connectionId,
|
||||||
rootUri: filesystem.contribution.root_uri,
|
rootUri: filesystem.contribution.root_uri,
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Boot-time tab restore only replays tab metadata: after a host restart the
|
||||||
|
* sidecar's in-memory connection registry starts empty (credentials are
|
||||||
|
* injected per connect via `connection/connect`), so a restored plugin
|
||||||
|
* workbench/filesystem tab fails its first session/open with "Connection is
|
||||||
|
* not active" until the user reopens the connection from the sidebar. Replay
|
||||||
|
* the connect lifecycle for every distinct restored plugin connection —
|
||||||
|
* fire-and-forget so an interactive password prompt or a slow sidecar spawn
|
||||||
|
* never blocks startup; per-connection failures surface in the tab's own UI.
|
||||||
|
*/
|
||||||
|
async function reconnectRestoredPluginTabs() {
|
||||||
|
const connectionStore = useConnectionStore();
|
||||||
|
const activeConnectionId = tabs.value.find((tab) => tab.id === activeTabId.value)?.connectionId;
|
||||||
|
const orderedIds: string[] = [];
|
||||||
|
for (const tab of tabs.value) {
|
||||||
|
if (tab.mode !== "plugin-workbench" && tab.mode !== "plugin-filesystem") continue;
|
||||||
|
if (!tab.connectionId || orderedIds.includes(tab.connectionId)) continue;
|
||||||
|
if (tab.connectionId === activeConnectionId) orderedIds.unshift(tab.connectionId);
|
||||||
|
else orderedIds.push(tab.connectionId);
|
||||||
|
}
|
||||||
|
for (const connectionId of orderedIds) {
|
||||||
|
if (connectionStore.getConfig(connectionId)?.db_type !== "plugin") continue;
|
||||||
|
try {
|
||||||
|
// activate:false keeps the boot restore from overriding the last
|
||||||
|
// active connection already chosen by restoreActiveConnectionContext().
|
||||||
|
await connectionStore.ensureConnected(connectionId, { activate: false });
|
||||||
|
} catch (error) {
|
||||||
|
console.warn("[DBX][plugin-tab-restore:reconnect]", connectionId, error);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
function applyTableStructureInitialTab(tab: QueryTab, initialTab?: TableInfoTab, initialTarget?: TableStructureEditorTarget) {
|
function applyTableStructureInitialTab(tab: QueryTab, initialTab?: TableInfoTab, initialTarget?: TableStructureEditorTarget) {
|
||||||
if (!initialTab && !initialTarget?.name) return;
|
if (!initialTab && !initialTarget?.name) return;
|
||||||
if (initialTab) tab.structureInitialTab = initialTab;
|
if (initialTab) tab.structureInitialTab = initialTab;
|
||||||
@@ -3790,6 +3846,39 @@ export const useQueryStore = defineStore("query", () => {
|
|||||||
continuePendingBatchClose();
|
continuePendingBatchClose();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
const pluginReleaseInFlight = new Set<string>();
|
||||||
|
/**
|
||||||
|
* Closing the last plugin tab (workbench or filesystem) bound to a plugin
|
||||||
|
* connection ends that connection: the sidecar session has no remaining
|
||||||
|
* owner, so disconnecting tears the pool down and drops the sidebar's
|
||||||
|
* "connected" dot. Fire-and-forget; concurrent releases for the same
|
||||||
|
* connection coalesce, and a reopen racing the release wins.
|
||||||
|
*/
|
||||||
|
function releasePluginConnectionsAfterClose(closedTabs: ReadonlyArray<QueryTab>) {
|
||||||
|
const connectionIds = new Set(closedTabs.filter((tab) => (tab.mode === "plugin-workbench" || tab.mode === "plugin-filesystem") && tab.connectionId).map((tab) => tab.connectionId));
|
||||||
|
for (const connectionId of connectionIds) {
|
||||||
|
if (pluginReleaseInFlight.has(connectionId)) continue;
|
||||||
|
pluginReleaseInFlight.add(connectionId);
|
||||||
|
void (async () => {
|
||||||
|
try {
|
||||||
|
// Yield one microtask so a same-tick reopen registers its
|
||||||
|
// replacement plugin tab before we tear the connection down.
|
||||||
|
await Promise.resolve();
|
||||||
|
if (tabs.value.some((tab) => (tab.mode === "plugin-workbench" || tab.mode === "plugin-filesystem") && tab.connectionId === connectionId)) return;
|
||||||
|
const connectionStore = useConnectionStore();
|
||||||
|
// A user-initiated disconnect that closed these tabs already owns
|
||||||
|
// the teardown — don't stack a second one on top of it.
|
||||||
|
if (connectionStore.hasDisconnectInFlight(connectionId)) return;
|
||||||
|
await connectionStore.disconnect(connectionId);
|
||||||
|
} catch (error) {
|
||||||
|
console.warn("[DBX][plugin-tab-close:disconnect]", connectionId, error);
|
||||||
|
} finally {
|
||||||
|
pluginReleaseInFlight.delete(connectionId);
|
||||||
|
}
|
||||||
|
})();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
function closeTab(id: string, { force = false }: { force?: boolean } = {}) {
|
function closeTab(id: string, { force = false }: { force?: boolean } = {}) {
|
||||||
const tab = tabs.value.find((t) => t.id === id);
|
const tab = tabs.value.find((t) => t.id === id);
|
||||||
if (!tab) return;
|
if (!tab) return;
|
||||||
@@ -3822,6 +3911,7 @@ export const useQueryStore = defineStore("query", () => {
|
|||||||
const wasGlobalActive = activeTabId.value === id;
|
const wasGlobalActive = activeTabId.value === id;
|
||||||
|
|
||||||
tabs.value.splice(idx, 1);
|
tabs.value.splice(idx, 1);
|
||||||
|
releasePluginConnectionsAfterClose([tab]);
|
||||||
if (tab.externalSqlPath) refreshExternalSqlFileTitles();
|
if (tab.externalSqlPath) refreshExternalSqlFileTitles();
|
||||||
|
|
||||||
if (owner) {
|
if (owner) {
|
||||||
@@ -4161,29 +4251,29 @@ export const useQueryStore = defineStore("query", () => {
|
|||||||
const closingIds = new Set(tabs.value.filter((tab) => predicate(tab)).map((tab) => tab.id));
|
const closingIds = new Set(tabs.value.filter((tab) => predicate(tab)).map((tab) => tab.id));
|
||||||
if (closingIds.size === 0) return;
|
if (closingIds.size === 0) return;
|
||||||
|
|
||||||
tabs.value
|
const closingTabs = tabs.value.filter((tab) => closingIds.has(tab.id));
|
||||||
.filter((tab) => closingIds.has(tab.id))
|
closingTabs.forEach((tab) => {
|
||||||
.forEach((tab) => {
|
if (tab.mode === "sqlserver-trace") void disposeSqlServerActivityTrace(tab.id);
|
||||||
if (tab.mode === "sqlserver-trace") void disposeSqlServerActivityTrace(tab.id);
|
clearDataGridPendingSnapshotsForTab(tab.id);
|
||||||
clearDataGridPendingSnapshotsForTab(tab.id);
|
beginClosingDataGridViewSnapshotsForTab(tab.id);
|
||||||
beginClosingDataGridViewSnapshotsForTab(tab.id);
|
beginClosingBrowserState(tab.id);
|
||||||
beginClosingBrowserState(tab.id);
|
clearDataGridStructuredFilterStatesForTab(tab.id);
|
||||||
clearDataGridStructuredFilterStatesForTab(tab.id);
|
clearDataGridSearchStatesForTab(tab.id);
|
||||||
clearDataGridSearchStatesForTab(tab.id);
|
if (tab.txnSessionId) void rollbackTransaction(tab.id);
|
||||||
if (tab.txnSessionId) void rollbackTransaction(tab.id);
|
if (tab.isExecuting) void cancelTabExecution(tab.id);
|
||||||
if (tab.isExecuting) void cancelTabExecution(tab.id);
|
if (tab.isExplaining) void cancelTabExplain(tab.id);
|
||||||
if (tab.isExplaining) void cancelTabExplain(tab.id);
|
void closeResultSession(tab);
|
||||||
void closeResultSession(tab);
|
void closeClientConnectionSession(tab);
|
||||||
void closeClientConnectionSession(tab);
|
clearResultRunSnapshots(tab);
|
||||||
clearResultRunSnapshots(tab);
|
void deleteTabResultSnapshot(tabResultCacheKey(tab.id));
|
||||||
void deleteTabResultSnapshot(tabResultCacheKey(tab.id));
|
releaseTabResultObjectPayloads(tab);
|
||||||
releaseTabResultObjectPayloads(tab);
|
clearResultRuns(tab);
|
||||||
clearResultRuns(tab);
|
clearResultPayload(tab);
|
||||||
clearResultPayload(tab);
|
});
|
||||||
});
|
|
||||||
|
|
||||||
const activeClosingIndex = tabs.value.findIndex((tab) => tab.id === activeTabId.value && closingIds.has(tab.id));
|
const activeClosingIndex = tabs.value.findIndex((tab) => tab.id === activeTabId.value && closingIds.has(tab.id));
|
||||||
tabs.value = tabs.value.filter((tab) => !closingIds.has(tab.id));
|
tabs.value = tabs.value.filter((tab) => !closingIds.has(tab.id));
|
||||||
|
releasePluginConnectionsAfterClose(closingTabs);
|
||||||
// Resolve the fallback against the POST-filter array: the survivor at the
|
// Resolve the fallback against the POST-filter array: the survivor at the
|
||||||
// closing tab's index, not the closing tab itself.
|
// closing tab's index, not the closing tab itself.
|
||||||
const fallbackTabId = activeClosingIndex >= 0 ? tabs.value[Math.min(activeClosingIndex, tabs.value.length - 1)]?.id : undefined;
|
const fallbackTabId = activeClosingIndex >= 0 ? tabs.value[Math.min(activeClosingIndex, tabs.value.length - 1)]?.id : undefined;
|
||||||
@@ -8492,10 +8582,11 @@ export const useQueryStore = defineStore("query", () => {
|
|||||||
openMqAdmin,
|
openMqAdmin,
|
||||||
openMqttAdmin,
|
openMqttAdmin,
|
||||||
openNacosAdmin,
|
openNacosAdmin,
|
||||||
clearNacosNavigationTarget,
|
|
||||||
openPluginWorkbench,
|
openPluginWorkbench,
|
||||||
openPluginFilesystem,
|
openPluginFilesystem,
|
||||||
|
reconnectRestoredPluginTabs,
|
||||||
openPluginConnection,
|
openPluginConnection,
|
||||||
|
clearNacosNavigationTarget,
|
||||||
openTableStructure,
|
openTableStructure,
|
||||||
linkSavedSql,
|
linkSavedSql,
|
||||||
linkExternalSqlPath,
|
linkExternalSqlPath,
|
||||||
|
|||||||
@@ -269,11 +269,29 @@ export type PluginFormFieldBinding = "config" | "secret" | "name" | "host" | "po
|
|||||||
|
|
||||||
export type PluginFormFieldValue = string | number | boolean | undefined;
|
export type PluginFormFieldValue = string | number | boolean | undefined;
|
||||||
|
|
||||||
|
export interface LocalSshKey {
|
||||||
|
/** Absolute path to the private key file. */
|
||||||
|
path: string;
|
||||||
|
/** SSH algorithm name (e.g. `ssh-ed25519`); empty when undetectable. */
|
||||||
|
algorithm: string;
|
||||||
|
/** SHA-256 fingerprint (`SHA256:...`); empty when the key could not be decoded. */
|
||||||
|
fingerprint: string;
|
||||||
|
/** Heuristic: the key looks passphrase-protected. */
|
||||||
|
hasPassphrase: boolean;
|
||||||
|
}
|
||||||
|
|
||||||
export interface PluginFormFieldOption {
|
export interface PluginFormFieldOption {
|
||||||
label: string;
|
label: string;
|
||||||
value: string;
|
value: string;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
export interface PluginFieldCondition {
|
||||||
|
/** Key of another plugin form field whose current value drives the condition. */
|
||||||
|
field: string;
|
||||||
|
/** The condition matches when the referenced field's value is in this list. */
|
||||||
|
one_of: string[];
|
||||||
|
}
|
||||||
|
|
||||||
export interface PluginFormField {
|
export interface PluginFormField {
|
||||||
key: string;
|
key: string;
|
||||||
label: string;
|
label: string;
|
||||||
@@ -283,7 +301,12 @@ export interface PluginFormField {
|
|||||||
required?: boolean;
|
required?: boolean;
|
||||||
default?: PluginFormFieldValue;
|
default?: PluginFormFieldValue;
|
||||||
options?: PluginFormFieldOption[];
|
options?: PluginFormFieldOption[];
|
||||||
|
/** Plugin method returning `{ options: [{ value, label }] }` for dynamic
|
||||||
|
* select rendering; falls back to the declared type when unavailable. */
|
||||||
|
options_action?: string;
|
||||||
binding?: PluginFormFieldBinding;
|
binding?: PluginFormFieldBinding;
|
||||||
|
visible_when?: PluginFieldCondition;
|
||||||
|
required_when?: PluginFieldCondition;
|
||||||
}
|
}
|
||||||
|
|
||||||
export type PluginConnectionCapability = "test" | "connect" | "disconnect";
|
export type PluginConnectionCapability = "test" | "connect" | "disconnect";
|
||||||
|
|||||||
@@ -83,4 +83,4 @@ export const DATABASE_TYPES = [
|
|||||||
"plugin",
|
"plugin",
|
||||||
] as const;
|
] as const;
|
||||||
|
|
||||||
export type DatabaseType = (typeof DATABASE_TYPES)[number];
|
export type DatabaseType = (typeof DATABASE_TYPES)[number] | "plugin";
|
||||||
@@ -0,0 +1,29 @@
|
|||||||
|
//! One-shot plugin installer for local DBX app stores:
|
||||||
|
//! cargo run -p dbx-core --example install_plugin -- <plugins-root> <dbxp> <app-version> [--rollback-plugin <id>]
|
||||||
|
use dbx_core::plugins::{PluginInstallPolicy, PluginPackageInstaller};
|
||||||
|
|
||||||
|
fn main() {
|
||||||
|
let args: Vec<String> = std::env::args().skip(1).collect();
|
||||||
|
if args.len() < 3 {
|
||||||
|
eprintln!("usage: install_plugin <plugins-root> <package.dbxp> <app-version>");
|
||||||
|
std::process::exit(2);
|
||||||
|
}
|
||||||
|
let installer = PluginPackageInstaller::new(std::path::PathBuf::from(&args[0]), &args[2]).expect("installer");
|
||||||
|
match installer.install_file(std::path::Path::new(&args[1]), PluginInstallPolicy::LocalDevelopment) {
|
||||||
|
Ok(result) => {
|
||||||
|
let response = result.response();
|
||||||
|
println!(
|
||||||
|
"installed {} v{} (previous: {:?}, signature: {:?}, sha256: {})",
|
||||||
|
response.plugin.manifest.id,
|
||||||
|
response.plugin.manifest.version,
|
||||||
|
response.previous_version,
|
||||||
|
response.signature,
|
||||||
|
response.package_sha256
|
||||||
|
);
|
||||||
|
}
|
||||||
|
Err(error) => {
|
||||||
|
eprintln!("install failed: {error}");
|
||||||
|
std::process::exit(1);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -13,9 +13,9 @@ use std::net::{IpAddr, Ipv4Addr};
|
|||||||
|
|
||||||
use crate::ai::AiConfigItem;
|
use crate::ai::AiConfigItem;
|
||||||
use crate::connection_secrets::{
|
use crate::connection_secrets::{
|
||||||
CASSANDRA_KEYSTORE_PASSWORD_KEY, CASSANDRA_TRUSTSTORE_PASSWORD_KEY, MQ_AUTH_API_KEY_VALUE_KEY,
|
plugin_connection_secret_key, CASSANDRA_KEYSTORE_PASSWORD_KEY, CASSANDRA_TRUSTSTORE_PASSWORD_KEY,
|
||||||
MQ_AUTH_CLIENT_SECRET_KEY, MQ_AUTH_PASSWORD_KEY, MQ_AUTH_TOKEN_KEY, MQ_TOKEN_SIGNING_KEY, NACOS_AUTH_PASSWORD_KEY,
|
MQ_AUTH_API_KEY_VALUE_KEY, MQ_AUTH_CLIENT_SECRET_KEY, MQ_AUTH_PASSWORD_KEY, MQ_AUTH_TOKEN_KEY,
|
||||||
NACOS_RNACOS_CONSOLE_PASSWORD_KEY, PLUGIN_CONNECTION_SECRET_PREFIX,
|
MQ_TOKEN_SIGNING_KEY, NACOS_AUTH_PASSWORD_KEY, NACOS_RNACOS_CONSOLE_PASSWORD_KEY, PLUGIN_CONNECTION_SECRET_PREFIX,
|
||||||
};
|
};
|
||||||
use crate::models::connection::{ConnectionConfig, DatabaseType, TransportLayerConfig};
|
use crate::models::connection::{ConnectionConfig, DatabaseType, TransportLayerConfig};
|
||||||
use crate::saved_sql::SavedSqlLibrary;
|
use crate::saved_sql::SavedSqlLibrary;
|
||||||
@@ -970,6 +970,9 @@ fn scrub_connection_secrets(config: &mut ConnectionConfig) {
|
|||||||
config.connection_string = None;
|
config.connection_string = None;
|
||||||
config.init_script = None;
|
config.init_script = None;
|
||||||
scrub_mqtt_auth_secrets(config);
|
scrub_mqtt_auth_secrets(config);
|
||||||
|
for secret in config.connection_secrets.values_mut() {
|
||||||
|
secret.clear();
|
||||||
|
}
|
||||||
scrub_mq_external_config_secrets(config);
|
scrub_mq_external_config_secrets(config);
|
||||||
scrub_nacos_auth_secrets(config);
|
scrub_nacos_auth_secrets(config);
|
||||||
scrub_cassandra_tls_secrets(config);
|
scrub_cassandra_tls_secrets(config);
|
||||||
@@ -1009,14 +1012,6 @@ async fn build_sensitive_payload(
|
|||||||
if config.save_password {
|
if config.save_password {
|
||||||
push_secret(&mut connection_secrets, &config.id, "password", &config.password);
|
push_secret(&mut connection_secrets, &config.id, "password", &config.password);
|
||||||
}
|
}
|
||||||
for (key, secret) in &config.connection_secrets {
|
|
||||||
push_secret(
|
|
||||||
&mut connection_secrets,
|
|
||||||
&config.id,
|
|
||||||
&format!("{PLUGIN_CONNECTION_SECRET_PREFIX}{key}"),
|
|
||||||
secret,
|
|
||||||
);
|
|
||||||
}
|
|
||||||
push_secret(&mut connection_secrets, &config.id, "init_script", config.init_script.as_deref().unwrap_or(""));
|
push_secret(&mut connection_secrets, &config.id, "init_script", config.init_script.as_deref().unwrap_or(""));
|
||||||
for (index, layer) in config.transport_layers.iter().enumerate() {
|
for (index, layer) in config.transport_layers.iter().enumerate() {
|
||||||
match layer {
|
match layer {
|
||||||
@@ -1060,6 +1055,9 @@ async fn build_sensitive_payload(
|
|||||||
push_cassandra_tls_secrets(&mut connection_secrets, config);
|
push_cassandra_tls_secrets(&mut connection_secrets, config);
|
||||||
if config.save_password {
|
if config.save_password {
|
||||||
push_nacos_external_config_secrets(&mut connection_secrets, config);
|
push_nacos_external_config_secrets(&mut connection_secrets, config);
|
||||||
|
for (key, secret) in &config.connection_secrets {
|
||||||
|
push_secret(&mut connection_secrets, &config.id, &plugin_connection_secret_key(key)?, secret);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -2219,6 +2217,7 @@ mod tests {
|
|||||||
production_databases: vec![],
|
production_databases: vec![],
|
||||||
database_info: None,
|
database_info: None,
|
||||||
};
|
};
|
||||||
|
config.connection_secrets.insert("api_token".to_string(), "plugin-secret".to_string());
|
||||||
scrub_connection_secrets(&mut config);
|
scrub_connection_secrets(&mut config);
|
||||||
assert!(config.password.is_empty());
|
assert!(config.password.is_empty());
|
||||||
match &config.transport_layers[0] {
|
match &config.transport_layers[0] {
|
||||||
@@ -2235,8 +2234,10 @@ mod tests {
|
|||||||
assert!(config.redis_sentinel_password.is_empty());
|
assert!(config.redis_sentinel_password.is_empty());
|
||||||
assert!(config.connection_string.is_none());
|
assert!(config.connection_string.is_none());
|
||||||
assert!(config.init_script.is_none());
|
assert!(config.init_script.is_none());
|
||||||
|
assert_eq!(config.connection_secrets.get("api_token").map(String::as_str), None);
|
||||||
let public_json = serde_json::to_string(&config).unwrap();
|
let public_json = serde_json::to_string(&config).unwrap();
|
||||||
assert!(!public_json.contains("token-value"));
|
assert!(!public_json.contains("token-value"));
|
||||||
|
assert!(!public_json.contains("plugin-secret"));
|
||||||
assert!(super::SECRET_KEYS.contains(&"init_script"));
|
assert!(super::SECRET_KEYS.contains(&"init_script"));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -29,7 +29,10 @@ use crate::models::connection::{
|
|||||||
use crate::mongo_oidc::MongoOidcBrowserOpener;
|
use crate::mongo_oidc::MongoOidcBrowserOpener;
|
||||||
use crate::nacos::config::{NACOS_CONSOLE_SESSION_PASSWORD, NACOS_PRIMARY_SESSION_PASSWORD};
|
use crate::nacos::config::{NACOS_CONSOLE_SESSION_PASSWORD, NACOS_PRIMARY_SESSION_PASSWORD};
|
||||||
use crate::path_utils::expand_tilde;
|
use crate::path_utils::expand_tilde;
|
||||||
use crate::plugins::{PluginConnectionHandle, PluginDriverSession, PluginHost, PluginRegistry, PluginRuntimeEnv};
|
use crate::plugins::{
|
||||||
|
PluginConnectionActionResult, PluginConnectionHandle, PluginDriverSession, PluginHost, PluginRegistry,
|
||||||
|
PluginRuntimeEnv,
|
||||||
|
};
|
||||||
use crate::query_cancel::RunningQueries;
|
use crate::query_cancel::RunningQueries;
|
||||||
use crate::session_credentials::SessionCredentialStore;
|
use crate::session_credentials::SessionCredentialStore;
|
||||||
use crate::storage::{normalize_duckdb_worker_max_processes, Storage, DUCKDB_WORKER_MAX_PROCESSES_DEFAULT};
|
use crate::storage::{normalize_duckdb_worker_max_processes, Storage, DUCKDB_WORKER_MAX_PROCESSES_DEFAULT};
|
||||||
@@ -1346,8 +1349,10 @@ impl AppState {
|
|||||||
agent_dir: PathBuf,
|
agent_dir: PathBuf,
|
||||||
app_version: impl Into<String>,
|
app_version: impl Into<String>,
|
||||||
) -> Self {
|
) -> Self {
|
||||||
let data_dir = storage.data_dir().to_path_buf();
|
|
||||||
let app_version = app_version.into();
|
let app_version = app_version.into();
|
||||||
|
let data_dir = storage.data_dir().to_path_buf();
|
||||||
|
let plugins = PluginRegistry::new_with_app_version(plugin_dir, app_version.clone());
|
||||||
|
let plugin_host = PluginHost::new(plugins.clone());
|
||||||
Self {
|
Self {
|
||||||
connections: Arc::new(RwLock::new(ConnectionPoolRegistry::new())),
|
connections: Arc::new(RwLock::new(ConnectionPoolRegistry::new())),
|
||||||
task_supervisor: TaskSupervisor::new(),
|
task_supervisor: TaskSupervisor::new(),
|
||||||
@@ -1360,8 +1365,8 @@ impl AppState {
|
|||||||
proxy_tunnels: ProxyTunnelManager::new(),
|
proxy_tunnels: ProxyTunnelManager::new(),
|
||||||
http_tunnels: HttpTunnelManager::new(),
|
http_tunnels: HttpTunnelManager::new(),
|
||||||
storage,
|
storage,
|
||||||
plugins: PluginRegistry::new_with_app_version(plugin_dir.clone(), app_version.clone()),
|
plugins,
|
||||||
plugin_host: PluginHost::new(PluginRegistry::new_with_app_version(plugin_dir, app_version.clone())),
|
plugin_host,
|
||||||
agent_manager: crate::agent_manager::AgentManager::new_with_base_dir_and_app_version(
|
agent_manager: crate::agent_manager::AgentManager::new_with_base_dir_and_app_version(
|
||||||
agent_dir,
|
agent_dir,
|
||||||
app_version,
|
app_version,
|
||||||
@@ -2033,6 +2038,7 @@ impl AppState {
|
|||||||
self.proxy_tunnels.stop_all_tunnels(),
|
self.proxy_tunnels.stop_all_tunnels(),
|
||||||
self.http_tunnels.stop_all_tunnels(),
|
self.http_tunnels.stop_all_tunnels(),
|
||||||
self.agent_manager.stop_daemons(),
|
self.agent_manager.stop_daemons(),
|
||||||
|
self.plugin_host.stop_all(),
|
||||||
);
|
);
|
||||||
};
|
};
|
||||||
if tokio::time::timeout(deadline, shutdown).await.is_err() {
|
if tokio::time::timeout(deadline, shutdown).await.is_err() {
|
||||||
@@ -2204,7 +2210,9 @@ impl AppState {
|
|||||||
self.reset_connection_transport_for_config(connection_id, &db_config).await;
|
self.reset_connection_transport_for_config(connection_id, &db_config).await;
|
||||||
return Err(err);
|
return Err(err);
|
||||||
}
|
}
|
||||||
probe_connection_endpoint(&db_config, &host, port).await?;
|
if db_config.db_type != DatabaseType::Plugin {
|
||||||
|
probe_connection_endpoint(&db_config, &host, port).await?;
|
||||||
|
}
|
||||||
if let Err(err) = self.ensure_current_connection_attempt(connection_id, connection_attempt).await {
|
if let Err(err) = self.ensure_current_connection_attempt(connection_id, connection_attempt).await {
|
||||||
self.reset_connection_transport_for_config(connection_id, &db_config).await;
|
self.reset_connection_transport_for_config(connection_id, &db_config).await;
|
||||||
return Err(err);
|
return Err(err);
|
||||||
@@ -2787,7 +2795,9 @@ impl AppState {
|
|||||||
}
|
}
|
||||||
self.external_driver_pool("jdbc", &jdbc_config).await?
|
self.external_driver_pool("jdbc", &jdbc_config).await?
|
||||||
}
|
}
|
||||||
DatabaseType::Plugin => return Err("Plugin-owned connections use the plugin host".to_string()),
|
DatabaseType::Plugin => {
|
||||||
|
PoolKind::PluginConnection(self.plugin_host.connect_connection(&db_config, &host, port).await?)
|
||||||
|
}
|
||||||
#[cfg(feature = "mq-admin")]
|
#[cfg(feature = "mq-admin")]
|
||||||
DatabaseType::MessageQueue => {
|
DatabaseType::MessageQueue => {
|
||||||
// MQ admin connections don't hold a data query pool. We just test
|
// MQ admin connections don't hold a data query pool. We just test
|
||||||
@@ -3056,6 +3066,28 @@ impl AppState {
|
|||||||
Ok(("127.0.0.1".to_string(), local_port))
|
Ok(("127.0.0.1".to_string(), local_port))
|
||||||
}
|
}
|
||||||
|
|
||||||
|
pub async fn invoke_plugin_connection_action(
|
||||||
|
&self,
|
||||||
|
config: ConnectionConfig,
|
||||||
|
action_id: &str,
|
||||||
|
) -> Result<PluginConnectionActionResult, String> {
|
||||||
|
if config.db_type != DatabaseType::Plugin {
|
||||||
|
return Err("Connection is not owned by a plugin".to_string());
|
||||||
|
}
|
||||||
|
let config = config.canonicalized();
|
||||||
|
let transport_id = format!("{}:plugin-action:{action_id}", config.id);
|
||||||
|
let has_transport_layers = config.has_effective_transport_layers();
|
||||||
|
let connection_id = if has_transport_layers { transport_id.as_str() } else { config.id.as_str() };
|
||||||
|
let result = match self.connection_host_port(connection_id, &config).await {
|
||||||
|
Ok((host, port)) => self.plugin_host.invoke_connection_action(&config, action_id, &host, port).await,
|
||||||
|
Err(error) => Err(error),
|
||||||
|
};
|
||||||
|
if has_transport_layers {
|
||||||
|
self.reset_connection_transport_for_config(&transport_id, &config).await;
|
||||||
|
}
|
||||||
|
result
|
||||||
|
}
|
||||||
|
|
||||||
pub async fn connect_redis_sentinel(
|
pub async fn connect_redis_sentinel(
|
||||||
&self,
|
&self,
|
||||||
connection_id: &str,
|
connection_id: &str,
|
||||||
@@ -3838,13 +3870,13 @@ impl AppState {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
PoolKind::PluginConnection(handle) => !handle.is_running(),
|
||||||
PoolKind::Sqlite(_)
|
PoolKind::Sqlite(_)
|
||||||
| PoolKind::DuckDbWorker(_)
|
| PoolKind::DuckDbWorker(_)
|
||||||
| PoolKind::ExternalDriver { .. }
|
| PoolKind::ExternalDriver { .. }
|
||||||
| PoolKind::MessageQueue
|
| PoolKind::MessageQueue
|
||||||
| PoolKind::Nacos
|
| PoolKind::Nacos
|
||||||
| PoolKind::Consul(_) => false,
|
| PoolKind::Consul(_) => false,
|
||||||
PoolKind::PluginConnection(handle) => !handle.is_running(),
|
|
||||||
#[cfg(feature = "mq-admin")]
|
#[cfg(feature = "mq-admin")]
|
||||||
PoolKind::Mqtt(_) => false,
|
PoolKind::Mqtt(_) => false,
|
||||||
}
|
}
|
||||||
@@ -5002,15 +5034,6 @@ impl AppState {
|
|||||||
self.pool_routing_control().close_removed(removed).await;
|
self.pool_routing_control().close_removed(removed).await;
|
||||||
}
|
}
|
||||||
|
|
||||||
pub async fn invoke_plugin_connection_action(
|
|
||||||
&self,
|
|
||||||
config: ConnectionConfig,
|
|
||||||
action_id: &str,
|
|
||||||
) -> Result<crate::plugins::PluginConnectionActionResult, String> {
|
|
||||||
let (host, port) = self.connection_host_port(&config.id, &config).await?;
|
|
||||||
self.plugin_host.invoke_connection_action(&config, action_id, &host, port).await
|
|
||||||
}
|
|
||||||
|
|
||||||
async fn drain_connection_pools(&self, connection_id: &str) -> Vec<(String, PoolKind)> {
|
async fn drain_connection_pools(&self, connection_id: &str) -> Vec<(String, PoolKind)> {
|
||||||
let pool_prefix = format!("{connection_id}:");
|
let pool_prefix = format!("{connection_id}:");
|
||||||
let keys_to_remove: Vec<String> = self
|
let keys_to_remove: Vec<String> = self
|
||||||
@@ -5771,7 +5794,14 @@ async fn close_pool_kind(pool: PoolKind) -> Result<(), String> {
|
|||||||
session.shutdown().await;
|
session.shutdown().await;
|
||||||
}
|
}
|
||||||
PoolKind::PluginConnection(handle) => {
|
PoolKind::PluginConnection(handle) => {
|
||||||
handle.disconnect().await?;
|
if let Err(error) = handle.disconnect().await {
|
||||||
|
log::warn!(
|
||||||
|
"Failed to disconnect plugin connection '{}' ({}/{}): {error}",
|
||||||
|
handle.connection_id,
|
||||||
|
handle.plugin_id,
|
||||||
|
handle.provider_id
|
||||||
|
);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
PoolKind::MessageQueue => {}
|
PoolKind::MessageQueue => {}
|
||||||
PoolKind::Nacos => {}
|
PoolKind::Nacos => {}
|
||||||
|
|||||||
@@ -29,6 +29,16 @@ pub const CASSANDRA_TRUSTSTORE_PASSWORD_KEY: &str = "cassandra.tls.truststore_pa
|
|||||||
pub const CASSANDRA_KEYSTORE_PASSWORD_KEY: &str = "cassandra.tls.keystore_password";
|
pub const CASSANDRA_KEYSTORE_PASSWORD_KEY: &str = "cassandra.tls.keystore_password";
|
||||||
pub const PLUGIN_CONNECTION_SECRET_PREFIX: &str = "plugin_connection.";
|
pub const PLUGIN_CONNECTION_SECRET_PREFIX: &str = "plugin_connection.";
|
||||||
|
|
||||||
|
/// Storage-level secret key for one plugin connection field: namespaced under
|
||||||
|
/// [`PLUGIN_CONNECTION_SECRET_PREFIX`] so plugin keys never collide with the
|
||||||
|
/// fixed driver keys and can be scrubbed with a single prefix delete.
|
||||||
|
pub fn plugin_connection_secret_key(key: &str) -> Result<String, String> {
|
||||||
|
if key.is_empty() {
|
||||||
|
return Err("Plugin connection secret key must not be empty".to_string());
|
||||||
|
}
|
||||||
|
Ok(format!("{PLUGIN_CONNECTION_SECRET_PREFIX}{key}"))
|
||||||
|
}
|
||||||
|
|
||||||
pub trait ConnectionSecretStore {
|
pub trait ConnectionSecretStore {
|
||||||
fn set_secret(&self, connection_id: &str, key: &str, secret: &str) -> Result<(), String>;
|
fn set_secret(&self, connection_id: &str, key: &str, secret: &str) -> Result<(), String>;
|
||||||
fn get_secret(&self, connection_id: &str, key: &str) -> Result<Option<String>, String>;
|
fn get_secret(&self, connection_id: &str, key: &str) -> Result<Option<String>, String>;
|
||||||
@@ -117,6 +127,10 @@ pub fn save_connections_to_file(
|
|||||||
persist_mq_token_signing_secret(store, config)?;
|
persist_mq_token_signing_secret(store, config)?;
|
||||||
persist_mqtt_auth_secrets(store, config)?;
|
persist_mqtt_auth_secrets(store, config)?;
|
||||||
persist_cassandra_tls_secrets(store, config)?;
|
persist_cassandra_tls_secrets(store, config)?;
|
||||||
|
delete_secret_prefix(store, &config.id, PLUGIN_CONNECTION_SECRET_PREFIX)?;
|
||||||
|
for (key, secret) in &config.connection_secrets {
|
||||||
|
persist_secret(store, &config.id, &plugin_connection_secret_key(key)?, secret)?;
|
||||||
|
}
|
||||||
|
|
||||||
// New configs persist transport-layer secrets only. Remove legacy transport secret slots after the
|
// New configs persist transport-layer secrets only. Remove legacy transport secret slots after the
|
||||||
// migrated layer values have been written so old configs do not keep two sources of truth.
|
// migrated layer values have been written so old configs do not keep two sources of truth.
|
||||||
@@ -187,6 +201,19 @@ pub fn load_connections_from_file(
|
|||||||
hydrate_mq_token_signing_secret(store, config, &mut needs_rewrite)?;
|
hydrate_mq_token_signing_secret(store, config, &mut needs_rewrite)?;
|
||||||
hydrate_mqtt_auth_secrets(store, config, &mut needs_rewrite)?;
|
hydrate_mqtt_auth_secrets(store, config, &mut needs_rewrite)?;
|
||||||
hydrate_cassandra_tls_secrets(store, config, &mut needs_rewrite)?;
|
hydrate_cassandra_tls_secrets(store, config, &mut needs_rewrite)?;
|
||||||
|
let plugin_secret_keys = config.connection_secrets.keys().cloned().collect::<Vec<_>>();
|
||||||
|
for key in plugin_secret_keys {
|
||||||
|
let storage_key = plugin_connection_secret_key(&key)?;
|
||||||
|
let current = config.connection_secrets.get(&key).cloned().unwrap_or_default();
|
||||||
|
if current.is_empty() {
|
||||||
|
if let Some(secret) = store.get_secret(&config.id, &storage_key)? {
|
||||||
|
config.connection_secrets.insert(key, secret);
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
store.set_secret(&config.id, &storage_key, ¤t)?;
|
||||||
|
needs_rewrite = true;
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
if needs_rewrite {
|
if needs_rewrite {
|
||||||
@@ -818,11 +845,18 @@ fn sanitize_connections(configs: &[ConnectionConfig]) -> Vec<ConnectionConfig> {
|
|||||||
scrub_mq_token_signing_secret(&mut config);
|
scrub_mq_token_signing_secret(&mut config);
|
||||||
scrub_mqtt_auth_secrets(&mut config);
|
scrub_mqtt_auth_secrets(&mut config);
|
||||||
scrub_cassandra_tls_secrets(&mut config);
|
scrub_cassandra_tls_secrets(&mut config);
|
||||||
|
scrub_plugin_connection_secrets(&mut config);
|
||||||
config
|
config
|
||||||
})
|
})
|
||||||
.collect()
|
.collect()
|
||||||
}
|
}
|
||||||
|
|
||||||
|
fn scrub_plugin_connection_secrets(config: &mut ConnectionConfig) {
|
||||||
|
for secret in config.connection_secrets.values_mut() {
|
||||||
|
secret.clear();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
pub fn secret_account(connection_id: &str, key: &str) -> String {
|
pub fn secret_account(connection_id: &str, key: &str) -> String {
|
||||||
format!("connection:{connection_id}:{key}")
|
format!("connection:{connection_id}:{key}")
|
||||||
}
|
}
|
||||||
@@ -833,7 +867,7 @@ mod tests {
|
|||||||
load_connections_from_file, save_connections_to_file, ConnectionSecretStore, CASSANDRA_KEYSTORE_PASSWORD_KEY,
|
load_connections_from_file, save_connections_to_file, ConnectionSecretStore, CASSANDRA_KEYSTORE_PASSWORD_KEY,
|
||||||
CASSANDRA_TRUSTSTORE_PASSWORD_KEY, CONNECTION_STRING_KEY, INIT_SCRIPT_KEY, MAIN_PASSWORD_KEY,
|
CASSANDRA_TRUSTSTORE_PASSWORD_KEY, CONNECTION_STRING_KEY, INIT_SCRIPT_KEY, MAIN_PASSWORD_KEY,
|
||||||
MQTT_AUTH_PASSWORD_KEY, MQ_AUTH_PASSWORD_KEY, MQ_AUTH_TOKEN_KEY, MQ_TOKEN_SIGNING_KEY,
|
MQTT_AUTH_PASSWORD_KEY, MQ_AUTH_PASSWORD_KEY, MQ_AUTH_TOKEN_KEY, MQ_TOKEN_SIGNING_KEY,
|
||||||
REDIS_SENTINEL_PASSWORD_KEY, SSH_PASSWORD_KEY,
|
PLUGIN_CONNECTION_SECRET_PREFIX, REDIS_SENTINEL_PASSWORD_KEY, SSH_PASSWORD_KEY,
|
||||||
};
|
};
|
||||||
use crate::models::connection::{
|
use crate::models::connection::{
|
||||||
ConnectionConfig, DatabaseType, HttpTunnelConfig, SshTunnelConfig, TransportLayerConfig,
|
ConnectionConfig, DatabaseType, HttpTunnelConfig, SshTunnelConfig, TransportLayerConfig,
|
||||||
@@ -1543,4 +1577,33 @@ mod tests {
|
|||||||
|
|
||||||
assert_eq!(store.get_existing("mqtt-broker", MQTT_AUTH_PASSWORD_KEY), None);
|
assert_eq!(store.get_existing("mqtt-broker", MQTT_AUTH_PASSWORD_KEY), None);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn save_connections_moves_plugin_secrets_to_secret_store_and_restores_them() {
|
||||||
|
let path = temp_connections_file("plugin-connection-secret");
|
||||||
|
let store = MemorySecretStore::default();
|
||||||
|
let mut config = connection("plugin-connection", "", "");
|
||||||
|
config.db_type = DatabaseType::Plugin;
|
||||||
|
config.plugin_id = Some("dbx.example.hello".to_string());
|
||||||
|
config.plugin_connection_provider = Some("hello.connection".to_string());
|
||||||
|
config.plugin_connection_type = Some("hello".to_string());
|
||||||
|
config.external_config = Some(serde_json::json!({ "greeting": "Hello" }));
|
||||||
|
config.connection_secrets.insert("access_token".to_string(), "plugin-secret".to_string());
|
||||||
|
|
||||||
|
save_connections_to_file(&path, &[config], &store).unwrap();
|
||||||
|
|
||||||
|
let raw = std::fs::read_to_string(&path).unwrap();
|
||||||
|
assert!(!raw.contains("plugin-secret"));
|
||||||
|
let persisted: Vec<ConnectionConfig> = serde_json::from_str(&raw).unwrap();
|
||||||
|
assert_eq!(persisted[0].connection_secrets.get("access_token").map(String::as_str), Some(""));
|
||||||
|
assert_eq!(
|
||||||
|
store
|
||||||
|
.get_existing("plugin-connection", &format!("{PLUGIN_CONNECTION_SECRET_PREFIX}access_token"))
|
||||||
|
.as_deref(),
|
||||||
|
Some("plugin-secret")
|
||||||
|
);
|
||||||
|
|
||||||
|
let loaded = load_connections_from_file(&path, &store).unwrap();
|
||||||
|
assert_eq!(loaded[0].connection_secrets.get("access_token").map(String::as_str), Some("plugin-secret"));
|
||||||
|
}
|
||||||
}
|
}
|
||||||
@@ -39,11 +39,12 @@ pub use manifest::{
|
|||||||
current_plugin_target, resolve_safe_plugin_path, PluginBackendEntrypoint, PluginBackendTransport,
|
current_plugin_target, resolve_safe_plugin_path, PluginBackendEntrypoint, PluginBackendTransport,
|
||||||
PluginCompatibility, PluginConnectionActionContribution, PluginConnectionActionVariant, PluginConnectionActionWhen,
|
PluginCompatibility, PluginConnectionActionContribution, PluginConnectionActionVariant, PluginConnectionActionWhen,
|
||||||
PluginConnectionCapability, PluginConnectionProviderContribution, PluginContribution, PluginDriverManifest,
|
PluginConnectionCapability, PluginConnectionProviderContribution, PluginContribution, PluginDriverManifest,
|
||||||
PluginEngines, PluginEntrypoints, PluginFilesystemCapability, PluginFilesystemProviderContribution,
|
PluginEngines, PluginEntrypoints, PluginFieldCondition, PluginFilesystemCapability,
|
||||||
PluginFormFieldBinding, PluginFormFieldDefinition, PluginFormFieldOption, PluginFormFieldType, PluginManifest,
|
PluginFilesystemProviderContribution, PluginFormFieldBinding, PluginFormFieldDefinition, PluginFormFieldOption,
|
||||||
PluginUiEntrypoint, PluginWorkbenchContribution, PLUGIN_CONNECTION_ACTION_METHOD, PLUGIN_CONNECTION_CONNECT_METHOD,
|
PluginFormFieldType, PluginManifest, PluginUiEntrypoint, PluginWorkbenchContribution,
|
||||||
PLUGIN_CONNECTION_DISCONNECT_METHOD, PLUGIN_CONNECTION_TEST_METHOD, SUPPORTED_PLUGIN_HOST_API_VERSION,
|
PLUGIN_CONNECTION_ACTION_METHOD, PLUGIN_CONNECTION_CONNECT_METHOD, PLUGIN_CONNECTION_DISCONNECT_METHOD,
|
||||||
SUPPORTED_PLUGIN_MANIFEST_VERSION, SUPPORTED_PLUGIN_PERMISSIONS, SUPPORTED_PLUGIN_PROTOCOL_VERSION,
|
PLUGIN_CONNECTION_TEST_METHOD, SUPPORTED_PLUGIN_HOST_API_VERSION, SUPPORTED_PLUGIN_MANIFEST_VERSION,
|
||||||
|
SUPPORTED_PLUGIN_PERMISSIONS, SUPPORTED_PLUGIN_PROTOCOL_VERSION,
|
||||||
};
|
};
|
||||||
pub use runtime::{
|
pub use runtime::{
|
||||||
PluginBinaryMessage, PluginEvent, PluginHandshake, PluginHandshakeIdentity, PluginSessionState,
|
PluginBinaryMessage, PluginEvent, PluginHandshake, PluginHandshakeIdentity, PluginSessionState,
|
||||||
@@ -100,12 +101,27 @@ pub struct PluginRuntimeEnv {
|
|||||||
vars: Vec<(String, String)>,
|
vars: Vec<(String, String)>,
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Environment variable that tells a plugin sidecar where to keep its
|
||||||
|
/// persistent, version-independent local data (preferences, audit logs,
|
||||||
|
/// known hosts, ...). Injected by the registry so plugins never have to fall
|
||||||
|
/// back to the OS temp dir, which macOS wipes on reboot.
|
||||||
|
pub const PLUGIN_DATA_DIR_ENV: &str = "DBX_PLUGIN_DATA_DIR";
|
||||||
|
|
||||||
impl PluginRuntimeEnv {
|
impl PluginRuntimeEnv {
|
||||||
pub fn with_var(mut self, key: impl Into<String>, value: impl Into<String>) -> Self {
|
pub fn with_var(mut self, key: impl Into<String>, value: impl Into<String>) -> Self {
|
||||||
self.vars.push((key.into(), value.into()));
|
self.vars.push((key.into(), value.into()));
|
||||||
self
|
self
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Sets `DBX_PLUGIN_DATA_DIR` unless the caller already provided one, so
|
||||||
|
/// an explicit override keeps winning over the registry default.
|
||||||
|
pub fn with_plugin_data_dir(self, data_dir: &Path) -> Self {
|
||||||
|
if self.get(PLUGIN_DATA_DIR_ENV).is_some() {
|
||||||
|
return self;
|
||||||
|
}
|
||||||
|
self.with_var(PLUGIN_DATA_DIR_ENV, data_dir.to_string_lossy().into_owned())
|
||||||
|
}
|
||||||
|
|
||||||
pub fn get(&self, key: &str) -> Option<&str> {
|
pub fn get(&self, key: &str) -> Option<&str> {
|
||||||
self.vars.iter().find_map(|(name, value)| (name == key).then_some(value.as_str()))
|
self.vars.iter().find_map(|(name, value)| (name == key).then_some(value.as_str()))
|
||||||
}
|
}
|
||||||
@@ -140,6 +156,14 @@ impl PluginRegistry {
|
|||||||
&self.app_version
|
&self.app_version
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Persistent data directory for one plugin: `<data dir>/plugin-data/<id>`,
|
||||||
|
/// a sibling of the `plugins/` registry root so it survives version
|
||||||
|
/// upgrades and never collides with the installer-managed
|
||||||
|
/// `versions/` + `activations/` tree.
|
||||||
|
pub fn plugin_data_dir(&self, plugin_id: &str) -> PathBuf {
|
||||||
|
self.root_dir.parent().unwrap_or(&self.root_dir).join("plugin-data").join(plugin_id)
|
||||||
|
}
|
||||||
|
|
||||||
pub fn list_installed(&self) -> Result<Vec<InstalledPlugin>, String> {
|
pub fn list_installed(&self) -> Result<Vec<InstalledPlugin>, String> {
|
||||||
let entries = match std::fs::read_dir(&self.root_dir) {
|
let entries = match std::fs::read_dir(&self.root_dir) {
|
||||||
Ok(entries) => entries,
|
Ok(entries) => entries,
|
||||||
@@ -241,6 +265,7 @@ impl PluginRegistry {
|
|||||||
let plugin =
|
let plugin =
|
||||||
self.find_driver(driver_id)?.ok_or_else(|| format!("Plugin driver '{driver_id}' is not installed"))?;
|
self.find_driver(driver_id)?.ok_or_else(|| format!("Plugin driver '{driver_id}' is not installed"))?;
|
||||||
ensure_plugin_compatible(&plugin)?;
|
ensure_plugin_compatible(&plugin)?;
|
||||||
|
let env = env.with_plugin_data_dir(&self.plugin_data_dir(&plugin.manifest.id));
|
||||||
let session = PluginSidecarSession::start(plugin, self.app_version.clone(), env).await?;
|
let session = PluginSidecarSession::start(plugin, self.app_version.clone(), env).await?;
|
||||||
let result = session.invoke_with_timeout(method, params, Some(driver_id), timeout_duration).await;
|
let result = session.invoke_with_timeout(method, params, Some(driver_id), timeout_duration).await;
|
||||||
session.shutdown().await;
|
session.shutdown().await;
|
||||||
@@ -259,6 +284,7 @@ impl PluginRegistry {
|
|||||||
let plugin =
|
let plugin =
|
||||||
self.find_driver(driver_id)?.ok_or_else(|| format!("Plugin driver '{driver_id}' is not installed"))?;
|
self.find_driver(driver_id)?.ok_or_else(|| format!("Plugin driver '{driver_id}' is not installed"))?;
|
||||||
ensure_plugin_compatible(&plugin)?;
|
ensure_plugin_compatible(&plugin)?;
|
||||||
|
let env = env.with_plugin_data_dir(&self.plugin_data_dir(&plugin.manifest.id));
|
||||||
PluginDriverSession::start(plugin, driver_id.to_string(), self.app_version.clone(), env).await.map(Arc::new)
|
PluginDriverSession::start(plugin, driver_id.to_string(), self.app_version.clone(), env).await.map(Arc::new)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -362,9 +388,98 @@ impl PluginDriverSession {
|
|||||||
|
|
||||||
#[cfg(test)]
|
#[cfg(test)]
|
||||||
mod tests {
|
mod tests {
|
||||||
use super::{InstalledPlugin, PluginContribution, PluginManifest, PluginRegistry};
|
use std::path::{Path, PathBuf};
|
||||||
|
|
||||||
|
use super::{InstalledPlugin, PluginContribution, PluginManifest, PluginRegistry, PluginRuntimeEnv};
|
||||||
#[cfg(unix)]
|
#[cfg(unix)]
|
||||||
use super::{PluginDriverManifest, PluginDriverSession, PluginRuntimeEnv};
|
use super::{PluginDriverManifest, PluginDriverSession};
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn plugin_data_dir_lives_beside_the_plugin_registry() {
|
||||||
|
let registry = PluginRegistry::new(PathBuf::from("/data/plugins"));
|
||||||
|
assert_eq!(registry.plugin_data_dir("io.dbx.ssh"), PathBuf::from("/data/plugin-data/io.dbx.ssh"));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn plugin_data_dir_falls_back_to_registry_root_without_a_parent() {
|
||||||
|
let registry = PluginRegistry::new(PathBuf::from("/"));
|
||||||
|
assert_eq!(registry.plugin_data_dir("io.dbx.ssh"), PathBuf::from("/plugin-data/io.dbx.ssh"));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn with_plugin_data_dir_sets_the_env_var_once() {
|
||||||
|
let env = PluginRuntimeEnv::default().with_plugin_data_dir(Path::new("/data/plugin-data/io.dbx.ssh"));
|
||||||
|
assert_eq!(env.get("DBX_PLUGIN_DATA_DIR"), Some("/data/plugin-data/io.dbx.ssh"));
|
||||||
|
|
||||||
|
// An explicit caller-provided value wins over the registry default.
|
||||||
|
let explicit = PluginRuntimeEnv::default()
|
||||||
|
.with_var("DBX_PLUGIN_DATA_DIR", "/custom")
|
||||||
|
.with_plugin_data_dir(Path::new("/ignored"));
|
||||||
|
assert_eq!(explicit.get("DBX_PLUGIN_DATA_DIR"), Some("/custom"));
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The registry-injected data dir must reach the sidecar process itself,
|
||||||
|
/// not just the `PluginRuntimeEnv` value object.
|
||||||
|
#[cfg(unix)]
|
||||||
|
#[tokio::test]
|
||||||
|
async fn activated_sidecar_receives_plugin_data_dir_env() {
|
||||||
|
use std::os::unix::fs::PermissionsExt;
|
||||||
|
|
||||||
|
use super::PluginHost;
|
||||||
|
|
||||||
|
let data_dir = tempfile::tempdir().unwrap();
|
||||||
|
let plugin_dir = data_dir.path().join("plugins").join("sample.sidecar");
|
||||||
|
std::fs::create_dir_all(&plugin_dir).unwrap();
|
||||||
|
let executable = plugin_dir.join("plugin.sh");
|
||||||
|
std::fs::write(
|
||||||
|
&executable,
|
||||||
|
r#"#!/bin/sh
|
||||||
|
IFS= read -r initialize
|
||||||
|
initialize_id=$(printf '%s' "$initialize" | sed -E 's/.*"id":([0-9]+).*/\1/')
|
||||||
|
printf '{"jsonrpc":"2.0","id":%s,"result":{"protocolVersion":1,"capabilities":[],"plugin":{"id":"sample.sidecar","version":"1.0.0"}}}\n' "$initialize_id"
|
||||||
|
IFS= read -r request
|
||||||
|
request_id=$(printf '%s' "$request" | sed -E 's/.*"id":([0-9]+).*/\1/')
|
||||||
|
printf '{"jsonrpc":"2.0","id":%s,"result":"%s"}\n' "$request_id" "$DBX_PLUGIN_DATA_DIR"
|
||||||
|
sleep 30
|
||||||
|
"#,
|
||||||
|
)
|
||||||
|
.unwrap();
|
||||||
|
let mut permissions = std::fs::metadata(&executable).unwrap().permissions();
|
||||||
|
permissions.set_mode(0o755);
|
||||||
|
std::fs::set_permissions(&executable, permissions).unwrap();
|
||||||
|
std::fs::write(
|
||||||
|
plugin_dir.join("manifest.json"),
|
||||||
|
serde_json::json!({
|
||||||
|
"manifest_version": 1,
|
||||||
|
"id": "sample.sidecar",
|
||||||
|
"name": "Sample Sidecar",
|
||||||
|
"version": "1.0.0",
|
||||||
|
"publisher": "dbx",
|
||||||
|
"engines": { "dbx": ">=0.1.0", "host_api": "^1.0" },
|
||||||
|
"permissions": [],
|
||||||
|
"entrypoints": {
|
||||||
|
"backend": {
|
||||||
|
"protocol_versions": [1],
|
||||||
|
"transport": "stdio-jsonl",
|
||||||
|
"executable": "plugin.sh"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
})
|
||||||
|
.to_string(),
|
||||||
|
)
|
||||||
|
.unwrap();
|
||||||
|
|
||||||
|
let registry = PluginRegistry::new_with_app_version(data_dir.path().join("plugins"), "0.5.67");
|
||||||
|
let host = PluginHost::new(registry);
|
||||||
|
let reported: String =
|
||||||
|
host.invoke("sample.sidecar", "sample/dataDir", serde_json::Value::Null, None, None).await.unwrap();
|
||||||
|
assert_eq!(
|
||||||
|
PathBuf::from(reported),
|
||||||
|
data_dir.path().join("plugin-data").join("sample.sidecar"),
|
||||||
|
"sidecar must see <data dir>/plugin-data/<id> in DBX_PLUGIN_DATA_DIR"
|
||||||
|
);
|
||||||
|
host.stop_all().await;
|
||||||
|
}
|
||||||
|
|
||||||
#[cfg(unix)]
|
#[cfg(unix)]
|
||||||
#[tokio::test]
|
#[tokio::test]
|
||||||
|
|||||||
@@ -133,6 +133,7 @@ impl PluginHost {
|
|||||||
if !plugin.compatibility.compatible {
|
if !plugin.compatibility.compatible {
|
||||||
return Err(format!("Plugin '{plugin_id}' is incompatible: {}", plugin.compatibility.errors.join("; ")));
|
return Err(format!("Plugin '{plugin_id}' is incompatible: {}", plugin.compatibility.errors.join("; ")));
|
||||||
}
|
}
|
||||||
|
let env = env.with_plugin_data_dir(&self.inner.registry.plugin_data_dir(&plugin.manifest.id));
|
||||||
let session = PluginSidecarSession::start(plugin, self.inner.registry.app_version().to_string(), env).await?;
|
let session = PluginSidecarSession::start(plugin, self.inner.registry.app_version().to_string(), env).await?;
|
||||||
self.forward_session_events(&session);
|
self.forward_session_events(&session);
|
||||||
self.inner.sessions.write().await.insert(plugin_id.to_string(), session.clone());
|
self.inner.sessions.write().await.insert(plugin_id.to_string(), session.clone());
|
||||||
@@ -179,6 +180,15 @@ impl PluginHost {
|
|||||||
session.send_binary(channel, data).await
|
session.send_binary(channel, data).await
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Builds the standard plugin connection lifecycle payload for a config
|
||||||
|
/// using the config endpoint as the runtime endpoint (no desktop tunnel
|
||||||
|
/// available, e.g. the MCP CLI bridge). Validates that the config maps
|
||||||
|
/// to an installed connection provider.
|
||||||
|
pub fn connection_params_standalone(&self, config: &ConnectionConfig) -> Result<serde_json::Value, String> {
|
||||||
|
let (_, provider) = self.resolve_connection_provider(config)?;
|
||||||
|
plugin_connection_params(config, &provider, &config.host, config.port)
|
||||||
|
}
|
||||||
|
|
||||||
pub async fn test_connection(
|
pub async fn test_connection(
|
||||||
&self,
|
&self,
|
||||||
config: &ConnectionConfig,
|
config: &ConnectionConfig,
|
||||||
@@ -390,7 +400,8 @@ fn plugin_connection_params(
|
|||||||
"runtime": {
|
"runtime": {
|
||||||
"host": runtime_host,
|
"host": runtime_host,
|
||||||
"port": runtime_port,
|
"port": runtime_port,
|
||||||
}
|
},
|
||||||
|
"operationId": uuid::Uuid::new_v4().to_string(),
|
||||||
}))
|
}))
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -430,10 +441,22 @@ fn validate_plugin_connection_values_for_action(
|
|||||||
}
|
}
|
||||||
for field in &provider.fields {
|
for field in &provider.fields {
|
||||||
let value = plugin_connection_field_value(config, field);
|
let value = plugin_connection_field_value(config, field);
|
||||||
if require_required_fields && field.required && plugin_field_value_is_empty(value.as_ref()) {
|
// Required enforcement is condition-aware (Host API 1.1): fields hidden
|
||||||
|
// by `visible_when` or only conditionally required via `required_when`
|
||||||
|
// are validated against the current stored values, mirroring the
|
||||||
|
// connection dialog's `pluginFieldConditions` semantics. This keeps
|
||||||
|
// non-dialog write paths (MCP/import) from unconditionally rejecting
|
||||||
|
// connections whose protocol-specific fields are simply not visible.
|
||||||
|
if require_required_fields
|
||||||
|
&& plugin_field_is_visible(field, config, provider)
|
||||||
|
&& plugin_field_is_required(field, config, provider)
|
||||||
|
&& plugin_field_value_is_empty(value.as_ref())
|
||||||
|
{
|
||||||
return Err(format!("Plugin connection field '{}' is required", field.label));
|
return Err(format!("Plugin connection field '{}' is required", field.label));
|
||||||
}
|
}
|
||||||
if let Some(value) = value {
|
// A stored JSON null means "unset" (older dialog builds wrote nulls for
|
||||||
|
// untouched optional fields); it must not fail the declared type check.
|
||||||
|
if let Some(value) = value.filter(|value| !value.is_null()) {
|
||||||
validate_plugin_field_type(field, &value)?;
|
validate_plugin_field_type(field, &value)?;
|
||||||
if field.effective_binding() == PluginFormFieldBinding::Port
|
if field.effective_binding() == PluginFormFieldBinding::Port
|
||||||
&& value.as_u64().is_none_or(|port| port == 0 || port > u16::MAX as u64)
|
&& value.as_u64().is_none_or(|port| port == 0 || port > u16::MAX as u64)
|
||||||
@@ -523,6 +546,89 @@ fn plugin_field_value_is_empty(value: Option<&serde_json::Value>) -> bool {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Evaluates a plugin manifest field condition (`visible_when` / `required_when`,
|
||||||
|
/// Host API 1.1) against the stored connection values. Mirrors the frontend
|
||||||
|
/// `pluginFieldConditions.ts` semantics: the condition matches when the current
|
||||||
|
/// value of the referenced sibling field is listed in `one_of`; a missing
|
||||||
|
/// sibling field or an unset/empty value never matches.
|
||||||
|
fn plugin_field_condition_matches(
|
||||||
|
condition: &super::PluginFieldCondition,
|
||||||
|
config: &ConnectionConfig,
|
||||||
|
provider: &PluginConnectionProviderContribution,
|
||||||
|
) -> bool {
|
||||||
|
let Some(sibling) = provider.fields.iter().find(|field| field.key == condition.field) else {
|
||||||
|
return false;
|
||||||
|
};
|
||||||
|
let Some(value) = plugin_connection_field_value(config, sibling) else {
|
||||||
|
return false;
|
||||||
|
};
|
||||||
|
let text = match value {
|
||||||
|
serde_json::Value::Null => return false,
|
||||||
|
serde_json::Value::String(text) => text,
|
||||||
|
other => other.to_string(),
|
||||||
|
};
|
||||||
|
if text.trim().is_empty() {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
condition.one_of.iter().any(|option| option == &text)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A field participates in the form when its `visible_when` (if any) matches.
|
||||||
|
/// Mirrors the frontend cascade (`pluginFieldConditions.ts`): once the raw
|
||||||
|
/// condition matches, the referenced sibling must itself be visible — a hidden
|
||||||
|
/// container field's stored default (e.g. `krb_credential_type: "password"`
|
||||||
|
/// while auth is simple) must not mark grandchild fields visible + required,
|
||||||
|
/// otherwise non-dialog write paths reject connections the dialog accepts.
|
||||||
|
fn plugin_field_is_visible(
|
||||||
|
field: &PluginFormFieldDefinition,
|
||||||
|
config: &ConnectionConfig,
|
||||||
|
provider: &PluginConnectionProviderContribution,
|
||||||
|
) -> bool {
|
||||||
|
let mut seen = HashSet::new();
|
||||||
|
seen.insert(field.key.clone());
|
||||||
|
plugin_field_is_visible_cached(field, config, provider, &mut seen)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn plugin_field_is_visible_cached(
|
||||||
|
field: &PluginFormFieldDefinition,
|
||||||
|
config: &ConnectionConfig,
|
||||||
|
provider: &PluginConnectionProviderContribution,
|
||||||
|
seen: &mut HashSet<String>,
|
||||||
|
) -> bool {
|
||||||
|
let Some(condition) = &field.visible_when else {
|
||||||
|
return true;
|
||||||
|
};
|
||||||
|
if !plugin_field_condition_matches(condition, config, provider) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
// The condition matched, so the sibling exists (its value was readable);
|
||||||
|
// guard cycles anyway and fall through to visible, mirroring the frontend.
|
||||||
|
let Some(sibling) = provider.fields.iter().find(|candidate| candidate.key == condition.field) else {
|
||||||
|
return true;
|
||||||
|
};
|
||||||
|
if seen.contains(&sibling.key) {
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
seen.insert(sibling.key.clone());
|
||||||
|
plugin_field_is_visible_cached(sibling, config, provider, seen)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Effective required = static `required` OR a matching `required_when`
|
||||||
|
/// (a missing `required_when` never implies required).
|
||||||
|
fn plugin_field_is_required(
|
||||||
|
field: &PluginFormFieldDefinition,
|
||||||
|
config: &ConnectionConfig,
|
||||||
|
provider: &PluginConnectionProviderContribution,
|
||||||
|
) -> bool {
|
||||||
|
if field.required {
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
match &field.required_when {
|
||||||
|
None => false,
|
||||||
|
Some(condition) => plugin_field_condition_matches(condition, config, provider),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
fn validate_plugin_field_type(field: &PluginFormFieldDefinition, value: &serde_json::Value) -> Result<(), String> {
|
fn validate_plugin_field_type(field: &PluginFormFieldDefinition, value: &serde_json::Value) -> Result<(), String> {
|
||||||
let valid = match field.field_type {
|
let valid = match field.field_type {
|
||||||
PluginFormFieldType::Text
|
PluginFormFieldType::Text
|
||||||
@@ -624,6 +730,225 @@ mod tests {
|
|||||||
.contains("port between 1 and 65535"));
|
.contains("port between 1 and 65535"));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn tolerates_stored_null_config_values_for_type_check() {
|
||||||
|
let config: ConnectionConfig = serde_json::from_value(serde_json::json!({
|
||||||
|
"id": "plugin-connection",
|
||||||
|
"name": "Plugin connection",
|
||||||
|
"db_type": "plugin",
|
||||||
|
"host": "localhost",
|
||||||
|
"port": 22,
|
||||||
|
"username": "root",
|
||||||
|
"password": "",
|
||||||
|
"database": null,
|
||||||
|
"plugin_id": "sample",
|
||||||
|
"plugin_connection_provider": "sample.connection",
|
||||||
|
"plugin_connection_type": "sample",
|
||||||
|
"external_config": { "authentication": "agent", "agent_socket": null }
|
||||||
|
}))
|
||||||
|
.unwrap();
|
||||||
|
let provider: PluginConnectionProviderContribution = serde_json::from_value(serde_json::json!({
|
||||||
|
"id": "sample.connection",
|
||||||
|
"label": "Sample",
|
||||||
|
"database_type": "sample",
|
||||||
|
"fields": [
|
||||||
|
{
|
||||||
|
"key": "authentication",
|
||||||
|
"label": "Authentication",
|
||||||
|
"type": "select",
|
||||||
|
"binding": "config",
|
||||||
|
"default": "password",
|
||||||
|
"options": [
|
||||||
|
{ "value": "password", "label": "Password" },
|
||||||
|
{ "value": "agent", "label": "Agent" }
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{ "key": "agent_socket", "label": "Agent socket", "type": "text", "binding": "config" }
|
||||||
|
]
|
||||||
|
}))
|
||||||
|
.unwrap();
|
||||||
|
|
||||||
|
assert!(validate_plugin_connection_values(&config, &provider).is_ok());
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Mirrors the files plugin manifest shape: `bucket` is required only when
|
||||||
|
/// `protocol` selects `s3` (`required_when` paired with `visible_when`).
|
||||||
|
#[test]
|
||||||
|
fn conditional_required_field_enforced_only_when_condition_matches() {
|
||||||
|
let provider: PluginConnectionProviderContribution = serde_json::from_value(serde_json::json!({
|
||||||
|
"id": "sample.connection",
|
||||||
|
"label": "Sample",
|
||||||
|
"database_type": "sample",
|
||||||
|
"fields": [
|
||||||
|
{
|
||||||
|
"key": "protocol",
|
||||||
|
"label": "Protocol",
|
||||||
|
"type": "select",
|
||||||
|
"binding": "config",
|
||||||
|
"required": true,
|
||||||
|
"default": "fs",
|
||||||
|
"options": [
|
||||||
|
{ "value": "fs", "label": "fs" },
|
||||||
|
{ "value": "s3", "label": "s3" }
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"key": "bucket",
|
||||||
|
"label": "Bucket",
|
||||||
|
"type": "text",
|
||||||
|
"binding": "config",
|
||||||
|
"visible_when": { "field": "protocol", "one_of": ["s3"] },
|
||||||
|
"required_when": { "field": "protocol", "one_of": ["s3"] }
|
||||||
|
}
|
||||||
|
]
|
||||||
|
}))
|
||||||
|
.unwrap();
|
||||||
|
let config_for = |external: serde_json::Value| -> ConnectionConfig {
|
||||||
|
serde_json::from_value(serde_json::json!({
|
||||||
|
"id": "plugin-connection",
|
||||||
|
"name": "Plugin connection",
|
||||||
|
"db_type": "plugin",
|
||||||
|
"host": "localhost",
|
||||||
|
"port": 22,
|
||||||
|
"username": "",
|
||||||
|
"password": "",
|
||||||
|
"database": null,
|
||||||
|
"plugin_id": "sample",
|
||||||
|
"plugin_connection_provider": "sample.connection",
|
||||||
|
"plugin_connection_type": "sample",
|
||||||
|
"external_config": external
|
||||||
|
}))
|
||||||
|
.unwrap()
|
||||||
|
};
|
||||||
|
|
||||||
|
// fs: bucket not visible → not required → connection accepted.
|
||||||
|
assert!(
|
||||||
|
validate_plugin_connection_values(&config_for(serde_json::json!({ "protocol": "fs" })), &provider).is_ok()
|
||||||
|
);
|
||||||
|
// s3: bucket visible and conditionally required → empty bucket rejected.
|
||||||
|
assert!(validate_plugin_connection_values(&config_for(serde_json::json!({ "protocol": "s3" })), &provider)
|
||||||
|
.unwrap_err()
|
||||||
|
.contains("field 'Bucket' is required"));
|
||||||
|
// s3 with a bucket value passes.
|
||||||
|
assert!(validate_plugin_connection_values(
|
||||||
|
&config_for(serde_json::json!({ "protocol": "s3", "bucket": "demo" })),
|
||||||
|
&provider
|
||||||
|
)
|
||||||
|
.is_ok());
|
||||||
|
// Whitespace-only values count as empty.
|
||||||
|
assert!(validate_plugin_connection_values(
|
||||||
|
&config_for(serde_json::json!({ "protocol": "s3", "bucket": " " })),
|
||||||
|
&provider
|
||||||
|
)
|
||||||
|
.unwrap_err()
|
||||||
|
.contains("field 'Bucket' is required"));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn statically_required_field_only_enforced_while_visible() {
|
||||||
|
let provider: PluginConnectionProviderContribution = serde_json::from_value(serde_json::json!({
|
||||||
|
"id": "sample.connection",
|
||||||
|
"label": "Sample",
|
||||||
|
"database_type": "sample",
|
||||||
|
"fields": [
|
||||||
|
{
|
||||||
|
"key": "mode",
|
||||||
|
"label": "Mode",
|
||||||
|
"type": "select",
|
||||||
|
"binding": "config",
|
||||||
|
"default": "simple",
|
||||||
|
"options": [
|
||||||
|
{ "value": "simple", "label": "Simple" },
|
||||||
|
{ "value": "custom", "label": "Custom" }
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"key": "secret_key",
|
||||||
|
"label": "Secret key",
|
||||||
|
"type": "password",
|
||||||
|
"binding": "secret",
|
||||||
|
"required": true,
|
||||||
|
"visible_when": { "field": "mode", "one_of": ["custom"] }
|
||||||
|
}
|
||||||
|
]
|
||||||
|
}))
|
||||||
|
.unwrap();
|
||||||
|
let config_for = |external: serde_json::Value, secrets: serde_json::Value| -> ConnectionConfig {
|
||||||
|
serde_json::from_value(serde_json::json!({
|
||||||
|
"id": "plugin-connection",
|
||||||
|
"name": "Plugin connection",
|
||||||
|
"db_type": "plugin",
|
||||||
|
"host": "localhost",
|
||||||
|
"port": 22,
|
||||||
|
"username": "",
|
||||||
|
"password": "",
|
||||||
|
"database": null,
|
||||||
|
"plugin_id": "sample",
|
||||||
|
"plugin_connection_provider": "sample.connection",
|
||||||
|
"plugin_connection_type": "sample",
|
||||||
|
"external_config": external,
|
||||||
|
"connection_secrets": secrets
|
||||||
|
}))
|
||||||
|
.unwrap()
|
||||||
|
};
|
||||||
|
|
||||||
|
// Hidden static-required field must not block the connection.
|
||||||
|
assert!(validate_plugin_connection_values(
|
||||||
|
&config_for(serde_json::json!({ "mode": "simple" }), serde_json::json!({})),
|
||||||
|
&provider
|
||||||
|
)
|
||||||
|
.is_ok());
|
||||||
|
// Visible and empty → rejected.
|
||||||
|
assert!(validate_plugin_connection_values(
|
||||||
|
&config_for(serde_json::json!({ "mode": "custom" }), serde_json::json!({})),
|
||||||
|
&provider
|
||||||
|
)
|
||||||
|
.unwrap_err()
|
||||||
|
.contains("field 'Secret key' is required"));
|
||||||
|
// Visible and filled → accepted.
|
||||||
|
assert!(validate_plugin_connection_values(
|
||||||
|
&config_for(serde_json::json!({ "mode": "custom" }), serde_json::json!({ "secret_key": "k" })),
|
||||||
|
&provider
|
||||||
|
)
|
||||||
|
.is_ok());
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn required_when_referencing_missing_sibling_field_is_never_required() {
|
||||||
|
let provider: PluginConnectionProviderContribution = serde_json::from_value(serde_json::json!({
|
||||||
|
"id": "sample.connection",
|
||||||
|
"label": "Sample",
|
||||||
|
"database_type": "sample",
|
||||||
|
"fields": [
|
||||||
|
{ "key": "root", "label": "Root", "type": "text", "binding": "config" },
|
||||||
|
{
|
||||||
|
"key": "orphan",
|
||||||
|
"label": "Orphan",
|
||||||
|
"type": "text",
|
||||||
|
"binding": "config",
|
||||||
|
"required_when": { "field": "ghost", "one_of": ["x"] }
|
||||||
|
}
|
||||||
|
]
|
||||||
|
}))
|
||||||
|
.unwrap();
|
||||||
|
let config: ConnectionConfig = serde_json::from_value(serde_json::json!({
|
||||||
|
"id": "plugin-connection",
|
||||||
|
"name": "Plugin connection",
|
||||||
|
"db_type": "plugin",
|
||||||
|
"host": "localhost",
|
||||||
|
"port": 22,
|
||||||
|
"username": "",
|
||||||
|
"password": "",
|
||||||
|
"database": null,
|
||||||
|
"plugin_id": "sample",
|
||||||
|
"plugin_connection_provider": "sample.connection",
|
||||||
|
"plugin_connection_type": "sample"
|
||||||
|
}))
|
||||||
|
.unwrap();
|
||||||
|
|
||||||
|
assert!(validate_plugin_connection_values(&config, &provider).is_ok());
|
||||||
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn allows_incomplete_fields_only_for_declared_permissive_actions() {
|
fn allows_incomplete_fields_only_for_declared_permissive_actions() {
|
||||||
let config: ConnectionConfig = serde_json::from_value(serde_json::json!({
|
let config: ConnectionConfig = serde_json::from_value(serde_json::json!({
|
||||||
@@ -699,4 +1024,97 @@ mod tests {
|
|||||||
.unwrap_err()
|
.unwrap_err()
|
||||||
.contains("invalid value type"));
|
.contains("invalid value type"));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Mirrors the ldap plugin manifest shape: `krb_password` conditions on
|
||||||
|
/// `krb_credential_type`, which is itself hidden unless `auth_type` is
|
||||||
|
/// `kerberos`. A stored default on the hidden container field ("password")
|
||||||
|
/// must not make `krb_password` visible + required — the connection dialog
|
||||||
|
/// (cascading visibility) accepts such a save, so validation must too.
|
||||||
|
#[test]
|
||||||
|
fn cascaded_hidden_container_default_does_not_force_grandchild_required() {
|
||||||
|
let provider: PluginConnectionProviderContribution = serde_json::from_value(serde_json::json!({
|
||||||
|
"id": "ldap.connection",
|
||||||
|
"label": "LDAP",
|
||||||
|
"database_type": "ldap",
|
||||||
|
"fields": [
|
||||||
|
{
|
||||||
|
"key": "auth_type",
|
||||||
|
"label": "Authentication",
|
||||||
|
"type": "select",
|
||||||
|
"binding": "config",
|
||||||
|
"default": "simple",
|
||||||
|
"options": [
|
||||||
|
{ "value": "simple", "label": "Simple" },
|
||||||
|
{ "value": "kerberos", "label": "Kerberos (GSSAPI)" }
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"key": "krb_credential_type",
|
||||||
|
"label": "Kerberos credential type",
|
||||||
|
"type": "select",
|
||||||
|
"binding": "config",
|
||||||
|
"default": "password",
|
||||||
|
"visible_when": { "field": "auth_type", "one_of": ["kerberos"] },
|
||||||
|
"options": [
|
||||||
|
{ "value": "password", "label": "Password" },
|
||||||
|
{ "value": "keytab", "label": "Keytab" }
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"key": "krb_password",
|
||||||
|
"label": "Kerberos password",
|
||||||
|
"type": "password",
|
||||||
|
"binding": "secret",
|
||||||
|
"visible_when": { "field": "krb_credential_type", "one_of": ["password"] },
|
||||||
|
"required_when": { "field": "krb_credential_type", "one_of": ["password"] }
|
||||||
|
}
|
||||||
|
]
|
||||||
|
}))
|
||||||
|
.unwrap();
|
||||||
|
let config_for = |external: serde_json::Value| -> ConnectionConfig {
|
||||||
|
serde_json::from_value(serde_json::json!({
|
||||||
|
"id": "plugin-connection",
|
||||||
|
"name": "KN-LDAP",
|
||||||
|
"db_type": "plugin",
|
||||||
|
"host": "ldap.example.com",
|
||||||
|
"port": 389,
|
||||||
|
"username": "",
|
||||||
|
"password": "",
|
||||||
|
"database": null,
|
||||||
|
"plugin_id": "io.dbx.ldap",
|
||||||
|
"plugin_connection_provider": "ldap.connection",
|
||||||
|
"plugin_connection_type": "ldap",
|
||||||
|
"external_config": external
|
||||||
|
}))
|
||||||
|
.unwrap()
|
||||||
|
};
|
||||||
|
|
||||||
|
// Simple auth with the stale stored default on the hidden container
|
||||||
|
// field: dialog saves it, host must not demand the hidden secret.
|
||||||
|
let simple = config_for(serde_json::json!({ "auth_type": "simple", "krb_credential_type": "password" }));
|
||||||
|
assert!(validate_plugin_connection_values(&simple, &provider).is_ok());
|
||||||
|
|
||||||
|
// Kerberos + password credential type: the grandchild is genuinely
|
||||||
|
// visible and required, and the empty secret must still be rejected.
|
||||||
|
let kerberos = config_for(serde_json::json!({ "auth_type": "kerberos", "krb_credential_type": "password" }));
|
||||||
|
assert!(validate_plugin_connection_values(&kerberos, &provider)
|
||||||
|
.unwrap_err()
|
||||||
|
.contains("Kerberos password' is required"));
|
||||||
|
|
||||||
|
// Cycle guard: mutual references must not hang or misclassify.
|
||||||
|
let cyclic: PluginConnectionProviderContribution = serde_json::from_value(serde_json::json!({
|
||||||
|
"id": "cyclic.connection",
|
||||||
|
"label": "Cyclic",
|
||||||
|
"database_type": "cyclic",
|
||||||
|
"fields": [
|
||||||
|
{ "key": "a", "label": "A", "type": "text", "binding": "config",
|
||||||
|
"visible_when": { "field": "b", "one_of": ["x"] } },
|
||||||
|
{ "key": "b", "label": "B", "type": "text", "binding": "config",
|
||||||
|
"visible_when": { "field": "a", "one_of": ["x"] } }
|
||||||
|
]
|
||||||
|
}))
|
||||||
|
.unwrap();
|
||||||
|
let cyclic_config = config_for(serde_json::json!({ "a": "x", "b": "x" }));
|
||||||
|
assert!(validate_plugin_connection_values(&cyclic_config, &cyclic).is_ok());
|
||||||
|
}
|
||||||
}
|
}
|
||||||
@@ -248,6 +248,23 @@ pub struct PluginFormFieldDefinition {
|
|||||||
pub options: Vec<PluginFormFieldOption>,
|
pub options: Vec<PluginFormFieldOption>,
|
||||||
#[serde(default)]
|
#[serde(default)]
|
||||||
pub binding: Option<PluginFormFieldBinding>,
|
pub binding: Option<PluginFormFieldBinding>,
|
||||||
|
/// Plugin method returning `{ options: [{ value, label }] }`; the host
|
||||||
|
/// connection form fetches it and renders the field as a dynamic select.
|
||||||
|
/// Optional and forward/backward compatible: older hosts reject the
|
||||||
|
/// manifest, hosts without UI support keep the declared type.
|
||||||
|
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||||
|
pub options_action: Option<String>,
|
||||||
|
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||||
|
pub visible_when: Option<PluginFieldCondition>,
|
||||||
|
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||||
|
pub required_when: Option<PluginFieldCondition>,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
|
||||||
|
#[serde(deny_unknown_fields)]
|
||||||
|
pub struct PluginFieldCondition {
|
||||||
|
pub field: String,
|
||||||
|
pub one_of: Vec<String>,
|
||||||
}
|
}
|
||||||
|
|
||||||
impl PluginFormFieldDefinition {
|
impl PluginFormFieldDefinition {
|
||||||
@@ -964,6 +981,7 @@ fn validate_connection_actions(
|
|||||||
|
|
||||||
fn validate_form_fields(fields: &[PluginFormFieldDefinition], contribution_index: usize, errors: &mut Vec<String>) {
|
fn validate_form_fields(fields: &[PluginFormFieldDefinition], contribution_index: usize, errors: &mut Vec<String>) {
|
||||||
let mut seen_keys = HashSet::new();
|
let mut seen_keys = HashSet::new();
|
||||||
|
let field_keys = fields.iter().map(|field| field.key.as_str()).collect::<HashSet<_>>();
|
||||||
for (field_index, field) in fields.iter().enumerate() {
|
for (field_index, field) in fields.iter().enumerate() {
|
||||||
if !valid_identifier(&field.key) || !seen_keys.insert(&field.key) {
|
if !valid_identifier(&field.key) || !seen_keys.insert(&field.key) {
|
||||||
errors.push(format!(
|
errors.push(format!(
|
||||||
@@ -976,6 +994,25 @@ fn validate_form_fields(fields: &[PluginFormFieldDefinition], contribution_index
|
|||||||
errors,
|
errors,
|
||||||
);
|
);
|
||||||
|
|
||||||
|
for (name, condition) in
|
||||||
|
[("visible_when", field.visible_when.as_ref()), ("required_when", field.required_when.as_ref())]
|
||||||
|
{
|
||||||
|
let Some(condition) = condition else {
|
||||||
|
continue;
|
||||||
|
};
|
||||||
|
if condition.one_of.is_empty() {
|
||||||
|
errors.push(format!(
|
||||||
|
"Contribution at index {contribution_index} field {field_index} {name} one_of cannot be empty"
|
||||||
|
));
|
||||||
|
}
|
||||||
|
if !field_keys.contains(condition.field.as_str()) {
|
||||||
|
errors.push(format!(
|
||||||
|
"Contribution at index {contribution_index} field {field_index} {name} references unknown field '{}'",
|
||||||
|
condition.field
|
||||||
|
));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
if matches!(field.field_type, PluginFormFieldType::Select | PluginFormFieldType::Radio) {
|
if matches!(field.field_type, PluginFormFieldType::Select | PluginFormFieldType::Radio) {
|
||||||
if field.options.is_empty() {
|
if field.options.is_empty() {
|
||||||
errors.push(format!(
|
errors.push(format!(
|
||||||
@@ -1675,4 +1712,113 @@ mod tests {
|
|||||||
assert!(errors.iter().any(|error| error.contains("invalid or duplicate id")));
|
assert!(errors.iter().any(|error| error.contains("invalid or duplicate id")));
|
||||||
assert!(errors.iter().any(|error| error.contains("timeout_ms must be between")));
|
assert!(errors.iter().any(|error| error.contains("timeout_ms must be between")));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn parses_form_field_conditions() {
|
||||||
|
let dir = tempfile::tempdir().unwrap();
|
||||||
|
let manifest: PluginManifest = serde_json::from_value(serde_json::json!({
|
||||||
|
"manifest_version": 1,
|
||||||
|
"id": "io.dbx.conditions",
|
||||||
|
"name": "Conditions",
|
||||||
|
"version": "1.0.0",
|
||||||
|
"publisher": "example",
|
||||||
|
"engines": { "dbx": ">=0.1.0", "host_api": "^1.0" },
|
||||||
|
"contributions": [{
|
||||||
|
"type": "connection-provider",
|
||||||
|
"id": "conditions.connection",
|
||||||
|
"database_type": "conditions",
|
||||||
|
"fields": [
|
||||||
|
{
|
||||||
|
"key": "mode",
|
||||||
|
"label": "Mode",
|
||||||
|
"type": "select",
|
||||||
|
"options": [
|
||||||
|
{ "label": "Local", "value": "local" },
|
||||||
|
{ "label": "Custom", "value": "custom" }
|
||||||
|
],
|
||||||
|
"default": "local"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"key": "private_key_path",
|
||||||
|
"label": "Private key",
|
||||||
|
"type": "text",
|
||||||
|
"visible_when": { "field": "mode", "one_of": ["custom"] },
|
||||||
|
"required_when": { "field": "mode", "one_of": ["custom"] }
|
||||||
|
}
|
||||||
|
]
|
||||||
|
}]
|
||||||
|
}))
|
||||||
|
.unwrap();
|
||||||
|
let compatibility = manifest.compatibility(dir.path(), "0.5.68");
|
||||||
|
let provider = manifest.connection_provider("conditions.connection").unwrap().unwrap();
|
||||||
|
|
||||||
|
assert!(compatibility.compatible, "{:?}", compatibility.errors);
|
||||||
|
let visible_when = provider.fields[1].visible_when.as_ref().unwrap();
|
||||||
|
assert_eq!(visible_when.field, "mode");
|
||||||
|
assert_eq!(visible_when.one_of, vec!["custom".to_string()]);
|
||||||
|
assert_eq!(provider.fields[1].required_when.as_ref().unwrap().one_of, vec!["custom".to_string()]);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn rejects_invalid_form_field_conditions() {
|
||||||
|
let dir = tempfile::tempdir().unwrap();
|
||||||
|
let malformed = serde_json::from_value::<PluginManifest>(serde_json::json!({
|
||||||
|
"manifest_version": 1,
|
||||||
|
"id": "io.dbx.conditions",
|
||||||
|
"name": "Conditions",
|
||||||
|
"version": "1.0.0",
|
||||||
|
"publisher": "example",
|
||||||
|
"engines": { "dbx": ">=0.1.0", "host_api": "^1.0" },
|
||||||
|
"contributions": [{
|
||||||
|
"type": "connection-provider",
|
||||||
|
"id": "conditions.connection",
|
||||||
|
"database_type": "conditions",
|
||||||
|
"fields": [
|
||||||
|
{ "key": "mode", "label": "Mode", "type": "text" },
|
||||||
|
{
|
||||||
|
"key": "private_key_path",
|
||||||
|
"label": "Private key",
|
||||||
|
"type": "text",
|
||||||
|
"visible_when": { "field": "missing", "one_of": [] },
|
||||||
|
"required_when": { "field": "mode", "one_of": ["custom"], "extra": true }
|
||||||
|
}
|
||||||
|
]
|
||||||
|
}]
|
||||||
|
}));
|
||||||
|
|
||||||
|
assert!(malformed.is_err());
|
||||||
|
|
||||||
|
let manifest: PluginManifest = serde_json::from_value(serde_json::json!({
|
||||||
|
"manifest_version": 1,
|
||||||
|
"id": "io.dbx.conditions",
|
||||||
|
"name": "Conditions",
|
||||||
|
"version": "1.0.0",
|
||||||
|
"publisher": "example",
|
||||||
|
"engines": { "dbx": ">=0.1.0", "host_api": "^1.0" },
|
||||||
|
"contributions": [{
|
||||||
|
"type": "connection-provider",
|
||||||
|
"id": "conditions.connection",
|
||||||
|
"database_type": "conditions",
|
||||||
|
"fields": [
|
||||||
|
{ "key": "mode", "label": "Mode", "type": "text" },
|
||||||
|
{
|
||||||
|
"key": "private_key_path",
|
||||||
|
"label": "Private key",
|
||||||
|
"type": "text",
|
||||||
|
"visible_when": { "field": "missing", "one_of": [] },
|
||||||
|
"required_when": { "field": "mode", "one_of": ["custom"] }
|
||||||
|
}
|
||||||
|
]
|
||||||
|
}]
|
||||||
|
}))
|
||||||
|
.unwrap();
|
||||||
|
let compatibility = manifest.compatibility(dir.path(), "0.5.68");
|
||||||
|
|
||||||
|
assert!(!compatibility.compatible);
|
||||||
|
assert!(compatibility.errors.iter().any(|error| error.contains("visible_when one_of cannot be empty")));
|
||||||
|
assert!(compatibility
|
||||||
|
.errors
|
||||||
|
.iter()
|
||||||
|
.any(|error| error.contains("visible_when references unknown field 'missing'")));
|
||||||
|
}
|
||||||
}
|
}
|
||||||
@@ -4181,6 +4181,7 @@ fn pool_kind_has_transactional_path(pool: &PoolKind) -> bool {
|
|||||||
PoolKind::MessageQueue
|
PoolKind::MessageQueue
|
||||||
| PoolKind::Nacos
|
| PoolKind::Nacos
|
||||||
| PoolKind::Consul(_)
|
| PoolKind::Consul(_)
|
||||||
|
| PoolKind::PluginConnection(_)
|
||||||
| PoolKind::HBase(_)
|
| PoolKind::HBase(_)
|
||||||
| PoolKind::DuckDbWorker(_)
|
| PoolKind::DuckDbWorker(_)
|
||||||
| PoolKind::Redis(_)
|
| PoolKind::Redis(_)
|
||||||
@@ -4193,8 +4194,7 @@ fn pool_kind_has_transactional_path(pool: &PoolKind) -> bool {
|
|||||||
| PoolKind::InfluxDb(_)
|
| PoolKind::InfluxDb(_)
|
||||||
| PoolKind::InfluxDb3(_)
|
| PoolKind::InfluxDb3(_)
|
||||||
| PoolKind::VictoriaMetrics(_)
|
| PoolKind::VictoriaMetrics(_)
|
||||||
| PoolKind::ExternalDriver { .. }
|
| PoolKind::ExternalDriver { .. } => false,
|
||||||
| PoolKind::PluginConnection(_) => false,
|
|
||||||
#[cfg(feature = "mq-admin")]
|
#[cfg(feature = "mq-admin")]
|
||||||
PoolKind::Mqtt(_) => false,
|
PoolKind::Mqtt(_) => false,
|
||||||
}
|
}
|
||||||
@@ -4575,9 +4575,11 @@ fn batch_transaction_path(pool: &PoolKind) -> BatchTransactionPath {
|
|||||||
PoolKind::Sqlite(pool) => BatchTransactionPath::Sqlite(pool.clone()),
|
PoolKind::Sqlite(pool) => BatchTransactionPath::Sqlite(pool.clone()),
|
||||||
PoolKind::SqlServer(_) => BatchTransactionPath::Explicit,
|
PoolKind::SqlServer(_) => BatchTransactionPath::Explicit,
|
||||||
PoolKind::Agent(client) => BatchTransactionPath::Agent(client.clone()),
|
PoolKind::Agent(client) => BatchTransactionPath::Agent(client.clone()),
|
||||||
PoolKind::MessageQueue | PoolKind::Nacos | PoolKind::Consul(_) | PoolKind::HBase(_) => {
|
PoolKind::MessageQueue
|
||||||
BatchTransactionPath::Unsupported
|
| PoolKind::Nacos
|
||||||
}
|
| PoolKind::PluginConnection(_)
|
||||||
|
| PoolKind::Consul(_)
|
||||||
|
| PoolKind::HBase(_) => BatchTransactionPath::Unsupported,
|
||||||
#[cfg(feature = "mq-admin")]
|
#[cfg(feature = "mq-admin")]
|
||||||
PoolKind::Mqtt(_) => BatchTransactionPath::Unsupported,
|
PoolKind::Mqtt(_) => BatchTransactionPath::Unsupported,
|
||||||
PoolKind::DuckDbWorker(_)
|
PoolKind::DuckDbWorker(_)
|
||||||
@@ -4595,8 +4597,7 @@ fn batch_transaction_path(pool: &PoolKind) -> BatchTransactionPath {
|
|||||||
| PoolKind::InfluxDb(_)
|
| PoolKind::InfluxDb(_)
|
||||||
| PoolKind::InfluxDb3(_)
|
| PoolKind::InfluxDb3(_)
|
||||||
| PoolKind::VictoriaMetrics(_)
|
| PoolKind::VictoriaMetrics(_)
|
||||||
| PoolKind::ExternalDriver { .. }
|
| PoolKind::ExternalDriver { .. } => BatchTransactionPath::Unsupported,
|
||||||
| PoolKind::PluginConnection(_) => BatchTransactionPath::Unsupported,
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -8809,7 +8810,7 @@ for line in sys.stdin:
|
|||||||
std::fs::write(
|
std::fs::write(
|
||||||
&executable,
|
&executable,
|
||||||
format!(
|
format!(
|
||||||
"#!/bin/sh\nwhile IFS= read -r line; do\n id=$(printf '%s' \"$line\" | sed -E 's/.*\"id\":([0-9]+).*/\\1/')\n case \"$line\" in\n *'\"method\":\"executeQueryPage\"'*)\n echo executeQueryPage >> '{}'\n case \"$line\" in\n *'left('*) printf '{{\"id\":%s,\"error\":{{\"message\":\"ERROR: invalid byte sequence for encoding \\\"UTF8\\\": 0xe2\"}}}}\\n' \"$id\" ;;\n *) printf '{{\"id\":%s,\"result\":{{\"columns\":[\"id\",\"description\",\"__DBX_LARGE_VALUE_BYTES_T_1\"],\"column_types\":[\"integer\",\"text\",\"text\"],\"rows\":[[1,\"abcdef\",\"T:3\"]],\"affected_rows\":0,\"execution_time_ms\":1,\"truncated\":false}}}}\\n' \"$id\" ;;\n esac\n ;;\n *'\"method\":\"executeQuery\"'*)\n echo executeQuery >> '{}'\n case \"$line\" in\n *'left('*) printf '{{\"id\":%s,\"error\":{{\"message\":\"ERROR: invalid byte sequence for encoding \\\"UTF8\\\": 0xe2\"}}}}\\n' \"$id\" ;;\n *) printf '{{\"id\":%s,\"result\":{{\"columns\":[\"id\",\"description\",\"__DBX_LARGE_VALUE_BYTES_T_1\"],\"column_types\":[\"integer\",\"text\",\"text\"],\"rows\":[[1,\"abcdef\",\"T:3\"]],\"affected_rows\":0,\"execution_time_ms\":1,\"truncated\":false}}}}\\n' \"$id\" ;;\n esac\n ;;\n esac\ndone\n",
|
"#!/bin/sh\nwhile IFS= read -r line; do\n id=$(printf '%s' \"$line\" | sed -E 's/.*\"id\":([0-9]+).*/\\1/')\n case \"$line\" in\n *'\"method\":\"executeQueryPage\"'*)\n echo executeQueryPage >> '{}'\n case \"$line\" in\n *'left('*) printf '{{\"id\":%s,\"error\":{{\"message\":\"ERROR: invalid byte sequence for encoding UTF8: 0xe2\"}}}}\\n' \"$id\" ;;\n *) printf '{{\"id\":%s,\"result\":{{\"columns\":[\"id\",\"description\",\"__DBX_LARGE_VALUE_BYTES_T_1\"],\"column_types\":[\"integer\",\"text\",\"text\"],\"rows\":[[1,\"abcdef\",\"T:3\"]],\"affected_rows\":0,\"execution_time_ms\":1,\"truncated\":false}}}}\\n' \"$id\" ;;\n esac\n ;;\n *'\"method\":\"executeQuery\"'*)\n echo executeQuery >> '{}'\n case \"$line\" in\n *'left('*) printf '{{\"id\":%s,\"error\":{{\"message\":\"ERROR: invalid byte sequence for encoding UTF8: 0xe2\"}}}}\\n' \"$id\" ;;\n *) printf '{{\"id\":%s,\"result\":{{\"columns\":[\"id\",\"description\",\"__DBX_LARGE_VALUE_BYTES_T_1\"],\"column_types\":[\"integer\",\"text\",\"text\"],\"rows\":[[1,\"abcdef\",\"T:3\"]],\"affected_rows\":0,\"execution_time_ms\":1,\"truncated\":false}}}}\\n' \"$id\" ;;\n esac\n ;;\n esac\ndone\n",
|
||||||
calls.display(),
|
calls.display(),
|
||||||
calls.display()
|
calls.display()
|
||||||
),
|
),
|
||||||
|
|||||||
@@ -15,10 +15,11 @@ use crate::ai::{
|
|||||||
AiRunStatus,
|
AiRunStatus,
|
||||||
};
|
};
|
||||||
use crate::connection_secrets::{
|
use crate::connection_secrets::{
|
||||||
CASSANDRA_KEYSTORE_PASSWORD_KEY, CASSANDRA_TLS_SECRET_PREFIX, CASSANDRA_TRUSTSTORE_PASSWORD_KEY,
|
plugin_connection_secret_key, CASSANDRA_KEYSTORE_PASSWORD_KEY, CASSANDRA_TLS_SECRET_PREFIX,
|
||||||
MQ_AUTH_API_KEY_VALUE_KEY, MQ_AUTH_CLIENT_SECRET_KEY, MQ_AUTH_PASSWORD_KEY, MQ_AUTH_SECRET_PREFIX,
|
CASSANDRA_TRUSTSTORE_PASSWORD_KEY, MQ_AUTH_API_KEY_VALUE_KEY, MQ_AUTH_CLIENT_SECRET_KEY, MQ_AUTH_PASSWORD_KEY,
|
||||||
MQ_AUTH_TOKEN_KEY, MQ_TOKEN_SIGNING_KEY, MQ_TOKEN_SIGNING_SECRET_PREFIX, NACOS_AUTH_PASSWORD_KEY,
|
MQ_AUTH_SECRET_PREFIX, MQ_AUTH_TOKEN_KEY, MQ_TOKEN_SIGNING_KEY, MQ_TOKEN_SIGNING_SECRET_PREFIX,
|
||||||
NACOS_AUTH_SECRET_PREFIX, NACOS_RNACOS_CONSOLE_PASSWORD_KEY, PLUGIN_CONNECTION_SECRET_PREFIX,
|
NACOS_AUTH_PASSWORD_KEY, NACOS_AUTH_SECRET_PREFIX, NACOS_RNACOS_CONSOLE_PASSWORD_KEY,
|
||||||
|
PLUGIN_CONNECTION_SECRET_PREFIX,
|
||||||
};
|
};
|
||||||
use crate::db::sqlite::{connect_path_create_if_missing, SqliteHandle};
|
use crate::db::sqlite::{connect_path_create_if_missing, SqliteHandle};
|
||||||
use crate::history::{
|
use crate::history::{
|
||||||
@@ -1363,6 +1364,12 @@ fn scrub_nacos_auth_secrets(config: &mut ConnectionConfig) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
fn scrub_plugin_connection_secrets(config: &mut ConnectionConfig) {
|
||||||
|
for secret in config.connection_secrets.values_mut() {
|
||||||
|
secret.clear();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
fn scrub_cassandra_tls_secrets(config: &mut ConnectionConfig) {
|
fn scrub_cassandra_tls_secrets(config: &mut ConnectionConfig) {
|
||||||
if config.db_type != DatabaseType::Cassandra {
|
if config.db_type != DatabaseType::Cassandra {
|
||||||
return;
|
return;
|
||||||
@@ -3776,16 +3783,32 @@ impl Storage {
|
|||||||
let needs_mq_token_signing_rewrite = self.hydrate_mq_token_signing_secret(&id, &mut config).await?;
|
let needs_mq_token_signing_rewrite = self.hydrate_mq_token_signing_secret(&id, &mut config).await?;
|
||||||
let needs_nacos_auth_rewrite = self.hydrate_nacos_auth_secret(&id, &mut config).await?;
|
let needs_nacos_auth_rewrite = self.hydrate_nacos_auth_secret(&id, &mut config).await?;
|
||||||
let needs_cassandra_tls_rewrite = self.hydrate_cassandra_tls_secrets(&id, &mut config).await?;
|
let needs_cassandra_tls_rewrite = self.hydrate_cassandra_tls_secrets(&id, &mut config).await?;
|
||||||
|
let mut needs_plugin_secret_rewrite = false;
|
||||||
|
let plugin_secret_keys = config.connection_secrets.keys().cloned().collect::<Vec<_>>();
|
||||||
|
for key in plugin_secret_keys {
|
||||||
|
let storage_key = plugin_connection_secret_key(&key)?;
|
||||||
|
let current = config.connection_secrets.get(&key).cloned().unwrap_or_default();
|
||||||
|
if current.is_empty() {
|
||||||
|
if let Some(secret) = self.get_secret(&id, &storage_key).await? {
|
||||||
|
config.connection_secrets.insert(key, secret);
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
self.set_secret(&id, &storage_key, ¤t).await?;
|
||||||
|
needs_plugin_secret_rewrite = true;
|
||||||
|
}
|
||||||
|
}
|
||||||
let needs_external_secret_rewrite = needs_mq_auth_rewrite
|
let needs_external_secret_rewrite = needs_mq_auth_rewrite
|
||||||
|| needs_mq_token_signing_rewrite
|
|| needs_mq_token_signing_rewrite
|
||||||
|| needs_nacos_auth_rewrite
|
|| needs_nacos_auth_rewrite
|
||||||
|| needs_cassandra_tls_rewrite;
|
|| needs_cassandra_tls_rewrite
|
||||||
|
|| needs_plugin_secret_rewrite;
|
||||||
if needs_external_secret_rewrite {
|
if needs_external_secret_rewrite {
|
||||||
let mut sanitized = config.clone().canonicalized();
|
let mut sanitized = config.clone().canonicalized();
|
||||||
scrub_mq_auth_secrets(&mut sanitized);
|
scrub_mq_auth_secrets(&mut sanitized);
|
||||||
scrub_mq_token_signing_secret(&mut sanitized);
|
scrub_mq_token_signing_secret(&mut sanitized);
|
||||||
scrub_nacos_auth_secrets(&mut sanitized);
|
scrub_nacos_auth_secrets(&mut sanitized);
|
||||||
scrub_cassandra_tls_secrets(&mut sanitized);
|
scrub_cassandra_tls_secrets(&mut sanitized);
|
||||||
|
scrub_plugin_connection_secrets(&mut sanitized);
|
||||||
let sanitized_json = serde_json::to_string(&sanitized).map_err(|e| e.to_string())?;
|
let sanitized_json = serde_json::to_string(&sanitized).map_err(|e| e.to_string())?;
|
||||||
let update_id = id.clone();
|
let update_id = id.clone();
|
||||||
self.with_conn(move |conn| {
|
self.with_conn(move |conn| {
|
||||||
@@ -5353,8 +5376,9 @@ mod tests {
|
|||||||
};
|
};
|
||||||
use crate::connection_secrets::NACOS_RNACOS_CONSOLE_PASSWORD_KEY;
|
use crate::connection_secrets::NACOS_RNACOS_CONSOLE_PASSWORD_KEY;
|
||||||
use crate::connection_secrets::{
|
use crate::connection_secrets::{
|
||||||
CASSANDRA_KEYSTORE_PASSWORD_KEY, CASSANDRA_TRUSTSTORE_PASSWORD_KEY, MQ_AUTH_PASSWORD_KEY, MQ_AUTH_TOKEN_KEY,
|
plugin_connection_secret_key, CASSANDRA_KEYSTORE_PASSWORD_KEY, CASSANDRA_TRUSTSTORE_PASSWORD_KEY,
|
||||||
MQ_TOKEN_SIGNING_KEY, NACOS_AUTH_PASSWORD_KEY, PLUGIN_CONNECTION_SECRET_PREFIX,
|
MQ_AUTH_PASSWORD_KEY, MQ_AUTH_TOKEN_KEY, MQ_TOKEN_SIGNING_KEY, NACOS_AUTH_PASSWORD_KEY,
|
||||||
|
PLUGIN_CONNECTION_SECRET_PREFIX,
|
||||||
};
|
};
|
||||||
use crate::history::{HistoryConnectionFilter, HistoryDatabaseFilter, HistoryEntry, HistorySearchRequest};
|
use crate::history::{HistoryConnectionFilter, HistoryDatabaseFilter, HistoryEntry, HistorySearchRequest};
|
||||||
use crate::models::connection::{
|
use crate::models::connection::{
|
||||||
@@ -6084,7 +6108,7 @@ mod tests {
|
|||||||
}
|
}
|
||||||
|
|
||||||
#[tokio::test]
|
#[tokio::test]
|
||||||
async fn save_connections_moves_plugin_secrets_to_secret_table_and_restores_them() {
|
async fn save_connections_moves_plugin_secrets_to_secret_table_and_clears_removed_values() {
|
||||||
let path = temp_db_path("plugin-secrets");
|
let path = temp_db_path("plugin-secrets");
|
||||||
let storage = Storage::open(&path).await.unwrap();
|
let storage = Storage::open(&path).await.unwrap();
|
||||||
let mut config = plain_connection("plugin", "");
|
let mut config = plain_connection("plugin", "");
|
||||||
@@ -6673,6 +6697,39 @@ mod tests {
|
|||||||
let _ = std::fs::remove_file(path);
|
let _ = std::fs::remove_file(path);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[tokio::test]
|
||||||
|
async fn save_connections_moves_plugin_secrets_to_secret_table_and_restores_them() {
|
||||||
|
let path = temp_db_path("plugin-connection-secret");
|
||||||
|
let storage = Storage::open(&path).await.unwrap();
|
||||||
|
let mut config = mq_connection("plugin-connection", "");
|
||||||
|
config.name = "Hello plugin".to_string();
|
||||||
|
config.db_type = DatabaseType::Plugin;
|
||||||
|
config.driver_profile = Some("plugin".to_string());
|
||||||
|
config.external_config = Some(serde_json::json!({ "greeting": "Hello" }));
|
||||||
|
config.plugin_id = Some("dbx.example.hello".to_string());
|
||||||
|
config.plugin_connection_provider = Some("hello.connection".to_string());
|
||||||
|
config.plugin_connection_type = Some("hello".to_string());
|
||||||
|
config.connection_secrets.insert("access_token".to_string(), "plugin-secret".to_string());
|
||||||
|
|
||||||
|
storage.save_connections(&[config]).await.unwrap();
|
||||||
|
|
||||||
|
let raw_json = raw_connection_json(&storage, "plugin-connection").await;
|
||||||
|
assert!(!raw_json.contains("plugin-secret"));
|
||||||
|
let persisted: ConnectionConfig = serde_json::from_str(&raw_json).unwrap();
|
||||||
|
assert_eq!(persisted.connection_secrets.get("access_token"), None);
|
||||||
|
assert_eq!(
|
||||||
|
storage
|
||||||
|
.get_secret("plugin-connection", &plugin_connection_secret_key("access_token").unwrap())
|
||||||
|
.await
|
||||||
|
.unwrap()
|
||||||
|
.as_deref(),
|
||||||
|
Some("plugin-secret")
|
||||||
|
);
|
||||||
|
|
||||||
|
let loaded = storage.load_connections().await.unwrap();
|
||||||
|
assert_eq!(loaded[0].connection_secrets.get("access_token").map(String::as_str), Some("plugin-secret"));
|
||||||
|
}
|
||||||
|
|
||||||
#[tokio::test]
|
#[tokio::test]
|
||||||
async fn metadata_save_scrubs_mq_auth_token_and_preserves_existing_secret() {
|
async fn metadata_save_scrubs_mq_auth_token_and_preserves_existing_secret() {
|
||||||
let path = temp_db_path("mq-token-metadata");
|
let path = temp_db_path("mq-token-metadata");
|
||||||
|
|||||||
@@ -0,0 +1,38 @@
|
|||||||
|
//! Verifies a real DBX app store: plugin discovery + MCP tool bridge.
|
||||||
|
//! cargo run -p dbx-mcp --example verify_plugin_store -- <data-dir> [app-version]
|
||||||
|
use dbx_mcp::LocalBackend;
|
||||||
|
|
||||||
|
#[tokio::main]
|
||||||
|
async fn main() {
|
||||||
|
let args: Vec<String> = std::env::args().skip(1).collect();
|
||||||
|
let data_dir = std::path::PathBuf::from(&args[0]);
|
||||||
|
let app_version = args.get(1).map(String::as_str).unwrap_or("0.5.96");
|
||||||
|
let backend =
|
||||||
|
LocalBackend::open_with_app_version(&data_dir.join("dbx.db"), app_version).await.expect("open local backend");
|
||||||
|
|
||||||
|
let installed = backend.state().plugins.list_installed().unwrap();
|
||||||
|
for plugin in &installed {
|
||||||
|
println!(
|
||||||
|
"plugin: {} v{} compatible={} errors={:?}",
|
||||||
|
plugin.manifest.id, plugin.manifest.version, plugin.compatibility.compatible, plugin.compatibility.errors
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
let providers = backend.list_plugin_tools().await.expect("list plugin tools");
|
||||||
|
for provider in &providers {
|
||||||
|
let tools = provider["tools"].as_array().map(|tools| tools.len()).unwrap_or(0);
|
||||||
|
println!("mcp tools: {} -> {} tools", provider["pluginId"], tools);
|
||||||
|
let call = backend
|
||||||
|
.call_plugin_tool(
|
||||||
|
provider["pluginId"].as_str().unwrap(),
|
||||||
|
"ssh_list_known_hosts",
|
||||||
|
None,
|
||||||
|
&serde_json::json!({}),
|
||||||
|
)
|
||||||
|
.await;
|
||||||
|
match call {
|
||||||
|
Ok(result) => println!("tool call ok: isError={}", result["isError"].as_bool().unwrap_or(true)),
|
||||||
|
Err(error) => println!("tool call failed: {error}"),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -582,6 +582,12 @@ impl LocalBackend {
|
|||||||
}
|
}
|
||||||
|
|
||||||
pub async fn open(path: &Path) -> Result<Self, String> {
|
pub async fn open(path: &Path) -> Result<Self, String> {
|
||||||
|
Self::open_with_app_version(path, env!("CARGO_PKG_VERSION")).await
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Same as [`open`], but lets tests and embedded callers pin the app version
|
||||||
|
/// used for plugin compatibility checks instead of the compile-time version.
|
||||||
|
pub async fn open_with_app_version(path: &Path, app_version: &str) -> Result<Self, String> {
|
||||||
let storage = Storage::open(path).await?;
|
let storage = Storage::open(path).await?;
|
||||||
let configs = storage.load_connections().await?;
|
let configs = storage.load_connections().await?;
|
||||||
let desktop_settings = storage.load_desktop_settings().await.unwrap_or_default();
|
let desktop_settings = storage.load_desktop_settings().await.unwrap_or_default();
|
||||||
@@ -592,7 +598,7 @@ impl LocalBackend {
|
|||||||
storage,
|
storage,
|
||||||
plugin_dir,
|
plugin_dir,
|
||||||
agent_dir,
|
agent_dir,
|
||||||
env!("CARGO_PKG_VERSION"),
|
app_version,
|
||||||
));
|
));
|
||||||
let config_map: HashMap<String, ConnectionConfig> =
|
let config_map: HashMap<String, ConnectionConfig> =
|
||||||
configs.into_iter().map(|config| (config.id.clone(), config)).collect();
|
configs.into_iter().map(|config| (config.id.clone(), config)).collect();
|
||||||
@@ -604,6 +610,65 @@ impl LocalBackend {
|
|||||||
&self.state
|
&self.state
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// List the MCP tools exposed by every installed plugin.
|
||||||
|
///
|
||||||
|
/// Plugin MCP surfaces are discovered through the same `mcp/tools`
|
||||||
|
/// protocol used by the desktop bridge. Keep the response grouped by
|
||||||
|
/// plugin so callers can select the correct sidecar for a tool call.
|
||||||
|
pub async fn list_plugin_tools(&self) -> Result<Vec<Value>, String> {
|
||||||
|
let plugins = self.state.plugins.list_installed()?;
|
||||||
|
let mut providers = Vec::new();
|
||||||
|
for plugin in plugins {
|
||||||
|
if !plugin.compatibility.compatible || plugin.manifest.backend_entrypoint().is_none() {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
let tools: Value = self
|
||||||
|
.state
|
||||||
|
.plugin_host
|
||||||
|
.invoke(&plugin.manifest.id, "mcp/tools", json!({}), None, Some(std::time::Duration::from_secs(30)))
|
||||||
|
.await?;
|
||||||
|
let tool_list = tools
|
||||||
|
.get("tools")
|
||||||
|
.cloned()
|
||||||
|
.or_else(|| tools.is_array().then_some(tools.clone()))
|
||||||
|
.unwrap_or_else(|| json!([]));
|
||||||
|
providers.push(json!({
|
||||||
|
"pluginId": plugin.manifest.id,
|
||||||
|
"tools": tool_list,
|
||||||
|
}));
|
||||||
|
}
|
||||||
|
Ok(providers)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Call one plugin MCP tool through the host-managed sidecar session.
|
||||||
|
/// When a saved connection is supplied, only its host-generated lifecycle
|
||||||
|
/// payload is sent to the plugin; credentials remain host-managed.
|
||||||
|
pub async fn call_plugin_tool(
|
||||||
|
&self,
|
||||||
|
plugin_id: &str,
|
||||||
|
tool: &str,
|
||||||
|
connection_id: Option<&str>,
|
||||||
|
arguments: &Value,
|
||||||
|
) -> Result<Value, String> {
|
||||||
|
let mut params = json!({ "tool": tool, "arguments": arguments });
|
||||||
|
if let Some(connection_id) = connection_id {
|
||||||
|
let config = self
|
||||||
|
.state
|
||||||
|
.configs
|
||||||
|
.read()
|
||||||
|
.await
|
||||||
|
.get(connection_id)
|
||||||
|
.cloned()
|
||||||
|
.ok_or_else(|| format!("Connection not found: {connection_id}"))?;
|
||||||
|
let lifecycle = self.state.plugin_host.connection_params_standalone(&config)?;
|
||||||
|
params["lifecycle"] = lifecycle;
|
||||||
|
}
|
||||||
|
self.state
|
||||||
|
.plugin_host
|
||||||
|
.invoke(plugin_id, "mcp/call", params, None, Some(std::time::Duration::from_secs(300)))
|
||||||
|
.await
|
||||||
|
}
|
||||||
|
|
||||||
/// Sync the latest connection list from storage into the `AppState.configs` in-memory cache:
|
/// Sync the latest connection list from storage into the `AppState.configs` in-memory cache:
|
||||||
/// upsert new/changed entries and remove connections deleted from storage. Only LocalBackend
|
/// upsert new/changed entries and remove connections deleted from storage. Only LocalBackend
|
||||||
/// needs this — WebBackend talks HTTP and holds no local AppState, and the desktop mcp_bridge
|
/// needs this — WebBackend talks HTTP and holds no local AppState, and the desktop mcp_bridge
|
||||||
|
|||||||
@@ -0,0 +1,66 @@
|
|||||||
|
//! Full installation-pipeline test: installs the real ssh-sftp `.dbxp`
|
||||||
|
//! package through PluginPackageInstaller, then verifies the MCP bridge can
|
||||||
|
//! discover the plugin, start its sidecar, and call a tool.
|
||||||
|
//!
|
||||||
|
//! Set DBX_SSH_SFTP_PACKAGE to the packaged artifact; the test skips itself
|
||||||
|
//! otherwise.
|
||||||
|
|
||||||
|
use dbx_core::plugins::{PluginInstallPolicy, PluginPackageInstaller, PluginSignatureStatus};
|
||||||
|
use dbx_mcp::LocalBackend;
|
||||||
|
|
||||||
|
#[tokio::test]
|
||||||
|
async fn ssh_sftp_package_installs_and_serves_mcp_tools() {
|
||||||
|
let Ok(package) = std::env::var("DBX_SSH_SFTP_PACKAGE") else {
|
||||||
|
eprintln!("skipping: DBX_SSH_SFTP_PACKAGE is not set");
|
||||||
|
return;
|
||||||
|
};
|
||||||
|
let package = std::path::PathBuf::from(package);
|
||||||
|
assert!(package.is_file(), "package missing: {}", package.display());
|
||||||
|
|
||||||
|
let data_dir = tempfile::tempdir().unwrap();
|
||||||
|
let plugins_root = data_dir.path().join("plugins");
|
||||||
|
|
||||||
|
// 1. Install the .dbxp exactly like the DBX desktop app would.
|
||||||
|
let installer = PluginPackageInstaller::new(plugins_root.clone(), "0.6.0").expect("installer");
|
||||||
|
let result = installer.install_file(&package, PluginInstallPolicy::LocalDevelopment).expect("install .dbxp");
|
||||||
|
let response = result.response();
|
||||||
|
assert_eq!(response.plugin.manifest.id, "io.dbx.ssh-sftp");
|
||||||
|
assert!(!response.plugin.manifest.version.is_empty());
|
||||||
|
assert_eq!(response.signature, PluginSignatureStatus::Unsigned);
|
||||||
|
|
||||||
|
// 2. The installed layout is discoverable as a connection provider.
|
||||||
|
let database_path = data_dir.path().join("dbx.db");
|
||||||
|
let storage = dbx_core::storage::Storage::open(&database_path).await.unwrap();
|
||||||
|
drop(storage);
|
||||||
|
let backend = LocalBackend::open_with_app_version(&database_path, "0.6.0").await.unwrap();
|
||||||
|
let installed = backend.state().plugins.list_installed().unwrap();
|
||||||
|
let plugin =
|
||||||
|
installed.iter().find(|plugin| plugin.manifest.id == "io.dbx.ssh-sftp").expect("installed plugin listed");
|
||||||
|
assert!(plugin.compatibility.compatible, "plugin incompatible: {:?}", plugin.compatibility.errors);
|
||||||
|
|
||||||
|
// 3. MCP bridge: tool discovery over the real sidecar process.
|
||||||
|
let providers = backend.list_plugin_tools().await.expect("list plugin tools");
|
||||||
|
let ssh = providers
|
||||||
|
.iter()
|
||||||
|
.find(|provider| provider["pluginId"] == "io.dbx.ssh-sftp")
|
||||||
|
.expect("plugin contributes MCP tools");
|
||||||
|
let names = ssh["tools"]
|
||||||
|
.as_array()
|
||||||
|
.expect("tools array")
|
||||||
|
.iter()
|
||||||
|
.map(|tool| tool["name"].as_str().unwrap_or_default())
|
||||||
|
.collect::<Vec<_>>();
|
||||||
|
for expected in ["ssh_exec", "ssh_exec_sudo", "ssh_metrics", "sftp_list_dir", "sftp_chmod"] {
|
||||||
|
assert!(names.contains(&expected), "missing {expected} in {names:?}");
|
||||||
|
}
|
||||||
|
|
||||||
|
// 4. MCP bridge: a real tool call through the installed sidecar.
|
||||||
|
let listed = backend
|
||||||
|
.call_plugin_tool("io.dbx.ssh-sftp", "ssh_list_known_hosts", None, &serde_json::json!({}))
|
||||||
|
.await
|
||||||
|
.expect("call plugin tool");
|
||||||
|
assert!(!listed["isError"].as_bool().unwrap_or(true), "tool failed: {listed}");
|
||||||
|
let text = listed["content"][0]["text"].as_str().expect("result text");
|
||||||
|
let parsed: serde_json::Value = serde_json::from_str(text).expect("result JSON");
|
||||||
|
assert!(parsed["knownHosts"].is_array());
|
||||||
|
}
|
||||||
+2
-1
@@ -14,7 +14,8 @@ function occurrences(source: string, pattern: RegExp): number {
|
|||||||
test("sidebar rows stay within the hot-path source budget", () => {
|
test("sidebar rows stay within the hot-path source budget", () => {
|
||||||
assert.ok(treeItem.split("\n").length <= 2_200, "TreeItem must stay below 2,200 lines");
|
assert.ok(treeItem.split("\n").length <= 2_200, "TreeItem must stay below 2,200 lines");
|
||||||
assert.ok(occurrences(treeItem, /^(?:async )?function /gm) <= 90, "TreeItem must stay below 90 top-level functions");
|
assert.ok(occurrences(treeItem, /^(?:async )?function /gm) <= 90, "TreeItem must stay below 90 top-level functions");
|
||||||
assert.ok(occurrences(treeItem, /^const [A-Za-z0-9_]+ = computed\(/gm) <= 30, "TreeItem must stay below 30 computed values");
|
// +1 for the plugin-platform connection visual (provider SVG on plugin rows).
|
||||||
|
assert.ok(occurrences(treeItem, /^const [A-Za-z0-9_]+ = computed\(/gm) <= 26, "TreeItem must stay below 26 computed values");
|
||||||
assert.doesNotMatch(treeItem, /ContextMenuItem|emit\("open-data"|getTreeItemDialogController|executeWithProductionSqlGuard/);
|
assert.doesNotMatch(treeItem, /ContextMenuItem|emit\("open-data"|getTreeItemDialogController|executeWithProductionSqlGuard/);
|
||||||
});
|
});
|
||||||
|
|
||||||
|
|||||||
@@ -141,6 +141,15 @@
|
|||||||
"contributions": { "type": "object", "propertyNames": { "$ref": "#/$defs/identifier" }, "additionalProperties": { "$ref": "#/$defs/contributionLocalization" } }
|
"contributions": { "type": "object", "propertyNames": { "$ref": "#/$defs/identifier" }, "additionalProperties": { "$ref": "#/$defs/contributionLocalization" } }
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
|
"fieldCondition": {
|
||||||
|
"type": "object",
|
||||||
|
"additionalProperties": false,
|
||||||
|
"required": ["field", "one_of"],
|
||||||
|
"properties": {
|
||||||
|
"field": { "$ref": "#/$defs/identifier" },
|
||||||
|
"one_of": { "type": "array", "items": { "type": "string" }, "minItems": 1 }
|
||||||
|
}
|
||||||
|
},
|
||||||
"formField": {
|
"formField": {
|
||||||
"type": "object",
|
"type": "object",
|
||||||
"additionalProperties": false,
|
"additionalProperties": false,
|
||||||
@@ -154,7 +163,9 @@
|
|||||||
"required": { "type": "boolean" },
|
"required": { "type": "boolean" },
|
||||||
"default": { "type": ["string", "number", "boolean", "null"] },
|
"default": { "type": ["string", "number", "boolean", "null"] },
|
||||||
"options": { "type": "array", "items": { "$ref": "#/$defs/selectOption" } },
|
"options": { "type": "array", "items": { "$ref": "#/$defs/selectOption" } },
|
||||||
"binding": { "enum": ["config", "secret", "name", "host", "port", "username", "password", "database"] }
|
"binding": { "enum": ["config", "secret", "name", "host", "port", "username", "password", "database"] },
|
||||||
|
"visible_when": { "$ref": "#/$defs/fieldCondition" },
|
||||||
|
"required_when": { "$ref": "#/$defs/fieldCondition" }
|
||||||
},
|
},
|
||||||
"allOf": [
|
"allOf": [
|
||||||
{
|
{
|
||||||
|
|||||||
+27
-42
@@ -736,8 +736,12 @@ fn prompt_project_template<R: BufRead, W: Write>(reader: &mut R, writer: &mut W)
|
|||||||
"2" | "svelte" => return Ok(ProjectTemplate::Svelte),
|
"2" | "svelte" => return Ok(ProjectTemplate::Svelte),
|
||||||
"3" | "rust" => return Ok(ProjectTemplate::Rust),
|
"3" | "rust" => return Ok(ProjectTemplate::Rust),
|
||||||
"4" | "go" | "golang" => return Ok(ProjectTemplate::Go),
|
"4" | "go" | "golang" => return Ok(ProjectTemplate::Go),
|
||||||
_ => writeln!(writer, "{} choose 1/Frontend, 2/Svelte, 3/Rust, or 4/Go", styled_stdout("Invalid:", ANSI_WARNING))
|
_ => writeln!(
|
||||||
.map_err(|error| error.to_string())?,
|
writer,
|
||||||
|
"{} choose 1/Frontend, 2/Svelte, 3/Rust, or 4/Go",
|
||||||
|
styled_stdout("Invalid:", ANSI_WARNING)
|
||||||
|
)
|
||||||
|
.map_err(|error| error.to_string())?,
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -1135,44 +1139,28 @@ fn build_go_backend(
|
|||||||
return Err(format!("Go backend is missing {}/go.mod", backend_directory.display()));
|
return Err(format!("Go backend is missing {}/go.mod", backend_directory.display()));
|
||||||
}
|
}
|
||||||
let mut command = Command::new("go");
|
let mut command = Command::new("go");
|
||||||
command.current_dir(&backend_directory).arg("build").arg("-trimpath");
|
command.current_dir(&backend_directory).arg("build").arg("-trimpath").arg("-o").arg(staged_executable).arg(".");
|
||||||
if let Some(sdk_root) = sdk_root_from_environment()? {
|
if let Some(sdk_root) = sdk_root_from_environment()? {
|
||||||
let sdk = sdk_root.join("plugins/sdk/go/dbx-plugin-sdk");
|
let sdk = sdk_root.join("plugins/sdk/go/dbx-plugin-sdk");
|
||||||
if !sdk.join("go.mod").is_file() {
|
if !sdk.join("go.mod").is_file() {
|
||||||
return Err(format!("Go plugin SDK was not found at {}", sdk.display()));
|
return Err(format!("Go plugin SDK was not found at {}", sdk.display()));
|
||||||
}
|
}
|
||||||
fs::create_dir_all(build_directory).map_err(|error| error.to_string())?;
|
fs::create_dir_all(build_directory).map_err(|error| error.to_string())?;
|
||||||
let mod_file = build_directory.join("dbx-plugin.mod");
|
let work_file = build_directory.join("go.work");
|
||||||
fs::copy(backend_directory.join("go.mod"), &mod_file).map_err(|error| error.to_string())?;
|
fs::write(
|
||||||
if backend_directory.join("go.sum").is_file() {
|
&work_file,
|
||||||
fs::copy(backend_directory.join("go.sum"), build_directory.join("dbx-plugin.sum"))
|
format!(
|
||||||
.map_err(|error| error.to_string())?;
|
"go 1.22\n\nuse (\n\t{}\n\t{}\n)\n",
|
||||||
}
|
serde_json::to_string(&backend_directory.to_string_lossy()).map_err(|error| error.to_string())?,
|
||||||
let sdk_module = go_module_path(&sdk.join("go.mod"))?;
|
serde_json::to_string(&sdk.to_string_lossy()).map_err(|error| error.to_string())?
|
||||||
let mut mod_command = Command::new("go");
|
),
|
||||||
mod_command
|
)
|
||||||
.current_dir(&backend_directory)
|
.map_err(|error| error.to_string())?;
|
||||||
.arg("mod")
|
command.env("GOWORK", work_file);
|
||||||
.arg("edit")
|
|
||||||
.arg("-modfile")
|
|
||||||
.arg(&mod_file)
|
|
||||||
.arg(format!("-replace={sdk_module}={}", sdk.display()));
|
|
||||||
run_command(&mut mod_command, "Go module configuration")?;
|
|
||||||
command.arg("-modfile").arg(mod_file).env("GOWORK", "off");
|
|
||||||
}
|
}
|
||||||
command.arg("-o").arg(staged_executable).arg(".");
|
|
||||||
run_command(&mut command, "Go backend build")
|
run_command(&mut command, "Go backend build")
|
||||||
}
|
}
|
||||||
|
|
||||||
fn go_module_path(path: &Path) -> Result<String, String> {
|
|
||||||
let contents = fs::read_to_string(path).map_err(|error| format!("Failed to read {}: {error}", path.display()))?;
|
|
||||||
contents
|
|
||||||
.lines()
|
|
||||||
.find_map(|line| line.strip_prefix("module ").map(str::trim).filter(|module| !module.is_empty()))
|
|
||||||
.map(str::to_string)
|
|
||||||
.ok_or_else(|| format!("{} is missing a module directive", path.display()))
|
|
||||||
}
|
|
||||||
|
|
||||||
fn run_command(command: &mut Command, label: &str) -> Result<(), String> {
|
fn run_command(command: &mut Command, label: &str) -> Result<(), String> {
|
||||||
command.stdin(Stdio::inherit()).stdout(Stdio::inherit()).stderr(Stdio::inherit());
|
command.stdin(Stdio::inherit()).stdout(Stdio::inherit()).stderr(Stdio::inherit());
|
||||||
let status = command.status().map_err(|error| format!("Failed to start {label}: {error}"))?;
|
let status = command.status().map_err(|error| format!("Failed to start {label}: {error}"))?;
|
||||||
@@ -1484,7 +1472,10 @@ fn print_usage() {
|
|||||||
println!("\n{}", styled_stdout("Usage:", ANSI_PROMPT));
|
println!("\n{}", styled_stdout("Usage:", ANSI_PROMPT));
|
||||||
println!(" dbx-plugin <command> [options]");
|
println!(" dbx-plugin <command> [options]");
|
||||||
println!("\n{}", styled_stdout("Commands:", ANSI_PROMPT));
|
println!("\n{}", styled_stdout("Commands:", ANSI_PROMPT));
|
||||||
println!(" {} Create a frontend-only, Svelte, Rust, or Go plugin project", styled_stdout("create", ANSI_SUCCESS));
|
println!(
|
||||||
|
" {} Create a frontend-only, Svelte, Rust, or Go plugin project",
|
||||||
|
styled_stdout("create", ANSI_SUCCESS)
|
||||||
|
);
|
||||||
println!(" {} Build a .dbxp package and artifact metadata", styled_stdout("package", ANSI_SUCCESS));
|
println!(" {} Build a .dbxp package and artifact metadata", styled_stdout("package", ANSI_SUCCESS));
|
||||||
println!(
|
println!(
|
||||||
" {} Run a plugin in the local browser development host (Node.js 22+)",
|
" {} Run a plugin in the local browser development host (Node.js 22+)",
|
||||||
@@ -1573,7 +1564,6 @@ fn keygen_usage() -> String {
|
|||||||
|
|
||||||
#[cfg(test)]
|
#[cfg(test)]
|
||||||
mod tests {
|
mod tests {
|
||||||
use std::fs;
|
|
||||||
use std::io::Cursor;
|
use std::io::Cursor;
|
||||||
use std::path::PathBuf;
|
use std::path::PathBuf;
|
||||||
|
|
||||||
@@ -1583,14 +1573,6 @@ mod tests {
|
|||||||
BackendConfig, CreateInputs, CreateOptions, PackageOptions, ProjectTemplate, ANSI_ACCENT,
|
BackendConfig, CreateInputs, CreateOptions, PackageOptions, ProjectTemplate, ANSI_ACCENT,
|
||||||
};
|
};
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn reads_go_module_paths() {
|
|
||||||
let root = tempfile::tempdir().unwrap();
|
|
||||||
let module_file = root.path().join("go.mod");
|
|
||||||
fs::write(&module_file, "module example.com/plugin\n\ngo 1.22\n").unwrap();
|
|
||||||
assert_eq!(super::go_module_path(&module_file).unwrap(), "example.com/plugin");
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn rejects_development_data_in_package_inputs() {
|
fn rejects_development_data_in_package_inputs() {
|
||||||
let root = tempfile::tempdir().unwrap();
|
let root = tempfile::tempdir().unwrap();
|
||||||
@@ -1805,7 +1787,8 @@ mod tests {
|
|||||||
fn creates_frontend_rust_and_go_projects() {
|
fn creates_frontend_rust_and_go_projects() {
|
||||||
let root = tempfile::tempdir().unwrap();
|
let root = tempfile::tempdir().unwrap();
|
||||||
let sdk_root = PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("../../..");
|
let sdk_root = PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("../../..");
|
||||||
for template in [ProjectTemplate::Frontend, ProjectTemplate::Svelte, ProjectTemplate::Rust, ProjectTemplate::Go] {
|
for template in [ProjectTemplate::Frontend, ProjectTemplate::Svelte, ProjectTemplate::Rust, ProjectTemplate::Go]
|
||||||
|
{
|
||||||
let directory = root.path().join(template.as_str());
|
let directory = root.path().join(template.as_str());
|
||||||
create_project(&CreateOptions {
|
create_project(&CreateOptions {
|
||||||
directory: directory.clone(),
|
directory: directory.clone(),
|
||||||
@@ -1821,7 +1804,9 @@ mod tests {
|
|||||||
.unwrap();
|
.unwrap();
|
||||||
|
|
||||||
assert!(directory.join("manifest.json").is_file());
|
assert!(directory.join("manifest.json").is_file());
|
||||||
assert!(directory.join(if template == ProjectTemplate::Svelte { "index.html" } else { "ui/index.html" }).is_file());
|
assert!(directory
|
||||||
|
.join(if template == ProjectTemplate::Svelte { "index.html" } else { "ui/index.html" })
|
||||||
|
.is_file());
|
||||||
assert!(directory.join(".github/workflows/plugin-release.yml").is_file());
|
assert!(directory.join(".github/workflows/plugin-release.yml").is_file());
|
||||||
let readme = std::fs::read_to_string(directory.join("README.md")).unwrap();
|
let readme = std::fs::read_to_string(directory.join("README.md")).unwrap();
|
||||||
assert!(readme.contains("autoUpdate: true"));
|
assert!(readme.contains("autoUpdate: true"));
|
||||||
|
|||||||
@@ -22,14 +22,17 @@ function installBridge(channel) {
|
|||||||
};
|
};
|
||||||
const decode = (value) => Uint8Array.from(atob(value), (c) => c.charCodeAt(0));
|
const decode = (value) => Uint8Array.from(atob(value), (c) => c.charCodeAt(0));
|
||||||
const stream = async (method, params = {}, options = {}) => {
|
const stream = async (method, params = {}, options = {}) => {
|
||||||
const streamId = options.streamId || (globalThis.crypto?.randomUUID?.() || "stream-" + Date.now() + "-" + (++sequence));
|
const streamId = options.streamId || globalThis.crypto?.randomUUID?.() || "stream-" + Date.now() + "-" + ++sequence;
|
||||||
const closeMethod = options.closeMethod || "filesystem/stream/close";
|
const closeMethod = options.closeMethod || "filesystem/stream/close";
|
||||||
let removeListener;
|
let removeListener;
|
||||||
let closeRequested = false;
|
let closeRequested = false;
|
||||||
let resolveOpen;
|
let resolveOpen;
|
||||||
let rejectOpen;
|
let rejectOpen;
|
||||||
const metadata = {};
|
const metadata = {};
|
||||||
const opened = new Promise((resolve, reject) => { resolveOpen = resolve; rejectOpen = reject; });
|
const opened = new Promise((resolve, reject) => {
|
||||||
|
resolveOpen = resolve;
|
||||||
|
rejectOpen = reject;
|
||||||
|
});
|
||||||
const readable = new ReadableStream({
|
const readable = new ReadableStream({
|
||||||
start(controller) {
|
start(controller) {
|
||||||
const onEvent = (message) => {
|
const onEvent = (message) => {
|
||||||
@@ -37,7 +40,11 @@ function installBridge(channel) {
|
|||||||
const event = message.params || {};
|
const event = message.params || {};
|
||||||
if (event.streamId !== streamId) return;
|
if (event.streamId !== streamId) return;
|
||||||
if (message.method === "host.stream.chunk") {
|
if (message.method === "host.stream.chunk") {
|
||||||
try { controller.enqueue(decode(event.dataBase64 || "")); } catch (error) { controller.error(error); }
|
try {
|
||||||
|
controller.enqueue(decode(event.dataBase64 || ""));
|
||||||
|
} catch (error) {
|
||||||
|
controller.error(error);
|
||||||
|
}
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
removeListener?.();
|
removeListener?.();
|
||||||
@@ -53,7 +60,7 @@ function installBridge(channel) {
|
|||||||
};
|
};
|
||||||
removeListener = () => listeners.event.delete(onEvent);
|
removeListener = () => listeners.event.delete(onEvent);
|
||||||
listeners.event.add(onEvent);
|
listeners.event.add(onEvent);
|
||||||
request("backend.invoke", { method, params: { ...(params || {}), streamId }, timeoutMs: options.timeoutMs }).then(resolveOpen, (error) => {
|
request("backend.invoke", { method, params: { ...params, streamId }, timeoutMs: options.timeoutMs }).then(resolveOpen, (error) => {
|
||||||
removeListener?.();
|
removeListener?.();
|
||||||
removeListener = undefined;
|
removeListener = undefined;
|
||||||
rejectOpen(error);
|
rejectOpen(error);
|
||||||
|
|||||||
@@ -228,7 +228,7 @@ export async function createMockHost(options) {
|
|||||||
if (p.contributionId !== undefined && !contribution) throw new Error("Unknown icon contribution");
|
if (p.contributionId !== undefined && !contribution) throw new Error("Unknown icon contribution");
|
||||||
const icon = contribution?.icon || manifest.icon;
|
const icon = contribution?.icon || manifest.icon;
|
||||||
if (!icon) return null;
|
if (!icon) return null;
|
||||||
if (typeof icon !== "string" || /[:\\\0]/.test(icon) || icon.split("/").some((part) => !part || part === "." || part === "..")) throw new Error("Invalid plugin icon path");
|
if (typeof icon !== "string" || icon.includes(":") || icon.includes("\\") || icon.includes("\u0000") || icon.split("/").some((part) => !part || part === "." || part === "..")) throw new Error("Invalid plugin icon path");
|
||||||
const asset = await readAsset(project, icon);
|
const asset = await readAsset(project, icon);
|
||||||
if (!asset.contentType.startsWith("image/")) throw new Error("Plugin icon is not an image");
|
if (!asset.contentType.startsWith("image/")) throw new Error("Plugin icon is not an image");
|
||||||
return asset;
|
return asset;
|
||||||
|
|||||||
@@ -238,7 +238,10 @@ function jsonOutput(descriptors) {
|
|||||||
|
|
||||||
function typeOutput(descriptors) {
|
function typeOutput(descriptors) {
|
||||||
const values = descriptors.map((descriptor) => ` "${descriptor.dbType}",`).join("\n");
|
const values = descriptors.map((descriptor) => ` "${descriptor.dbType}",`).join("\n");
|
||||||
return `// Generated by scripts/sync-connection-types.mjs. Do not edit manually.\nexport const DATABASE_TYPES = [\n${values}\n] as const;\n\nexport type DatabaseType = (typeof DATABASE_TYPES)[number];\n`;
|
// "plugin" is the plugin-framework internal connection type: it is not a
|
||||||
|
// user-selectable driver (hence absent from DATABASE_TYPES) but connection
|
||||||
|
// configs can carry it, so the DatabaseType union must accept it.
|
||||||
|
return `// Generated by scripts/sync-connection-types.mjs. Do not edit manually.\nexport const DATABASE_TYPES = [\n${values}\n] as const;\n\nexport type DatabaseType = (typeof DATABASE_TYPES)[number] | "plugin";\n`;
|
||||||
}
|
}
|
||||||
|
|
||||||
function typescriptPropertyName(value) {
|
function typescriptPropertyName(value) {
|
||||||
|
|||||||
@@ -77,6 +77,7 @@ sysinfo = { version = "0.32", features = ["system"] }
|
|||||||
|
|
||||||
[dev-dependencies]
|
[dev-dependencies]
|
||||||
tauri = { version = "2.10.3", features = ["test"] }
|
tauri = { version = "2.10.3", features = ["test"] }
|
||||||
|
tempfile = "3"
|
||||||
|
|
||||||
[target.'cfg(target_os = "macos")'.dependencies]
|
[target.'cfg(target_os = "macos")'.dependencies]
|
||||||
objc2 = { version = "0.6.4", default-features = false, features = ["std"] }
|
objc2 = { version = "0.6.4", default-features = false, features = ["std"] }
|
||||||
|
|||||||
@@ -232,6 +232,10 @@ pub fn start(app_handle: AppHandle, state: Arc<AppState>, data_dir: PathBuf) {
|
|||||||
|
|
||||||
if first_line.starts_with("POST /open-table") {
|
if first_line.starts_with("POST /open-table") {
|
||||||
handle_open_table(&app, &st, body, &mut stream).await;
|
handle_open_table(&app, &st, body, &mut stream).await;
|
||||||
|
} else if first_line.starts_with("POST /call-plugin-tool") {
|
||||||
|
handle_call_plugin_tool(&app, &st, body, &mut stream).await;
|
||||||
|
} else if first_line.starts_with("POST /list-plugin-connections") {
|
||||||
|
handle_list_plugin_connections(&st, body, &mut stream).await;
|
||||||
} else if first_line.starts_with("POST /data/list-tables") {
|
} else if first_line.starts_with("POST /data/list-tables") {
|
||||||
handle_list_tables_data(&st, body, &mut stream).await;
|
handle_list_tables_data(&st, body, &mut stream).await;
|
||||||
} else if first_line.starts_with("POST /data/describe-table") {
|
} else if first_line.starts_with("POST /data/describe-table") {
|
||||||
@@ -298,8 +302,9 @@ mod tests {
|
|||||||
use super::{
|
use super::{
|
||||||
effective_database_execution_policy, ensure_connection_in_mcp_scope, ensure_mcp_connection_sql_write_allowed,
|
effective_database_execution_policy, ensure_connection_in_mcp_scope, ensure_mcp_connection_sql_write_allowed,
|
||||||
ensure_mcp_execute_and_show_supported, ensure_mcp_mongo_pipeline_target_allowed_by_id,
|
ensure_mcp_execute_and_show_supported, ensure_mcp_mongo_pipeline_target_allowed_by_id,
|
||||||
ensure_mcp_sql_database_switch_allowed, mongo_filter_is_effectively_unbounded, mongo_pipeline_has_write_stage,
|
ensure_mcp_sql_database_switch_allowed, is_terminal_routed_exec, mongo_filter_is_effectively_unbounded,
|
||||||
resolve_connection, resolve_mongo_database, resolve_mongo_target_values, write_port_file, AppState,
|
mongo_pipeline_has_write_stage, plugin_connection_summaries, plugin_connection_summary, resolve_connection,
|
||||||
|
resolve_mongo_database, resolve_mongo_target_values, write_port_file, AppState,
|
||||||
};
|
};
|
||||||
use dbx_core::models::connection::{ConnectionConfig, DatabaseType};
|
use dbx_core::models::connection::{ConnectionConfig, DatabaseType};
|
||||||
use dbx_core::storage::{McpConnectionPolicy, McpDatabasePolicy, McpDatabaseScope, McpGlobalPolicy, Storage};
|
use dbx_core::storage::{McpConnectionPolicy, McpDatabasePolicy, McpDatabaseScope, McpGlobalPolicy, Storage};
|
||||||
@@ -340,6 +345,19 @@ mod tests {
|
|||||||
let _ = std::fs::remove_dir_all(root);
|
let _ = std::fs::remove_dir_all(root);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn only_ssh_exec_tools_may_open_the_workbench_terminal() {
|
||||||
|
// The workbench open (and its tab churn) exists solely so a
|
||||||
|
// terminal-routed exec lands in a real PTY; forwarded sftp/metrics
|
||||||
|
// calls are hidden-channel by design and must never trigger it,
|
||||||
|
// whatever runInTerminal says.
|
||||||
|
assert!(is_terminal_routed_exec("ssh_exec"));
|
||||||
|
assert!(is_terminal_routed_exec("ssh_exec_sudo"));
|
||||||
|
assert!(!is_terminal_routed_exec("sftp_list_dir"));
|
||||||
|
assert!(!is_terminal_routed_exec("ssh_metrics"));
|
||||||
|
assert!(!is_terminal_routed_exec("mcp_exec"));
|
||||||
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn mongo_database_uses_configured_default_for_missing_or_blank_request() {
|
fn mongo_database_uses_configured_default_for_missing_or_blank_request() {
|
||||||
let configured = Some("sample_db".to_string());
|
let configured = Some("sample_db".to_string());
|
||||||
@@ -577,6 +595,80 @@ mod tests {
|
|||||||
assert!(!mongo_filter_is_effectively_unbounded(filter), "{filter}");
|
assert!(!mongo_filter_is_effectively_unbounded(filter), "{filter}");
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
fn plugin_connection_config(id: &str, name: &str, external_config: serde_json::Value) -> ConnectionConfig {
|
||||||
|
serde_json::from_value(serde_json::json!({
|
||||||
|
"id": id,
|
||||||
|
"name": name,
|
||||||
|
"db_type": "plugin",
|
||||||
|
"plugin_id": "io.dbx.ssh",
|
||||||
|
"plugin_connection_type": "ssh",
|
||||||
|
"host": "server.example.com",
|
||||||
|
"port": 2222,
|
||||||
|
"username": "deploy",
|
||||||
|
"password": "",
|
||||||
|
"connection_secrets": { "password": "hunter2", "totp_secret": "otpauth://secret" },
|
||||||
|
"external_config": external_config
|
||||||
|
}))
|
||||||
|
.unwrap()
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn plugin_connection_summary_is_metadata_only() {
|
||||||
|
let config = plugin_connection_config(
|
||||||
|
"conn-ssh-1",
|
||||||
|
"prod-bastion",
|
||||||
|
serde_json::json!({ "authentication": "private-key", "read_only": true, "agent_socket": "/tmp/agent" }),
|
||||||
|
);
|
||||||
|
let value = serde_json::to_value(plugin_connection_summary(&config)).unwrap();
|
||||||
|
let object = value.as_object().unwrap();
|
||||||
|
let keys: std::collections::HashSet<_> = object.keys().cloned().collect();
|
||||||
|
assert_eq!(
|
||||||
|
keys,
|
||||||
|
["id", "name", "host", "port", "username", "authentication", "readOnly"]
|
||||||
|
.into_iter()
|
||||||
|
.map(String::from)
|
||||||
|
.collect()
|
||||||
|
);
|
||||||
|
assert_eq!(value["id"], "conn-ssh-1");
|
||||||
|
assert_eq!(value["host"], "server.example.com");
|
||||||
|
assert_eq!(value["port"], 2222);
|
||||||
|
assert_eq!(value["username"], "deploy");
|
||||||
|
assert_eq!(value["authentication"], "private-key");
|
||||||
|
assert_eq!(value["readOnly"], true);
|
||||||
|
let rendered = value.to_string();
|
||||||
|
for secret in ["hunter2", "otpauth", "password", "connection_secrets", "external_config", "agent_socket"] {
|
||||||
|
assert!(!rendered.contains(secret), "summary must not leak {secret}");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn plugin_connection_summary_falls_back_to_safe_defaults() {
|
||||||
|
let mut config = plugin_connection_config("conn-ssh-2", "fallback", serde_json::json!({}));
|
||||||
|
config.read_only = true;
|
||||||
|
let value = serde_json::to_value(plugin_connection_summary(&config)).unwrap();
|
||||||
|
assert_eq!(value["authentication"], "password");
|
||||||
|
assert_eq!(value["readOnly"], true);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn plugin_connection_summaries_filter_by_plugin_and_sort_by_name() {
|
||||||
|
let ssh_b = plugin_connection_config("b", "Beta", serde_json::json!({}));
|
||||||
|
let ssh_a = plugin_connection_config("a", "alpha", serde_json::json!({}));
|
||||||
|
let mut ldap = plugin_connection_config("l", "zeta", serde_json::json!({}));
|
||||||
|
ldap.plugin_id = Some("io.dbx.ldap".to_string());
|
||||||
|
let mysql = mysql_config(false);
|
||||||
|
|
||||||
|
let summaries = plugin_connection_summaries(&[ssh_b, ldap, mysql, ssh_a], "io.dbx.ssh");
|
||||||
|
let names: Vec<_> = summaries.iter().map(|s| s.name.as_str()).collect();
|
||||||
|
assert_eq!(names, vec!["alpha", "Beta"]);
|
||||||
|
|
||||||
|
assert!(plugin_connection_summaries(
|
||||||
|
&[plugin_connection_config("a", "alpha", serde_json::json!({}))],
|
||||||
|
"io.dbx.files"
|
||||||
|
)
|
||||||
|
.is_empty());
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
async fn respond(stream: &mut tokio::net::TcpStream, status: &str, body: &str) {
|
async fn respond(stream: &mut tokio::net::TcpStream, status: &str, body: &str) {
|
||||||
@@ -1203,6 +1295,201 @@ async fn handle_open_table(app: &AppHandle, state: &Arc<AppState>, body: &str, s
|
|||||||
respond(stream, "200 OK", "ok").await;
|
respond(stream, "200 OK", "ok").await;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[derive(Deserialize)]
|
||||||
|
struct CallPluginToolRequest {
|
||||||
|
connection_id: String,
|
||||||
|
tool: String,
|
||||||
|
#[serde(default)]
|
||||||
|
arguments: serde_json::Value,
|
||||||
|
plugin_id: Option<String>,
|
||||||
|
timeout_ms: Option<u64>,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Tools whose terminal routing (`runInTerminal` / terminal MCP mode) can
|
||||||
|
/// require the workbench terminal to exist. Every other forwarded tool runs
|
||||||
|
/// on the hidden channel by design and must never open the workbench.
|
||||||
|
fn is_terminal_routed_exec(tool: &str) -> bool {
|
||||||
|
tool == "ssh_exec" || tool == "ssh_exec_sudo"
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Asks the plugin for a connection's terminal MCP mode (the toggle in the
|
||||||
|
/// SSH terminal toolbar). Any failure — an older plugin without the probe
|
||||||
|
/// route, a busy sidecar — degrades to off, so the silent path can never
|
||||||
|
/// regress into opening the workbench.
|
||||||
|
async fn plugin_agent_mode_on(state: &Arc<AppState>, plugin_id: &str, connection_id: &str) -> bool {
|
||||||
|
let probe: Result<serde_json::Value, String> = state
|
||||||
|
.plugin_host
|
||||||
|
.invoke(
|
||||||
|
plugin_id,
|
||||||
|
"ssh/agent/mode/get",
|
||||||
|
serde_json::json!({ "connectionId": connection_id }),
|
||||||
|
None,
|
||||||
|
Some(std::time::Duration::from_secs(5)),
|
||||||
|
)
|
||||||
|
.await;
|
||||||
|
probe
|
||||||
|
.ok()
|
||||||
|
.and_then(|value| value.get("agentTerminalMode").and_then(serde_json::Value::as_str).map(str::to_string))
|
||||||
|
.is_some_and(|mode| mode == "auto" || mode == "strict")
|
||||||
|
}
|
||||||
|
|
||||||
|
/// POST /call-plugin-tool: runs a plugin MCP tool on the desktop app's own
|
||||||
|
/// plugin session — the same sidecar process the workbench talks to. The
|
||||||
|
/// connection's workbench tab is opened only when the call will route into
|
||||||
|
/// the visible terminal (ssh runInTerminal / terminal MCP mode), so
|
||||||
|
/// agent-terminal commands execute in a real PTY while silent hidden-channel
|
||||||
|
/// calls never open or focus the app. The lifecycle payload comes from the
|
||||||
|
/// saved connection config, so callers never pass credentials.
|
||||||
|
async fn handle_call_plugin_tool(
|
||||||
|
app: &AppHandle,
|
||||||
|
state: &Arc<AppState>,
|
||||||
|
body: &str,
|
||||||
|
stream: &mut tokio::net::TcpStream,
|
||||||
|
) {
|
||||||
|
let req: CallPluginToolRequest = match serde_json::from_str(body) {
|
||||||
|
Ok(r) => r,
|
||||||
|
Err(e) => {
|
||||||
|
respond_error(stream, "400 Bad Request", &format!("invalid body: {e}")).await;
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
};
|
||||||
|
let config = match resolve_connection(state, Some(&req.connection_id), "").await {
|
||||||
|
Ok(c) => c,
|
||||||
|
Err(e) => {
|
||||||
|
respond_error(stream, "404 Not Found", &e).await;
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
};
|
||||||
|
let plugin_id = req.plugin_id.or_else(|| config.plugin_id.clone()).unwrap_or_default();
|
||||||
|
if plugin_id.is_empty() {
|
||||||
|
respond_error(stream, "400 Bad Request", "connection is not bound to a plugin").await;
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
// The workbench tab only needs to exist when the forwarded call will
|
||||||
|
// actually route into the visible terminal: an explicit runInTerminal,
|
||||||
|
// or no flag plus the connection's terminal MCP mode being on (asked
|
||||||
|
// from the plugin, so the toggle in the terminal UI owns the decision).
|
||||||
|
// Everything else — sftp listings, silent execs on the hidden channel —
|
||||||
|
// must not open (let alone focus) the app while the agent works.
|
||||||
|
let route_terminal = is_terminal_routed_exec(&req.tool)
|
||||||
|
&& match req.arguments.get("runInTerminal").and_then(serde_json::Value::as_bool) {
|
||||||
|
Some(explicit) => explicit,
|
||||||
|
None => plugin_agent_mode_on(state, &plugin_id, &config.id).await,
|
||||||
|
};
|
||||||
|
if route_terminal {
|
||||||
|
let _ = app.emit("mcp-open-connection-workbench", serde_json::json!({ "connection_id": config.id }));
|
||||||
|
}
|
||||||
|
let lifecycle = match state.plugin_host.connection_params_standalone(&config) {
|
||||||
|
Ok(l) => l,
|
||||||
|
Err(e) => {
|
||||||
|
respond_error(stream, "500 Internal Server Error", &e).await;
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
};
|
||||||
|
let params = serde_json::json!({
|
||||||
|
"tool": req.tool,
|
||||||
|
"arguments": req.arguments,
|
||||||
|
"lifecycle": lifecycle,
|
||||||
|
});
|
||||||
|
// Long ceiling: agent-terminal calls may sit in a workbench approval
|
||||||
|
// prompt (default 120s) before the command even starts.
|
||||||
|
let timeout = std::time::Duration::from_millis(req.timeout_ms.unwrap_or(300_000).clamp(1_000, 600_000));
|
||||||
|
let result: Result<serde_json::Value, String> =
|
||||||
|
state.plugin_host.invoke(&plugin_id, "mcp/call", params, None, Some(timeout)).await;
|
||||||
|
match result {
|
||||||
|
Ok(value) => respond_json(stream, &value).await,
|
||||||
|
Err(e) => respond_error(stream, "502 Bad Gateway", &e).await,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Deserialize)]
|
||||||
|
struct ListPluginConnectionsRequest {
|
||||||
|
plugin_id: String,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Metadata-only view of a saved plugin connection. This is a deliberate
|
||||||
|
/// field whitelist: credentials (`password`, `connection_secrets`, private
|
||||||
|
/// keys, `sudo_password`, `totp_secret`, ...) can never reach the response
|
||||||
|
/// because they are not part of this struct and `external_config` is only
|
||||||
|
/// probed for the two safe keys below.
|
||||||
|
#[derive(Serialize)]
|
||||||
|
#[serde(rename_all = "camelCase")]
|
||||||
|
struct PluginConnectionSummary {
|
||||||
|
id: String,
|
||||||
|
name: String,
|
||||||
|
host: String,
|
||||||
|
port: u16,
|
||||||
|
username: String,
|
||||||
|
authentication: String,
|
||||||
|
read_only: bool,
|
||||||
|
}
|
||||||
|
|
||||||
|
fn plugin_connection_summary(config: &crate::models::connection::ConnectionConfig) -> PluginConnectionSummary {
|
||||||
|
let external = config.external_config.as_ref();
|
||||||
|
// The dialog persists every declared config-bound field (including
|
||||||
|
// defaults), so `authentication` is normally present; fall back to the
|
||||||
|
// provider's historical default ("password") for pre-existing rows.
|
||||||
|
let authentication = external
|
||||||
|
.and_then(|v| v.get("authentication"))
|
||||||
|
.and_then(serde_json::Value::as_str)
|
||||||
|
.unwrap_or("password")
|
||||||
|
.to_string();
|
||||||
|
let read_only =
|
||||||
|
external.and_then(|v| v.get("read_only")).and_then(serde_json::Value::as_bool).unwrap_or(config.read_only);
|
||||||
|
PluginConnectionSummary {
|
||||||
|
id: config.id.clone(),
|
||||||
|
name: config.name.clone(),
|
||||||
|
host: config.host.clone(),
|
||||||
|
port: config.port,
|
||||||
|
username: config.username.clone(),
|
||||||
|
authentication,
|
||||||
|
read_only,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn plugin_connection_summaries(
|
||||||
|
configs: &[crate::models::connection::ConnectionConfig],
|
||||||
|
plugin_id: &str,
|
||||||
|
) -> Vec<PluginConnectionSummary> {
|
||||||
|
let mut summaries: Vec<PluginConnectionSummary> = configs
|
||||||
|
.iter()
|
||||||
|
.filter(|c| {
|
||||||
|
c.db_type == crate::models::connection::DatabaseType::Plugin && c.plugin_id.as_deref() == Some(plugin_id)
|
||||||
|
})
|
||||||
|
.map(plugin_connection_summary)
|
||||||
|
.collect();
|
||||||
|
summaries.sort_by_key(|summary| summary.name.to_lowercase());
|
||||||
|
summaries
|
||||||
|
}
|
||||||
|
|
||||||
|
/// POST /list-plugin-connections: returns saved connection metadata for one
|
||||||
|
/// plugin so standalone stdio MCP agents can pick a connection without
|
||||||
|
/// reading the SQLite store. Metadata only — this route never returns
|
||||||
|
/// credentials; connecting still goes through /call-plugin-tool, whose
|
||||||
|
/// lifecycle payload comes from the host-side saved config.
|
||||||
|
async fn handle_list_plugin_connections(state: &Arc<AppState>, body: &str, stream: &mut tokio::net::TcpStream) {
|
||||||
|
let req: ListPluginConnectionsRequest = match serde_json::from_str(body) {
|
||||||
|
Ok(r) => r,
|
||||||
|
Err(e) => {
|
||||||
|
respond_error(stream, "400 Bad Request", &format!("invalid body: {e}")).await;
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
};
|
||||||
|
if req.plugin_id.trim().is_empty() {
|
||||||
|
respond_error(stream, "400 Bad Request", "plugin_id is required").await;
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
let configs = match state.storage.load_connections().await {
|
||||||
|
Ok(c) => c,
|
||||||
|
Err(e) => {
|
||||||
|
respond_error(stream, "500 Internal Server Error", &e).await;
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
};
|
||||||
|
let connections = plugin_connection_summaries(&configs, req.plugin_id.trim());
|
||||||
|
respond_json(stream, &serde_json::json!({ "connections": connections })).await;
|
||||||
|
}
|
||||||
|
|
||||||
async fn handle_execute_query(app: &AppHandle, state: &Arc<AppState>, body: &str, stream: &mut tokio::net::TcpStream) {
|
async fn handle_execute_query(app: &AppHandle, state: &Arc<AppState>, body: &str, stream: &mut tokio::net::TcpStream) {
|
||||||
let req: ExecuteQueryRequest = match serde_json::from_str(body) {
|
let req: ExecuteQueryRequest = match serde_json::from_str(body) {
|
||||||
Ok(r) => r,
|
Ok(r) => r,
|
||||||
|
|||||||
@@ -50,6 +50,7 @@ pub mod schema_diff;
|
|||||||
pub mod sql_file;
|
pub mod sql_file;
|
||||||
pub mod sqlite_backup;
|
pub mod sqlite_backup;
|
||||||
pub mod ssh_config;
|
pub mod ssh_config;
|
||||||
|
pub mod ssh_keys;
|
||||||
pub mod ssh_prompt;
|
pub mod ssh_prompt;
|
||||||
pub mod support_info;
|
pub mod support_info;
|
||||||
pub mod system_fonts;
|
pub mod system_fonts;
|
||||||
|
|||||||
@@ -0,0 +1,207 @@
|
|||||||
|
use std::collections::BTreeSet;
|
||||||
|
use std::path::{Path, PathBuf};
|
||||||
|
|
||||||
|
use russh::keys::{decode_secret_key, Error as KeysError, HashAlg};
|
||||||
|
use serde::Serialize;
|
||||||
|
|
||||||
|
/// A local SSH private key offered as a connection-form suggestion
|
||||||
|
/// (`private_key_path` plugin field convenience picker).
|
||||||
|
#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
|
||||||
|
#[serde(rename_all = "camelCase")]
|
||||||
|
pub struct LocalSshKey {
|
||||||
|
/// Absolute path to the private key file.
|
||||||
|
pub path: String,
|
||||||
|
/// SSH algorithm name (for example `ssh-ed25519`); empty when undetectable.
|
||||||
|
pub algorithm: String,
|
||||||
|
/// SHA-256 fingerprint (`SHA256:...`); empty when the key could not be decoded.
|
||||||
|
pub fingerprint: String,
|
||||||
|
/// Heuristic: the key looks passphrase-protected.
|
||||||
|
pub has_passphrase: bool,
|
||||||
|
}
|
||||||
|
|
||||||
|
const FIXED_KEY_NAMES: [&str; 5] = ["id_rsa", "id_ed25519", "id_ecdsa", "id_dsa", "identity"];
|
||||||
|
|
||||||
|
/// Lists private keys from `$HOME/.ssh` (well-known names, `id_*`, `*.pem`,
|
||||||
|
/// `*.key`) plus `IdentityFile` entries declared in `~/.ssh/config`.
|
||||||
|
#[tauri::command]
|
||||||
|
pub async fn list_local_ssh_keys() -> Result<Vec<LocalSshKey>, String> {
|
||||||
|
tauri::async_runtime::spawn_blocking(list_local_ssh_keys_blocking).await.map_err(|err| err.to_string())?
|
||||||
|
}
|
||||||
|
|
||||||
|
fn list_local_ssh_keys_blocking() -> Result<Vec<LocalSshKey>, String> {
|
||||||
|
let home = home_dir().ok_or_else(|| "Could not resolve the home directory".to_string())?;
|
||||||
|
Ok(list_local_ssh_keys_in(&home))
|
||||||
|
}
|
||||||
|
|
||||||
|
fn home_dir() -> Option<PathBuf> {
|
||||||
|
std::env::var("HOME").or_else(|_| std::env::var("USERPROFILE")).ok().map(PathBuf::from)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn list_local_ssh_keys_in(home: &Path) -> Vec<LocalSshKey> {
|
||||||
|
let mut candidates: BTreeSet<PathBuf> = scan_ssh_directory(&home.join(".ssh")).into_iter().collect();
|
||||||
|
for identity in ssh_config_identity_files() {
|
||||||
|
if let Some(path) = resolve_identity_file(&identity, home) {
|
||||||
|
candidates.insert(path);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
candidates.into_iter().filter(|path| path.is_file()).map(|path| inspect_local_ssh_key(&path)).collect()
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Fixed well-known names plus `id_*` / `*.pem` / `*.key` globs, skipping `.pub`.
|
||||||
|
fn is_candidate_key_file(name: &str) -> bool {
|
||||||
|
if name.starts_with('.') || name.ends_with(".pub") {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
FIXED_KEY_NAMES.contains(&name) || name.starts_with("id_") || name.ends_with(".pem") || name.ends_with(".key")
|
||||||
|
}
|
||||||
|
|
||||||
|
fn scan_ssh_directory(ssh_dir: &Path) -> Vec<PathBuf> {
|
||||||
|
let mut entries = Vec::new();
|
||||||
|
let Ok(read_dir) = std::fs::read_dir(ssh_dir) else {
|
||||||
|
return entries;
|
||||||
|
};
|
||||||
|
for entry in read_dir.flatten() {
|
||||||
|
let path = entry.path();
|
||||||
|
let Some(name) = path.file_name().and_then(|name| name.to_str()) else { continue };
|
||||||
|
if path.is_file() && is_candidate_key_file(name) {
|
||||||
|
entries.push(path);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
entries
|
||||||
|
}
|
||||||
|
|
||||||
|
fn ssh_config_identity_files() -> Vec<String> {
|
||||||
|
dbx_core::ssh_config::list_hosts().unwrap_or_default().into_iter().filter_map(|entry| entry.identity_file).collect()
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Expands `~`-prefixed and absolute paths as-is; relative `IdentityFile`
|
||||||
|
/// values are interpreted relative to `~/.ssh` (OpenSSH behavior).
|
||||||
|
fn resolve_identity_file(raw: &str, home: &Path) -> Option<PathBuf> {
|
||||||
|
let raw = raw.trim();
|
||||||
|
if raw.is_empty() {
|
||||||
|
return None;
|
||||||
|
}
|
||||||
|
let path = if let Some(rest) = raw.strip_prefix('~') {
|
||||||
|
let rest = rest.strip_prefix('/').or_else(|| rest.strip_prefix('\\')).unwrap_or(rest);
|
||||||
|
if rest.is_empty() {
|
||||||
|
home.to_path_buf()
|
||||||
|
} else {
|
||||||
|
home.join(rest)
|
||||||
|
}
|
||||||
|
} else if Path::new(raw).is_absolute() {
|
||||||
|
PathBuf::from(raw)
|
||||||
|
} else {
|
||||||
|
home.join(".ssh").join(raw)
|
||||||
|
};
|
||||||
|
Some(path)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Reads the key and derives algorithm/fingerprint via `russh::keys`.
|
||||||
|
/// Undecodable and encrypted keys are still listed.
|
||||||
|
fn inspect_local_ssh_key(path: &Path) -> LocalSshKey {
|
||||||
|
let bytes = std::fs::read(path).unwrap_or_default();
|
||||||
|
let content = String::from_utf8_lossy(&bytes);
|
||||||
|
let file_name = path.file_name().and_then(|name| name.to_str()).unwrap_or("");
|
||||||
|
|
||||||
|
let (algorithm, fingerprint, has_passphrase) = match decode_secret_key(&content, None) {
|
||||||
|
Ok(key) => (key.algorithm().to_string(), key.public_key().fingerprint(HashAlg::Sha256).to_string(), false),
|
||||||
|
Err(KeysError::KeyIsEncrypted) => (String::new(), String::new(), true),
|
||||||
|
Err(_) => (String::new(), String::new(), false),
|
||||||
|
};
|
||||||
|
|
||||||
|
let algorithm = if algorithm.is_empty() { guess_algorithm_from_name(file_name) } else { algorithm };
|
||||||
|
let has_passphrase = has_passphrase || content.contains("ENCRYPTED");
|
||||||
|
|
||||||
|
LocalSshKey { path: path.display().to_string(), algorithm, fingerprint, has_passphrase }
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Fallback for keys that cannot be decoded: infer the algorithm from the name.
|
||||||
|
fn guess_algorithm_from_name(file_name: &str) -> String {
|
||||||
|
let lower = file_name.to_ascii_lowercase();
|
||||||
|
if lower.contains("ed25519") {
|
||||||
|
"ssh-ed25519".to_string()
|
||||||
|
} else if lower.contains("ecdsa") {
|
||||||
|
"ecdsa".to_string()
|
||||||
|
} else if lower.contains("dsa") {
|
||||||
|
"ssh-dss".to_string()
|
||||||
|
} else if lower.contains("rsa") {
|
||||||
|
"ssh-rsa".to_string()
|
||||||
|
} else {
|
||||||
|
String::new()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(test)]
|
||||||
|
mod tests {
|
||||||
|
use super::*;
|
||||||
|
|
||||||
|
const TEST_ED25519_KEY: &str = r#"-----BEGIN OPENSSH PRIVATE KEY-----
|
||||||
|
b3BlbnNzaC1rZXktdjEAAAAABG5vbmUAAAAEbm9uZQAAAAAAAAABAAAAMwAAAAtzc2gtZW
|
||||||
|
QyNTUxOQAAACAVDlhwKBk+QMZN+WNAUKL6qLr3hf3S5p1TdSK4hMhLxwAAAJD9wI28/cCN
|
||||||
|
vAAAAAtzc2gtZWQyNTUxOQAAACAVDlhwKBk+QMZN+WNAUKL6qLr3hf3S5p1TdSK4hMhLxw
|
||||||
|
AAAEDxqdMQX37UdhziSi5Br3kyRM/Xrpo9ZcXoguYkeogq0hUOWHAoGT5Axk35Y0BQovqo
|
||||||
|
uveF/dLmnVN1IriEyEvHAAAACGRieC10ZXN0AQIDBAU=
|
||||||
|
-----END OPENSSH PRIVATE KEY-----"#;
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn filters_candidate_key_files() {
|
||||||
|
assert!(is_candidate_key_file("id_rsa"));
|
||||||
|
assert!(is_candidate_key_file("id_ed25519"));
|
||||||
|
assert!(is_candidate_key_file("identity"));
|
||||||
|
assert!(is_candidate_key_file("id_deploy_company"));
|
||||||
|
assert!(is_candidate_key_file("server.pem"));
|
||||||
|
assert!(is_candidate_key_file("client.key"));
|
||||||
|
assert!(!is_candidate_key_file("id_rsa.pub"));
|
||||||
|
assert!(!is_candidate_key_file("known_hosts"));
|
||||||
|
assert!(!is_candidate_key_file("authorized_keys"));
|
||||||
|
assert!(!is_candidate_key_file("config"));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn resolves_identity_file_paths() {
|
||||||
|
let home = Path::new("/home/dev");
|
||||||
|
assert_eq!(resolve_identity_file("~/.ssh/id_ed25519", home), Some(PathBuf::from("/home/dev/.ssh/id_ed25519")));
|
||||||
|
assert_eq!(resolve_identity_file("id_ed25519", home), Some(PathBuf::from("/home/dev/.ssh/id_ed25519")));
|
||||||
|
assert_eq!(resolve_identity_file("/opt/keys/prod", home), Some(PathBuf::from("/opt/keys/prod")));
|
||||||
|
assert_eq!(resolve_identity_file(" ", home), None);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn decodes_key_algorithm_and_fingerprint() {
|
||||||
|
let dir = tempfile::tempdir().unwrap();
|
||||||
|
let path = dir.path().join("id_ed25519");
|
||||||
|
std::fs::write(&path, TEST_ED25519_KEY).unwrap();
|
||||||
|
|
||||||
|
let key = inspect_local_ssh_key(&path);
|
||||||
|
|
||||||
|
assert_eq!(key.algorithm, "ssh-ed25519");
|
||||||
|
assert!(key.fingerprint.starts_with("SHA256:"));
|
||||||
|
assert!(!key.has_passphrase);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn lists_undecodable_and_encrypted_keys_without_failing() {
|
||||||
|
let dir = tempfile::tempdir().unwrap();
|
||||||
|
let ssh_dir = dir.path().join(".ssh");
|
||||||
|
std::fs::create_dir_all(&ssh_dir).unwrap();
|
||||||
|
std::fs::write(ssh_dir.join("id_ed25519"), b"not a key").unwrap();
|
||||||
|
std::fs::write(ssh_dir.join("legacy_rsa.pem"), "-----BEGIN RSA PRIVATE KEY-----\nProc-Type: 4,ENCRYPTED\n")
|
||||||
|
.unwrap();
|
||||||
|
std::fs::write(ssh_dir.join("id_rsa.pub"), b"public part").unwrap();
|
||||||
|
std::fs::write(ssh_dir.join("known_hosts"), b"# hosts").unwrap();
|
||||||
|
|
||||||
|
let keys = list_local_ssh_keys_in(dir.path());
|
||||||
|
let by_name = |name: &str| keys.iter().find(|key| key.path.ends_with(name)).cloned().unwrap();
|
||||||
|
|
||||||
|
let undecodable = by_name("id_ed25519");
|
||||||
|
assert_eq!(undecodable.algorithm, "ssh-ed25519");
|
||||||
|
assert!(undecodable.fingerprint.is_empty());
|
||||||
|
assert!(!undecodable.has_passphrase);
|
||||||
|
|
||||||
|
let encrypted = by_name("legacy_rsa.pem");
|
||||||
|
assert_eq!(encrypted.algorithm, "ssh-rsa");
|
||||||
|
assert!(encrypted.has_passphrase);
|
||||||
|
assert!(!keys.iter().any(|key| key.path.ends_with(".pub")));
|
||||||
|
assert!(!keys.iter().any(|key| key.path.ends_with("known_hosts")));
|
||||||
|
}
|
||||||
|
}
|
||||||
+45
-15
@@ -45,6 +45,10 @@ const APP_CLOSE_REQUESTED_EVENT: &str = "dbx-app-close-requested";
|
|||||||
const APP_MENU_QUIT_ID: &str = "app-menu-quit";
|
const APP_MENU_QUIT_ID: &str = "app-menu-quit";
|
||||||
#[cfg(target_os = "macos")]
|
#[cfg(target_os = "macos")]
|
||||||
const APP_MENU_COPY_SUPPORT_INFO_ID: &str = "app-menu-copy-support-info";
|
const APP_MENU_COPY_SUPPORT_INFO_ID: &str = "app-menu-copy-support-info";
|
||||||
|
#[cfg(target_os = "macos")]
|
||||||
|
const APP_MENU_CLOSE_TAB_ID: &str = "app-menu-close-tab";
|
||||||
|
#[cfg(target_os = "macos")]
|
||||||
|
const APP_CLOSE_ACTIVE_TAB_EVENT: &str = "dbx-close-active-tab";
|
||||||
|
|
||||||
pub struct CloseBehaviorState {
|
pub struct CloseBehaviorState {
|
||||||
confirmed_exit: AtomicBool,
|
confirmed_exit: AtomicBool,
|
||||||
@@ -226,6 +230,13 @@ fn build_app_menu<R: tauri::Runtime>(app_handle: &tauri::AppHandle<R>) -> tauri:
|
|||||||
true,
|
true,
|
||||||
Some("Cmd+Q"),
|
Some("Cmd+Q"),
|
||||||
)?;
|
)?;
|
||||||
|
let close_tab_item = MenuItem::with_id(
|
||||||
|
app_handle,
|
||||||
|
APP_MENU_CLOSE_TAB_ID,
|
||||||
|
app_menu_close_tab_label(¤t_app_locale(app_handle)),
|
||||||
|
true,
|
||||||
|
Some("Cmd+W"),
|
||||||
|
)?;
|
||||||
|
|
||||||
Menu::with_items(
|
Menu::with_items(
|
||||||
app_handle,
|
app_handle,
|
||||||
@@ -246,7 +257,7 @@ fn build_app_menu<R: tauri::Runtime>(app_handle: &tauri::AppHandle<R>) -> tauri:
|
|||||||
&quit_item,
|
&quit_item,
|
||||||
],
|
],
|
||||||
)?,
|
)?,
|
||||||
&Submenu::with_items(app_handle, "File", true, &[&PredefinedMenuItem::close_window(app_handle, None)?])?,
|
&Submenu::with_items(app_handle, "File", true, &[&close_tab_item])?,
|
||||||
&Submenu::with_items(
|
&Submenu::with_items(
|
||||||
app_handle,
|
app_handle,
|
||||||
"Edit",
|
"Edit",
|
||||||
@@ -266,12 +277,7 @@ fn build_app_menu<R: tauri::Runtime>(app_handle: &tauri::AppHandle<R>) -> tauri:
|
|||||||
app_handle,
|
app_handle,
|
||||||
"Window",
|
"Window",
|
||||||
true,
|
true,
|
||||||
&[
|
&[&PredefinedMenuItem::minimize(app_handle, None)?, &PredefinedMenuItem::maximize(app_handle, None)?],
|
||||||
&PredefinedMenuItem::minimize(app_handle, None)?,
|
|
||||||
&PredefinedMenuItem::maximize(app_handle, None)?,
|
|
||||||
&PredefinedMenuItem::separator(app_handle)?,
|
|
||||||
&PredefinedMenuItem::close_window(app_handle, None)?,
|
|
||||||
],
|
|
||||||
)?,
|
)?,
|
||||||
&Submenu::with_items(app_handle, "Help", true, &[])?,
|
&Submenu::with_items(app_handle, "Help", true, &[])?,
|
||||||
],
|
],
|
||||||
@@ -774,6 +780,22 @@ fn app_menu_copy_support_info_label(locale: &str) -> &'static str {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[cfg_attr(not(target_os = "macos"), allow(dead_code))]
|
||||||
|
fn app_menu_close_tab_label(locale: &str) -> &'static str {
|
||||||
|
match locale_family(locale) {
|
||||||
|
LocaleFamily::SimplifiedChinese => "关闭标签页",
|
||||||
|
LocaleFamily::TraditionalChinese => "關閉分頁",
|
||||||
|
LocaleFamily::Japanese => "タブを閉じる",
|
||||||
|
LocaleFamily::Korean => "탭 닫기",
|
||||||
|
LocaleFamily::Azerbaijani => "Vərəqi bağla",
|
||||||
|
LocaleFamily::Spanish => "Cerrar pestaña",
|
||||||
|
LocaleFamily::Italian => "Chiudi scheda",
|
||||||
|
LocaleFamily::Turkish => "Sekmeyi kapat",
|
||||||
|
LocaleFamily::Portuguese => "Fechar aba",
|
||||||
|
LocaleFamily::English => "Close Tab",
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
#[cfg_attr(not(target_os = "macos"), allow(dead_code))]
|
#[cfg_attr(not(target_os = "macos"), allow(dead_code))]
|
||||||
fn app_menu_quit_label(locale: &str, app_name: &str) -> String {
|
fn app_menu_quit_label(locale: &str, app_name: &str) -> String {
|
||||||
match locale_family(locale) {
|
match locale_family(locale) {
|
||||||
@@ -967,14 +989,15 @@ pub(crate) fn apply_desktop_settings(app: &tauri::AppHandle, desktop_settings: &
|
|||||||
#[allow(clippy::items_after_test_module)]
|
#[allow(clippy::items_after_test_module)]
|
||||||
mod tests {
|
mod tests {
|
||||||
use super::{
|
use super::{
|
||||||
app_menu_copy_support_info_label, app_menu_quit_label, linux_appimage_requires_dmabuf_workaround,
|
app_menu_close_tab_label, app_menu_copy_support_info_label, app_menu_quit_label,
|
||||||
linux_drm_driver_is_software_only, linux_drm_render_devices_from_paths, linux_nvidia_driver_from_state,
|
linux_appimage_requires_dmabuf_workaround, linux_drm_driver_is_software_only,
|
||||||
linux_pci_id_from_sysfs_value, linux_selected_drm_render_device, linux_uses_native_wayland,
|
linux_drm_render_devices_from_paths, linux_nvidia_driver_from_state, linux_pci_id_from_sysfs_value,
|
||||||
linux_webkit_environment_override, linux_webkit_rendering_workarounds, native_window_decorations_override,
|
linux_selected_drm_render_device, linux_uses_native_wayland, linux_webkit_environment_override,
|
||||||
should_confirm_app_exit_request, should_enable_single_instance, should_fallback_to_native_quit,
|
linux_webkit_rendering_workarounds, native_window_decorations_override, should_confirm_app_exit_request,
|
||||||
should_hide_window_before_exit, should_hide_window_on_close, should_setup_desktop_tray,
|
should_enable_single_instance, should_fallback_to_native_quit, should_hide_window_before_exit,
|
||||||
should_show_main_window_after_setup, should_show_main_window_before_setup_tasks, startup_data_dir_mode,
|
should_hide_window_on_close, should_setup_desktop_tray, should_show_main_window_after_setup,
|
||||||
tray_menu_labels_for_locale, uses_application_level_icon, LinuxDrmRenderDevice, LinuxNvidiaDriver,
|
should_show_main_window_before_setup_tasks, startup_data_dir_mode, tray_menu_labels_for_locale,
|
||||||
|
uses_application_level_icon, LinuxDrmRenderDevice, LinuxNvidiaDriver,
|
||||||
};
|
};
|
||||||
use crate::data_dir::DataDirMode;
|
use crate::data_dir::DataDirMode;
|
||||||
use std::ffi::OsStr;
|
use std::ffi::OsStr;
|
||||||
@@ -1018,6 +1041,10 @@ mod tests {
|
|||||||
assert_eq!(app_menu_copy_support_info_label("tr-TR"), "Destek bilgilerini kopyala");
|
assert_eq!(app_menu_copy_support_info_label("tr-TR"), "Destek bilgilerini kopyala");
|
||||||
assert_eq!(app_menu_copy_support_info_label("az-AZ"), "Dəstək məlumatlarını kopyala");
|
assert_eq!(app_menu_copy_support_info_label("az-AZ"), "Dəstək məlumatlarını kopyala");
|
||||||
assert_eq!(app_menu_copy_support_info_label("en-US"), "Copy Support Info");
|
assert_eq!(app_menu_copy_support_info_label("en-US"), "Copy Support Info");
|
||||||
|
assert_eq!(app_menu_close_tab_label("zh-CN"), "关闭标签页");
|
||||||
|
assert_eq!(app_menu_close_tab_label("zh-TW"), "關閉分頁");
|
||||||
|
assert_eq!(app_menu_close_tab_label("ja-JP"), "タブを閉じる");
|
||||||
|
assert_eq!(app_menu_close_tab_label("en-US"), "Close Tab");
|
||||||
}
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
@@ -1471,6 +1498,8 @@ pub fn run() {
|
|||||||
if let Err(err) = app.clipboard().write_text(commands::support_info::format_support_info_for_clipboard()) {
|
if let Err(err) = app.clipboard().write_text(commands::support_info::format_support_info_for_clipboard()) {
|
||||||
log::warn!("Failed to copy support info from app menu: {err}");
|
log::warn!("Failed to copy support info from app menu: {err}");
|
||||||
}
|
}
|
||||||
|
} else if event.id() == APP_MENU_CLOSE_TAB_ID {
|
||||||
|
let _ = app.emit(APP_CLOSE_ACTIVE_TAB_EVENT, ());
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
@@ -2553,6 +2582,7 @@ pub fn run() {
|
|||||||
commands::agents::import_agent_jar_cmd,
|
commands::agents::import_agent_jar_cmd,
|
||||||
commands::system_fonts::list_system_fonts,
|
commands::system_fonts::list_system_fonts,
|
||||||
commands::ssh_config::list_ssh_config_hosts,
|
commands::ssh_config::list_ssh_config_hosts,
|
||||||
|
commands::ssh_keys::list_local_ssh_keys,
|
||||||
commands::ssh_prompt::ssh_prompt_ready,
|
commands::ssh_prompt::ssh_prompt_ready,
|
||||||
commands::ssh_prompt::ssh_prompt_not_ready,
|
commands::ssh_prompt::ssh_prompt_not_ready,
|
||||||
commands::ssh_prompt::resolve_ssh_prompt,
|
commands::ssh_prompt::resolve_ssh_prompt,
|
||||||
|
|||||||
Reference in new issue
Block a user