diff --git a/frontend/src/api/agent/index.ts b/frontend/src/api/agent/index.ts index 457e1316..35b8ea59 100644 --- a/frontend/src/api/agent/index.ts +++ b/frontend/src/api/agent/index.ts @@ -1,3 +1,4 @@ +import type { ConfigSchema } from '@/components/schema-form/schema' import { get, post, put, del } from "../../utils/request"; // 智能体配置 @@ -347,6 +348,35 @@ export interface IMChannelOverview { updated_at: string; } +// IMPlatformInfo describes one IM platform (internal/im.PlatformInfo): its +// connection modes, console links and the credential form. +export interface IMPlatformInfo { + id: string + name: string + names?: Record + order: number + /** Supported connection modes, default first. */ + modes: Array + mode_labels?: Record + mode_hint_key?: string + supports_thread: boolean + links?: Array<{ url: string; title: string; title_key?: string }> + config_schema?: ConfigSchema +} + +/** + * One channel for the editor, credentials included: plain fields as stored, + * set secrets as "***". Send them back unchanged to keep the stored secret. + */ +export function getIMChannel(id: string) { + return get<{ data: IMChannel }>(`/api/v1/im-channels/${id}`); +} + +/** The IM platforms this deployment has adapters for, in display order. */ +export function listIMPlatforms() { + return get<{ data: IMPlatformInfo[] }>('/api/v1/im-channels/platforms'); +} + export function listAllIMChannels() { return get<{ data: IMChannelOverview[] }>('/api/v1/im-channels'); } diff --git a/frontend/src/api/datasource/index.ts b/frontend/src/api/datasource/index.ts index 19096307..fc3322c5 100644 --- a/frontend/src/api/datasource/index.ts +++ b/frontend/src/api/datasource/index.ts @@ -1,3 +1,4 @@ +import type { ConfigSchema } from '@/components/schema-form/schema' import { get, post, put, del } from '../../utils/request' // --- Types --- @@ -72,6 +73,13 @@ export interface ConnectorMeta { priority: number auth_type: string capabilities: string[] + // Setup guide next to the credential form. + doc_url?: string + permission_doc_url?: string + permission_page_url?: string + required_permissions?: string[] + // Credential form: describes config.credentials for this connector. + config_schema?: ConfigSchema } export interface Resource { @@ -88,8 +96,9 @@ export interface Resource { // --- API calls --- +/** Connectors this deployment can create, with their credential forms. */ export function getConnectorTypes() { - return get('/api/v1/datasource/types') + return get('/api/v1/datasource/types') } export function listDataSources(kbId: string) { diff --git a/frontend/src/api/initialization/index.ts b/frontend/src/api/initialization/index.ts index 9f020cd8..fb974835 100644 --- a/frontend/src/api/initialization/index.ts +++ b/frontend/src/api/initialization/index.ts @@ -1,3 +1,4 @@ +import type { ConfigSchema } from '@/components/schema-form/schema'; import { get, post, put } from '../../utils/request'; import i18n from '@/i18n' import type { ModelCapabilities, ModelSpecOverride, ReasoningEffortLevel } from '../model' @@ -661,6 +662,8 @@ export interface ModelProviderOption { defaultUrls: Record; // 按模型类型区分的默认 URL modelTypes: string[]; // 支持的模型类型 extraFields?: ModelProviderExtraField[]; + // extraFields as a config schema over extra_config (secrets included). + configSchema?: ConfigSchema; credentialLabels?: ModelProviderCredentialLabel[]; models?: ModelCatalogEntry[]; thinking?: ModelProviderThinking; diff --git a/frontend/src/api/plugin.ts b/frontend/src/api/plugin.ts new file mode 100644 index 00000000..e2bb529e --- /dev/null +++ b/frontend/src/api/plugin.ts @@ -0,0 +1,48 @@ +import { get, put } from '@/utils/request' + +import type { LocalizedText } from '@/utils/localizedText' + +export type { LocalizedText } from '@/utils/localizedText' + +export type ExtensionPoint = 'modelVendors' | 'connectors' | 'imChannels' | 'webSearch' | 'tools' | 'parsers' + +export interface PluginContribution { + id: string + name: LocalizedText + description?: LocalizedText + icon?: string + aliases?: string[] + capabilities?: string[] + order?: number +} + +/** A plugin's manifest (internal/plugin/manifest.Manifest). */ +export interface PluginManifest { + schemaVersion: number + id: string + version: string + name: LocalizedText + description?: LocalizedText + publisher: { id: string; name?: string; url?: string } + icon?: string + builtin?: boolean + required?: boolean + runtime: { type: string } + contributes: Partial> +} + +/** A plugin as the current workspace sees it. */ +export interface TenantPlugin { + manifest: PluginManifest + enabled: boolean + updatedAt?: string +} + +export function listPlugins() { + return get<{ data: TenantPlugin[] }>('/api/v1/plugins') +} + +/** Turns a plugin on or off for the current workspace (Admin+). */ +export function setPluginEnabled(id: string, enabled: boolean) { + return put<{ data: TenantPlugin }>(`/api/v1/plugins/${encodeURIComponent(id)}/enabled`, { enabled }) +} diff --git a/frontend/src/api/web-search-provider.ts b/frontend/src/api/web-search-provider.ts index 425c4013..73241067 100644 --- a/frontend/src/api/web-search-provider.ts +++ b/frontend/src/api/web-search-provider.ts @@ -1,3 +1,4 @@ +import type { ConfigSchema } from '@/components/schema-form/schema' import { get, post, put, del } from '@/utils/request' // WebSearchProviderEntity represents a configured web search provider instance @@ -37,6 +38,8 @@ export interface WebSearchProviderTypeInfo { description?: string docs_url?: string config_fields?: WebSearchProviderConfigField[] + // The parameters form as a config schema; the settings drawer renders it. + config_schema?: ConfigSchema } export interface WebSearchProviderConfigField { diff --git a/frontend/src/components/IMChannelPanel.vue b/frontend/src/components/IMChannelPanel.vue index 77e956f8..c05d4eb6 100644 --- a/frontend/src/components/IMChannelPanel.vue +++ b/frontend/src/components/IMChannelPanel.vue @@ -119,7 +119,7 @@
- + {{ item.label }}
@@ -146,28 +146,19 @@
-
+

