chore: 项目基线(基于 WeKnora 定制版,整理文件忽略规则)

This commit is contained in:
runny committed 2026-11-13 17:54:56 +08:00
commit 9097ee699d
5769 files changed
+1446466

No files matched your search

+100
View File
@@ -0,0 +1,100 @@
import type { TenantAPIKeyCapability } from '@/api/tenant'
export type ApiKeyCapabilityOption = {
value: TenantAPIKeyCapability
labelKey: string
hintKey: string
}
export type ApiKeyCapabilityGroup = {
key: string
labelKey: string
capabilities: ApiKeyCapabilityOption[]
}
export const TENANT_API_KEY_CAPABILITIES: TenantAPIKeyCapability[] = [
'retrieve', 'chat', 'read_agents', 'ingest', 'manage_kbs',
'message_history', 'manage_agents', 'manage_mcp_services',
'manage_datasources', 'manage_models', 'manage_vector_stores',
'manage_storage_backends', 'manage_web_search', 'manage_channels',
'run_evaluations', 'manage_members', 'manage_spaces',
'manage_tenant_settings',
]
export const SYSTEM_API_KEY_CAPABILITIES: TenantAPIKeyCapability[] = [
'system_tenants_read', 'system_tenants_manage',
'system_settings_read', 'system_settings_manage',
'system_runtime_read', 'system_runtime_manage', 'system_audit_read',
]
export const DEFAULT_TENANT_API_KEY_CAPABILITIES = new Set<TenantAPIKeyCapability>([
'retrieve', 'chat', 'read_agents',
])
export const KB_SCOPED_API_KEY_CAPABILITIES = new Set<TenantAPIKeyCapability>([
'retrieve', 'chat', 'ingest', 'manage_kbs', 'manage_agents', 'manage_datasources',
])
export const TENANT_API_KEY_CAPABILITY_GROUPS: ApiKeyCapabilityGroup[] = [
{
key: 'knowledge',
labelKey: 'integrations.api.apiKeyCapabilityGroupKnowledge',
capabilities: [
{ value: 'retrieve', labelKey: 'integrations.api.capabilityRetrieve', hintKey: 'integrations.api.capabilityRetrieveHint' },
{ value: 'chat', labelKey: 'integrations.api.capabilityChat', hintKey: 'integrations.api.capabilityChatHint' },
{ value: 'ingest', labelKey: 'integrations.api.capabilityIngest', hintKey: 'integrations.api.capabilityIngestHint' },
{ value: 'manage_kbs', labelKey: 'integrations.api.capabilityManageKbs', hintKey: 'integrations.api.capabilityManageKbsHint' },
{ value: 'message_history', labelKey: 'integrations.api.capabilityMessageHistory', hintKey: 'integrations.api.capabilityMessageHistoryHint' },
],
},
{
key: 'automation',
labelKey: 'integrations.api.apiKeyCapabilityGroupAutomation',
capabilities: [
{ value: 'read_agents', labelKey: 'integrations.api.capabilityReadAgents', hintKey: 'integrations.api.capabilityReadAgentsHint' },
{ value: 'manage_agents', labelKey: 'integrations.api.capabilityManageAgents', hintKey: 'integrations.api.capabilityManageAgentsHint' },
{ value: 'manage_mcp_services', labelKey: 'integrations.api.capabilityManageMcpServices', hintKey: 'integrations.api.capabilityManageMcpServicesHint' },
{ value: 'manage_datasources', labelKey: 'integrations.api.capabilityManageDatasources', hintKey: 'integrations.api.capabilityManageDatasourcesHint' },
],
},
{
key: 'collaboration',
labelKey: 'integrations.api.apiKeyCapabilityGroupCollaboration',
capabilities: [
{ value: 'manage_members', labelKey: 'integrations.api.capabilityManageMembers', hintKey: 'integrations.api.capabilityManageMembersHint' },
{ value: 'manage_spaces', labelKey: 'integrations.api.capabilityManageSpaces', hintKey: 'integrations.api.capabilityManageSpacesHint' },
],
},
{
key: 'tenant',
labelKey: 'integrations.api.apiKeyCapabilityGroupTenant',
capabilities: [
{ value: 'manage_models', labelKey: 'integrations.api.capabilityManageModels', hintKey: 'integrations.api.capabilityManageModelsHint' },
{ value: 'manage_vector_stores', labelKey: 'integrations.api.capabilityManageVectorStores', hintKey: 'integrations.api.capabilityManageVectorStoresHint' },
{ value: 'manage_storage_backends', labelKey: 'integrations.api.capabilityManageStorageBackends', hintKey: 'integrations.api.capabilityManageStorageBackendsHint' },
{ value: 'manage_web_search', labelKey: 'integrations.api.capabilityManageWebSearch', hintKey: 'integrations.api.capabilityManageWebSearchHint' },
{ value: 'manage_channels', labelKey: 'integrations.api.capabilityManageChannels', hintKey: 'integrations.api.capabilityManageChannelsHint' },
{ value: 'run_evaluations', labelKey: 'integrations.api.capabilityRunEvaluations', hintKey: 'integrations.api.capabilityRunEvaluationsHint' },
{ value: 'manage_tenant_settings', labelKey: 'integrations.api.capabilityManageTenantSettings', hintKey: 'integrations.api.capabilityManageTenantSettingsHint' },
],
},
]
export const SYSTEM_API_KEY_CAPABILITY_GROUP: ApiKeyCapabilityGroup = {
key: 'system',
labelKey: 'platformApiKeys.systemCapabilityGroup',
capabilities: [
{ value: 'system_tenants_read', labelKey: 'platformApiKeys.capabilities.tenantsRead', hintKey: 'platformApiKeys.capabilityHints.tenantsRead' },
{ value: 'system_tenants_manage', labelKey: 'platformApiKeys.capabilities.tenantsManage', hintKey: 'platformApiKeys.capabilityHints.tenantsManage' },
{ value: 'system_settings_read', labelKey: 'platformApiKeys.capabilities.settingsRead', hintKey: 'platformApiKeys.capabilityHints.settingsRead' },
{ value: 'system_settings_manage', labelKey: 'platformApiKeys.capabilities.settingsManage', hintKey: 'platformApiKeys.capabilityHints.settingsManage' },
{ value: 'system_runtime_read', labelKey: 'platformApiKeys.capabilities.runtimeRead', hintKey: 'platformApiKeys.capabilityHints.runtimeRead' },
{ value: 'system_runtime_manage', labelKey: 'platformApiKeys.capabilities.runtimeManage', hintKey: 'platformApiKeys.capabilityHints.runtimeManage' },
{ value: 'system_audit_read', labelKey: 'platformApiKeys.capabilities.auditRead', hintKey: 'platformApiKeys.capabilityHints.auditRead' },
],
}
export const PLATFORM_API_KEY_CAPABILITY_GROUPS: ApiKeyCapabilityGroup[] = [
SYSTEM_API_KEY_CAPABILITY_GROUP,
...TENANT_API_KEY_CAPABILITY_GROUPS,
]
+151
View File
@@ -0,0 +1,151 @@
import type { SpotlightGuideStep } from '@/types/spotlightGuide'
export const GLOBAL_USER_GUIDE_KEY = 'weknora:new-user-guide-done:v1'
export const OPEN_NEW_USER_GUIDE_EVENT = 'weknora:open-new-user-guide'
export function openNewUserGuide() {
window.dispatchEvent(new CustomEvent(OPEN_NEW_USER_GUIDE_EVENT))
}
export const KB_EDITOR_FOCUS_SECTION_EVENT = 'weknora:kb-editor-focus-section'
export const AGENT_EDITOR_FOCUS_SECTION_EVENT = 'weknora:agent-editor-focus-section'
export type ContextualGuideTourId =
| 'kbList'
| 'kbCreate'
| 'kbDetail'
| 'chat'
| 'tenantModels'
| 'agentList'
| 'agentCreate'
export const focusKbEditorSection = (section: string) => {
window.dispatchEvent(
new CustomEvent(KB_EDITOR_FOCUS_SECTION_EVENT, { detail: { section } }),
)
}
export const focusAgentEditorSection = (section: string) => {
window.dispatchEvent(
new CustomEvent(AGENT_EDITOR_FOCUS_SECTION_EVENT, { detail: { section } }),
)
}
const focusKbEditorBasic = () => focusKbEditorSection('basic')
export interface ContextualGuideTourConfig {
storageKey: string
stepI18nPrefix: string
steps: SpotlightGuideStep[]
/** 首次展示前的延迟(毫秒) */
openDelayMs: number
/** 完成本引导时一并标记为已完成的其他引导 */
alsoCompleteTours?: ContextualGuideTourId[]
}
export const CONTEXTUAL_GUIDE_TOURS: Record<ContextualGuideTourId, ContextualGuideTourConfig> = {
kbList: {
storageKey: 'weknora:contextual-guide-kb-list:v2',
stepI18nPrefix: 'contextualGuide.kbList.steps',
openDelayMs: 500,
steps: [
{
key: 'create',
// 空列表时优先高亮居中的主 CTA,否则退化为顶栏新建按钮
target: '.empty-state-btn[data-guide="kb-list-create"], [data-guide="kb-list-create"]',
placement: 'bottom',
interact: true,
},
],
},
// 步骤由 KbCreateContextualGuide.vue 按文档库/FAQ 动态组装
kbCreate: {
storageKey: 'weknora:contextual-guide-kb-create:v3',
stepI18nPrefix: 'contextualGuide.kbCreate.steps',
openDelayMs: 450,
alsoCompleteTours: ['kbList'],
steps: [],
},
tenantModels: {
storageKey: 'weknora:contextual-guide-tenant-models:v1',
stepI18nPrefix: 'contextualGuide.tenantModels.steps',
openDelayMs: 500,
steps: [],
},
kbDetail: {
storageKey: 'weknora:contextual-guide-kb-detail:v1',
stepI18nPrefix: 'contextualGuide.kbDetail.steps',
openDelayMs: 600,
steps: [
{
key: 'intro',
},
{
key: 'upload',
target: '[data-guide="kb-detail-add-doc"]',
placement: 'bottom',
},
{ key: 'done' },
],
},
chat: {
storageKey: 'weknora:contextual-guide-chat:v1',
stepI18nPrefix: 'contextualGuide.chat.steps',
openDelayMs: 800,
steps: [
{
key: 'kb',
target: '[data-guide="chat-kb-mention"]',
placement: 'top',
optional: true,
},
{
key: 'input',
target: '[data-guide="chat-input"]',
placement: 'top',
},
{
key: 'send',
target: '[data-guide="chat-send"]',
placement: 'top',
},
{ key: 'done' },
],
},
agentList: {
storageKey: 'weknora:contextual-guide-agent-list:v1',
stepI18nPrefix: 'contextualGuide.agentList.steps',
openDelayMs: 500,
steps: [
{
key: 'create',
target: '.empty-state-btn[data-guide="agent-list-create"], [data-guide="agent-list-create"]',
placement: 'bottom',
interact: true,
},
],
},
agentCreate: {
storageKey: 'weknora:contextual-guide-agent-create:v1',
stepI18nPrefix: 'contextualGuide.agentCreate.steps',
openDelayMs: 450,
alsoCompleteTours: ['agentList'],
steps: [],
},
}
export function isContextualGuideDone(tourId: ContextualGuideTourId): boolean {
return localStorage.getItem(CONTEXTUAL_GUIDE_TOURS[tourId].storageKey) === '1'
}
export function markContextualGuideDone(tourId: ContextualGuideTourId) {
const config = CONTEXTUAL_GUIDE_TOURS[tourId]
localStorage.setItem(config.storageKey, '1')
config.alsoCompleteTours?.forEach((id) => {
localStorage.setItem(CONTEXTUAL_GUIDE_TOURS[id].storageKey, '1')
})
}
export function isGlobalUserGuideDone(): boolean {
return localStorage.getItem(GLOBAL_USER_GUIDE_KEY) === '1'
}
@@ -0,0 +1,127 @@
import assert from 'node:assert/strict'
import test from 'node:test'
import {
SETTINGS_SECTION_CAPABILITY,
isDeploymentCapabilitySupported,
skillSettingsSupported,
type DeploymentCapabilityMap,
} from './deploymentCapabilities'
test('capability filtering is fail-open unless backend explicitly disables a feature', () => {
assert.equal(isDeploymentCapabilitySupported({}, 'organizations'), true)
const capabilities: DeploymentCapabilityMap = {
organizations: { supported: false, reason: 'not_supported_in_lite' },
agents: { supported: true },
}
assert.equal(isDeploymentCapabilitySupported(capabilities, 'organizations'), false)
assert.equal(isDeploymentCapabilitySupported(capabilities, 'agents'), true)
})
test('organizations stay hidden in lite even when capabilities fail open', () => {
assert.equal(
isDeploymentCapabilitySupported({}, 'organizations', { liteMode: true }),
false,
)
assert.equal(
isDeploymentCapabilitySupported({}, 'organizations', { edition: 'lite' }),
false,
)
assert.equal(
isDeploymentCapabilitySupported({}, 'agents', { liteMode: true }),
true,
)
})
test('only route-backed settings sections require deployment capabilities', () => {
assert.equal(SETTINGS_SECTION_CAPABILITY.mcp, 'settings.mcp')
assert.equal(SETTINGS_SECTION_CAPABILITY.storage, 'settings.storage')
assert.equal(SETTINGS_SECTION_CAPABILITY.parser, undefined)
assert.equal(SETTINGS_SECTION_CAPABILITY['runtime-queues'], undefined)
})
test('skill credentials follow the sandbox capability rather than a key of their own', () => {
// The values are injected into a skill script's process, so a deployment with
// no sandbox support has nowhere to put them and the page could only ever show
// its empty state. Task 16 will gate this section with skillSettingsSupported.
assert.equal(SETTINGS_SECTION_CAPABILITY.envvars, 'settings.sandbox')
})
test('the skill catalog follows the sandbox capability', () => {
// Task 16 will gate this section with skillSettingsSupported.
assert.equal(SETTINGS_SECTION_CAPABILITY.skills, 'settings.sandbox')
})
test('sandbox settings section requires the remote sandbox capability', () => {
assert.equal(SETTINGS_SECTION_CAPABILITY.sandbox, 'settings.sandbox.remote')
})
test('host sandbox stays hidden unless the deployment explicitly enables it', () => {
assert.equal(isDeploymentCapabilitySupported({}, 'settings.sandbox.host'), false)
assert.equal(
isDeploymentCapabilitySupported(
{ 'settings.sandbox.host': { supported: false, reason: 'platform_unsupported' } },
'settings.sandbox.host',
),
false,
)
assert.equal(
isDeploymentCapabilitySupported(
{ 'settings.sandbox.host': { supported: true } },
'settings.sandbox.host',
),
true,
)
})
test('docker sandbox stays hidden unless the deployment explicitly enables it', () => {
assert.equal(isDeploymentCapabilitySupported({}, 'settings.sandbox.docker'), false)
assert.equal(
isDeploymentCapabilitySupported(
{ 'settings.sandbox.docker': { supported: false, reason: 'docker_backend_disabled' } },
'settings.sandbox.docker',
),
false,
)
assert.equal(
isDeploymentCapabilitySupported(
{ 'settings.sandbox.docker': { supported: true } },
'settings.sandbox.docker',
),
true,
)
})
test('remote sandbox capability fails closed', () => {
assert.equal(isDeploymentCapabilitySupported({}, 'settings.sandbox.remote'), false)
assert.equal(
isDeploymentCapabilitySupported({ 'settings.sandbox.remote': { supported: true } }, 'settings.sandbox.remote'),
true,
)
})
test('user allocation stays hidden unless the deployment explicitly enables it', () => {
assert.equal(isDeploymentCapabilitySupported({}, 'settings.sandbox.user_allocation'), false)
assert.equal(
isDeploymentCapabilitySupported(
{ 'settings.sandbox.user_allocation': { supported: false, reason: 'deployment_gate_off' } },
'settings.sandbox.user_allocation',
),
false,
)
assert.equal(
isDeploymentCapabilitySupported(
{ 'settings.sandbox.user_allocation': { supported: true } },
'settings.sandbox.user_allocation',
),
true,
)
})
test('skill settings need a remote sandbox or the host sandbox', () => {
assert.equal(skillSettingsSupported({ 'settings.sandbox': { supported: true }, 'settings.sandbox.remote': { supported: true } }), true)
assert.equal(skillSettingsSupported({ 'settings.sandbox': { supported: true }, 'settings.sandbox.host': { supported: true } }), true)
assert.equal(skillSettingsSupported({ 'settings.sandbox': { supported: true } }), false)
assert.equal(skillSettingsSupported({ 'settings.sandbox': { supported: false }, 'settings.sandbox.host': { supported: true } }), false)
})
@@ -0,0 +1,85 @@
export const DEPLOYMENT_CAPABILITY_KEYS = [
'organizations',
'agents',
'integrations.im',
'integrations.embed',
'integrations.api',
'integrations.mcpserver',
'settings.mcp',
'settings.websearch',
'settings.vectorstore',
'settings.storage',
'settings.sandbox',
'settings.sandbox.docker',
'settings.sandbox.host',
'settings.sandbox.remote',
'settings.sandbox.user_allocation',
] as const
export type DeploymentCapabilityKey = typeof DEPLOYMENT_CAPABILITY_KEYS[number]
export interface DeploymentCapability {
supported: boolean
reason?: string
}
export type DeploymentCapabilityMap = Partial<Record<DeploymentCapabilityKey, DeploymentCapability>>
/**
* 能力接口失败或旧版后端没有返回某个键时保持可见,避免一次探测失败把整个菜单清空。
* 只有后端明确返回 supported: false 时才隐藏入口。
*/
export function isDeploymentCapabilitySupported(
capabilities: DeploymentCapabilityMap,
key?: DeploymentCapabilityKey,
options?: { liteMode?: boolean; edition?: string },
): boolean {
if (!key) return true
if (key === 'organizations') {
const isLite =
options?.liteMode === true ||
options?.edition?.trim().toLowerCase() === 'lite'
if (isLite) return false
}
// Docker talks to a local Engine API (often docker.sock = host root), so
// missing or failed capability probes must not leave the picker visible.
// Host sandbox is Lite-desktop-only; keep the same fail-closed gate so a
// missed probe does not show the new-session open-project UI on other deployments.
// Remote sandbox is unavailable on Lite desktop; fail closed like docker/host.
// User allocation is a deployment gate (env opt-in plus Redis). A missed
// probe must not show the switch.
if (
key === 'settings.sandbox.docker'
|| key === 'settings.sandbox.host'
|| key === 'settings.sandbox.remote'
|| key === 'settings.sandbox.user_allocation'
) {
return capabilities[key]?.supported === true
}
return capabilities[key]?.supported !== false
}
export const SETTINGS_SECTION_CAPABILITY: Partial<Record<string, DeploymentCapabilityKey>> = {
websearch: 'settings.websearch',
vectorstore: 'settings.vectorstore',
storage: 'settings.storage',
sandbox: 'settings.sandbox.remote',
// Skills are baked into a sandbox image. Hide the catalog when the
// deployment has no sandbox support, same as personal skill credentials.
skills: 'settings.sandbox',
// Skill credentials exist only because sandboxes do: the values are injected
// into a skill script's process. A deployment without sandbox support has
// nowhere to inject them, so the page would only ever show its empty state.
envvars: 'settings.sandbox',
mcp: 'settings.mcp',
}
/**
* Skills and skill credentials need somewhere to run: a remote sandbox, or
* Lite's host sandbox.
*/
export function skillSettingsSupported(capabilities: DeploymentCapabilityMap): boolean {
if (capabilities['settings.sandbox']?.supported === false) return false
return capabilities['settings.sandbox.remote']?.supported === true
|| capabilities['settings.sandbox.host']?.supported === true
}
+42
View File
@@ -0,0 +1,42 @@
import type { DeploymentCapabilityKey } from './deploymentCapabilities'
export const CHROME_EXTENSION_URL =
'https://chromewebstore.google.com/detail/jpemjbopikggjlmikmclgbmkhhopjdgd?utm_source=item-share-cb'
export const CLAWHUB_SKILL_URL = 'https://clawhub.ai/lyingbug/weknora'
export type IntegrationTab = 'im' | 'embed' | 'api' | 'mcpserver' | 'cli' | 'chrome' | 'claw'
export const INTEGRATION_TABS: IntegrationTab[] = ['im', 'embed', 'api', 'mcpserver', 'cli', 'chrome', 'claw']
/** Aligns with Settings.vue SECTION_MIN_ROLE.api and router.go g.Owner() on /api-principal-config. */
export type IntegrationTabRole = 'viewer' | 'contributor' | 'admin' | 'owner'
export const INTEGRATION_TAB_MIN_ROLE: Partial<Record<IntegrationTab, IntegrationTabRole>> = {
api: 'owner',
}
export const INTEGRATION_TAB_CAPABILITY: Partial<Record<IntegrationTab, DeploymentCapabilityKey>> = {
im: 'integrations.im',
embed: 'integrations.embed',
api: 'integrations.api',
mcpserver: 'integrations.mcpserver',
}
export type IntegrationPreviewIcon =
| { type: 'icon'; name: string }
| { type: 'emoji'; value: string }
/** Sidebar hover preview + Integrations modal nav — add new entries here. */
export const INTEGRATION_PREVIEW_ITEMS: Array<{
key: IntegrationTab
icon: IntegrationPreviewIcon
}> = [
{ key: 'im', icon: { type: 'icon', name: 'chat-message' } },
{ key: 'embed', icon: { type: 'icon', name: 'code' } },
{ key: 'api', icon: { type: 'icon', name: 'secured' } },
{ key: 'mcpserver', icon: { type: 'icon', name: 'tools' } },
{ key: 'cli', icon: { type: 'icon', name: 'code' } },
{ key: 'chrome', icon: { type: 'icon', name: 'extension' } },
{ key: 'claw', icon: { type: 'emoji', value: '🦞' } },
]
@@ -0,0 +1,39 @@
import assert from 'node:assert/strict'
import test from 'node:test'
import {
SETTINGS_MANAGEMENT_SHORTCUT_MIN_ROLE,
SETTINGS_SECTION_MIN_ROLE,
SYSTEM_ADMIN_SETTINGS_SECTIONS,
} from './settingsAccess'
test('management shortcuts are stricter than read-only settings pages', () => {
assert.equal(SETTINGS_SECTION_MIN_ROLE.members, 'viewer')
assert.equal(SETTINGS_MANAGEMENT_SHORTCUT_MIN_ROLE.members, 'owner')
assert.equal(SETTINGS_SECTION_MIN_ROLE.models, 'viewer')
assert.equal(SETTINGS_MANAGEMENT_SHORTCUT_MIN_ROLE.models, 'admin')
})
test('the skill catalog is admin-only like the sandbox it installs into', () => {
assert.equal(SETTINGS_SECTION_MIN_ROLE.skills, 'admin')
assert.equal(SETTINGS_SECTION_MIN_ROLE.skills, SETTINGS_SECTION_MIN_ROLE.sandbox)
// Skills live in the sidebar toolbox, so the avatar menu has no shortcut.
assert.equal(Object.prototype.hasOwnProperty.call(SETTINGS_MANAGEMENT_SHORTCUT_MIN_ROLE, 'skills'), false)
})
test('personal skill environment variables are visible to every member', () => {
assert.equal(SETTINGS_SECTION_MIN_ROLE.envvars, 'viewer')
// Workspace-wide skill env values live on the Admin+ skills page; a
// management shortcut on the avatar menu would only duplicate that entrance.
assert.equal(
Object.prototype.hasOwnProperty.call(SETTINGS_MANAGEMENT_SHORTCUT_MIN_ROLE, 'envvars'),
false,
)
})
test('system administration settings stay explicitly system-admin-only', () => {
assert.deepEqual(
[...SYSTEM_ADMIN_SETTINGS_SECTIONS],
['system-global', 'model-catalog', 'runtime-queues', 'platform-api-keys', 'system-audit-log'],
)
})
+54
View File
@@ -0,0 +1,54 @@
export type SettingsRoleKey = 'viewer' | 'contributor' | 'admin' | 'owner'
/**
* Workspace-scoped settings access policy.
*
* Keep this as the single frontend source of truth for both the complete
* Settings navigation and any shortcuts that lead into it. Backend route
* guards remain authoritative.
*/
export const SETTINGS_SECTION_MIN_ROLE: Record<string, SettingsRoleKey> = {
general: 'viewer',
ollama: 'admin',
weknoracloud: 'admin',
models: 'viewer',
websearch: 'admin',
chathistory: 'admin',
vectorstore: 'admin',
parser: 'admin',
storage: 'admin',
sandbox: 'admin',
// Install writes a root shell into the sandbox image every session of
// that config boots. Same Admin+ bar as the sandbox editor itself.
skills: 'admin',
mcp: 'admin',
system: 'viewer',
userprofile: 'viewer',
browserconnection: 'viewer',
tenant: 'viewer',
members: 'viewer',
mymemory: 'viewer',
memory: 'admin',
// Everyone sets their own preferences; the workspace part is Admin+ inside.
assistant: 'viewer',
// Every member fills in their own environment variables; the workspace-wide
// values stay on the Admin+ skills page.
envvars: 'viewer',
}
/**
* A management-labelled avatar shortcut has a stricter threshold than the
* corresponding read-only Settings page.
*/
export const SETTINGS_MANAGEMENT_SHORTCUT_MIN_ROLE = {
members: 'owner',
models: 'admin',
} as const satisfies Record<string, SettingsRoleKey>
export const SYSTEM_ADMIN_SETTINGS_SECTIONS = new Set([
'system-global',
'model-catalog',
'runtime-queues',
'platform-api-keys',
'system-audit-log',
])
+98
View File
@@ -0,0 +1,98 @@
import assert from 'node:assert/strict'
import test from 'node:test'
import {
buildSettingsRouteQuery,
integrationSectionKey,
isIntegrationSection,
normalizeSettingsSection,
settingsQueryUnchanged,
} from './settingsRoute'
test('settings nav writes section, and keeps a system-settings panel only there', () => {
assert.deepEqual(
buildSettingsRouteQuery('models', {
section: 'system-global',
tab: 'im',
agentId: 'agt_1',
}),
{ section: 'models' },
)
assert.deepEqual(
buildSettingsRouteQuery('general', { section: 'system-global' }),
{ section: 'general' },
)
assert.deepEqual(
buildSettingsRouteQuery('runtime-queues', { section: 'system-global' }),
{ section: 'runtime-queues' },
)
assert.deepEqual(
buildSettingsRouteQuery('system-global', { section: 'system-global', panel: 'users', tab: 'im' }),
{ section: 'system-global', panel: 'users' },
)
assert.deepEqual(
buildSettingsRouteQuery('models', { section: 'system-global', panel: 'users' }),
{ section: 'models' },
)
assert.deepEqual(
buildSettingsRouteQuery('system-global', { section: 'system-global', panel: 'billing' }),
{ section: 'system-global' },
)
assert.deepEqual(
buildSettingsRouteQuery(integrationSectionKey('claw'), {
section: 'integrations',
tab: 'im',
}),
{ section: 'integration-claw' },
)
assert.deepEqual(
buildSettingsRouteQuery(integrationSectionKey('api'), {
section: 'integrations',
tab: 'im',
agentId: 'agt_1',
}),
{ section: 'integration-api', agentId: 'agt_1' },
)
})
test('legacy api / integrations / bare-tab query strings normalize to nav keys', () => {
assert.equal(normalizeSettingsSection('api'), 'integration-api')
assert.equal(normalizeSettingsSection('claw'), 'integration-claw')
assert.equal(normalizeSettingsSection('cli'), 'integration-cli')
assert.equal(normalizeSettingsSection('mcpserver'), 'integration-mcpserver')
// 'mcp' is the MCP-client settings page, not the MCP server integration tab.
assert.equal(normalizeSettingsSection('mcp'), 'mcp')
assert.equal(normalizeSettingsSection('integrations', 'cli'), 'integration-cli')
assert.equal(normalizeSettingsSection('integrations', 'embed'), 'integration-embed')
assert.equal(normalizeSettingsSection('integrations'), 'integration-im')
assert.equal(normalizeSettingsSection('integration-chrome'), 'integration-chrome')
assert.equal(normalizeSettingsSection('system-global'), 'system-global')
assert.equal(isIntegrationSection('integration-chrome'), true)
assert.equal(isIntegrationSection('integration-cli'), true)
assert.equal(isIntegrationSection('models'), false)
assert.equal(isIntegrationSection('integration-unknown'), false)
})
test('canonical settings query skips a redundant replace', () => {
assert.equal(
settingsQueryUnchanged(
{ section: 'integration-claw' },
{ section: 'integration-claw' },
),
true,
)
assert.equal(
settingsQueryUnchanged(
{ section: 'integrations', tab: 'claw' },
{ section: 'integration-claw' },
),
false,
)
assert.equal(
settingsQueryUnchanged(
{ section: 'system-global', panel: 'users' },
{ section: 'system-global', panel: 'access' },
),
false,
)
})
+84
View File
@@ -0,0 +1,84 @@
import { INTEGRATION_TABS, type IntegrationTab } from './integrations'
export const INTEGRATION_SECTION_PREFIX = 'integration-'
type QueryValue = string | number | null | undefined | Array<string | number | null>
export type SettingsRouteQuery = Record<string, QueryValue>
export function integrationSectionKey(tab: IntegrationTab): string {
return `${INTEGRATION_SECTION_PREFIX}${tab}`
}
export function integrationTabFromSection(section: string): IntegrationTab {
const raw = section.startsWith(INTEGRATION_SECTION_PREFIX)
? section.slice(INTEGRATION_SECTION_PREFIX.length)
: section
if (INTEGRATION_TABS.includes(raw as IntegrationTab)) {
return raw as IntegrationTab
}
return 'im'
}
export function isIntegrationSection(section: string): boolean {
if (!section.startsWith(INTEGRATION_SECTION_PREFIX)) return false
const raw = section.slice(INTEGRATION_SECTION_PREFIX.length)
return (INTEGRATION_TABS as readonly string[]).includes(raw)
}
const SYSTEM_SETTINGS_PANELS = new Set(['access', 'users', 'tenant', 'runtime', 'security', 'other'])
function isBareIntegrationTab(section: string): section is IntegrationTab {
return (INTEGRATION_TABS as readonly string[]).includes(section)
}
/**
* Map URL `section` (and a leftover `tab` from old bookmarks) onto the
* settings nav key. Canonical form is `integration-<tab>`; `integrations`,
* `api`, and bare tab names remain aliases.
*/
export function normalizeSettingsSection(section: string, tab?: string | null): string {
if (section === 'integrations') {
return integrationSectionKey(integrationTabFromSection(tab || 'im'))
}
if (isBareIntegrationTab(section)) {
return integrationSectionKey(section)
}
return section
}
/**
* Settings left-nav → URL. Every page, including integrations, is
* `?section=<navKey>` (e.g. `integration-claw`). `tab` is dropped.
* `panel` is the tab inside system settings and stays only on that page.
*/
export function buildSettingsRouteQuery(
sectionKey: string,
currentQuery: object = {},
): SettingsRouteQuery {
const query: SettingsRouteQuery = { ...(currentQuery as SettingsRouteQuery) }
delete query.tab
if (!isIntegrationSection(sectionKey)) {
delete query.agentId
}
if (sectionKey === 'system-global') {
const raw = Array.isArray(query.panel) ? query.panel[0] : query.panel
if (typeof raw === 'string' && SYSTEM_SETTINGS_PANELS.has(raw)) query.panel = raw
else delete query.panel
} else {
delete query.panel
}
query.section = sectionKey
return query
}
export function settingsQueryUnchanged(
currentQuery: object,
nextQuery: SettingsRouteQuery,
): boolean {
const current = currentQuery as SettingsRouteQuery
return String(current.section ?? '') === String(nextQuery.section ?? '')
&& current.tab == null
&& nextQuery.tab == null
&& String(current.agentId ?? '') === String(nextQuery.agentId ?? '')
&& String(current.panel ?? '') === String(nextQuery.panel ?? '')
}
+100
View File
@@ -0,0 +1,100 @@
import assert from 'node:assert/strict'
import test from 'node:test'
import { readFileSync } from 'node:fs'
import { computed, ref } from 'vue'
import { runInNewContext } from 'node:vm'
import ts from 'typescript'
import { TOOLBOX_ITEMS, canAccessToolboxSection, isToolboxSection, toolboxLocation } from './toolbox'
import zhCN from '../i18n/locales/zh-CN'
const roles = ['viewer', 'contributor', 'admin', 'owner']
const access = (role: string | null, unsupported: string[] = [], superuser = false) => ({
currentTenantRole: role,
canAccessAllTenants: superuser,
hasRole: (min: string) => roles.indexOf(role || '') >= roles.indexOf(min),
isSupported: (capability?: string) => !capability || !unsupported.includes(capability),
})
test('toolbox contains only the agreed tools; infrastructure and secrets stay in settings', () => {
assert.deepEqual(TOOLBOX_ITEMS.map((item) => item.key), ['skills', 'mcp', 'browserconnection'])
const lookup = (key: string) => key.split('.').reduce<any>((node, part) => node?.[part], zhCN)
for (const item of TOOLBOX_ITEMS) {
for (const key of [item.title, item.description, 'help' in item ? item.help : undefined,
'action' in item ? item.action : undefined]) {
if (key) assert.equal(typeof lookup(key), 'string', key)
}
}
for (const key of ['sandbox', 'websearch', 'envvars', 'integration-api', undefined, 'unknown']) {
assert.equal(isToolboxSection(key), false)
}
})
test('toolbox preserves role and deployment gates, including workspace switches', () => {
for (const role of ['viewer', 'contributor']) {
assert.equal(canAccessToolboxSection('skills', access(role)), false)
assert.equal(canAccessToolboxSection('mcp', access(role)), false)
assert.equal(canAccessToolboxSection('browserconnection', access(role)), true)
}
assert.equal(canAccessToolboxSection('skills', access('admin')), true)
assert.equal(canAccessToolboxSection('skills', access('owner', ['settings.sandbox'])), false)
assert.equal(canAccessToolboxSection('mcp', access('owner', ['settings.mcp'])), false)
assert.equal(canAccessToolboxSection('mcp', access(null)), false)
assert.equal(canAccessToolboxSection('mcp', access(null, [], true)), true)
assert.equal(canAccessToolboxSection('mcp', access(null, ['settings.mcp'], true)), false)
const role = ref('admin')
const allowed = computed(() => canAccessToolboxSection('skills', access(role.value)))
assert.equal(allowed.value, true)
role.value = 'viewer'
assert.equal(allowed.value, false)
})
test('skill shortcut retains its target sandbox without leaking it to other tools', () => {
assert.deepEqual(toolboxLocation('skills', 'sandbox-123'), {
path: '/platform/toolbox/skills', query: { sandboxId: 'sandbox-123' },
})
assert.deepEqual(toolboxLocation('browserconnection', 'sandbox-123'), {
path: '/platform/toolbox/browserconnection', query: {},
})
assert.deepEqual(toolboxLocation(), { path: '/platform/toolbox', query: {} })
})
const settings = readFileSync(new URL('../views/settings/Settings.vue', import.meta.url), 'utf8')
const script = settings.match(/<script setup lang="ts">([\s\S]*?)<\/script>/)![1]!
const ast = ts.createSourceFile('Settings.ts', script, ts.ScriptTarget.Latest, true)
function declaration(name: string) {
const node = ast.statements.find((s) => ts.isVariableStatement(s)
&& s.declarationList.declarations.some((d) => ts.isIdentifier(d.name) && d.name.text === name))
assert.ok(node, `${name} exists`)
return ts.transpileModule(node.getText(ast), { compilerOptions: { target: ts.ScriptTarget.ES2022 } }).outputText
}
test('legacy shortcuts close settings and route to the selected tool and sandbox', () => {
const calls: unknown[] = []
const redirect = runInNewContext(`${declaration('redirectToToolbox')}\nredirectToToolbox`, {
isToolboxSection, toolboxLocation,
uiStore: { closeSettings: () => calls.push('close') },
router: { push: (location: unknown) => calls.push(location) },
})
assert.equal(redirect('skills', 'sandbox-123'), true)
assert.deepEqual(calls, ['close', toolboxLocation('skills', 'sandbox-123')])
calls.length = 0
assert.equal(redirect('sandbox'), false)
assert.deepEqual(calls, [])
assert.match(script, /redirectToToolbox\(normalizedSection, uiStore.settingsInitialSubSection\)/)
assert.match(script, /redirectToToolbox\(normalizedSection, subsection\)/)
})
test('settings no longer render moved panels, and old bookmarks reach toolbox', () => {
for (const component of ['SkillSettings', 'McpSettings', 'BrowserConnectionSettings']) {
assert.equal(settings.includes(`<${component}`), false)
}
for (const item of TOOLBOX_ITEMS) {
assert.equal(settings.includes(`{ key: '${item.key}',`), false)
}
const router = readFileSync(new URL('../router/index.ts', import.meta.url), 'utf8')
assert.match(router, /to\.path === '\/platform\/settings' && isToolboxSection\(to\.query\.section\)/)
assert.match(router, /toolboxLocation\(to\.query\.section/)
const page = readFileSync(new URL('../views/toolbox/Toolbox.vue', import.meta.url), 'utf8')
assert.match(page, /if \(!selectedItem\.value && fallback\) void router\.replace\(toolboxLocation\(fallback\.key\)\)/)
assert.match(page, /:key="sandboxId"\s+:initial-sandbox-id="sandboxId"/)
})
+54
View File
@@ -0,0 +1,54 @@
import { SETTINGS_SECTION_MIN_ROLE, type SettingsRoleKey } from './settingsAccess'
import { SETTINGS_SECTION_CAPABILITY, type DeploymentCapabilityKey } from './deploymentCapabilities'
import { SKILL_ICON } from '../types/mention'
export const TOOLBOX_ITEMS = [
{
key: 'skills',
icon: SKILL_ICON,
title: 'settings.skills.title',
description: 'settings.skills.description',
help: 'settings.skills.helpTooltip',
action: 'settings.skills.addSkill',
},
{
key: 'mcp',
icon: 'tools',
title: 'settings.mcpService',
description: 'mcpSettings.description',
action: 'mcpSettings.addService',
},
{
key: 'browserconnection',
title: 'localBrowser.settingsTitle',
description: 'localBrowser.settingsDescription',
},
] as const
export type ToolboxSection = typeof TOOLBOX_ITEMS[number]['key']
export function isToolboxSection(section: unknown): section is ToolboxSection {
return TOOLBOX_ITEMS.some((item) => item.key === section)
}
export function toolboxLocation(section?: ToolboxSection, sandboxId?: string) {
return {
path: section ? `/platform/toolbox/${section}` : '/platform/toolbox',
query: section === 'skills' && sandboxId ? { sandboxId } : {},
}
}
/** Use the same role and deployment gates as the original settings panels. */
export function canAccessToolboxSection(
section: ToolboxSection,
access: {
currentTenantRole: string | null | undefined
canAccessAllTenants: boolean
hasRole: (role: SettingsRoleKey) => boolean
isSupported: (capability?: DeploymentCapabilityKey) => boolean
},
): boolean {
if (!access.currentTenantRole && !access.canAccessAllTenants) return false
return (access.canAccessAllTenants || access.hasRole(SETTINGS_SECTION_MIN_ROLE[section] ?? 'viewer'))
&& access.isSupported(SETTINGS_SECTION_CAPABILITY[section])
}