ui(skills): split the skill catalog out of the sandbox editor

Installing skills was buried as a wizard step. Give it a first-class settings page so admins can browse and install without opening the sandbox drawer, and keep rollout on the runtime step.
main
wizardchen 2026-08-28 10:16:43 +08:00 committed by lyingbug
parent 29b8fa3d9a
commit 721952cea3
15 changed files with 944 additions and 778 deletions

View File

@ -430,24 +430,16 @@
</div>
<div v-else class="env-empty">{{ $t('settings.sandbox.noEnvVars') }}</div>
</section>
</t-form>
<!--
Skills need an image to be installed into, so this step is only reachable
once the config exists. During creation the wizard walks into it right
after the first successful save; the hint covers the one case left, a
config whose save was refused.
-->
<template v-if="currentStepKey === 'skills'">
<SandboxSkillsPanel
v-if="effectiveRecord"
:record="effectiveRecord"
@updated="onSkillsConfigUpdated"
@skills-changed="emit('skillsChanged')"
@in-flight-change="inFlightFromPanel = $event"
/>
<p v-else class="skills-locked">{{ $t('settings.sandbox.stepSkillsLocked') }}</p>
</template>
<section v-if="currentStepKey === 'runtime'" class="setting-drawer__section">
<h4 class="setting-drawer__section-title">{{ $t('settings.sandbox.skillRollout') }}</h4>
<p class="section-help section-help--under-title">{{ $t('settings.sandbox.skillRolloutHint') }}</p>
<t-radio-group v-model="skillRollout" class="skill-rollout-group">
<t-radio value="next_turn">{{ $t('settings.sandbox.skillRolloutNextTurn') }}</t-radio>
<t-radio value="new_session">{{ $t('settings.sandbox.skillRolloutNewSession') }}</t-radio>
</t-radio-group>
</section>
</t-form>
<div
v-if="checkResult && showCheckResult"
@ -486,13 +478,13 @@ import { MessagePlugin } from 'tdesign-vue-next'
import { useI18n } from 'vue-i18n'
import SettingDrawer from '@/components/settings/SettingDrawer.vue'
import SandboxBackendBadge from '@/components/settings/SandboxBackendBadge.vue'
import SandboxSkillsPanel from '@/components/SandboxSkillsPanel.vue'
import {
checkSandboxConfig,
createSandboxConfig,
parseSandboxConflict,
updateSandboxConfigById,
querySandboxTemplates,
listConfigSkills,
type SandboxCheckItem,
type SandboxCheckResult,
type SandboxConfig,
@ -506,22 +498,17 @@ import {
NAMED_SANDBOX_BACKEND_TYPES,
} from '@/api/system'
type SandboxStepKey = 'connection' | 'template' | 'runtime' | 'skills'
type SandboxStepKey = 'connection' | 'template' | 'runtime'
const props = defineProps<{
visible: boolean
record: SandboxConfigRecord | null
presetType?: string
// Which page to land on when opening an existing config, e.g. 'skills' from
// the card's 管理技能 entry. Ignored while creating, where order is enforced.
initialStep?: SandboxStepKey
hasInFlightSkill?: boolean
}>()
const emit = defineEmits<{
(e: 'update:visible', value: boolean): void
(e: 'saved'): void
(e: 'skillsChanged', record?: SandboxConfigRecord): void
}>()
const { t } = useI18n()
@ -566,6 +553,8 @@ const docker = reactive<SandboxDockerConfig>({})
// mean "keep the saved key" instead of "no key configured".
const storedSecrets = reactive({ cube: false, e2b: false })
const envRows = ref<{ key: string; value: string; stored?: boolean }[]>([])
const skillRollout = ref<'next_turn' | 'new_session'>('next_turn')
const inFlightFromSkills = ref(false)
const templates = ref<SandboxTemplate[]>([])
const templatesLoading = ref(false)
const templatesLoaded = ref(false)
@ -593,7 +582,6 @@ const wizardSteps = computed<Array<{ key: SandboxStepKey; title: string }>>(() =
steps.push({ key: 'template', title: t('settings.sandbox.stepTemplate') })
}
steps.push({ key: 'runtime', title: t('settings.sandbox.stepRuntime') })
steps.push({ key: 'skills', title: t('settings.sandbox.stepSkills') })
return steps
})
const currentStepKey = computed<SandboxStepKey>(() => wizardSteps.value[wizardStep.value]?.key || 'connection')
@ -601,14 +589,6 @@ const stepDescription = computed(() => t(`settings.sandbox.stepDescriptions.${cu
const primaryText = computed(() => {
if (currentStepKey.value === 'connection') return t('settings.sandbox.connectAndContinue')
if (currentStepKey.value === 'template') return t('common.next')
// Nothing on the skills step is pending a save — each install, toggle and
// removal already went to the server on its own.
if (currentStepKey.value === 'skills') return t('common.finish')
// Runtime is the last page of settings. If skills follow, keep the wizard
// going after the save; otherwise this press closes the drawer.
if (wizardSteps.value.some((step) => step.key === 'skills')) {
return t('settings.sandbox.saveAndContinue')
}
return t('common.save')
})
// Deep check needs the fields that actually get probed. Docker collects
@ -625,29 +605,21 @@ const primaryDisabled = computed(() => (
))
// savedRecord is the config this drawer is editing, including one it just
// created: after the first save the wizard keeps going into the skills step,
// which needs an ID, and a second press of save must update that config rather
// than create another one.
// created: a second press of save must update that config rather than create
// another one if the admin walks back through the wizard before closing.
const savedRecord = ref<SandboxConfigRecord | null>(null)
const effectiveRecord = computed(() => savedRecord.value || props.record)
const hasSkillSnapshot = computed(() => (
Boolean(effectiveRecord.value?.config?.skill_image?.snapshot_id?.trim())
))
const inFlightFromPanel = ref(false)
const hasInFlightSkill = computed(() => Boolean(props.hasInFlightSkill) || inFlightFromPanel.value)
const hasInFlightSkill = computed(() => inFlightFromSkills.value)
const retargetFrozen = computed(() => hasSkillSnapshot.value || hasInFlightSkill.value)
function onSkillsConfigUpdated(record: SandboxConfigRecord) {
savedRecord.value = record
emit('skillsChanged', record)
}
// Jumping is what separates editing from creating. A config that does not exist
// yet has to be built in order — its connection has to check out before there
// are templates to choose from, and it has no image to install skills into. Once
// it exists, every step is just a page of its settings, so all of them open
// directly; steps already visited stay clickable during creation so the rail
// works as a way back.
// are templates to choose from. Once it exists, every step is just a page of
// its settings, so all of them open directly; steps already visited stay
// clickable during creation so the rail works as a way back.
function canJumpTo(index: number): boolean {
if (index === wizardStep.value) return false
return Boolean(effectiveRecord.value) || index < wizardStep.value
@ -785,6 +757,7 @@ function reset() {
envRows.value = Object.entries(cfg.env_vars || {}).map(([key, value]) => (
isMaskedSecret(value) ? { key, value: '', stored: true } : { key, value }
))
skillRollout.value = cfg.skill_rollout === 'new_session' ? 'new_session' : 'next_turn'
checkResult.value = null
conflict.value = null
nameError.value = ''
@ -793,14 +766,7 @@ function reset() {
templatesLoaded.value = false
templatesError.value = ''
savedRecord.value = null
inFlightFromPanel.value = false
wizardStep.value = 0
// "管理技能" opens this drawer straight on the skills step. It is a jump like
// any other, so it only holds for a config that already exists.
if (props.initialStep && props.record) {
const index = wizardSteps.value.findIndex((step) => step.key === props.initialStep)
if (index >= 0) wizardStep.value = index
}
}
function selectBackend(value: string) {
@ -812,12 +778,29 @@ function selectBackend(value: string) {
onBackendChange()
}
async function refreshInFlightSkill() {
const id = props.record?.id
if (!id) {
inFlightFromSkills.value = false
return
}
try {
const res = await listConfigSkills(id)
inFlightFromSkills.value = (res?.data || []).some(
(skill) => skill.status === 'installing' || skill.status === 'removing',
)
} catch {
inFlightFromSkills.value = false
}
}
watch(() => props.visible, (open) => {
if (open) {
reset()
void refreshInFlightSkill()
} else {
inFlightFromPanel.value = false
stopTemplatePolling()
inFlightFromSkills.value = false
}
})
@ -1056,7 +1039,7 @@ function collectPayload(): SandboxConfig {
default_timeout_sec: defaultTimeoutSec.value || undefined,
allow_private_endpoints: allowPrivateEndpoints.value || undefined,
env_vars: envVars,
skill_rollout: effectiveRecord.value?.config?.skill_rollout,
skill_rollout: skillRollout.value,
}
// Send only the selected backend's block so an unused one cannot fail
// validation (e.g. a stale private URL left in the other tab).
@ -1108,10 +1091,6 @@ async function handlePrimaryAction() {
wizardStep.value += 1
return
}
if (currentStepKey.value === 'skills') {
close()
return
}
await save()
}
@ -1144,11 +1123,6 @@ async function save() {
emit('saved')
const saved = res?.data
if (saved) savedRecord.value = saved
const skillsStep = wizardSteps.value.findIndex((step) => step.key === 'skills')
if (skillsStep >= 0 && savedRecord.value) {
wizardStep.value = skillsStep
return
}
close()
} catch (e: any) {
const refusal = parseSandboxConflict(e)
@ -1324,13 +1298,6 @@ onUnmounted(stopTemplatePolling)
}
}
.skills-locked {
margin: 24px 0;
color: var(--td-text-color-placeholder);
font-size: 13px;
text-align: center;
}
.sandbox-editor-form {
min-width: 0;
max-width: 100%;
@ -1752,6 +1719,13 @@ onUnmounted(stopTemplatePolling)
text-align: center;
}
.skill-rollout-group {
display: flex;
flex-direction: column;
align-items: flex-start;
gap: 8px;
}
.section-help {
margin: 0;
color: var(--td-text-color-placeholder);

File diff suppressed because it is too large Load Diff

View File

@ -135,7 +135,10 @@ async function follow(run: number): Promise<boolean> {
throw new Error(`transcript stream refused: ${response.status}`)
},
onmessage(ev) {
if (run !== openRun || !props.live) return
// Live tail and post-refresh replay share this stream. The old guard
// dropped every frame when the skill was already ready, which is why
// reopening the popup after a refresh showed an empty transcript.
if (run !== openRun) return
if (!ev.data) return
let frame: any
try {
@ -172,11 +175,17 @@ async function open() {
try {
// A finished install already has durable rows. Replaying the event log
// through processStreamChunk would animate every tool call again, which
// is what "view the run" must not do.
// is what "view the run" must not do. If the durable history is empty
// (which happens for maintenance sessions the chat message endpoint
// filters out), fall back to a one-shot transcript replay so the popup
// shows something on a refresh instead of the empty state.
if (!props.live) {
loading.value = true
if (props.sessionId) {
await loadPersisted(run)
if (!stale() && messages.length === 0 && props.messageId) {
await follow(run).catch(() => false)
}
}
return
}

View File

@ -47,3 +47,8 @@ test('skill credentials follow the sandbox capability rather than a key of their
assert.equal(SETTINGS_SECTION_CAPABILITY.envvars, 'settings.sandbox')
assert.equal(SETTINGS_SECTION_CAPABILITY.envvars, SETTINGS_SECTION_CAPABILITY.sandbox)
})
test('the skill catalog follows the sandbox capability', () => {
assert.equal(SETTINGS_SECTION_CAPABILITY.skills, 'settings.sandbox')
assert.equal(SETTINGS_SECTION_CAPABILITY.skills, SETTINGS_SECTION_CAPABILITY.sandbox)
})

View File

@ -44,6 +44,9 @@ export const SETTINGS_SECTION_CAPABILITY: Partial<Record<string, DeploymentCapab
vectorstore: 'settings.vectorstore',
storage: 'settings.storage',
sandbox: 'settings.sandbox',
// 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.

View File

@ -14,11 +14,15 @@ test('management shortcuts are stricter than read-only settings pages', () => {
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)
})
test('personal skill environment variables are visible to every member', () => {
assert.equal(SETTINGS_SECTION_MIN_ROLE.envvars, 'viewer')
// The workspace-wide values live in the sandbox config editor, which is
// already Admin+; a management shortcut on the avatar menu would only
// duplicate that entrance.
// 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,

View File

@ -18,6 +18,9 @@ export const SETTINGS_SECTION_MIN_ROLE: Record<string, SettingsRoleKey> = {
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',
@ -26,7 +29,7 @@ export const SETTINGS_SECTION_MIN_ROLE: Record<string, SettingsRoleKey> = {
mymemory: 'viewer',
memory: 'admin',
// Every member fills in their own environment variables; the workspace-wide
// values stay in the Admin+ sandbox editor.
// values stay on the Admin+ skills page.
envvars: 'viewer',
}

View File

@ -1014,7 +1014,7 @@ export default {
fallbackPrompt: 'Fallback Prompt',
fallbackPromptPlaceholder: 'Leave empty to use default prompt',
skillsConfig: 'Skills',
skillsConfigDesc: 'Choose the sandbox that runs skill scripts, and which skills from that sandbox the agent can use.',
skillsConfigDesc: 'Choose the sandbox that runs skill scripts, then pick which installed skills this agent can use. Install skills on the workspace Skills page.',
skillsSelection: 'Available skills',
skillsSelectionDesc: 'The list comes from skills installed in the selected sandbox.',
skillsAll: 'All',
@ -1025,6 +1025,7 @@ export default {
noSkillsAvailable: 'This sandbox has no skills installed.',
skillsNeedSandbox: 'Select a sandbox first.',
goSandboxSettings: 'Manage sandboxes',
goSkillSettings: 'Install skills',
sandboxBackend: 'Sandbox',
sandboxBackendDefault: 'Disabled',
sandboxBackendHint: 'Skill scripts do not run until a sandbox is selected.',
@ -1061,10 +1062,10 @@ export default {
parserEngine: 'Parser Engine',
storageEngine: 'Storage Engine',
sandbox: {
title: 'Skill Sandbox',
description: 'Manage isolated runtimes for agent skill scripts. Each agent can pick one workspace config.',
pageHintTitle: 'What is a skill sandbox?',
pageHint: 'A skill sandbox is the isolated environment where agent skill scripts run. A workspace can have several configs (Docker, E2B, CubeSandbox); each agent picks one. Scripts stay disabled until a config is selected.',
title: 'Sandbox',
description: 'Configure isolated runtimes for agent skill scripts. Each agent picks one workspace config.',
pageHintTitle: 'What is a sandbox?',
pageHint: 'A sandbox is the isolated environment where agent skill scripts run. A workspace can have several configs (Docker, E2B, CubeSandbox); each agent picks one. Skills are installed on the Skills page into the selected config\'s image. Scripts stay disabled until a config is selected.',
editorDescription: 'Configure a workspace runtime. Docker, CubeSandbox, and E2B use the same management flow.',
stepConnection: 'Connect',
stepTemplate: 'Template',
@ -1075,7 +1076,7 @@ export default {
stepDescriptions: {
connection: 'Configure the backend and verify the connection before loading templates.',
template: 'Choose a ready template returned by the connected cluster.',
runtime: 'Configure execution settings and environment variables, then save.',
runtime: 'Configure execution settings, environment variables, and when skill image updates apply, then save.',
skills: 'Install skills into this config\'s sandbox image. Once the config is saved you can come back any time.',
},
back: 'Back',
@ -1307,6 +1308,10 @@ export default {
skillUploadDrag: 'or drop a file here',
skillUploadHint: 'Install writes the skill onto the current image and takes a new snapshot. This can take several minutes. The current chat turn is not interrupted; open sessions rebuild their sandbox on the next turn, which clears the session workspace scratch.',
skillUploadHintNewSession: 'Install writes the skill onto the current image and takes a new snapshot. This can take several minutes. Already-open sessions keep their current sandbox until they end; only newly started sessions pick up this install.',
skillSourceSection: 'Install from a source',
skillSourceSectionHint: 'Paste a ClawHub, GitHub or SkillHub link, or {\'@\'}owner/slug.',
skillUploadSection: 'Upload a local bundle',
skillUploadSectionHint: 'Drop a zip that contains SKILL.md below, or click to pick a file.',
skillSourcePlaceholder: 'ClawHub: {\'@\'}owner/slug. GitHub/SkillHub: paste the full URL',
skillSourceInstall: 'Install',
skillInstallOr: 'or',
@ -1381,6 +1386,16 @@ export default {
valueTooLong: 'A value cannot exceed {max} bytes.'
},
},
skills: {
title: 'Skills',
description: 'Install into a sandbox image. Agents that use that sandbox can then pick from them.',
helpTooltip: 'Skills are baked into the selected sandbox image and take effect on the next session. Agents that use this sandbox can enable or disable each installed skill.',
goSandboxSettings: 'Configure sandboxes',
noConfigsDesc: 'No sandbox yet. Skills need an image to install into.',
installSkill: 'Install skill',
installDrawerDesc: 'Install into the {name} image. Paste a source or upload a zip.',
loadFailed: 'Failed to load',
},
mcpService: 'MCP Service',
versionInfo: 'Version Info',
taskQueue: 'Task Queues',

View File

@ -4967,10 +4967,10 @@ export default {
parserEngine: '파싱 엔진',
storageEngine: '스토리지 엔진',
sandbox: {
title: '스킬 샌드박스',
description: '에이전트 스킬 스크립트의 격리 실행 환경을 관리합니다. 각 에이전트는 워크스페이스 설정을 하나 선택할 수 있습니다.',
pageHintTitle: '스킬 샌드박스란?',
pageHint: '스킬 샌드박스는 에이전트 스킬 스크립트가 실행되는 격리 환경입니다. 워크스페이스에 Docker, E2B, CubeSandbox 설정을 여러 개 둘 수 있고, 각 에이전트가 하나를 선택합니다. 선택하지 않으면 스크립트는 실행되지 않습니다.',
title: '샌드박스',
description: '에이전트 스킬 스크립트의 격리 실행 환경을 구성합니다. 각 에이전트는 설정을 하나 선택합니다.',
pageHintTitle: '샌드박스란?',
pageHint: '샌드박스는 에이전트 스킬 스크립트가 실행되는 격리 환경입니다. 워크스페이스에 Docker, E2B, CubeSandbox 설정을 여러 개 둘 수 있고, 각 에이전트가 하나를 선택합니다. 스킬은 「스킬」 페이지에서 선택한 설정의 이미지에 설치됩니다. 선택하지 않으면 스크립트는 실행되지 않습니다.',
editorDescription: 'Configure a workspace runtime. Docker, CubeSandbox, and E2B use the same management flow.',
stepConnection: 'Connect',
stepTemplate: 'Template',
@ -4981,7 +4981,7 @@ export default {
stepDescriptions: {
connection: 'Configure the backend and verify the connection before loading templates.',
template: 'Choose a ready template returned by the connected cluster.',
runtime: 'Configure execution settings and environment variables, then save.',
runtime: 'Configure execution settings, environment variables, and when skill image updates apply, then save.',
skills: 'Install skills into this config\'s sandbox image. Once the config is saved you can come back any time.',
},
back: 'Back',
@ -5213,6 +5213,10 @@ export default {
skillUploadDrag: '또는 여기로 드래그',
skillUploadHint: '설치하면 현재 이미지에 스킬을 쓰고 새 스냅샷을 만듭니다. 몇 분이 걸릴 수 있습니다. 현재 대화 턴은 중단되지 않으며, 이미 열린 세션은 다음 턴에서 새 이미지로 샌드박스를 다시 만들고 그때 세션 작업 공간 초안이 지워집니다.',
skillUploadHintNewSession: '설치하면 현재 이미지에 스킬을 쓰고 새 스냅샷을 만듭니다. 몇 분이 걸릴 수 있습니다. 이미 열린 세션은 세션이 끝날 때까지 기존 샌드박스를 유지하며, 이번에 설치한 스킬은 새로 시작한 세션에만 적용됩니다.',
skillSourceSection: '소스에서 설치',
skillSourceSectionHint: 'ClawHub, GitHub 또는 SkillHub 링크, 혹은 {\'@\'}owner/slug를 붙여넣으세요.',
skillUploadSection: '로컬 번들 업로드',
skillUploadSectionHint: 'SKILL.md가 포함된 zip을 아래로 끌어다 놓거나 클릭해서 선택하세요.',
skillSourcePlaceholder: 'ClawHub는 {\'@\'}owner/slug, GitHub/SkillHub는 전체 URL을 붙여넣으세요',
skillSourceInstall: '설치',
skillInstallOr: '또는',
@ -5287,6 +5291,16 @@ export default {
valueTooLong: '값 하나는 {max}바이트를 초과할 수 없습니다.'
},
},
skills: {
title: '스킬',
description: '샌드박스 이미지에 설치합니다. 그 샌드박스를 쓰는 에이전트가 이 스킬을 고를 수 있습니다.',
helpTooltip: '스킬은 선택한 샌드박스 이미지에 구워지며, 다음 세션부터 적용됩니다. 해당 샌드박스를 쓰는 에이전트는 설치된 스킬을 개별로 켜고 끌 수 있습니다.',
goSandboxSettings: '샌드박스 구성',
noConfigsDesc: '샌드박스가 없습니다. 스킬을 설치하려면 먼저 이미지가 필요합니다.',
installSkill: '스킬 설치',
installDrawerDesc: '「{name}」 이미지에 설치합니다. 소스를 붙여넣거나 zip을 업로드하세요.',
loadFailed: '불러오지 못했습니다',
},
mcpService: 'MCP 서비스',
versionInfo: '버전 정보',
taskQueue: '작업 큐',
@ -5680,7 +5694,7 @@ export default {
fallbackPrompt: '폴백 프롬프트',
fallbackPromptPlaceholder: '시스템 기본 프롬프트를 사용하려면 비워 두세요.',
skillsConfig: '스킬',
skillsConfigDesc: '스킬 스크립트가 실행될 샌드박스와, 그 샌드박스에서 사용할 스킬을 지정합니다.',
skillsConfigDesc: '스킬 스크립트가 실행될 샌드박스를 고른 뒤, 그 샌드박스에 설치된 스킬을 지정합니다. 설치는 워크스페이스 설정의 「스킬」 페이지에서 합니다.',
skillsSelection: '사용 가능한 스킬',
skillsSelectionDesc: '목록은 선택한 샌드박스에 설치된 스킬에서 가져옵니다.',
skillsAll: '전체',
@ -5691,6 +5705,7 @@ export default {
noSkillsAvailable: '이 샌드박스에 설치된 스킬이 없습니다.',
skillsNeedSandbox: '먼저 실행 샌드박스를 선택하세요.',
goSandboxSettings: '샌드박스 관리',
goSkillSettings: '스킬 설치',
sandboxBackend: '실행 샌드박스',
sandboxBackendDefault: '사용 안 함',
sandboxBackendHint: '선택하지 않으면 스킬 스크립트가 실행되지 않습니다.',

View File

@ -4967,10 +4967,10 @@ export default {
parserEngine: 'Движок парсинга',
storageEngine: 'Движок хранения',
sandbox: {
title: 'Песочница навыков',
description: 'Управление изолированными средами для скриптов навыков агента. Каждый агент может выбрать одну конфигурацию пространства.',
pageHintTitle: 'Что такое песочница навыков?',
pageHint: 'Песочница навыков — изолированная среда, в которой выполняются скрипты навыков агента. В пространстве можно создать несколько конфигураций (Docker, E2B, CubeSandbox); каждый агент выбирает одну. Пока конфигурация не выбрана, скрипты не выполняются.',
title: 'Песочница',
description: 'Настройка изолированных сред для скриптов навыков. Каждый агент выбирает одну конфигурацию.',
pageHintTitle: 'Что такое песочница?',
pageHint: 'Песочница — изолированная среда, в которой выполняются скрипты навыков агента. В пространстве можно создать несколько конфигураций (Docker, E2B, CubeSandbox); каждый агент выбирает одну. Навыки устанавливаются на странице «Навыки» в образ выбранной конфигурации. Пока конфигурация не выбрана, скрипты не выполняются.',
editorDescription: 'Configure a workspace runtime. Docker, CubeSandbox, and E2B use the same management flow.',
stepConnection: 'Connect',
stepTemplate: 'Template',
@ -4981,7 +4981,7 @@ export default {
stepDescriptions: {
connection: 'Configure the backend and verify the connection before loading templates.',
template: 'Choose a ready template returned by the connected cluster.',
runtime: 'Configure execution settings and environment variables, then save.',
runtime: 'Configure execution settings, environment variables, and when skill image updates apply, then save.',
skills: 'Install skills into this config\'s sandbox image. Once the config is saved you can come back any time.',
},
back: 'Back',
@ -5213,6 +5213,10 @@ export default {
skillUploadDrag: 'или перетащите файл сюда',
skillUploadHint: 'Установка записывает навык в текущий образ и создаёт новый снимок. Это может занять несколько минут. Текущий ход диалога не прерывается; открытые сессии пересоздадут песочницу при следующем сообщении, и тогда черновики рабочей области сессии будут очищены.',
skillUploadHintNewSession: 'Установка записывает навык в текущий образ и создаёт новый снимок. Это может занять несколько минут. Уже открытые сессии продолжают использовать текущую песочницу до своего завершения; этот навык появится только у новых сессий.',
skillSourceSection: 'Установить из источника',
skillSourceSectionHint: 'Вставьте ссылку ClawHub, GitHub или SkillHub, либо {\'@\'}owner/slug.',
skillUploadSection: 'Загрузить локальный пакет',
skillUploadSectionHint: 'Перетащите zip с файлом SKILL.md ниже или нажмите, чтобы выбрать файл.',
skillSourcePlaceholder: 'ClawHub: {\'@\'}owner/slug. GitHub/SkillHub: вставьте полный URL',
skillSourceInstall: 'Установить',
skillInstallOr: 'или',
@ -5287,6 +5291,16 @@ export default {
valueTooLong: 'Значение не может превышать {max} байт.'
},
},
skills: {
title: 'Навыки',
description: 'Установка в образ песочницы. Агенты, использующие эту песочницу, могут выбирать эти навыки.',
helpTooltip: 'Навыки запекаются в образ выбранной песочницы и применяются со следующей сессии. Агенты, использующие эту песочницу, могут включать и отключать установленные навыки по одному.',
goSandboxSettings: 'Настроить песочницы',
noConfigsDesc: 'Песочницы ещё нет. Для установки навыков нужен образ.',
installSkill: 'Установить навык',
installDrawerDesc: 'Установка в образ «{name}». Вставьте источник или загрузите zip.',
loadFailed: 'Не удалось загрузить',
},
mcpService: 'Сервис MCP',
versionInfo: 'Информация о версии',
taskQueue: 'Очереди задач',
@ -5680,7 +5694,7 @@ export default {
fallbackPrompt: 'Fallback Prompt',
fallbackPromptPlaceholder: 'Leave empty to use default prompt',
skillsConfig: 'Навыки',
skillsConfigDesc: 'Выберите песочницу для скриптов навыков и навыки, доступные агенту в этой песочнице.',
skillsConfigDesc: 'Выберите песочницу для скриптов навыков, затем укажите, какие установленные навыки доступны агенту. Установка выполняется на странице «Навыки» в настройках пространства.',
skillsSelection: 'Доступные навыки',
skillsSelectionDesc: 'Список берётся из навыков, установленных в выбранной песочнице.',
skillsAll: 'Все',
@ -5691,6 +5705,7 @@ export default {
noSkillsAvailable: 'В этой песочнице нет установленных навыков.',
skillsNeedSandbox: 'Сначала выберите песочницу.',
goSandboxSettings: 'Управление песочницами',
goSkillSettings: 'Установить навыки',
sandboxBackend: 'Песочница',
sandboxBackendDefault: 'Не использовать',
sandboxBackendHint: 'Без выбора скрипты навыков не запускаются.',

View File

@ -4969,10 +4969,10 @@ export default {
parserEngine: '解析引擎',
storageEngine: '存储引擎',
sandbox: {
title: '技能沙箱',
description: '管理智能体技能脚本的隔离运行环境,每个智能体可以选择一份空间配置。',
pageHintTitle: '什么是技能沙箱?',
pageHint: '技能沙箱是智能体执行技能脚本的隔离环境。一个空间可以添加多份配置(Docker、E2B、CubeSandbox),每个智能体选择一份;未选择时不会执行技能脚本。',
title: '沙箱',
description: '配置智能体运行技能脚本的隔离环境。每个智能体选择一份配置。',
pageHintTitle: '什么是沙箱?',
pageHint: '沙箱是智能体执行技能脚本的隔离环境。一个空间可以添加多份配置(Docker、E2B、CubeSandbox),每个智能体选择一份。技能安装在「技能」页,写入所选配置的镜像;未选择沙箱时不会执行技能脚本。',
editorDescription: '配置空间运行环境,Docker、CubeSandbox 和 E2B 使用同一套管理流程。',
stepConnection: '连接',
stepTemplate: '模板',
@ -4983,7 +4983,7 @@ export default {
stepDescriptions: {
connection: '先配置后端并验证连接,通过后再从集群加载模板。',
template: '选择当前集群返回且已经就绪的运行模板。',
runtime: '配置执行参数和环境变量,然后保存。',
runtime: '配置执行参数、环境变量,以及技能镜像如何生效,然后保存。',
skills: '把技能装进这份配置的沙箱镜像;配置已保存后可随时回来增删。',
},
back: '上一步',
@ -5215,6 +5215,10 @@ export default {
skillUploadDrag: '或将文件拖到此处',
skillUploadHint: '安装会在当前镜像上生成新快照,可能需要数分钟。当前这一轮对话不会中断;下一轮提问时才会按新镜像重建沙箱,会话工作区草稿会在那时清空。',
skillUploadHintNewSession: '安装会在当前镜像上生成新快照,可能需要数分钟。已打开的会话继续使用原沙箱,直到该会话结束;只有新打开的会话才会带上这次安装的技能。',
skillSourceSection: '从来源安装',
skillSourceSectionHint: '粘贴 ClawHub、GitHub 或 SkillHub 链接,或 {\'@\'}owner/slug。',
skillUploadSection: '上传本地压缩包',
skillUploadSectionHint: '把包含 SKILL.md 的 zip 拖到下方,或点击选择文件。',
skillSourcePlaceholder: 'ClawHub 用 {\'@\'}owner/slug,GitHub / SkillHub 请粘贴完整链接',
skillSourceInstall: '安装',
skillInstallOr: '或',
@ -5289,6 +5293,16 @@ export default {
valueTooLong: '单个值不能超过 {max} 字节。'
},
},
skills: {
title: '技能',
description: '安装到沙箱镜像。使用该沙箱的智能体都可以选用。',
helpTooltip: '技能会安装到所选沙箱的镜像中,下一次会话启动时生效。使用该沙箱的智能体可以按需启用或停用已装技能。',
goSandboxSettings: '去配置沙箱',
noConfigsDesc: '还没有沙箱,技能需要先有一份可写入的镜像。',
installSkill: '安装技能',
installDrawerDesc: '安装到「{name}」的镜像。粘贴来源或上传 zip。',
loadFailed: '加载失败',
},
mcpService: 'MCP服务',
versionInfo: '版本信息',
taskQueue: '任务队列',
@ -5682,7 +5696,7 @@ export default {
fallbackPrompt: '兜底提示词',
fallbackPromptPlaceholder: '留空使用系统默认提示词',
skillsConfig: '技能',
skillsConfigDesc: '指定技能脚本的运行沙箱,以及该沙箱中可供使用的技能。',
skillsConfigDesc: '先选择运行沙箱,再从该沙箱已安装的技能中选用。安装在空间设置的「技能」页完成。',
skillsSelection: '可用技能',
skillsSelectionDesc: '列表来自所选沙箱已安装的技能。',
skillsAll: '全部',
@ -5693,6 +5707,7 @@ export default {
noSkillsAvailable: '该沙箱尚未安装技能。',
skillsNeedSandbox: '请先选择运行沙箱。',
goSandboxSettings: '管理沙箱',
goSkillSettings: '安装技能',
sandboxBackend: '运行沙箱',
sandboxBackendDefault: '不启用',
sandboxBackendHint: '未选择时不会执行技能脚本。',

View File

@ -1298,6 +1298,14 @@
@click.prevent="uiStore.openSettings('sandbox')">
{{ $t('agent.editor.goSandboxSettings') }}
</a>
<a
v-if="hasSandboxSelected && canInstallSkills"
href="javascript:void(0)"
class="go-settings-link"
@click.prevent="openSkillSettings"
>
{{ $t('agent.editor.goSkillSettings') }}
</a>
<p v-if="sandboxConfigOptions.length === 0" class="desc empty-hint">
{{ $t('agent.editor.sandboxNoConfigs') }}
</p>
@ -1319,7 +1327,15 @@
{{ $t('agent.editor.skillsNeedSandbox') }}
</p>
<p v-else-if="hasSandboxSelected && skillOptions.length === 0" class="desc empty-hint">
{{ $t('agent.editor.noSkillsAvailable') }}
<span>{{ $t('agent.editor.noSkillsAvailable') }}</span>
<a
v-if="canInstallSkills"
href="javascript:void(0)"
class="go-settings-link"
@click.prevent="openSkillSettings"
>
{{ $t('agent.editor.goSkillSettings') }}
</a>
</p>
</div>
</div>
@ -1943,6 +1959,12 @@ const skillOptions = ref<{ name: string; description: string }[]>([]);
// 是否允许启用 Skills(当前沙箱配置上有可执行技能时为 true;未选配置前为 false)
const skillsAvailable = ref(false);
const hasSandboxSelected = computed(() => !!formData.value.config.sandbox_config_id);
const canInstallSkills = computed(() => authStore.hasRole('admin'));
function openSkillSettings() {
const configId = formData.value.config.sandbox_config_id || ''
uiStore.openSettings('skills', configId || undefined)
}
function pruneSelectedSkills() {
const configId = formData.value.config.sandbox_config_id || ''
@ -5733,6 +5755,11 @@ const handleSave = async () => {
.empty-hint {
color: var(--td-text-color-placeholder);
font-style: italic;
.go-settings-link {
display: inline-block;
font-style: normal;
}
}

View File

@ -101,30 +101,6 @@
<div v-if="targetSummary(record)" class="sandbox-card__url" :title="targetSummary(record)">
{{ targetSummary(record) }}
</div>
<div
v-if="supportsSkills(record) && (skillsOf(record) || skillsFailed(record))"
class="sandbox-card__skills"
>
<template v-if="(skillsOf(record) || []).length">
<t-tag
v-for="skill in visibleSkills(record)"
:key="skill.id"
size="small"
variant="light"
:theme="skillTagTheme(skill)"
:title="skill.name"
>{{ skill.name }}</t-tag>
<span v-if="extraSkillCount(record)" class="sandbox-card__skills-more">
{{ $t('settings.sandbox.cardSkillsMore', { count: extraSkillCount(record) }) }}
</span>
</template>
<span v-else-if="skillsFailed(record)" class="sandbox-card__skills-empty">
{{ $t('settings.sandbox.skillLoadFailed') }}
</span>
<span v-else class="sandbox-card__skills-empty">
{{ $t('settings.sandbox.cardSkillsNone') }}
</span>
</div>
<ul v-if="cardWarnings[record.id]?.length" class="sandbox-card__warnings">
<li v-for="item in cardWarnings[record.id]" :key="item.key">
<t-icon name="error-circle" size="12px" />
@ -144,9 +120,8 @@
</t-loading>
<SandboxConfigEditorDrawer v-model:visible="showEditor" :record="editingRecord"
:preset-type="activeType === 'all' ? '' : activeType" :initial-step="editorStep"
:has-in-flight-skill="editorHasInFlightSkill"
@saved="load" @skills-changed="onSkillsChanged" />
:preset-type="activeType === 'all' ? '' : activeType"
@saved="load" />
<!--
Same SettingDrawer chrome as the skill editor. The list is chat sessions
@ -232,12 +207,10 @@ import {
deleteSandboxConfig,
getSandboxConfigInventory,
isNamedSandboxBackend,
listConfigSkills,
listSandboxConfigs,
NAMED_SANDBOX_BACKEND_TYPES,
parseSandboxConflict,
setSandboxWorkspacePolicy,
type ConfigSkill,
type SandboxConfigRecord,
type SandboxInventory,
} from '@/api/system'
@ -255,18 +228,9 @@ const policySaving = ref(false)
const workspaceScriptsDisabled = ref(false)
const records = ref<SandboxConfigRecord[]>([])
const activeType = ref<string>('all')
// Skill names on cube/e2b cards. Missing until the per-config list returns, so
// the empty hint does not flash on first paint. A failed fetch is tracked
// separately so it is not shown as "no skills installed".
const skillsByConfig = ref<Record<string, ConfigSkill[]>>({})
const skillsLoadFailed = ref<Record<string, boolean>>({})
const SKILL_TAG_LIMIT = 3
const showEditor = ref(false)
const editingRecord = ref<SandboxConfigRecord | null>(null)
// Which page of the editor to open on. Skills live there as the last step, so
// clicking a cube/e2b/docker card lands on that page.
const editorStep = ref<'skills' | undefined>(undefined)
const showInventory = ref(false)
const inventoryLoading = ref(false)
@ -281,44 +245,6 @@ const backendLabel = (value: string) => t(`settings.sandbox.backends.${value}`)
const isLegacyRecord = (record: SandboxConfigRecord) => !isNamedSandboxBackend(record.sandbox_type)
// Skills are baked into the snapshot image. Legacy configs (removed backends)
// have no skills step, so their cards stay a connection summary.
function supportsSkills(record: SandboxConfigRecord) {
return record.sandbox_type === 'cube' || record.sandbox_type === 'e2b' || record.sandbox_type === 'docker'
}
function skillsOf(record: SandboxConfigRecord): ConfigSkill[] | undefined {
return skillsByConfig.value[record.id]
}
function skillsFailed(record: SandboxConfigRecord): boolean {
return skillsLoadFailed.value[record.id] === true
}
function visibleSkills(record: SandboxConfigRecord): ConfigSkill[] {
return (skillsOf(record) || []).slice(0, SKILL_TAG_LIMIT)
}
function extraSkillCount(record: SandboxConfigRecord): number {
return Math.max(0, (skillsOf(record) || []).length - SKILL_TAG_LIMIT)
}
function skillTagTheme(skill: ConfigSkill): 'default' | 'warning' | 'primary' {
if (skill.status === 'failed') return 'warning'
if (skill.status === 'installing' || skill.status === 'removing') return 'primary'
return 'default'
}
function skillInFlight(skill: ConfigSkill): boolean {
return skill.status === 'installing' || skill.status === 'removing'
}
const editorHasInFlightSkill = computed(() => {
const id = editingRecord.value?.id
if (!id) return false
return (skillsByConfig.value[id] || []).some(skillInFlight)
})
const filteredRecords = computed(() => {
const base = activeType.value === 'all'
? records.value
@ -331,8 +257,7 @@ const countByType = (type: string) =>
type CardMenuOption = { content: string; value: string; theme?: 'error' }
// Card click already opens skills, and the editor has the connection check,
// so the menu stays edit / running instances / delete.
// Card click opens the connection editor. Skills live on their own settings page.
const cardMenu = (record: SandboxConfigRecord): CardMenuOption[] => {
if (isLegacyRecord(record)) {
return [{ content: t('common.delete'), value: 'delete', theme: 'error' }]
@ -426,31 +351,16 @@ async function onDeleteConfirmOpen(visible: boolean, record: SandboxConfigRecord
function openCreate() {
editingRecord.value = null
editorStep.value = undefined
showEditor.value = true
}
function openEdit(record: SandboxConfigRecord) {
if (isLegacyRecord(record)) return
editingRecord.value = record
editorStep.value = undefined
showEditor.value = true
}
function openSkills(record: SandboxConfigRecord) {
if (isLegacyRecord(record) || !supportsSkills(record)) return
editingRecord.value = record
editorStep.value = 'skills'
showEditor.value = true
}
// Cube/E2B/Docker cards lead with installed skills, so a click lands on that
// step. Connection and runtime stay behind the card menu's edit action.
function openCard(record: SandboxConfigRecord) {
if (supportsSkills(record)) {
openSkills(record)
return
}
openEdit(record)
}
@ -510,28 +420,6 @@ function buildCardWarnings(record: SandboxConfigRecord): CardWarning[] {
return warnings
}
async function loadSkills(configs: SandboxConfigRecord[]) {
const remotes = configs.filter(supportsSkills)
const remoteIDs = new Set(remotes.map((record) => record.id))
const next: Record<string, ConfigSkill[]> = {}
for (const [id, skills] of Object.entries(skillsByConfig.value)) {
if (remoteIDs.has(id)) next[id] = skills
}
const failed: Record<string, boolean> = {}
await Promise.all(remotes.map(async (record) => {
try {
const res = await listConfigSkills(record.id)
next[record.id] = (res?.data || []).filter((skill) => skill.status !== 'removed')
} catch {
// Keep a previous successful list. Only the first-load miss is an error
// row; replacing it with [] would read as "no skills installed".
if (next[record.id] === undefined) failed[record.id] = true
}
}))
skillsByConfig.value = next
skillsLoadFailed.value = failed
}
async function load() {
loading.value = true
try {
@ -543,14 +431,6 @@ async function load() {
} finally {
loading.value = false
}
await loadSkills(records.value)
}
async function onSkillsChanged(record?: SandboxConfigRecord) {
if (record?.id) {
records.value = records.value.map((item) => (item.id === record.id ? { ...item, ...record } : item))
}
await loadSkills(records.value)
}
async function setScriptsDisabled(disabled: boolean) {
@ -988,33 +868,6 @@ onMounted(load)
min-width: 0;
}
.sandbox-card__skills {
display: flex;
flex-wrap: wrap;
align-items: center;
gap: 4px;
margin-top: 2px;
min-width: 0;
:deep(.t-tag) {
max-width: 100%;
overflow: hidden;
text-overflow: ellipsis;
}
}
.sandbox-card__skills-empty,
.sandbox-card__skills-more {
color: var(--td-text-color-placeholder);
font-size: 12px;
line-height: 1.4;
}
.sandbox-card__skills-empty:hover,
.sandbox-card__skills:hover .sandbox-card__skills-more {
color: var(--td-brand-color);
}
.sandbox-card__warnings {
display: flex;
flex-wrap: wrap;

View File

@ -44,7 +44,7 @@
<path d="M4.5 5.5L6.5 12.5L9 7.5L11.5 12.5L13.5 5.5" stroke="currentColor" stroke-width="1.3"
stroke-linecap="round" stroke-linejoin="round" fill="none" />
</svg>
<!-- 技能沙箱:隔离运行窗口,避免和 Ollama / 系统设置共用 server -->
<!-- 沙箱:隔离运行窗口,避免和 Ollama / 系统设置共用 server -->
<svg v-else-if="item.key === 'sandbox'" width="17" height="17" viewBox="0 0 18 18" fill="none"
xmlns="http://www.w3.org/2000/svg" class="nav-icon">
<rect x="2.5" y="3" width="13" height="12" rx="2" stroke="currentColor" stroke-width="1.2"
@ -153,11 +153,16 @@
<StorageEngineSettings />
</div>
<!-- 技能沙箱 -->
<!-- 沙箱 -->
<div v-if="currentSection === 'sandbox'" class="section">
<SandboxSettings />
</div>
<!-- 技能目录:安装到所选沙箱镜像,智能体只从中选用 -->
<div v-if="currentSection === 'skills'" class="section">
<SkillSettings :initial-sandbox-id="currentSubSection" />
</div>
<!-- 系统信息 -->
<div v-if="currentSection === 'system'" class="section">
<SystemInfo />
@ -241,6 +246,7 @@ import VectorStoreSettings from './VectorStoreSettings.vue'
import ParserEngineSettings from './ParserEngineSettings.vue'
import StorageEngineSettings from './StorageBackendSettings.vue'
import SandboxSettings from './SandboxSettings.vue'
import SkillSettings from './SkillSettings.vue'
import WeKnoraCloudSettings from './WeKnoraCloudSettings.vue'
import TenantMembers from './TenantMembers.vue'
import SystemSettings from '@/views/system/SystemSettings.vue'
@ -258,6 +264,7 @@ import {
SYSTEM_ADMIN_SETTINGS_SECTIONS,
} from '@/config/settingsAccess'
import { SETTINGS_SECTION_CAPABILITY } from '@/config/deploymentCapabilities'
import { SKILL_ICON } from '@/types/mention'
import {
buildSettingsRouteQuery,
integrationSectionKey,
@ -296,7 +303,7 @@ type NavGroup = {
// internal/router/router.go 的守卫矩阵对齐。
// 以「页面里至少有 1 个有意义的写操作所要求的最低角色」为基准,把基础设
// 施配置(models 写、ollama 下载、websearch 写、parser/storage/vector/mcp
// CRUD、chat-history 配置)统一收到 admin;只读类(general / system info /
// CRUD、sandbox 连接、skills 安装、chat-history 配置)统一收到 admin;只读类(general / system info /
// tenant-info / members 名册)保留 viewer 可见;最高敏感的 reset api
// key 是 owner-only。改这张表前请在 router.go 里复核对应路由组。
//
@ -371,6 +378,7 @@ const navItems = computed(() => {
{ 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: 'skills', icon: SKILL_ICON, label: t('settings.skills.title') },
{ key: 'mcp', icon: 'tools', label: t('settings.mcpService') },
{ key: 'system', icon: 'info-circle', label: t('settings.versionInfo') },
{ key: 'system-global', icon: 'server', label: t('settings.system') },
@ -435,6 +443,7 @@ const navGroups = computed<NavGroup[]>(() => {
'parser',
'storage',
'sandbox',
'skills',
'websearch',
'mcp',
]),
@ -536,12 +545,22 @@ watch(() => uiStore.settingsInitialSection, (section) => {
}
}, 300)
}
} else if (normalizedSection === 'skills') {
// Sandbox config id from the agent editor / sandbox cards. Skills has
// no nav children, so this is the only way to preselect the target image.
currentSubSection.value = uiStore.settingsInitialSubSection || ''
} else {
currentSubSection.value = ''
}
}
}, { immediate: true })
watch(() => uiStore.settingsInitialSubSection, (sub) => {
if (uiStore.settingsInitialSection === 'skills' && visible.value) {
currentSubSection.value = sub || ''
}
})
watch(
() => [visible.value, route.path, route.query.section, deploymentCapabilities.loaded] as const,
([isVisible, path, section, capabilitiesLoaded]) => {
@ -563,7 +582,9 @@ watch(
return
}
currentSection.value = normalizedSection
currentSubSection.value = ''
currentSubSection.value = normalizedSection === 'skills'
? (uiStore.settingsInitialSubSection || '')
: ''
syncSettingsRoute(normalizedSection)
},
{ immediate: true },

View File

@ -0,0 +1,311 @@
<template>
<div class="skill-settings">
<div class="section-header">
<div class="section-header__title-row">
<h2>{{ $t('settings.skills.title') }}</h2>
<t-tooltip
:content="$t('settings.skills.helpTooltip')"
placement="right"
overlay-class-name="skill-settings__help-tooltip"
>
<t-icon
name="help-circle"
class="section-header__help"
:aria-label="$t('settings.skills.helpTooltip')"
/>
</t-tooltip>
</div>
<p class="section-description">{{ $t('settings.skills.description') }}</p>
</div>
<div v-if="loading" class="loading-container">
<t-loading :text="$t('common.loading')" />
</div>
<div v-else-if="skillConfigs.length === 0" class="empty-state">
<t-empty :description="$t('settings.skills.noConfigsDesc')" />
<t-button theme="primary" variant="outline" @click="uiStore.openSettings('sandbox')">
{{ $t('settings.skills.goSandboxSettings') }}
</t-button>
</div>
<template v-else>
<div v-if="skillConfigs.length > 1" class="sandbox-switcher" role="tablist">
<button
v-for="cfg in skillConfigs"
:key="cfg.id"
type="button"
role="tab"
class="sandbox-switcher__item"
:class="{ 'is-active': cfg.id === selectedId }"
:aria-selected="cfg.id === selectedId"
@click="selectedId = cfg.id"
>
<SandboxBackendBadge :type="cfg.sandbox_type" size="sm" class="sandbox-switcher__badge" />
<span class="sandbox-switcher__name" :title="cfg.name">{{ cfg.name }}</span>
</button>
</div>
<SandboxSkillsPanel
v-if="selectedRecord"
ref="listPanel"
:record="selectedRecord"
mode="list"
@updated="onPanelUpdated"
@install="openInstall"
/>
</template>
<SettingDrawer
v-model:visible="showInstall"
:title="$t('settings.skills.installSkill')"
:description="installDrawerDesc"
:icon="SKILL_ICON"
width="680px"
:min-width="560"
:max-width="920"
storage-key="setting-drawer:width:skill-catalog"
:hide-footer="true"
>
<SandboxSkillsPanel
v-if="showInstall && selectedRecord"
:record="selectedRecord"
mode="install"
@updated="onPanelUpdated"
@skills-changed="reloadList"
@installed="onInstalled"
/>
</SettingDrawer>
</div>
</template>
<script setup lang="ts">
import { computed, nextTick, onMounted, ref, watch } from 'vue'
import { MessagePlugin } from 'tdesign-vue-next'
import { useI18n } from 'vue-i18n'
import SandboxSkillsPanel from '@/components/SandboxSkillsPanel.vue'
import SandboxBackendBadge from '@/components/settings/SandboxBackendBadge.vue'
import SettingDrawer from '@/components/settings/SettingDrawer.vue'
import { SKILL_ICON } from '@/types/mention'
import { useUIStore } from '@/stores/ui'
import {
isNamedSandboxBackend,
listSandboxConfigs,
type SandboxConfigRecord,
} from '@/api/system'
const props = defineProps<{
initialSandboxId?: string
}>()
const { t } = useI18n()
const uiStore = useUIStore()
const loading = ref(false)
const records = ref<SandboxConfigRecord[]>([])
const selectedId = ref('')
const showInstall = ref(false)
const listPanel = ref<{
reload: () => Promise<unknown>
revealSkill: (skillId: string) => void
} | null>(null)
const skillConfigs = computed(() =>
records.value.filter((record) => isNamedSandboxBackend(record.sandbox_type)),
)
const selectedRecord = computed(() =>
skillConfigs.value.find((record) => record.id === selectedId.value) || null,
)
const installDrawerDesc = computed(() => {
const record = selectedRecord.value
if (!record) return ''
return t('settings.skills.installDrawerDesc', { name: record.name })
})
function applyPreferredSelection() {
const preferred = (props.initialSandboxId || '').trim()
if (preferred && skillConfigs.value.some((record) => record.id === preferred)) {
selectedId.value = preferred
return
}
if (selectedId.value && skillConfigs.value.some((record) => record.id === selectedId.value)) return
selectedId.value = skillConfigs.value[0]?.id || ''
}
function openInstall() {
if (!selectedRecord.value) return
showInstall.value = true
}
function onPanelUpdated(record: SandboxConfigRecord) {
records.value = records.value.map((item) => (item.id === record.id ? { ...item, ...record } : item))
}
function reloadList() {
void listPanel.value?.reload()
}
// Server accepted the install; jump back to the list so the just-added card
// is where progress and errors show up. Reload before closing the drawer so
// the row exists when revealSkill tries to scroll to it, and skip the
// showInstall watcher's own reload for this transition.
async function onInstalled(skillId: string) {
await listPanel.value?.reload()
showInstall.value = false
if (skillId) {
await nextTick()
listPanel.value?.revealSkill(skillId)
}
}
async function load() {
loading.value = true
try {
const res = await listSandboxConfigs()
records.value = res?.data || []
applyPreferredSelection()
} catch (e: any) {
MessagePlugin.error(e?.message || t('settings.skills.loadFailed'))
} finally {
loading.value = false
}
}
watch(() => props.initialSandboxId, () => {
applyPreferredSelection()
})
watch(selectedId, () => {
if (loading.value) return
showInstall.value = false
})
watch(showInstall, (open) => {
if (!open) reloadList()
})
onMounted(load)
</script>
<style lang="less" scoped>
.skill-settings {
width: 100%;
}
.section-header {
margin-bottom: 28px;
&__title-row {
display: flex;
align-items: center;
gap: 8px;
margin-bottom: 8px;
}
h2 {
font-size: 20px;
font-weight: 600;
color: var(--td-text-color-primary);
margin: 0;
}
&__help {
color: var(--td-text-color-placeholder);
font-size: 16px;
cursor: help;
transition: color 0.15s ease;
&:hover {
color: var(--td-text-color-secondary);
}
}
.section-description {
font-size: 14px;
color: var(--td-text-color-secondary);
margin: 0;
line-height: 1.6;
}
}
:global(.skill-settings__help-tooltip .t-popup__content) {
max-width: 340px;
line-height: 1.55;
}
.loading-container {
padding: 40px 0;
text-align: center;
}
.empty-state {
padding: 80px 0;
text-align: center;
:deep(.t-empty__description) {
font-size: 14px;
color: var(--td-text-color-placeholder);
margin-bottom: 16px;
}
}
.sandbox-switcher {
display: inline-flex;
align-items: center;
gap: 4px;
max-width: 100%;
margin-bottom: 16px;
overflow-x: auto;
scrollbar-width: none;
&::-webkit-scrollbar {
display: none;
}
}
.sandbox-switcher__item {
flex: 0 0 auto;
display: inline-flex;
align-items: center;
gap: 6px;
max-width: 220px;
padding: 4px 10px 4px 4px;
background: transparent;
border: 1px solid transparent;
border-radius: 999px;
cursor: pointer;
font: inherit;
color: var(--td-text-color-secondary);
text-align: left;
transition: background 0.15s ease, border-color 0.15s ease, color 0.15s ease;
&:hover:not(.is-active) {
color: var(--td-text-color-primary);
background: var(--td-bg-color-container-hover);
}
&.is-active {
background: var(--td-bg-color-secondarycontainer);
color: var(--td-text-color-primary);
}
}
.sandbox-switcher__badge {
transform: scale(0.82);
transform-origin: center;
}
.sandbox-switcher__name {
font-size: 13px;
font-weight: 500;
line-height: 1.2;
color: inherit;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
</style>