{{ $t('agentEditor.im.sectionAccess') }}

- -
-

- {{ formData.platform === 'mattermost' ? $t('agentEditor.im.mattermostModeHint') : - formData.platform === 'yunzhijia' ? $t('agentEditor.im.yunzhijiaModeHint') : - $t('agentEditor.im.modeHint') }} -

+

{{ modeHint }}

@@ -249,292 +240,19 @@

{{ $t('agentEditor.im.sectionCredentials') }}

- - + - - - - - - - - - - - - - - - - - - - - + +
-
- -
- - -
- -
- - -
- -
- - -
- -
- - -
- -
- - -
- -
- - -
- -
- - -
- -
- - -
- -
- - -
- -
- - -
- -
- - -
- -
- - -
- -
- - -
- -
- - -
- -
- -
- -
- - -
- -
- -
- -
- -
- -
- - -
- -
- - -
- -
- - -
- -
- - -
- -
- + +
+ +
@@ -201,46 +62,20 @@ import { useI18n } from 'vue-i18n' import { MessagePlugin } from 'tdesign-vue-next' import { useModalShell } from '@/composables/useModalShell' import SettingsModalShell from '@/components/SettingsModalShell.vue' -import SystemInfo from './SystemInfo.vue' -import TenantInfo from './TenantInfo.vue' -import UserProfile from './UserProfile.vue' -import GeneralSettings from './GeneralSettings.vue' -import ModelSettings from './ModelSettings.vue' -import ModelCatalog from '../system/ModelCatalog.vue' -import OllamaSettings from './OllamaSettings.vue' -import WebSearchSettings from './WebSearchSettings.vue' -import ChatHistorySettings from './ChatHistorySettings.vue' -import MemorySettings from './MemorySettings.vue' -import EnvVarSettings from './EnvVarSettings.vue' -import MemoryWorkspaceSettings from './MemoryWorkspaceSettings.vue' -import VectorStoreSettings from './VectorStoreSettings.vue' -import ParserEngineSettings from './ParserEngineSettings.vue' -import StorageBackendSettings from './StorageBackendSettings.vue' -import SandboxSettings from './SandboxSettings.vue' -import WeKnoraCloudSettings from './WeKnoraCloudSettings.vue' -import TenantMembers from './TenantMembers.vue' -import SystemSettings from '@/views/system/SystemSettings.vue' -import RuntimeQueues from '@/views/system/RuntimeQueues.vue' -import PlatformAPIKeys from '@/views/system/PlatformAPIKeys.vue' -import SystemAuditLog from '@/views/system/SystemAuditLog.vue' -import IntegrationSettingsSection from '@/views/integrations/IntegrationSettingsSection.vue' +import SettingsNavIcon from '@/extensions/SettingsNavIcon.vue' +import { registerBuiltinSettings } from '@/extensions/builtin/settings' import { - INTEGRATION_PREVIEW_ITEMS, - INTEGRATION_TAB_CAPABILITY, - INTEGRATION_TAB_MIN_ROLE, -} from '@/config/integrations' -import { - SETTINGS_SECTION_MIN_ROLE, - SYSTEM_ADMIN_SETTINGS_SECTIONS, -} from '@/config/settingsAccess' -import { SETTINGS_SECTION_CAPABILITY, skillSettingsSupported } from '@/config/deploymentCapabilities' + groupSections, + sectionPermitted, + sectionSupported, + settingsGroups, + settingsSections, + type SettingsAccessContext, + type SettingsSection, +} from '@/extensions/settingsSections' import { isToolboxSection, toolboxLocation } from '@/config/toolbox' -import { hostSkillsOnly } from '@/utils/skillTarget' import { buildSettingsRouteQuery, - integrationSectionKey, - integrationTabFromSection, - isIntegrationSection, normalizeSettingsSection as normalizeSettingsSectionFromQuery, settingsQueryUnchanged, } from '@/config/settingsRoute' @@ -250,51 +85,27 @@ const router = useRouter() const uiStore = useUIStore() const authStore = useAuthStore() const deploymentCapabilities = useDeploymentCapabilitiesStore() -const { t, te } = useI18n() -const hostSkills = computed(() => hostSkillsOnly( - deploymentCapabilities.isSupported('settings.sandbox.remote'), - deploymentCapabilities.isSupported('settings.sandbox.host'), -)) -function envNavLabel(): string { - const hostKey = 'envVarSettings.host.title' - if (hostSkills.value && te(hostKey)) return t(hostKey) - return t('envVarSettings.title') -} + +const { t } = useI18n() + +// Sections are registered, not listed here: builtins first, plugins later. +registerBuiltinSettings() const currentSection = ref('general') const currentSubSection = ref('') const expandedMenus = ref([]) -type NavItem = { - key: string - icon: string - label: string - emoji?: string - children?: Array<{ key: string; label: string }> -} - -type NavGroup = { - key: string - label: string - items: NavItem[] -} - -// 设置二级导航的最低可见角色来自 settingsAccess.ts,和 -// internal/router/router.go 的守卫矩阵对齐。 -// 以「页面里至少有 1 个有意义的写操作所要求的最低角色」为基准,把基础设 -// 施配置(models 写、ollama 下载、websearch 写、parser/storage/vector/mcp -// CRUD、sandbox 连接、skills 安装、chat-history 配置)统一收到 admin;只读类(general / system info / -// tenant-info / members 名册)保留 viewer 可见;最高敏感的 reset api -// key 是 owner-only。改这张表前请在 router.go 里复核对应路由组。 -// -// 特别说明: -// - chathistory 页面唯一的「启用消息索引」开关 PUT /tenants/kv/chat-history-config -// 后端走 g.Admin()。给 viewer/contributor 看到入口、点开开关、保存时 -// 403,体验很差,所以入口本身归 admin。 -// - models 列表 viewer 可读,页面内的「+ 添加模型 / 编辑 / 删除」按钮在 -// ModelSettings.vue 里另用 hasRole('admin') 自己 gate,所以入口保留 -// viewer 是合理的(contributor 也能浏览模型列表)。 -const SYSTEM_ADMIN_SECTIONS = SYSTEM_ADMIN_SETTINGS_SECTIONS +// Who may see a section comes from each section's access rules (for builtins, +// settingsAccess.ts and deploymentCapabilities.ts, aligned with the guards in +// internal/router). They only decide whether the UI offers the entry; the +// server checks every route itself. +const accessContext = computed(() => ({ + isSystemAdmin: authStore.isSystemAdmin, + canAccessAllTenants: authStore.canAccessAllTenants, + hasRole: (role) => authStore.hasRole(role), + isSupported: (capability) => deploymentCapabilities.isSupported(capability), + capabilities: deploymentCapabilities.capabilities, +})) const normalizeSettingsSection = (section: string) => { return normalizeSettingsSectionFromQuery(section, route.query.tab as string | undefined) @@ -311,129 +122,28 @@ const syncSettingsRoute = (sectionKey: string) => { } const isSectionSupported = (key: string): boolean => { - if (isIntegrationSection(key)) { - return deploymentCapabilities.isSupported( - INTEGRATION_TAB_CAPABILITY[integrationTabFromSection(key)], - ) - } - if (key === 'skills' || key === 'envvars') { - return skillSettingsSupported(deploymentCapabilities.capabilities) - } - return deploymentCapabilities.isSupported(SETTINGS_SECTION_CAPABILITY[key]) + const section = settingsSections.get(key) + return !!section && sectionSupported(section, accessContext.value) } const canSeeSection = (key: string): boolean => { - if (isIntegrationSection(key)) { - const min = INTEGRATION_TAB_MIN_ROLE[integrationTabFromSection(key)] - if (!min) return true - if (authStore.canAccessAllTenants) return true - return authStore.hasRole(min) - } - if (SYSTEM_ADMIN_SECTIONS.has(key)) { - return authStore.isSystemAdmin - } - const min = SETTINGS_SECTION_MIN_ROLE[key] ?? 'viewer' - // canAccessAllTenants(superuser)和路由层一样必须 bypass,否则 cross-tenant - // 管理员看不到自己有权操作的入口(参考 TenantMembers.vue 的 canManage)。 - if (authStore.canAccessAllTenants) return true - return authStore.hasRole(min) + const section = settingsSections.get(key) + // An unknown key (stale deep link) falls through to the fallback watchers. + return !section || sectionPermitted(section, accessContext.value) } -const navItems = computed(() => { - // 一律走 SETTINGS_SECTION_MIN_ROLE 表,避免 ad-hoc isAdmin/isOwner 散落在多处。 - // 服务端在每条路由上仍以 g.Viewer/Admin/Owner 为准,这里只决定 UI 是 - // 否露入口;改动入口规则请同步更新 settingsAccess.ts 和对应后端路由。 - const integrationItems: NavItem[] = INTEGRATION_PREVIEW_ITEMS.map((item) => ({ - key: integrationSectionKey(item.key), - icon: item.icon.type === 'icon' ? item.icon.name : 'integration', - emoji: item.icon.type === 'emoji' ? item.icon.value : undefined, - label: t(`integrations.tabs.${item.key}`), - })) - const all: NavItem[] = [ - { key: 'general', icon: 'setting', label: t('general.title') }, - { key: 'ollama', icon: 'server', label: 'Ollama' }, - { key: 'weknoracloud', icon: '', label: 'WeKnora Cloud' }, - { key: 'models', icon: 'control-platform', label: t('settings.modelManagement') }, - { key: 'websearch', icon: 'search', label: t('settings.webSearchConfig') }, - { key: 'chathistory', icon: 'chat', label: t('chatHistorySettings.title') }, - { key: 'memory', icon: 'bulletpoint', label: t('memoryWorkspaceSettings.title') }, - { key: 'vectorstore', icon: 'data-base', label: t('settings.vectorStoreEngine') }, - { key: 'parser', icon: 'file-search', label: t('settings.parserEngine') }, - { key: 'storage', icon: 'cloud', label: t('settings.storageEngine') }, - { key: 'sandbox', icon: 'code', label: t('settings.sandbox.title') }, - { key: 'system', icon: 'info-circle', label: t('settings.versionInfo') }, - { key: 'system-global', icon: 'server', label: t('settings.system') }, - { key: 'model-catalog', icon: 'control-platform', label: t('modelCatalog.title') }, - { key: 'runtime-queues', icon: 'queue', label: t('settings.taskQueue') }, - { key: 'platform-api-keys', icon: 'secured', label: t('platformApiKeys.title') }, - { key: 'system-audit-log', icon: 'history', label: t('system.globalSettings.audit.tabLabel') }, - { key: 'userprofile', icon: 'user', label: t('userProfile.title') }, - { key: 'mymemory', icon: 'bookmark', label: t('memorySettings.title') }, - { key: 'envvars', icon: 'key', label: envNavLabel() }, - { key: 'tenant', icon: 'user-circle', label: t('settings.tenantInfo') }, - { key: 'members', icon: 'usergroup', label: t('tenantMember.title') }, - ...integrationItems, - ] +const currentEntry = computed(() => settingsSections.get(currentSection.value)) + +const navItems = computed(() => { // currentTenantRole 为空表示「membership 还没加载」—— 比起渲染整套 - // viewer 入口然后角色一返回又消失,先卡住不渲染更稳,跟原先 members - // 入口的策略一致。 - if (!authStore.currentTenantRole && !authStore.canAccessAllTenants) { - return [] as NavItem[] - } - return all.filter((it) => canSeeSection(it.key) && isSectionSupported(it.key)) + // viewer 入口然后角色一返回又消失,先卡住不渲染更稳。 + if (!authStore.currentTenantRole && !authStore.canAccessAllTenants) return [] + return settingsSections.items.filter((section) => + sectionPermitted(section, accessContext.value) && sectionSupported(section, accessContext.value), + ) }) -const navGroups = computed(() => { - const itemMap = new Map(navItems.value.map((item) => [item.key, item])) - const pickItems = (keys: string[]) => keys.map((key) => itemMap.get(key)).filter(Boolean) as NavItem[] - // 分组:账户 → 空间 → 模型 → 发布集成 → 数据与扩展 → 系统管理 → 平台 - // 关键调整:把个人偏好(general)和用户信息收进「账户」; - // 把空间内功能开关(chathistory)从「平台」挪到「空间」; - // 把检索引擎和外部集成合并为「数据与扩展」,避免两个 2~3 项的窄分组。 - return [ - { - key: 'account', - label: t('settings.navGroups.account'), - items: pickItems(['general', 'userprofile', 'mymemory', 'envvars']), - }, - { - key: 'workspace', - label: t('settings.navGroups.workspace'), - items: pickItems(['tenant', 'members', 'chathistory', 'memory']), - }, - { - key: 'models_runtime', - label: t('settings.navGroups.modelsRuntime'), - items: pickItems(['models', 'ollama', 'weknoracloud']), - }, - { - key: 'integrations', - label: t('integrations.title'), - items: pickItems(INTEGRATION_PREVIEW_ITEMS.map((item) => integrationSectionKey(item.key))), - }, - { - key: 'data_extensions', - label: t('settings.navGroups.dataExtensions'), - items: pickItems([ - 'vectorstore', - 'parser', - 'storage', - 'sandbox', - 'websearch', - ]), - }, - { - key: 'system_administration', - label: t('settings.navGroups.systemAdministration'), - items: pickItems(['system-global', 'model-catalog', 'runtime-queues', 'platform-api-keys', 'system-audit-log']), - }, - { - key: 'platform', - label: t('settings.navGroups.platform'), - items: pickItems(['system']), - }, - ].filter((group) => group.items.length > 0) -}) +const navGroups = computed(() => groupSections(settingsGroups.items, navItems.value)) // 导航项点击处理 const handleNavClick = (item: any) => { diff --git a/frontend/src/views/settings/WebSearchSettings.vue b/frontend/src/views/settings/WebSearchSettings.vue index 5010602b..b1f484ca 100644 --- a/frontend/src/views/settings/WebSearchSettings.vue +++ b/frontend/src/views/settings/WebSearchSettings.vue @@ -202,96 +202,42 @@
- -
+ +

{{ t('webSearchSettings.credentialsSection', '连接配置') }}

-
- - -
- -
- - - - - -
- -
- - -
- -
- - - + - -

- {{ configFieldText(field.description_key, field.description) }} -

-
+ +
-
+

{{ t('webSearchSettings.optionsSection', '选项') }}

-
- - -

{{ t('webSearchSettings.proxyUrlHelp') }}

-
+
@@ -324,6 +270,17 @@ import { type WebSearchCredentialField, } from '@/api/web-search-provider' import SettingDrawer from '@/components/settings/SettingDrawer.vue' +import SchemaForm from '@/components/schema-form/SchemaForm.vue' +import { + inGroup, + isPlainObject, + orderedFields, + applyDefaults, + validateConfig, + type ConfigSchema, + type ConfigValue, + type FieldError, +} from '@/components/schema-form/schema' import CredentialResource, { type CredentialFieldDef, type CredentialResourceApi, @@ -353,26 +310,25 @@ const formRef = ref() // is initialized so the watch's source function doesn't trip on TDZ). const lastTestOk = ref(null) +// parameters follows the selected type's config_schema: api_key, engine_id, +// base_url, proxy_url and extra_config, whichever the type declares. const providerForm = ref<{ name: string provider: string description: string - parameters: { - api_key?: string - engine_id?: string - base_url?: string - proxy_url?: string - extra_config: Record - } + parameters: ConfigValue is_default: boolean }>({ name: '', provider: 'duckduckgo', description: '', - parameters: { extra_config: {} }, + parameters: {}, is_default: false, }) +// Field errors from the last save attempt, shown under each field. +const formErrors = ref([]) + // Invalidate the cached test result whenever the user edits a connection // field. Set up after providerForm is declared so the watch's source // function — which dereferences providerForm.value on first run — doesn't @@ -381,22 +337,29 @@ const providerForm = ref<{ watch( () => [ providerForm.value.provider, - providerForm.value.parameters?.api_key, - providerForm.value.parameters?.engine_id, - providerForm.value.parameters?.base_url, - JSON.stringify(providerForm.value.parameters?.extra_config || {}), + JSON.stringify({ ...providerForm.value.parameters, proxy_url: undefined }), ], () => { lastTestOk.value = null }, ) +// Any edit clears the errors of the last save attempt. +watch(() => JSON.stringify(providerForm.value.parameters), () => { formErrors.value = [] }) + // ===== Computed ===== const selectedProviderType = computed(() => { return providerTypes.value.find(pt => pt.id === providerForm.value.provider) }) -// Create-mode placeholder (edit mode replaces the input with -// , which has its own placeholder). -const apiKeyPlaceholder = computed(() => t('webSearchSettings.apiKeyPlaceholder')) +const EMPTY_SCHEMA: ConfigSchema = { type: 'object', properties: {} } + +const parametersSchema = computed(() => selectedProviderType.value?.config_schema ?? EMPTY_SCHEMA) + +const hasGroup = (group: string) => orderedFields(parametersSchema.value).some(f => inGroup(f.schema, group)) + +// Validation for the parameters. In edit mode secrets are committed through +// , and the stored key stands in for an empty input. +const parameterErrors = () => + validateConfig(parametersSchema.value, providerForm.value.parameters, { skipSecrets: !!editingProvider.value }) const credentialFields = computed[]>(() => [ { key: 'api_key', label: t('webSearchSettings.apiKeyLabel') as string }, @@ -449,14 +412,9 @@ const drawerLogoStyle = computed((): Record => { // can fire with no fresh api_key because the backend will fall back to // the stored credential. Free providers don't show the button at all. const canTestConnection = computed(() => { - const pt = selectedProviderType.value - if (!pt) return false + if (!selectedProviderType.value) return false if (editingProvider.value) return true - if (pt.requires_api_key && !providerForm.value.parameters.api_key) return false - if (pt.requires_engine_id && !providerForm.value.parameters.engine_id) return false - if (pt.requires_base_url && !providerForm.value.parameters.base_url) return false - if (pt.config_fields?.some(field => field.required && !providerForm.value.parameters.extra_config?.[field.key])) return false - return true + return parameterErrors().length === 0 }) // 卡片首字母徽章。复用 providerType 信息表,让多字节缩写也走同一处。 @@ -486,25 +444,17 @@ const providerTypeLabel = (providerId: string) => { return providerTypes.value.find(p => p.id === providerId)?.name || providerId } -const configFieldText = (key: string | undefined, fallback: string) => { - return key ? t(key, fallback) : fallback -} - -const providerConfigDefaults = (providerId: string) => { - const fields = providerTypes.value.find(p => p.id === providerId)?.config_fields || [] - return Object.fromEntries( - fields - .filter(field => field.default !== undefined) - .map(field => [field.key, field.default as string]), - ) +// Fills a type's schema defaults (e.g. Zhipu's search engine) into parameters. +const parametersWithDefaults = (providerId: string, parameters: ConfigValue = {}) => { + const schema = providerTypes.value.find(p => p.id === providerId)?.config_schema + return schema ? applyDefaults(schema, parameters) : { ...parameters } } // ===== Methods ===== const onProviderTypeChange = () => { - providerForm.value.parameters = { - extra_config: providerConfigDefaults(providerForm.value.provider), - } + providerForm.value.parameters = parametersWithDefaults(providerForm.value.provider) lastTestOk.value = null + formErrors.value = [] } // 走 chatResources 的共享快照并强刷:增删改之后对话输入栏读到的就是最新列表, @@ -532,12 +482,11 @@ const openAddDialog = () => { name: '', provider: providerTypes.value[0]?.id || 'duckduckgo', description: '', - parameters: { - extra_config: providerConfigDefaults(providerTypes.value[0]?.id || 'duckduckgo'), - }, + parameters: parametersWithDefaults(providerTypes.value[0]?.id || 'duckduckgo'), is_default: providerEntities.value.length === 0 } lastTestOk.value = null + formErrors.value = [] showAddProviderDialog.value = true } @@ -547,21 +496,13 @@ const editProvider = (entity: WebSearchProviderEntity) => { name: entity.name, provider: entity.provider, description: entity.description || '', - parameters: { - // Never pre-fill the api_key — even the redacted placeholder from the - // server is ignored so that "non-empty means user typed it" holds. - api_key: '', - engine_id: entity.parameters?.engine_id || '', - base_url: entity.parameters?.base_url || '', - proxy_url: entity.parameters?.proxy_url || '', - extra_config: { - ...providerConfigDefaults(entity.provider), - ...(entity.parameters?.extra_config || {}), - }, - }, + // Never pre-fill the api_key — even the redacted placeholder from the + // server is ignored so that "non-empty means user typed it" holds. + parameters: parametersWithDefaults(entity.provider, { ...(entity.parameters || {}), api_key: undefined }), is_default: entity.is_default || false, } lastTestOk.value = null + formErrors.value = [] showAddProviderDialog.value = true } @@ -572,27 +513,15 @@ const saveProvider = async () => { MessagePlugin.warning(typeof firstError === 'string' ? firstError : 'Please check the form fields') return } + formErrors.value = parameterErrors() + if (formErrors.value.length > 0) return saving.value = true try { // Build the parameters payload. api_key only flows in on initial // create — edit mode commits credentials through // (a dedicated PUT /credentials call) before this save runs. - const paramsOut: WebSearchProviderEntity['parameters'] = { - engine_id: providerForm.value.parameters.engine_id, - base_url: providerForm.value.parameters.base_url, - proxy_url: providerForm.value.parameters.proxy_url, - } - const extraConfig = Object.fromEntries( - Object.entries(providerForm.value.parameters.extra_config || {}) - .filter(([, value]) => value !== ''), - ) - if (Object.keys(extraConfig).length > 0) { - paramsOut.extra_config = extraConfig - } - if (!editingProvider.value && providerForm.value.parameters.api_key) { - paramsOut.api_key = providerForm.value.parameters.api_key - } + const paramsOut = buildParametersPayload(providerForm.value.parameters, !editingProvider.value) const data: Partial = { name: providerForm.value.name.trim() || selectedProviderType.value?.name || providerForm.value.provider, @@ -618,6 +547,22 @@ const saveProvider = async () => { } } +// Drops empty values (an empty extra_config entry means "unset") and, in edit +// mode, the api_key, which is committed through . +const buildParametersPayload = (parameters: ConfigValue, includeSecrets: boolean) => { + const out: Record = {} + for (const [key, value] of Object.entries(parameters)) { + if (key === 'api_key' && !includeSecrets) continue + if (isPlainObject(value)) { + const nested = Object.fromEntries(Object.entries(value).filter(([, v]) => v !== '' && v !== undefined)) + if (Object.keys(nested).length > 0) out[key] = nested + continue + } + if (value !== undefined && value !== '') out[key] = value + } + return out as WebSearchProviderEntity['parameters'] +} + const deleteProvider = (entity: WebSearchProviderEntity) => { confirmDelete({ body: t('webSearchSettings.deleteConfirm'), diff --git a/frontend/src/views/settings/pluginCenterState.test.ts b/frontend/src/views/settings/pluginCenterState.test.ts new file mode 100644 index 00000000..fb094824 --- /dev/null +++ b/frontend/src/views/settings/pluginCenterState.test.ts @@ -0,0 +1,39 @@ +import assert from 'node:assert/strict' +import test from 'node:test' + +import type { TenantPlugin } from '../../api/plugin' +import { contributionSummary, filterPlugins } from './pluginCenterState' + +const plugin = (id: string, name: string, contributes: TenantPlugin['manifest']['contributes'], zh?: string): TenantPlugin => ({ + enabled: true, + manifest: { + schemaVersion: 1, id, version: '1.0.0', publisher: { id: 'weknora' }, runtime: { type: 'builtin' }, + name: zh ? { default: name, 'zh-CN': zh } : { default: name }, + contributes, + }, +}) + +const feishu = plugin('weknora.feishu', 'Feishu / Lark', { + connectors: [{ id: 'feishu', name: { default: 'Feishu' } }, { id: 'lark', name: { default: 'Lark' } }], + imChannels: [{ id: 'feishu', name: { default: 'Feishu' } }], +}, '飞书 / Lark') +const bing = plugin('weknora.bing', 'Bing', { webSearch: [{ id: 'bing', name: { default: 'Bing' } }] }) +const openai = plugin('weknora.openai', 'OpenAI', { modelVendors: [{ id: 'openai', name: { default: 'OpenAI' } }] }) + +test('contributionSummary counts per point in point order', () => { + assert.deepEqual(contributionSummary(feishu.manifest), [ + { point: 'connectors', count: 2 }, + { point: 'imChannels', count: 1 }, + ]) +}) + +test('filterPlugins matches names, IDs and contributions, and filters by point', () => { + const all = [openai, feishu, bing] + const names = (list: TenantPlugin[]) => list.map((p) => p.manifest.id) + assert.deepEqual(names(filterPlugins(all, { query: '', point: '', locale: 'en-US' })), + ['weknora.bing', 'weknora.feishu', 'weknora.openai']) + assert.deepEqual(names(filterPlugins(all, { query: 'lark', point: '', locale: 'en-US' })), ['weknora.feishu']) + assert.deepEqual(names(filterPlugins(all, { query: '飞书', point: '', locale: 'zh-CN' })), ['weknora.feishu']) + assert.deepEqual(names(filterPlugins(all, { query: '', point: 'webSearch', locale: 'en-US' })), ['weknora.bing']) + assert.deepEqual(names(filterPlugins(all, { query: 'bing', point: 'connectors', locale: 'en-US' })), []) +}) diff --git a/frontend/src/views/settings/pluginCenterState.ts b/frontend/src/views/settings/pluginCenterState.ts new file mode 100644 index 00000000..a4916a0f --- /dev/null +++ b/frontend/src/views/settings/pluginCenterState.ts @@ -0,0 +1,47 @@ +// Pure helpers behind PluginCenter.vue, kept free of Vue so they run under +// node:test. +import type { ExtensionPoint, PluginManifest, TenantPlugin } from '../../api/plugin' +import { localizedText } from '../../utils/localizedText' + +/** Extension points in the order the plugin center shows them. */ +export const EXTENSION_POINTS: ExtensionPoint[] = [ + 'modelVendors', 'connectors', 'imChannels', 'webSearch', 'tools', 'parsers', +] + +/** How many contributions a plugin makes at each point, in point order. */ +export function contributionSummary(m: PluginManifest): Array<{ point: ExtensionPoint; count: number }> { + return EXTENSION_POINTS + .map((point) => ({ point, count: m.contributes[point]?.length ?? 0 })) + .filter((s) => s.count > 0) +} + +export interface PluginFilter { + query: string + /** Only plugins contributing to this point; empty for all. */ + point: ExtensionPoint | '' + locale: string +} + +/** + * Plugins matching a search and point filter, sorted by display name. The + * query matches the plugin name, ID and the names of its contributions, so + * searching "lark" finds the Feishu plugin. + */ +export function filterPlugins(list: readonly TenantPlugin[], f: PluginFilter): TenantPlugin[] { + const q = f.query.trim().toLowerCase() + const matches = (p: TenantPlugin) => { + const m = p.manifest + if (f.point && !(m.contributes[f.point]?.length)) return false + if (!q) return true + const texts = [m.id, localizedText(m.name, f.locale), m.name.default] + for (const point of EXTENSION_POINTS) { + for (const c of m.contributes[point] ?? []) { + texts.push(c.id, localizedText(c.name, f.locale)) + } + } + return texts.some((t) => t.toLowerCase().includes(q)) + } + return list + .filter(matches) + .sort((a, b) => localizedText(a.manifest.name, f.locale).localeCompare(localizedText(b.manifest.name, f.locale), f.locale)) +} diff --git a/frontend/src/views/settings/settingsNavigation.test.ts b/frontend/src/views/settings/settingsNavigation.test.ts index 2e9c04a7..e840c68d 100644 --- a/frontend/src/views/settings/settingsNavigation.test.ts +++ b/frontend/src/views/settings/settingsNavigation.test.ts @@ -1,46 +1,73 @@ import assert from 'node:assert/strict' -import { readFileSync } from 'node:fs' import test from 'node:test' -import { runInNewContext } from 'node:vm' -import ts from 'typescript' -import { computed } from 'vue' + import { INTEGRATION_PREVIEW_ITEMS } from '../../config/integrations' import { integrationSectionKey } from '../../config/settingsRoute' +import { BUILTIN_SETTINGS_GROUPS, BUILTIN_SETTINGS_SECTIONS } from '../../extensions/builtin/settingsCatalog' +import { + groupSections, + sectionPermitted, + type SettingsAccessContext, + type SettingsSection, +} from '../../extensions/settingsSections' -// Exercise the actual sidebar grouping without mounting the settings panels. -const source = readFileSync(new URL('./Settings.vue', import.meta.url), 'utf8') -const script = source.match(/