Open-source LLM knowledge platform: turn raw documents into a queryable RAG, an autonomous reasoning agent, and a self-maintaining Wiki.
Go agentagenticaichatbotdsh-pluginembeddingsevaluationgenerative-aigolangknowledge-basellmmulti-tenantollamaopenaiquestion-answeringragrerankingsemantic-searchvector-searchwiki
feat(skills): store skills in a tenant catalog and install per sandbox
wizardchencd3f8b4a9a88
diff --git a/frontend/src/api/skill/index.ts b/frontend/src/api/skill/index.tsindex e08421d93..03fb76435 100644--- a/frontend/src/api/skill/index.ts+++ b/frontend/src/api/skill/index.ts@@ -1,4 +1,5 @@-import { get } from "../../utils/request";+import { del, get, post, postUpload } from "../../utils/request";+import type { ConfigSkillFileContent, ConfigSkillFileEntry } from "../system";// Skill信息export interface SkillInfo {@@ -6,6 +7,35 @@ export interface SkillInfo {description: string;}+export interface SkillCatalogInstall {+ skill_id: string;+ sandbox_config_id: string;+ sandbox_config_name?: string;+ sandbox_type?: string;+ status: string;+ enabled: boolean;+ error?: string;+ updated_at: string;+}++export interface SkillCatalogItem {+ id: string;+ name: string;+ version?: string;+ description?: string;+ bundle_sha256?: string;+ created_at: string;+ updated_at: string;+ installations: SkillCatalogInstall[];+}++export interface SkillCatalogRegisterResult {+ id: string;+ name: string;+ version?: string;+ description?: string;+}+// 获取当前沙箱配置上可执行的 Skills;未传 sandboxConfigId 或// skills_available 为 false 时,前端应隐藏/禁用 Skills 配置export function listSkills(sandboxConfigId?: string) {@@ -13,3 +43,45 @@ export function listSkills(sandboxConfigId?: string) {params: sandboxConfigId ? { sandbox_config_id: sandboxConfigId } : {},});}++export function listSkillCatalog() {+ return get<{ data: SkillCatalogItem[] }>('/api/v1/skills/catalog');+}++export function registerSkillCatalogFromSource(source: string) {+ return post<{ data: SkillCatalogRegisterResult }>('/api/v1/skills/catalog', { source }, {+ timeout: 2 * 60 * 1000,+ });+}++export function registerSkillCatalogFromFile(+ file: File,+ onProgress?: (percent: number) => void,+) {+ const form = new FormData();+ form.append('file', file);+ return postUpload('/api/v1/skills/catalog', form, (e: any) => {+ if (e.total) onProgress?.(Math.round((e.loaded * 100) / e.total));+ }, { timeout: 5 * 60 * 1000 }) as Promise<{ data: SkillCatalogRegisterResult }>;+}++export function installSkillCatalog(catalogId: string, sandboxConfigIds: string[]) {+ return post<{ data: { installs: Record<string, string> } }>(+ `/api/v1/skills/catalog/${catalogId}/install`,+ { sandbox_config_ids: sandboxConfigIds },+ );+}++export function deleteSkillCatalog(catalogId: string) {+ return del(`/api/v1/skills/catalog/${catalogId}`);+}++export function listCatalogSkillFiles(catalogId: string) {+ return get<{ data: ConfigSkillFileEntry[] }>(`/api/v1/skills/catalog/${catalogId}/files`);+}++export function getCatalogSkillFile(catalogId: string, path: string) {+ return get<{ data: ConfigSkillFileContent }>(`/api/v1/skills/catalog/${catalogId}/files/content`, {+ params: { path },+ });+}diff --git a/frontend/src/components/SandboxSkillsPanel.test.mjs b/frontend/src/components/SandboxSkillsPanel.test.mjsnew file mode 100644index 000000000..68b819a17--- /dev/null+++ b/frontend/src/components/SandboxSkillsPanel.test.mjs@@ -0,0 +1,20 @@+import assert from 'node:assert/strict'+import { readFileSync } from 'node:fs'+import test from 'node:test'++const source = readFileSync(new URL('./SandboxSkillsPanel.vue', import.meta.url), 'utf8')+const manageBlock = source.slice(+ source.indexOf('mode === \'list\' && focusSkillId'),+ source.indexOf('v-else-if="mode === \'list\'"'),+)++test('focused skill management expands env vars and transcript without a mid-page save button', () => {+ assert.match(manageBlock, /skillHasDeclaredEnvs\(managedSkill\)/)+ assert.match(manageBlock, /onEnvFieldBlur/)+ assert.match(manageBlock, /SkillInstallTimeline/)+ assert.match(manageBlock, /settings\.skills\.manageUninstall/)+ assert.match(manageBlock, /skill-manage__progress/)+ assert.match(manageBlock, /v-if="!isBusy\(managedSkill\)"/)+ assert.doesNotMatch(manageBlock, /skill-manage__footer/)+ assert.doesNotMatch(manageBlock, /settings\.sandbox\.skillEnv\.save/)+})diff --git a/frontend/src/components/SandboxSkillsPanel.vue b/frontend/src/components/SandboxSkillsPanel.vueindex f16ad8f8a..5b61b15c7 100644--- a/frontend/src/components/SandboxSkillsPanel.vue+++ b/frontend/src/components/SandboxSkillsPanel.vue@@ -1,5 +1,8 @@<template>- <div class="sandbox-skills-panel" :class="{ 'sandbox-skills-panel--list': mode === 'list' }">+ <div class="sandbox-skills-panel" :class="{+ 'sandbox-skills-panel--list': mode === 'list',+ 'sandbox-skills-panel--focused': mode === 'list' && !!focusSkillId,+ }"><t-loading :loading="mode === 'list' && loading" size="small"><section v-if="mode === 'install'" class="setting-drawer__section"><h4 class="setting-drawer__section-title">{{ $t('settings.sandbox.skillInstallerModel') }}</h4>@@ -72,16 +75,163 @@<p class="upload-hint">{{ uploadHint }}</p></section>- <section v-if="mode === 'list'" class="skill-list-section">+ <section v-if="mode === 'list' && focusSkillId" class="skill-manage">+ <template v-if="managedSkill">+ <div class="skill-manage__row">+ <div class="skill-manage__info">+ <label>{{ $t('settings.skills.manageEnable') }}</label>+ <p>{{ $t('settings.sandbox.skillDisableHint') }}</p>+ </div>+ <div class="skill-manage__controls">+ <t-switch+ :value="managedSkill.enabled"+ :disabled="isBusy(managedSkill)"+ :loading="togglingId === managedSkill.id"+ @change="(v: any) => toggleEnabled(managedSkill, Boolean(v))"+ />+ <t-tooltip+ v-if="managedSkill.status === 'failed'"+ :content="$t('settings.sandbox.skillRetryHint')"+ placement="top"+ >+ <button+ type="button"+ class="skill-card__icon-btn"+ :disabled="retryingId === managedSkill.id"+ :title="$t('settings.sandbox.skillRetry')"+ :aria-label="$t('settings.sandbox.skillRetry')"+ @click="retrySkill(managedSkill)"+ >+ <t-icon name="refresh" size="16px" />+ </button>+ </t-tooltip>+ <t-popconfirm+ v-if="!isBusy(managedSkill)"+ theme="warning"+ :content="deleteHint"+ :confirm-btn="{ content: $t('settings.skills.manageUninstall'), theme: 'danger' }"+ :cancel-btn="{ content: $t('common.cancel') }"+ placement="top-right"+ @confirm="removeSkill(managedSkill)"+ >+ <button+ type="button"+ class="skill-card__icon-btn skill-card__icon-btn--danger"+ :disabled="deletingId === managedSkill.id"+ :title="$t('settings.skills.manageUninstall')"+ :aria-label="$t('settings.skills.manageUninstall')"+ >+ <t-icon name="delete" size="16px" />+ </button>+ </t-popconfirm>+ </div>+ </div>+ <ul v-if="failedErrorLines(managedSkill).length" class="skill-card__error">+ <li v-for="(line, i) in failedErrorLines(managedSkill)" :key="i">{{ line }}</li>+ </ul>+ <section v-if="skillHasDeclaredEnvs(managedSkill)" class="skill-manage__section">+ <h4>{{ $t('settings.sandbox.skillEnv.toggle') }}</h4>+ <p class="skill-envs__hint">{{ $t('settings.sandbox.skillEnv.workspaceHint') }}</p>+ <div class="skill-envs__rows">+ <div v-for="(env, envIdx) in managedSkill.envs" :key="env.name" class="skill-envs__row">+ <div class="skill-envs__meta">+ <code class="skill-envs__name">{{ env.name }}</code>+ <span v-if="env.required" class="skill-envs__tag skill-envs__tag--required">+ {{ $t('settings.sandbox.skillEnv.required') }}+ </span>+ <span+ class="skill-envs__tag"+ :class="env.is_set ? 'skill-envs__tag--set' : 'skill-envs__tag--unset'"+ >+ {{+ env.is_set+ ? $t('settings.sandbox.skillEnv.isSet')+ : $t('settings.sandbox.skillEnv.notSet')+ }}+ </span>+ <span v-if="env.description" class="skill-envs__desc">{{ env.description }}</span>+ </div>+ <div class="skill-envs__editor">+ <t-input+ :value="envDrafts[managedSkill.id]?.[env.name] ?? ''"+ type="password"+ autocomplete="new-password"+ :name="`wk-se-focus-${envIdx}`"+ :readonly="!isEnvInputUnlocked(managedSkill.id, env.name)"+ spellcheck="false"+ :placeholder="+ env.is_set+ ? $t('settings.sandbox.skillEnv.placeholderSet')+ : $t('settings.sandbox.skillEnv.placeholderUnset')+ "+ @focus="unlockEnvInput(managedSkill.id, env.name)"+ @update:value="(v: string) => setEnvDraft(managedSkill.id, env.name, v)"+ @enter="saveEnvs(managedSkill, true)"+ @blur="onEnvFieldBlur(managedSkill)"+ />+ <t-popconfirm+ v-if="canClearAdminSkillEnv(env)"+ theme="warning"+ attach="body"+ :content="$t('settings.sandbox.skillEnv.clearConfirm', { name: env.name })"+ :confirm-btn="{ content: $t('settings.sandbox.skillEnv.clear'), theme: 'danger' }"+ :cancel-btn="{ content: $t('common.cancel') }"+ @confirm="clearEnv(managedSkill, env.name)"+ >+ <t-button+ theme="danger"+ variant="text"+ size="small"+ :disabled="envSaveInFlight(managedSkill)"+ :loading="envSaveInFlight(managedSkill)"+ >+ {{ $t('settings.sandbox.skillEnv.clear') }}+ </t-button>+ </t-popconfirm>+ </div>+ </div>+ </div>+ </section>+ <section v-if="hasTranscript(managedSkill) || isBusy(managedSkill)" class="skill-manage__section">+ <div class="skill-manage__section-head">+ <h4>{{ $t('settings.sandbox.skillTranscriptTitle') }}</h4>+ <div v-if="isBusy(managedSkill)" class="skill-manage__progress">+ <t-progress+ theme="circle"+ :percentage="progressOf(managedSkill)"+ :size="18"+ :stroke-width="2"+ :label="false"+ />+ <span>{{ progressOf(managedSkill) }}%</span>+ </div>+ </div>+ <SkillInstallTimeline+ :key="`${managedSkill.id}-${managedSkill.install_session_id || ''}-${transcriptEpoch}`"+ compact+ :config-id="record?.id || ''"+ :skill-id="managedSkill.id"+ :session-id="managedSkill.install_session_id || ''"+ :message-id="managedSkill.install_message_id || ''"+ :live="managedSkill.status === 'installing'"+ />+ </section>+ </template>+ </section>++ <section v-else-if="mode === 'list'" class="skill-list-section"><div class="skill-list"><divv-for="skill in visibleSkills":key="skill.id":ref="(el) => bindSkillItem(skill.id, el)"class="skill-card"- :class="{ 'skill-card--focused': focusedSkillId === skill.id }"+ :class="{+ 'skill-card--focused': focusedSkillId === skill.id && !focusSkillId,+ 'skill-card--bare': !!focusSkillId,+ }">- <div class="skill-card__badge" aria-hidden="true">+ <div v-if="!focusSkillId" class="skill-card__badge" aria-hidden="true"><t-progressv-if="isBusy(skill)"theme="circle"@@ -93,8 +243,15 @@<t-icon v-else :name="SKILL_ICON" size="18px" /></div><div class="skill-card__body">- <div class="skill-card__header">- <h3 class="skill-card__title" :title="skill.name || skill.id">+ <div+ class="skill-card__header"+ :class="{ 'skill-card__header--toolbar': !!focusSkillId }"+ >+ <h3+ v-if="!focusSkillId"+ class="skill-card__title"+ :title="skill.name || skill.id"+ >{{ skill.name || skill.id }}</h3><span@@ -316,17 +473,6 @@<t-icon name="chat-bubble-history" size="14px" /></button></t-tooltip>- <t-tooltip :content="$t('settings.sandbox.skillFiles')" placement="top">- <button- type="button"- class="skill-card__icon-btn"- :class="{ 'is-on': filesDrawerVisible && filesSkillId === skill.id }"- :aria-label="$t('settings.sandbox.skillFiles')"- @click="openSkillFiles(skill)"- >- <t-icon name="folder" size="14px" />- </button>- </t-tooltip><t-tooltipv-if="skill.status === 'failed'":content="$t('settings.sandbox.skillRetryHint')"@@ -343,6 +489,7 @@</button></t-tooltip><t-popconfirm+ v-if="!isBusy(skill)"theme="warning":content="deleteHint":confirm-btn="{ content: $t('common.delete'), theme: 'danger' }"@@ -353,7 +500,7 @@<buttontype="button"class="skill-card__icon-btn skill-card__icon-btn--danger"- :disabled="isBusy(skill) || deletingId === skill.id"+ :disabled="deletingId === skill.id":aria-label="$t('common.delete')"><t-icon name="delete" size="14px" />@@ -361,9 +508,9 @@</t-popconfirm></div></div>- <div v-if="skill.version" class="skill-card__type">{{ skill.version }}</div>+ <div v-if="skill.version && !focusSkillId" class="skill-card__type">{{ skill.version }}</div><p- v-if="skill.description"+ v-if="skill.description && !focusSkillId"class="skill-card__desc":title="skill.description">{{ skill.description }}</p>@@ -378,7 +525,7 @@</div></div><button- v-if="mode === 'list'"+ v-if="mode === 'list' && !hideAdd"type="button"class="skill-card skill-card--add"@click="emit('install')"@@ -391,13 +538,6 @@</div></section></t-loading>-- <SkillFilesDrawer- v-model:visible="filesDrawerVisible"- :config-id="record?.id || ''"- :skill-id="filesSkillId"- :skill-name="filesSkillName"- /></div></template>@@ -409,7 +549,6 @@ import { useI18n } from 'vue-i18n'import { fetchEventSource } from '@microsoft/fetch-event-source'import ModelSelector from '@/components/ModelSelector.vue'import SkillInstallTimeline from '@/components/SkillInstallTimeline.vue'-import SkillFilesDrawer from '@/components/SkillFilesDrawer.vue'import { SKILL_ICON } from '@/types/mention'import {getAgentById,@@ -452,8 +591,12 @@ import {const props = withDefaults(defineProps<{record: SandboxConfigRecord | nullmode?: 'install' | 'list'+ hideAdd?: boolean+ focusSkillId?: string}>(), {mode: 'list',+ hideAdd: false,+ focusSkillId: '',})const emit = defineEmits<{@@ -478,9 +621,6 @@ const retryingId = ref('')// Only one install timeline is open at a time: each one holds an SSE// connection, and two runs' worth of agent steps in a drawer is unreadable.const expandedSkillId = ref('')-const filesSkillId = ref('')-const filesSkillName = ref('')-const filesDrawerVisible = ref(false)const transcriptEpoch = ref(0)const focusedSkillId = ref('')const skillItemEls = new Map<string, HTMLElement>()@@ -567,9 +707,19 @@ const visibleSkills = computed(() => {if (props.mode === 'install') {return skills.value.filter(isBusy)}- return skills.value.filter((skill) => skill.status !== 'removed')+ const rows = skills.value.filter((skill) => skill.status !== 'removed')+ if (!props.focusSkillId) return rows+ return rows.filter((skill) => skill.id === props.focusSkillId)})+const managedSkill = computed(() =>+ props.focusSkillId ? (visibleSkills.value[0] || null) : null,+)++watch(managedSkill, (skill) => {+ if (skill && skillHasDeclaredEnvs(skill)) ensureEnvDrafts(skill.id)+}, { immediate: true })+watch(() => skills.value.some(isBusy),(busy) => emit('inFlightChange', busy),@@ -607,7 +757,6 @@ function revealSkill(skillId: string) {function onTranscriptVisible(skill: ConfigSkill, visible: boolean) {if (visible) {- filesDrawerVisible.value = falseexpandedEnvSkillId.value = ''if (expandedSkillId.value !== skill.id) {expandedSkillId.value = skill.id@@ -622,18 +771,6 @@ function onTranscriptVisible(skill: ConfigSkill, visible: boolean) {}}-function openSkillFiles(skill: ConfigSkill) {- expandedSkillId.value = ''- expandedEnvSkillId.value = ''- if (filesDrawerVisible.value && filesSkillId.value === skill.id) {- filesDrawerVisible.value = false- return- }- filesSkillId.value = skill.id- filesSkillName.value = skill.name || skill.id- filesDrawerVisible.value = true-}-function ensureEnvDrafts(skillId: string) {if (!envDrafts[skillId]) envDrafts[skillId] = {}}@@ -662,7 +799,6 @@ function resetEnvInputLocks() {function onEnvVisible(skill: ConfigSkill, visible: boolean, context?: { e?: Event }) {if (visible) {if (!skillHasDeclaredEnvs(skill)) return- filesDrawerVisible.value = falseexpandedSkillId.value = ''if (expandedEnvSkillId.value !== skill.id) {// Reopening starts from a clean slate rather than resurrecting a@@ -704,7 +840,7 @@ function envSaveInFlight(skill: ConfigSkill): boolean {: false}-async function saveEnvs(skill: ConfigSkill) {+async function saveEnvs(skill: ConfigSkill, silent = false) {const envs = envPayload(skill)if (Object.keys(envs).length === 0) returnif (Object.values(envs).some((value) => !isValidEnvValueLength(value))) {@@ -713,7 +849,12 @@ async function saveEnvs(skill: ConfigSkill) {)return}- await submitEnvs(skill, envs, 'settings.sandbox.skillEnv.saveSuccess')+ await submitEnvs(skill, envs, silent ? '' : 'settings.sandbox.skillEnv.saveSuccess')+}++function onEnvFieldBlur(skill: ConfigSkill) {+ if (!hasEnvEdits(skill) || envSaveInFlight(skill)) return+ void saveEnvs(skill, true)}async function clearEnv(skill: ConfigSkill, name: string) {@@ -746,7 +887,7 @@ async function submitEnvs(// Nothing reads a stored value back. Remove only values that are still the// submitted ones; newer typing during the request must survive cleanup.envDrafts[skill.id] = clearSubmittedSkillEnvDrafts(envDrafts[skill.id] || {}, envs)- MessagePlugin.success(t(successKey))+ if (successKey) MessagePlugin.success(t(successKey))} catch (e: any) {if (!isCurrent()) returnMessagePlugin.error(e?.message || t('settings.sandbox.skillEnv.saveFailed'))@@ -912,6 +1053,7 @@ async function loadSkills(silent = false) {if (skillsSignature(skills.value) !== previous) {emit('skillsChanged')}+ if (props.focusSkillId) revealSkill(props.focusSkillId)if (wasBusy && !skills.value.some(isBusy)) {void refreshImage()}@@ -1120,6 +1262,13 @@ watch({ immediate: true },)+watch(+ () => props.focusSkillId,+ (skillId) => {+ if (skillId) revealSkill(skillId)+ },+)+onUnmounted(() => {stopAllFollows()stopPoll()@@ -1132,6 +1281,12 @@ onUnmounted(() => {min-height: 36px;}+.sandbox-skills-panel--focused .skill-list {+ display: flex;+ flex-direction: column;+ gap: 0;+}+.installer-model-hint {margin: 0 0 10px;font-size: 12px;@@ -1288,6 +1443,154 @@ onUnmounted(() => {}}+.sandbox-skills-panel--focused {+ min-height: 0;+}++.skill-manage {+ display: flex;+ flex-direction: column;+ gap: 16px;+}++.skill-manage__row {+ display: flex;+ align-items: flex-start;+ justify-content: space-between;+ gap: 16px;+}++.skill-manage__controls {+ display: flex;+ align-items: center;+ gap: 2px;+ flex-shrink: 0;+}++.skill-manage__info {+ min-width: 0;++ label {+ display: block;+ margin-bottom: 4px;+ font-size: 14px;+ font-weight: 500;+ color: var(--td-text-color-primary);+ }++ p {+ margin: 0;+ font-size: 12px;+ line-height: 1.5;+ color: var(--td-text-color-secondary);+ }+}++.skill-manage__section {+ display: flex;+ flex-direction: column;+ align-items: stretch;+ gap: 10px;+ padding-top: 12px;+ border-top: 1px solid var(--td-component-stroke);++ > .t-button {+ align-self: flex-start;+ }++ h4 {+ margin: 0;+ font-size: 13px;+ font-weight: 600;+ color: var(--td-text-color-primary);+ }++ .skill-manage__section-head {+ display: flex;+ align-items: center;+ justify-content: space-between;+ gap: 12px;+ }++ .skill-manage__progress {+ display: inline-flex;+ align-items: center;+ gap: 6px;+ font-size: 12px;+ font-weight: 500;+ line-height: 1;+ color: var(--td-brand-color);++ :deep(.t-progress--circle svg) {+ display: block;+ }+ }++ .skill-envs__hint {+ margin: 0;+ font-size: 12px;+ line-height: 1.5;+ color: var(--td-text-color-secondary);+ }++ .skill-envs__rows {+ display: flex;+ flex-direction: column;+ gap: 10px;+ }++ .skill-envs__row {+ display: flex;+ flex-direction: column;+ gap: 4px;+ }++ .skill-envs__meta {+ display: flex;+ align-items: center;+ flex-wrap: wrap;+ gap: 6px;+ }++ .skill-envs__name {+ font-family: var(--td-font-family-mono, ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, monospace);+ font-size: 12px;+ color: var(--td-text-color-primary);+ overflow-wrap: anywhere;+ }++ .skill-envs__tag {+ font-size: 12px;+ line-height: 18px;+ padding: 0 8px;+ border-radius: 10px;+ background: var(--td-bg-color-secondarycontainer);+ color: var(--td-text-color-secondary);+ }++ .skill-envs__tag--required {+ background: var(--td-warning-color-light);+ color: var(--td-warning-color);+ }++ .skill-envs__tag--set {+ background: var(--td-success-color-light);+ color: var(--td-success-color);+ }++ .skill-envs__desc {+ font-size: 12px;+ line-height: 1.5;+ color: var(--td-text-color-secondary);+ }++ .skill-envs__editor {+ display: flex;+ align-items: center;+ gap: 8px;+ }+}+.skill-list {margin: 0;padding: 0;@@ -1319,6 +1622,14 @@ onUnmounted(() => {box-shadow: 0 0 0 2px var(--td-brand-color-focus, rgba(0, 168, 112, 0.18));}+ &--bare {+ padding: 0;+ border: none;+ border-radius: 0;+ background: transparent;+ box-shadow: none;+ }+&--add {flex-direction: column;align-items: center;@@ -1396,6 +1707,11 @@ onUnmounted(() => {align-items: center;gap: 6px;min-width: 0;++ &--toolbar {+ justify-content: flex-end;+ width: 100%;+ }}.skill-card__title {diff --git a/frontend/src/components/SkillFilesDrawer.vue b/frontend/src/components/SkillFilesDrawer.vueindex 999f4a170..6f41bc48a 100644--- a/frontend/src/components/SkillFilesDrawer.vue+++ b/frontend/src/components/SkillFilesDrawer.vue@@ -47,9 +47,10 @@</button></header><SkillFilesPanel- v-if="visible && configId && skillId"+ v-if="visible && (catalogId || (configId && skillId))":config-id="configId":skill-id="skillId"+ :catalog-id="catalogId":drawer-width="drawerWidth"/></div>@@ -66,8 +67,9 @@ const MIN_WIDTH = 480const props = defineProps<{visible: boolean- configId: string- skillId: string+ configId?: string+ skillId?: string+ catalogId?: stringskillName: string}>()diff --git a/frontend/src/components/SkillFilesPanel.vue b/frontend/src/components/SkillFilesPanel.vueindex b7ce66ad3..4434f9a7f 100644--- a/frontend/src/components/SkillFilesPanel.vue+++ b/frontend/src/components/SkillFilesPanel.vue@@ -129,6 +129,10 @@ import {createMermaidCodeRenderer,enhanceMarkdownContainer,} from '@/utils/mermaidShared'+import {+ getCatalogSkillFile,+ listCatalogSkillFiles,+} from '@/api/skill'import {getConfigSkillFile,listConfigSkillFiles,@@ -157,8 +161,9 @@ interface FrontmatterField {}const props = defineProps<{- configId: string- skillId: string+ configId?: string+ skillId?: string+ catalogId?: stringdrawerWidth: number}>()@@ -484,7 +489,7 @@ async function enhancePreview() {}async function selectFile(path: string) {- if (!props.configId || !props.skillId) return+ if (!props.catalogId && (!props.configId || !props.skillId)) returnselectedPath.value = pathfileLoading.value = truefileError.value = ''@@ -494,7 +499,9 @@ async function selectFile(path: string) {frontmatterFields.value = []markdownMode.value = 'preview'try {- const res = await getConfigSkillFile(props.configId, props.skillId, path)+ const res = props.catalogId+ ? await getCatalogSkillFile(props.catalogId, path)+ : await getConfigSkillFile(props.configId || '', props.skillId || '', path)const data = res?.datafile.value = data || nullif (!data) {@@ -519,7 +526,7 @@ async function copyContent() {}async function loadFiles() {- if (!props.configId || !props.skillId) return+ if (!props.catalogId && (!props.configId || !props.skillId)) returnlistLoading.value = truelistError.value = ''nodes.value = []@@ -527,7 +534,9 @@ async function loadFiles() {file.value = nullfileError.value = ''try {- const res = await listConfigSkillFiles(props.configId, props.skillId)+ const res = props.catalogId+ ? await listCatalogSkillFiles(props.catalogId)+ : await listConfigSkillFiles(props.configId || '', props.skillId || '')const list = res?.data || []const tree = buildTree(list)nodes.value = tree@@ -544,7 +553,7 @@ async function loadFiles() {}watch(- () => [props.configId, props.skillId],+ () => [props.catalogId, props.configId, props.skillId],() => {void loadFiles()},diff --git a/frontend/src/components/settings/SandboxBackendBadge.vue b/frontend/src/components/settings/SandboxBackendBadge.vueindex 2baa3a5c9..5e247ed0f 100644--- a/frontend/src/components/settings/SandboxBackendBadge.vue+++ b/frontend/src/components/settings/SandboxBackendBadge.vue@@ -13,7 +13,7 @@ import { providerLogo } from '@/views/settings/providerLogos'// Vendors we ship a logo for (Docker) win over the generic TDesign glyphs.const props = withDefaults(defineProps<{type: string- size?: 'sm' | 'md'+ size?: 'xs' | 'sm' | 'md'}>(), { size: 'md' })const logo = computed(() => providerLogo('sandbox', props.type))@@ -59,6 +59,13 @@ const badgeStyle = computed((): Record<string, string> => (font-size: 14px;}+.sandbox-badge--xs {+ width: 16px;+ height: 16px;+ border-radius: 4px;+ font-size: 10px;+}+.sandbox-badge--e2b {background: rgba(98, 53, 187, 0.1);color: #6235bb;@@ -91,4 +98,9 @@ const badgeStyle = computed((): Record<string, string> => (width: 16px;height: 16px;}++.sandbox-badge--xs.sandbox-badge--mono::before {+ width: 10px;+ height: 10px;+}</style>diff --git a/frontend/src/i18n/locales/en-US.ts b/frontend/src/i18n/locales/en-US.tsindex 1d8655fe0..a62b1e0c2 100755--- a/frontend/src/i18n/locales/en-US.ts+++ b/frontend/src/i18n/locales/en-US.ts@@ -1014,18 +1014,26 @@ export default {fallbackPrompt: 'Fallback Prompt',fallbackPromptPlaceholder: 'Leave empty to use default prompt',skillsConfig: 'Skills',- skillsConfigDesc: 'Choose the sandbox that runs skill scripts, then pick which installed skills this agent can use. Install skills on the workspace Skills page.',+ skillsConfigDesc: 'Choose the sandbox that runs skill scripts, then pick from the workspace catalog. Skills not installed on that sandbox are visible but cannot be enabled until they are installed.',skillsSelection: 'Available skills',- skillsSelectionDesc: 'The list comes from skills installed in the selected sandbox.',+ skillsSelectionDesc: 'The list comes from the workspace skill catalog. Only skills that are ready on the selected sandbox can be enabled.',skillsAll: 'All',skillsSelected: 'Selected',skillsNone: 'Disabled',selectSkills: 'Select skills',- selectSkillsDesc: 'Choose which skills to enable.',- noSkillsAvailable: 'This sandbox has no skills installed.',+ selectSkillsDesc: 'Choose which skills to enable. Uninstalled or not-ready skills cannot be checked.',+ skillsAllListHint: 'Ready skills on this sandbox will be enabled. Uninstalled ones are not included until you install them.',+ skillsListSummary: '{ready} ready, {pending} not installed on this sandbox',+ skillsListSummaryReadyOnly: '{ready} ready',+ noSkillsAvailable: 'The workspace catalog has no skills yet.',skillsNeedSandbox: 'Select a sandbox first.',goSandboxSettings: 'Manage sandboxes',- goSkillSettings: 'Install skills',+ goSkillSettings: 'Manage skills',+ installToThisSandbox: 'Install onto this sandbox',+ installShort: 'Install',+ skillNotInstalled: 'Not installed on this sandbox',+ skillNotReady: 'Not ready yet',+ skillDisabledOnSandbox: 'Disabled on this sandbox',sandboxBackend: 'Sandbox',sandboxBackendDefault: 'Disabled',sandboxBackendHint: 'Skill scripts do not run until a sandbox is selected.',@@ -1388,12 +1396,42 @@ export default {},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.',+ description: 'Skills live in the workspace catalog. Register them first, then install onto one or more sandboxes. An agent can only enable skills that are ready on its sandbox.',+ helpTooltip: 'A catalog skill does not have to be installed anywhere. Scripts only run after the skill is installed into the sandbox image the agent uses. Docker, Cube, and E2B images are not interchangeable — install once per sandbox.',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.',+ addSkill: 'Add skill',+ addDrawerDesc: 'Paste a source or upload a zip to add it to the catalog. You can install it onto sandboxes now or later.',+ addProgress: 'Add progress',+ addStepRegister: 'Register',+ addStepInstall: 'Install',+ addStepRegisterDesc: 'Paste a source or upload a zip to add the skill to the workspace catalog.',+ addStepInstallDesc: 'Confirm the parsed skill, then choose which sandboxes to install into. You can skip this and install later from the list.',+ addFinish: 'Done',+ addRegisteredAs: 'Registered as “{name}”',+ addFileSelected: 'Selected {name}',+ addClearFile: 'Clear',+ emptyDesc: 'No skills yet. Add one, then install it onto one or more sandboxes.',+ emptyNoSandboxHint: 'There is no sandbox yet. Scripted skills cannot run until they are installed into an image.',+ installSkill: 'Add skill',+ installDrawerDesc: 'Install into the {name} image.',+ installToSandbox: 'Install onto sandbox',+ installToSandboxDesc: 'Each sandbox backend needs its own install. Docker, Cube, and E2B images are not interchangeable.',+ pickSandboxes: 'Install onto sandboxes',+ pickSandboxesHint: 'The skill is written into the image used by each selected sandbox. Docker, Cube, and E2B images are not interchangeable — install once per sandbox. You can skip this and install later from the catalog.',+ noSandboxToInstall: 'No sandbox is available to install into.',+ noInstalls: 'Not installed on any sandbox',+ installedOn: 'Installed on',+ manageOnSandbox: 'Manage this skill on “{name}”',+ manageDrawerDesc: 'Manage enablement, variables, and uninstall on sandbox “{name}”.',+ manageEnable: 'Enable',+ manageUninstall: 'Uninstall from sandbox',+ deleteCatalog: 'Remove from catalog',+ deleteCatalogConfirm: 'Remove “{name}” from the catalog? Uninstall it from every sandbox first.',+ deleteCatalogBlocked: 'Uninstall this skill from every sandbox first.',+ deleteSuccess: 'Removed from catalog',+ registerAccepted: 'Added to catalog',+ installAccepted: 'Install started',loadFailed: 'Failed to load',},mcpService: 'MCP Service',diff --git a/frontend/src/i18n/locales/ko-KR.ts b/frontend/src/i18n/locales/ko-KR.tsindex 7c884ae68..df02298b9 100755--- a/frontend/src/i18n/locales/ko-KR.ts+++ b/frontend/src/i18n/locales/ko-KR.ts@@ -5293,12 +5293,42 @@ export default {},skills: {title: '스킬',- description: '샌드박스 이미지에 설치합니다. 그 샌드박스를 쓰는 에이전트가 이 스킬을 고를 수 있습니다.',- helpTooltip: '스킬은 선택한 샌드박스 이미지에 구워지며, 다음 세션부터 적용됩니다. 해당 샌드박스를 쓰는 에이전트는 설치된 스킬을 개별로 켜고 끌 수 있습니다.',+ description: '스킬은 워크스페이스 카탈로그에 속합니다. 먼저 등록한 뒤 하나 이상의 샌드박스에 설치할 수 있습니다. 에이전트는 현재 샌드박스에서 준비된 스킬만 사용할 수 있습니다.',+ helpTooltip: '카탈로그 스킬은 아무 샌드박스에도 설치하지 않아도 됩니다. 스크립트를 실행하려면 에이전트가 쓰는 샌드박스 이미지에 설치해야 합니다. Docker, Cube, E2B 이미지는 호환되지 않으므로 샌드박스마다 따로 설치합니다.',goSandboxSettings: '샌드박스 구성',noConfigsDesc: '샌드박스가 없습니다. 스킬을 설치하려면 먼저 이미지가 필요합니다.',- installSkill: '스킬 설치',- installDrawerDesc: '「{name}」 이미지에 설치합니다. 소스를 붙여넣거나 zip을 업로드하세요.',+ addSkill: '스킬 추가',+ addDrawerDesc: '소스를 붙여넣거나 zip을 업로드해 카탈로그에 등록합니다. 지금 샌드박스에 설치할 수도 있습니다.',+ addProgress: '추가 진행',+ addStepRegister: '등록',+ addStepInstall: '설치',+ addStepRegisterDesc: '소스를 붙여넣거나 zip을 업로드해 먼저 워크스페이스 카탈로그에 등록합니다.',+ addStepInstallDesc: '파싱된 스킬을 확인한 뒤 설치할 샌드박스를 선택하세요. 건너뛰고 나중에 목록에서 설치할 수도 있습니다.',+ addFinish: '완료',+ addRegisteredAs: '「{name}」으로 등록됨',+ addFileSelected: '{name} 선택됨',+ addClearFile: '지우기',+ emptyDesc: '아직 스킬이 없습니다. 추가한 뒤 하나 이상의 샌드박스에 설치하세요.',+ emptyNoSandboxHint: '샌드박스가 없습니다. 스크립트 스킬은 이미지에 설치되기 전에는 실행되지 않습니다.',+ installSkill: '스킬 추가',+ installDrawerDesc: '「{name}」 이미지에 설치합니다.',+ installToSandbox: '샌드박스에 설치',+ installToSandboxDesc: '각 샌드박스 백엔드는 따로 설치해야 합니다. Docker, Cube, E2B 이미지는 호환되지 않습니다.',+ pickSandboxes: '설치할 샌드박스',+ pickSandboxesHint: '스킬은 선택한 샌드박스가 사용하는 이미지에 기록됩니다. Docker, Cube, E2B 이미지는 호환되지 않으므로 샌드박스마다 따로 설치합니다. 지금 건너뛰고 나중에 카탈로그에서 설치할 수 있습니다.',+ noSandboxToInstall: '설치할 수 있는 샌드박스가 없습니다.',+ noInstalls: '어떤 샌드박스에도 설치되지 않음',+ installedOn: '설치됨',+ manageOnSandbox: '「{name}」 샌드박스에서 관리',+ manageDrawerDesc: '샌드박스 「{name}」에서 사용 여부, 변수, 제거를 관리합니다.',+ manageEnable: '사용',+ manageUninstall: '샌드박스에서 제거',+ deleteCatalog: '카탈로그에서 삭제',+ deleteCatalogConfirm: '「{name}」을 카탈로그에서 삭제할까요? 모든 샌드박스에서 먼저 제거하세요.',+ deleteCatalogBlocked: '모든 샌드박스에서 이 스킬을 먼저 제거하세요.',+ deleteSuccess: '카탈로그에서 삭제했습니다',+ registerAccepted: '카탈로그에 추가했습니다',+ installAccepted: '설치를 시작했습니다',loadFailed: '불러오지 못했습니다',},mcpService: 'MCP 서비스',@@ -5694,18 +5724,26 @@ export default {fallbackPrompt: '폴백 프롬프트',fallbackPromptPlaceholder: '시스템 기본 프롬프트를 사용하려면 비워 두세요.',skillsConfig: '스킬',- skillsConfigDesc: '스킬 스크립트가 실행될 샌드박스를 고른 뒤, 그 샌드박스에 설치된 스킬을 지정합니다. 설치는 워크스페이스 설정의 「스킬」 페이지에서 합니다.',+ skillsConfigDesc: '스킬 스크립트가 실행될 샌드박스를 고른 뒤, 워크스페이스 카탈로그에서 선택합니다. 해당 샌드박스에 설치되지 않은 스킬은 보이지만 설치 전에는 선택할 수 없습니다.',skillsSelection: '사용 가능한 스킬',- skillsSelectionDesc: '목록은 선택한 샌드박스에 설치된 스킬에서 가져옵니다.',+ skillsSelectionDesc: '목록은 워크스페이스 스킬 카탈로그에서 가져옵니다. 선택한 샌드박스에서 준비된 스킬만 사용할 수 있습니다.',skillsAll: '전체',skillsSelected: '지정',skillsNone: '비활성화',selectSkills: '스킬 선택',- selectSkillsDesc: '사용할 스킬을 선택하세요.',- noSkillsAvailable: '이 샌드박스에 설치된 스킬이 없습니다.',+ selectSkillsDesc: '사용할 스킬을 선택하세요. 설치되지 않았거나 아직 준비되지 않은 스킬은 선택할 수 없습니다.',+ skillsAllListHint: '이 샌드박스에서 준비된 스킬이 사용됩니다. 설치되지 않은 스킬은 설치해야 「전체」에 포함됩니다.',+ skillsListSummary: '준비됨 {ready}개, 이 샌드박스에 미설치 {pending}개',+ skillsListSummaryReadyOnly: '준비됨 {ready}개',+ noSkillsAvailable: '워크스페이스 카탈로그에 스킬이 없습니다.',skillsNeedSandbox: '먼저 실행 샌드박스를 선택하세요.',goSandboxSettings: '샌드박스 관리',- goSkillSettings: '스킬 설치',+ goSkillSettings: '스킬 관리',+ installToThisSandbox: '이 샌드박스에 설치',+ installShort: '설치',+ skillNotInstalled: '현재 샌드박스에 설치되지 않음',+ skillNotReady: '아직 준비되지 않음',+ skillDisabledOnSandbox: '이 샌드박스에서 비활성화됨',sandboxBackend: '실행 샌드박스',sandboxBackendDefault: '사용 안 함',sandboxBackendHint: '선택하지 않으면 스킬 스크립트가 실행되지 않습니다.',diff --git a/frontend/src/i18n/locales/ru-RU.ts b/frontend/src/i18n/locales/ru-RU.tsindex 8bfb53a67..d05986d53 100755--- a/frontend/src/i18n/locales/ru-RU.ts+++ b/frontend/src/i18n/locales/ru-RU.ts@@ -5293,12 +5293,42 @@ export default {},skills: {title: 'Навыки',- description: 'Установка в образ песочницы. Агенты, использующие эту песочницу, могут выбирать эти навыки.',- helpTooltip: 'Навыки запекаются в образ выбранной песочницы и применяются со следующей сессии. Агенты, использующие эту песочницу, могут включать и отключать установленные навыки по одному.',+ description: 'Навыки живут в каталоге пространства. Их можно только зарегистрировать или установить в одну или несколько песочниц. Агент включает только навыки, которые готовы в выбранной песочнице.',+ helpTooltip: 'Навык из каталога можно не устанавливать никуда. Скрипты запускаются только после установки в образ песочницы агента. Образы Docker, Cube и E2B несовместимы — устанавливайте отдельно в каждую песочницу.',goSandboxSettings: 'Настроить песочницы',noConfigsDesc: 'Песочницы ещё нет. Для установки навыков нужен образ.',- installSkill: 'Установить навык',- installDrawerDesc: 'Установка в образ «{name}». Вставьте источник или загрузите zip.',+ addSkill: 'Добавить навык',+ addDrawerDesc: 'Вставьте источник или загрузите zip, чтобы добавить навык в каталог. Можно установить в песочницы сразу.',+ addProgress: 'Ход добавления',+ addStepRegister: 'Регистрация',+ addStepInstall: 'Установка',+ addStepRegisterDesc: 'Вставьте источник или загрузите zip, чтобы сначала добавить навык в каталог пространства.',+ addStepInstallDesc: 'Проверьте разобранный навык, затем выберите песочницы. Можно пропустить и установить позже из списка.',+ addFinish: 'Готово',+ addRegisteredAs: 'Зарегистрирован как «{name}»',+ addFileSelected: 'Выбран {name}',+ addClearFile: 'Очистить',+ emptyDesc: 'Навыков ещё нет. Добавьте навык, затем установите его в одну или несколько песочниц.',+ emptyNoSandboxHint: 'Песочницы нет. Скрипты навыков не запустятся, пока навык не установлен в образ.',+ installSkill: 'Добавить навык',+ installDrawerDesc: 'Установка в образ «{name}».',+ installToSandbox: 'Установить в песочницу',+ installToSandboxDesc: 'Каждый бэкенд песочницы требует отдельной установки. Образы Docker, Cube и E2B несовместимы.',+ pickSandboxes: 'Установить в песочницы',+ pickSandboxesHint: 'Навык записывается в образ выбранной песочницы. Образы Docker, Cube и E2B несовместимы — устанавливайте отдельно в каждую. Можно пропустить и установить позже из каталога.',+ noSandboxToInstall: 'Нет песочницы для установки.',+ noInstalls: 'Не установлен ни в одну песочницу',+ installedOn: 'Установлен в',+ manageOnSandbox: 'Управление в песочнице «{name}»',+ manageDrawerDesc: 'В песочнице «{name}» можно включать навык, править переменные и удалять установку.',+ manageEnable: 'Включить',+ manageUninstall: 'Удалить из песочницы',+ deleteCatalog: 'Удалить из каталога',+ deleteCatalogConfirm: 'Удалить «{name}» из каталога? Сначала снимите установку со всех песочниц.',+ deleteCatalogBlocked: 'Сначала снимите этот навык со всех песочниц.',+ deleteSuccess: 'Удалено из каталога',+ registerAccepted: 'Добавлено в каталог',+ installAccepted: 'Установка начата',loadFailed: 'Не удалось загрузить',},mcpService: 'Сервис MCP',@@ -5694,18 +5724,26 @@ export default {fallbackPrompt: 'Fallback Prompt',fallbackPromptPlaceholder: 'Leave empty to use default prompt',skillsConfig: 'Навыки',- skillsConfigDesc: 'Выберите песочницу для скриптов навыков, затем укажите, какие установленные навыки доступны агенту. Установка выполняется на странице «Навыки» в настройках пространства.',+ skillsConfigDesc: 'Выберите песочницу для скриптов, затем выберите навыки из каталога пространства. Навыки, не установленные в эту песочницу, видны, но их нельзя включить до установки.',skillsSelection: 'Доступные навыки',- skillsSelectionDesc: 'Список берётся из навыков, установленных в выбранной песочнице.',+ skillsSelectionDesc: 'Список берётся из каталога навыков пространства. Включить можно только навыки, готовые в выбранной песочнице.',skillsAll: 'Все',skillsSelected: 'Выбранные',skillsNone: 'Отключено',selectSkills: 'Выбрать навыки',- selectSkillsDesc: 'Отметьте навыки, которые нужно включить.',- noSkillsAvailable: 'В этой песочнице нет установленных навыков.',+ selectSkillsDesc: 'Отметьте навыки, которые нужно включить. Неустановленные или неготовые навыки выбрать нельзя.',+ skillsAllListHint: 'Будут включены готовые навыки в этой песочнице. Неустановленные не попадут в «Все», пока их не установить.',+ skillsListSummary: '{ready} готовы, {pending} не установлены в эту песочницу',+ skillsListSummaryReadyOnly: '{ready} готовы',+ noSkillsAvailable: 'В каталоге пространства ещё нет навыков.',skillsNeedSandbox: 'Сначала выберите песочницу.',goSandboxSettings: 'Управление песочницами',- goSkillSettings: 'Установить навыки',+ goSkillSettings: 'Управление навыками',+ installToThisSandbox: 'Установить в эту песочницу',+ installShort: 'Установить',+ skillNotInstalled: 'Не установлен в текущую песочницу',+ skillNotReady: 'Ещё не готов',+ skillDisabledOnSandbox: 'Отключён в этой песочнице',sandboxBackend: 'Песочница',sandboxBackendDefault: 'Не использовать',sandboxBackendHint: 'Без выбора скрипты навыков не запускаются.',diff --git a/frontend/src/i18n/locales/zh-CN.ts b/frontend/src/i18n/locales/zh-CN.tsindex 780708087..a593a826c 100755--- a/frontend/src/i18n/locales/zh-CN.ts+++ b/frontend/src/i18n/locales/zh-CN.ts@@ -5295,12 +5295,42 @@ export default {},skills: {title: '技能',- description: '安装到沙箱镜像。使用该沙箱的智能体都可以选用。',- helpTooltip: '技能会安装到所选沙箱的镜像中,下一次会话启动时生效。使用该沙箱的智能体可以按需启用或停用已装技能。',+ description: '技能属于空间目录,可以只登记,也可以装到一份或多份沙箱。智能体只能启用当前沙箱里已就绪的技能。',+ helpTooltip: '目录里的技能可以不装任何沙箱。脚本要跑起来,必须装进智能体所用的那份沙箱镜像。Docker、Cube、E2B 互不通用,装到几份就要装几次。',goSandboxSettings: '去配置沙箱',noConfigsDesc: '还没有沙箱,技能需要先有一份可写入的镜像。',- installSkill: '安装技能',- installDrawerDesc: '安装到「{name}」的镜像。粘贴来源或上传 zip。',+ addSkill: '添加技能',+ addDrawerDesc: '粘贴来源或上传 zip,登记到目录。可以选择现在装进哪些沙箱。',+ addProgress: '添加进度',+ addStepRegister: '登记',+ addStepInstall: '安装',+ addStepRegisterDesc: '粘贴来源或上传 zip,先登记到空间目录。',+ addStepInstallDesc: '确认解析结果后,选择要写入的沙箱。也可以跳过,稍后在列表里安装。',+ addFinish: '完成',+ addRegisteredAs: '已登记为「{name}」',+ addFileSelected: '已选择 {name}',+ addClearFile: '清除',+ emptyDesc: '还没有技能。添加后可以装到一份或多份沙箱。',+ emptyNoSandboxHint: '当前没有沙箱。带脚本的技能登记后无法运行,可先去配置沙箱。',+ installSkill: '添加技能',+ installDrawerDesc: '安装到「{name}」的镜像。',+ installToSandbox: '安装到沙箱',+ installToSandboxDesc: '每种沙箱后端要单独安装一次。Docker、Cube、E2B 的镜像互不通用。',+ pickSandboxes: '安装到哪些沙箱',+ pickSandboxesHint: '技能会写入所选沙箱当前使用的镜像。Docker、Cube、E2B 互不通用,勾几份就装几次。现在可以不选,稍后在目录里再装。',+ noSandboxToInstall: '没有可写入的沙箱。',+ noInstalls: '尚未装到任何沙箱',+ installedOn: '已安装到',+ manageOnSandbox: '管理沙箱「{name}」上的安装',+ manageDrawerDesc: '在沙箱「{name}」上管理启用、变量和卸载。',+ manageEnable: '启用',+ manageUninstall: '从沙箱卸载',+ deleteCatalog: '从目录删除',+ deleteCatalogConfirm: '确定从目录删除「{name}」?请先从所有沙箱卸载。',+ deleteCatalogBlocked: '请先从所有沙箱卸载此技能。',+ deleteSuccess: '已从目录删除',+ registerAccepted: '已添加到目录',+ installAccepted: '已开始安装',loadFailed: '加载失败',},mcpService: 'MCP服务',@@ -5696,18 +5726,26 @@ export default {fallbackPrompt: '兜底提示词',fallbackPromptPlaceholder: '留空使用系统默认提示词',skillsConfig: '技能',- skillsConfigDesc: '先选择运行沙箱,再从该沙箱已安装的技能中选用。安装在空间设置的「技能」页完成。',+ skillsConfigDesc: '先选择运行沙箱,再从空间目录中选用。未装到该沙箱的技能可以看见,但要先安装才能勾选。',skillsSelection: '可用技能',- skillsSelectionDesc: '列表来自所选沙箱已安装的技能。',+ skillsSelectionDesc: '列表来自空间技能目录。只能启用当前沙箱上已就绪的技能。',skillsAll: '全部',skillsSelected: '指定',skillsNone: '禁用',selectSkills: '选择技能',- selectSkillsDesc: '勾选要启用的技能。',- noSkillsAvailable: '该沙箱尚未安装技能。',+ selectSkillsDesc: '勾选要启用的技能。未安装或未就绪的不能勾选。',+ skillsAllListHint: '将启用此沙箱上已就绪的技能。未安装的不会自动带上,装好后才会纳入「全部」。',+ skillsListSummary: '{ready} 个已就绪,{pending} 个未安装到此沙箱',+ skillsListSummaryReadyOnly: '{ready} 个已就绪',+ noSkillsAvailable: '空间目录里还没有技能。',skillsNeedSandbox: '请先选择运行沙箱。',goSandboxSettings: '管理沙箱',- goSkillSettings: '安装技能',+ goSkillSettings: '管理技能',+ installToThisSandbox: '安装到此沙箱',+ installShort: '安装',+ skillNotInstalled: '未安装到当前沙箱',+ skillNotReady: '尚未就绪',+ skillDisabledOnSandbox: '已在沙箱中停用',sandboxBackend: '运行沙箱',sandboxBackendDefault: '不启用',sandboxBackendHint: '未选择时不会执行技能脚本。',diff --git a/frontend/src/stores/editorResources.ts b/frontend/src/stores/editorResources.tsindex 82cc55325..5041ff3e8 100644--- a/frontend/src/stores/editorResources.ts+++ b/frontend/src/stores/editorResources.ts@@ -12,7 +12,7 @@ import {type SystemInfo,} from '@/api/system'import { listMCPServices, type MCPService } from '@/api/mcp-service'-import { listSkills, type SkillInfo } from '@/api/skill'+import { listSkillCatalog, listSkills, type SkillCatalogItem, type SkillInfo } from '@/api/skill'import { getAgentTypePresets, getPlaceholders, type AgentTypePreset, type PlaceholdersResponse } from '@/api/agent'import { getTenantRetrievalConfig } from '@/api/retrieval'@@ -43,6 +43,7 @@ type EditorResourceKey =| 'storageEngine'| 'mcpServices'| 'skills'+ | 'skillCatalog'| 'agentTypePresets'| 'promptTemplates'| 'placeholders'@@ -58,6 +59,7 @@ export const useEditorResourcesStore = defineStore('editorResources', () => {const skills = ref<SkillInfo[]>([])const skillsAvailable = ref(false)const skillsConfigId = ref('')+ const skillCatalog = ref<SkillCatalogItem[]>([])const agentTypePresets = ref<AgentTypePreset[]>([])const promptTemplates = ref<PromptTemplatesConfig | null>(null)const placeholders = ref<PlaceholdersResponse | null>(null)@@ -136,6 +138,14 @@ export const useEditorResourcesStore = defineStore('editorResources', () => {})}+ async function ensureSkillCatalog(force = false): Promise<void> {+ return runOnce('skillCatalog', force, async () => {+ const res = await listSkillCatalog()+ skillCatalog.value = Array.isArray(res?.data) ? res.data : []+ loadedAt.value.skillCatalog = Date.now()+ })+ }+async function ensureAgentTypePresets(force = false): Promise<void> {return runOnce('agentTypePresets', force, async () => {const presetsRes: any = await getAgentTypePresets()@@ -206,6 +216,7 @@ export const useEditorResourcesStore = defineStore('editorResources', () => {skills.value = []skillsAvailable.value = falseskillsConfigId.value = ''+ skillCatalog.value = []agentTypePresets.value = []promptTemplates.value = nullplaceholders.value = null@@ -228,6 +239,7 @@ export const useEditorResourcesStore = defineStore('editorResources', () => {mcpServices,skills,skillsAvailable,+ skillCatalog,agentTypePresets,promptTemplates,placeholders,@@ -238,6 +250,7 @@ export const useEditorResourcesStore = defineStore('editorResources', () => {resolveUsableStorageProvider,ensureMcpServices,ensureSkills,+ ensureSkillCatalog,ensureAgentTypePresets,ensurePromptTemplates,ensurePlaceholders,diff --git a/frontend/src/views/agent/AgentEditorModal.test.mjs b/frontend/src/views/agent/AgentEditorModal.test.mjsindex 27b56780d..efe1908fd 100644--- a/frontend/src/views/agent/AgentEditorModal.test.mjs+++ b/frontend/src/views/agent/AgentEditorModal.test.mjs@@ -123,7 +123,25 @@ test('skills and sandbox share one editor section', () => {assert.doesNotMatch(source, /currentSection === 'sandbox' && isAgentMode/)assert.match(source, /sandbox: 'skills'/)assert.match(source, /formData\.config\.sandbox_config_id/)- assert.match(source, /:disabled="!hasSandboxSelected"/)+ assert.match(source, /:disabled="!canEnableSkills"/)assert.match(source, /sandbox-option/)assert.doesNotMatch(source, /skill-info-box/)})++test('agent skill picker uses the catalog and only enables ready installs', () => {+ assert.match(source, /function autoBindSoleSandbox\(/)+ assert.match(source, /canEnableSkills/)+ assert.match(source, /catalogSkillRows/)+ assert.match(source, /showCatalogSkillList/)+ assert.match(source, /skillsSelectionMode\.value !== 'none'/)+ assert.match(source, /:disabled="!skill\.selectable"/)+ assert.match(source, /installCatalogToCurrent/)+ assert.match(source, /agent\.editor\.installToThisSandbox/)+ assert.match(source, /skill-pick-list/)+ assert.match(source, /skill-ready-stat/)+ assert.match(source, /skillsListSummaryReadyOnly/)+ assert.match(source, /selectedSandboxSummary/)+ assert.match(source, /line-clamp: 2/)+ assert.doesNotMatch(source, /skillsSelectionMode === 'selected' && catalogSkillRows/)+ assert.doesNotMatch(source, /skill-list-summary/)+})diff --git a/frontend/src/views/agent/AgentEditorModal.vue b/frontend/src/views/agent/AgentEditorModal.vueindex 35bd524fb..26842053b 100644--- a/frontend/src/views/agent/AgentEditorModal.vue+++ b/frontend/src/views/agent/AgentEditorModal.vue@@ -1289,23 +1289,31 @@:label="cfg.name"><div class="sandbox-option">- <span class="sandbox-option__name">{{ cfg.name }}</span>- <span v-if="cfg.sandbox_type" class="sandbox-option__type">{{ backendLabel(cfg.sandbox_type) }}</span>+ <div class="sandbox-option__row">+ <span class="sandbox-option__name">{{ cfg.name }}</span>+ <span v-if="cfg.sandbox_type" class="sandbox-option__type">{{ backendLabel(cfg.sandbox_type) }}</span>+ </div>+ <div v-if="sandboxTargetLine(cfg)" class="sandbox-option__target">{{ sandboxTargetLine(cfg) }}</div></div></t-option></t-select>- <a href="javascript:void(0)" class="go-settings-link"- @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="selectedSandboxSummary" class="sandbox-selected-meta">{{ selectedSandboxSummary }}</p>+ <div class="sandbox-select-links">+ <a href="javascript:void(0)" class="go-settings-link"+ @click.prevent="uiStore.openSettings('sandbox')">+ {{ $t('agent.editor.goSandboxSettings') }}+ </a>+ <template v-if="hasSandboxSelected && canInstallSkills">+ <span class="sandbox-select-links__sep" aria-hidden="true">·</span>+ <a+ href="javascript:void(0)"+ class="go-settings-link"+ @click.prevent="openSkillSettings"+ >+ {{ $t('agent.editor.goSkillSettings') }}+ </a>+ </template>+ </div><p v-if="sandboxConfigOptions.length === 0" class="desc empty-hint">{{ $t('agent.editor.sandboxNoConfigs') }}</p>@@ -1315,18 +1323,19 @@<div class="setting-row"><div class="setting-info"><label>{{ $t('agent.editor.skillsSelection') }}</label>- <p class="desc">{{ $t('agent.editor.skillsSelectionDesc') }}</p>+ <p class="desc">{{ skillsSelectionHint }}</p></div><div class="setting-control sandbox-select-control"><t-radio-group v-model="skillsSelectionMode">- <t-radio-button value="all" :disabled="!hasSandboxSelected">{{ $t('agent.editor.skillsAll') }}</t-radio-button>- <t-radio-button value="selected" :disabled="!hasSandboxSelected">{{ $t('agent.editor.skillsSelected') }}</t-radio-button>+ <t-radio-button value="all" :disabled="!canEnableSkills">{{ $t('agent.editor.skillsAll') }}</t-radio-button>+ <t-radio-button value="selected" :disabled="!canEnableSkills">{{ $t('agent.editor.skillsSelected') }}</t-radio-button><t-radio-button value="none">{{ $t('agent.editor.skillsNone') }}</t-radio-button></t-radio-group>- <p v-if="!hasSandboxSelected && sandboxConfigOptions.length > 0" class="desc empty-hint">+ <p v-if="showCatalogSkillList" class="skill-ready-stat">{{ skillListSummary }}</p>+ <p v-if="!hasSandboxSelected && sandboxConfigOptions.length > 1" class="desc empty-hint">{{ $t('agent.editor.skillsNeedSandbox') }}</p>- <p v-else-if="hasSandboxSelected && skillOptions.length === 0" class="desc empty-hint">+ <p v-else-if="hasSandboxSelected && skillCatalog.length === 0" class="desc empty-hint"><span>{{ $t('agent.editor.noSkillsAvailable') }}</span><av-if="canInstallSkills"@@ -1340,21 +1349,53 @@</div></div>- <div v-if="skillsSelectionMode === 'selected' && skillOptions.length > 0"- class="setting-row setting-row-vertical">- <div class="setting-info">- <label>{{ $t('agent.editor.selectSkills') }}</label>- <p class="desc">{{ $t('agent.editor.selectSkillsDesc') }}</p>- </div>+ <div v-if="showCatalogSkillList" class="setting-row setting-row-vertical"><div class="setting-control setting-control-full">- <t-checkbox-group v-model="formData.config.selected_skills" class="skills-checkbox-group">- <t-checkbox v-for="skill in skillOptions" :key="skill.name" :value="skill.name"- class="skill-checkbox-item">- <div class="skill-item-content">- <span class="skill-name">{{ skill.name }}</span>- <span class="skill-desc">{{ skill.description }}</span>+ <t-checkbox-group+ v-model="formData.config.selected_skills"+ class="skill-pick-list"+ >+ <article+ v-for="skill in catalogSkillRows"+ :key="skill.name"+ class="skill-pick"+ :class="{+ 'skill-pick--ready': skill.selectable,+ 'skill-pick--pending': !skill.selectable,+ }"+ >+ <t-checkbox+ v-if="skillsSelectionMode === 'selected'"+ :value="skill.name"+ :disabled="!skill.selectable"+ class="skill-pick__check"+ />+ <div class="skill-pick__body">+ <div class="skill-pick__title-row">+ <span class="skill-name" :title="skill.name">{{ skill.name }}</span>+ <span+ v-if="!skill.selectable && skill.installed"+ class="skill-pick__hint"+ >{{ skillStatusHint(skill) }}</span>+ </div>+ <p+ v-if="skill.description"+ class="skill-desc"+ :title="skill.description"+ >{{ skill.description }}</p></div>- </t-checkbox>+ <t-button+ v-if="canInstallSkillRow(skill)"+ size="small"+ variant="text"+ theme="primary"+ :loading="installingCatalogId === skill.id"+ :title="$t('agent.editor.installToThisSandbox')"+ @click.stop="installCatalogToCurrent(skill)"+ >+ {{ $t('agent.editor.installShort') }}+ </t-button>+ </article></t-checkbox-group></div></div>@@ -1736,7 +1777,7 @@ import {} from '@/api/agent';import { type ModelConfig } from '@/api/model';import { type AgentNotReadyReasonKey, agentRequiresRerankModel } from '@/utils/agent-readiness';-import { type SkillInfo } from '@/api/skill';+import { installSkillCatalog, type SkillCatalogItem } from '@/api/skill';import { type WebSearchProviderEntity } from '@/api/web-search-provider';import {isNamedSandboxBackend,@@ -1955,23 +1996,101 @@ const showMcpServiceSelect = computed(() =>mcpOptions.value.length > 0 || (formData.value.config.mcp_services?.length ?? 0) > 0,);const webSearchProviderList = ref<WebSearchProviderEntity[]>([]);-const skillOptions = ref<{ name: string; description: string }[]>([]);-// 是否允许启用 Skills(当前沙箱配置上有可执行技能时为 true;未选配置前为 false)-const skillsAvailable = ref(false);+const skillCatalog = ref<SkillCatalogItem[]>([]);+const catalogReady = ref(false);+const installingCatalogId = ref('');+const skillsSelectionMode = ref<'all' | 'selected' | 'none'>('none');const hasSandboxSelected = computed(() => !!formData.value.config.sandbox_config_id);+const canEnableSkills = computed(() =>+ hasSandboxSelected.value || namedSandboxConfigs().length === 1,+);const canInstallSkills = computed(() => authStore.hasRole('admin'));+type CatalogSkillRow = SkillCatalogItem & {+ installed: boolean+ selectable: boolean+ installStatus: string+ installEnabled: boolean+}++const catalogSkillRows = computed<CatalogSkillRow[]>(() => {+ const sandboxId = formData.value.config.sandbox_config_id || ''+ return skillCatalog.value.map((item) => {+ const inst = sandboxId+ ? (item.installations || []).find((row) => row.sandbox_config_id === sandboxId)+ : undefined+ const installStatus = inst?.status || ''+ const installEnabled = Boolean(inst?.enabled)+ const installed = Boolean(inst) && installStatus !== 'removed'+ const selectable = installStatus === 'ready' && installEnabled+ return { ...item, installed, selectable, installStatus, installEnabled }+ })+})++const showCatalogSkillList = computed(() =>+ skillsSelectionMode.value !== 'none'+ && hasSandboxSelected.value+ && catalogSkillRows.value.length > 0,+)++const skillsSelectionHint = computed(() => {+ if (skillsSelectionMode.value === 'all') return t('agent.editor.skillsAllListHint')+ if (skillsSelectionMode.value === 'selected') return t('agent.editor.selectSkillsDesc')+ return t('agent.editor.skillsSelectionDesc')+})++const catalogReadyCount = computed(() =>+ catalogSkillRows.value.filter((skill) => skill.selectable).length,+)++const catalogPendingCount = computed(() =>+ catalogSkillRows.value.filter((skill) => !skill.installed || skill.installStatus === 'failed').length,+)++const skillListSummary = computed(() => {+ const ready = catalogReadyCount.value+ const pending = catalogPendingCount.value+ if (pending > 0) return t('agent.editor.skillsListSummary', { ready, pending })+ return t('agent.editor.skillsListSummaryReadyOnly', { ready })+})++function skillStatusHint(skill: CatalogSkillRow): string {+ if (!skill.installed) return t('agent.editor.skillNotInstalled')+ if (skill.installStatus === 'installing') return t('settings.sandbox.skillStatusInstalling')+ if (skill.installStatus === 'failed') return t('settings.sandbox.skillStatusFailed')+ if (skill.installStatus === 'removing') return t('settings.sandbox.skillStatusRemoving')+ if (skill.installStatus === 'ready' && !skill.installEnabled) {+ return t('agent.editor.skillDisabledOnSandbox')+ }+ return t('agent.editor.skillNotReady')+}++function canInstallSkillRow(skill: CatalogSkillRow): boolean {+ if (!canInstallSkills.value || !hasSandboxSelected.value) return false+ return !skill.installed || skill.installStatus === 'failed'+}++function namedSandboxConfigs(): SandboxConfigRecord[] {+ return chatResources.sandboxConfigs.filter((cfg) => isNamedSandboxBackend(cfg.sandbox_type))+}++function autoBindSoleSandbox() {+ if (skillsSelectionMode.value === 'none') return+ if (formData.value.config.sandbox_config_id) return+ const configs = namedSandboxConfigs()+ if (configs.length === 1) {+ formData.value.config.sandbox_config_id = configs[0].id+ }+}+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 || ''- if (!configId) return- // 拉取失败时不要把用户已选项清掉- if (!skillsAvailable.value && skillOptions.value.length === 0) return- const names = new Set(skillOptions.value.map((skill) => skill.name))+ if (!catalogReady.value) return+ const names = new Set(catalogSkillRows.value.filter((skill) => skill.selectable).map((skill) => skill.name))const selected: string[] = formData.value.config.selected_skills || []const kept = selected.filter((name: string) => names.has(name))if (kept.length !== selected.length) {@@ -1980,12 +2099,33 @@ function pruneSelectedSkills() {}async function syncInstalledSkills(force = false) {+ autoBindSoleSandbox()const configId = formData.value.config.sandbox_config_id || ''await editorResources.ensureSkills(configId, force)- skillsAvailable.value = editorResources.skillsAvailable- skillOptions.value = [...editorResources.skills]+ try {+ await editorResources.ensureSkillCatalog(force)+ skillCatalog.value = [...editorResources.skillCatalog]+ catalogReady.value = true+ } catch {+ catalogReady.value = false+ }pruneSelectedSkills()}++async function installCatalogToCurrent(skill: CatalogSkillRow) {+ const configId = formData.value.config.sandbox_config_id || ''+ if (!configId || installingCatalogId.value) return+ installingCatalogId.value = skill.id+ try {+ await installSkillCatalog(skill.id, [configId])+ MessagePlugin.success(t('settings.skills.installAccepted'))+ await syncInstalledSkills(true)+ } catch (e: any) {+ MessagePlugin.error(e?.message || t('settings.sandbox.skillUploadFailed'))+ } finally {+ installingCatalogId.value = ''+ }+}// 空间内的具名沙箱后端配置。始终包含当前已选中的那份,即使它已被删除——// 否则下拉会静默显示为“不启用沙箱”,看不出该智能体其实指着一份不存在的配置。const sandboxConfigOptions = computed(() => {@@ -1999,6 +2139,30 @@ const sandboxConfigOptions = computed(() => {});const backendLabel = (type: string) =>type ? t(`settings.sandbox.backends.${type}`) : t('common.error');++function sandboxTargetLine(cfg: SandboxConfigRecord): string {+ if (cfg.sandbox_type === 'docker') {+ return cfg.config?.docker?.image?.trim() || ''+ }+ const remote = cfg.config?.e2b || cfg.config?.cube+ const raw = remote?.api_url?.trim() || ''+ if (!raw) return ''+ try {+ return new URL(raw).host+ } catch {+ return raw+ }+}++const selectedSandboxSummary = computed(() => {+ const id = formData.value.config.sandbox_config_id+ const cfg = sandboxConfigOptions.value.find((item) => item.id === id)+ if (!cfg?.sandbox_type) return ''+ const parts = [backendLabel(cfg.sandbox_type), sandboxTargetLine(cfg)]+ const desc = cfg.description?.trim()+ if (desc) parts.push(desc)+ return parts.filter(Boolean).join(' · ')+})// 存储引擎可用状态(用于图片存储 provider 选择)const storageEngineStatus = ref<StorageEngineStatusItem[]>([]);const imageStorageOptions = computed(() => {@@ -2051,9 +2215,6 @@ const kbSelectionMode = ref<'all' | 'selected' | 'none'>('none');// MCP 服务选择模式:all=全部, selected=指定, none=不使用const mcpSelectionMode = ref<'all' | 'selected' | 'none'>('none');-// Skills 选择模式:all=全部, selected=指定, none=不使用-const skillsSelectionMode = ref<'all' | 'selected' | 'none'>('none');-// 可用工具列表(与后台 internal/agent/tools/definitions.go 保持一致)// group 决定 UI 分组:base / rag / wiki_read / wiki_edit / wiki_issue / data// danger: 写类破坏性工具,UI 上给出显著提示@@ -3225,6 +3386,7 @@ const initSkillsSelectionMode = () => {} else {skillsSelectionMode.value = 'none';}+ autoBindSoleSandbox();};// 内置智能体:填入系统默认值@@ -3293,6 +3455,33 @@ watch(() => formData.value.config.sandbox_config_id, async () => {await syncInstalledSkills()})+let catalogPollTimer: number | null = null++function stopCatalogPoll() {+ if (catalogPollTimer != null) {+ window.clearInterval(catalogPollTimer)+ catalogPollTimer = null+ }+}++watch(+ [() => props.visible, catalogSkillRows],+ () => {+ const busy = catalogSkillRows.value.some((skill) =>+ skill.installStatus === 'installing' || skill.installStatus === 'removing',+ )+ if (!props.visible || !busy) {+ stopCatalogPoll()+ return+ }+ if (catalogPollTimer != null) return+ catalogPollTimer = window.setInterval(() => {+ void syncInstalledSkills(true)+ }, 2500)+ },+ { flush: 'post' },+)+// 监听 Skills 选择模式变化watch(skillsSelectionMode, (mode) => {formData.value.config.skills_selection_mode = mode;@@ -3302,6 +3491,9 @@ watch(skillsSelectionMode, (mode) => {} else if (mode === 'all') {// 全部 Skills,清空指定列表formData.value.config.selected_skills = [];+ autoBindSoleSandbox()+ } else {+ autoBindSoleSandbox()}// selected 模式保持 selected_skills 不变});@@ -4407,6 +4599,8 @@ const handleSave = async () => {delete formData.value.config.intent_prompts;}+ pruneSelectedSkills()+saving.value = true;try {if (editorMode.value === 'create') {@@ -5022,7 +5216,7 @@ const handleSave = async () => {.go-settings-link {font-size: 12px;color: var(--td-brand-color);- margin-top: 4px;+ margin-top: 0;text-decoration: none;&:hover {@@ -5030,21 +5224,51 @@ const handleSave = async () => {}}+.sandbox-select-links {+ display: flex;+ align-items: center;+ justify-content: flex-end;+ flex-wrap: wrap;+ gap: 6px;+ margin-top: 4px;+}++.sandbox-select-links__sep {+ color: var(--td-text-color-placeholder);+ font-size: 12px;+}+.sandbox-select-control {flex-direction: column;align-items: flex-end;}+.skill-ready-stat {+ margin: 6px 0 0;+ max-width: 280px;+ font-size: 12px;+ color: var(--td-text-color-secondary);+ line-height: 1.45;+ text-align: right;+}+.sandbox-config-select {width: 280px;}.sandbox-option {+ display: flex;+ flex-direction: column;+ gap: 2px;+ width: 100%;+ min-width: 0;+}++.sandbox-option__row {display: flex;align-items: center;justify-content: space-between;gap: 12px;- width: 100%;min-width: 0;}@@ -5061,6 +5285,24 @@ const handleSave = async () => {font-size: 12px;}+.sandbox-option__target {+ overflow: hidden;+ text-overflow: ellipsis;+ white-space: nowrap;+ color: var(--td-text-color-placeholder);+ font-size: 12px;+ line-height: 1.35;+}++.sandbox-selected-meta {+ margin: 6px 0 0;+ max-width: 280px;+ font-size: 12px;+ line-height: 1.45;+ color: var(--td-text-color-secondary);+ word-break: break-word;+}+// 名称输入框带头像预览.name-input-wrapper {display: flex;@@ -5663,53 +5905,79 @@ const handleSave = async () => {font-style: italic;}-// Skills 选择样式-.skills-checkbox-group {- display: grid;- grid-template-columns: 1fr;- gap: 12px;+.skill-pick-list {+ display: flex;+ flex-direction: column;+ gap: 8px;width: 100%;++ :deep(.t-checkbox-group) {+ display: flex;+ flex-direction: column;+ gap: 8px;+ width: 100%;+ }}-.skill-checkbox-item {+.skill-pick {display: flex;- align-items: flex-start;- padding: 12px 16px;- background: var(--td-bg-color-secondarycontainer);- border-radius: 8px;+ align-items: center;+ gap: 10px;+ min-width: 0;+ padding: 8px 10px;+ background: var(--td-bg-color-container);border: 1px solid var(--td-component-stroke);- transition: all 0.2s ease;+ border-radius: 8px;+}- &:hover {- border-color: var(--td-brand-color);- background: var(--td-success-color-light);- }+.skill-pick--pending {+ background: var(--td-bg-color-secondarycontainer);+}- :deep(.t-checkbox__input) {- margin-top: 2px;- }+.skill-pick__check {+ flex-shrink: 0;+}- :deep(.t-checkbox__label) {- flex: 1;- }+.skill-pick__body {+ flex: 1;+ min-width: 0;}-.skill-item-content {+.skill-pick__title-row {display: flex;- flex-direction: column;- gap: 4px;+ align-items: center;+ gap: 8px;+ min-width: 0;}.skill-name {- font-size: 14px;+ min-width: 0;+ overflow: hidden;+ text-overflow: ellipsis;+ white-space: nowrap;+ font-size: 13px;font-weight: 500;color: var(--td-text-color-primary);}+.skill-pick__hint {+ flex-shrink: 0;+ font-size: 12px;+ color: var(--td-text-color-placeholder);+}+.skill-desc {+ display: -webkit-box;+ -webkit-box-orient: vertical;+ -webkit-line-clamp: 2;+ line-clamp: 2;+ margin: 2px 0 0;+ overflow: hidden;font-size: 12px;color: var(--td-text-color-secondary);- line-height: 1.5;+ line-height: 1.45;+ white-space: pre-line;+ word-break: break-word;}.hint-trigger {diff --git a/frontend/src/views/settings/Settings.vue b/frontend/src/views/settings/Settings.vueindex d114bf2d5..fabb91f61 100644--- a/frontend/src/views/settings/Settings.vue+++ b/frontend/src/views/settings/Settings.vue@@ -158,7 +158,7 @@<SandboxSettings /></div>- <!-- 技能目录:安装到所选沙箱镜像,智能体只从中选用 -->+ <!-- 技能目录:登记后可装到多份沙箱,智能体只从当前沙箱的就绪集合选用 --><div v-if="currentSection === 'skills'" class="section"><SkillSettings :initial-sandbox-id="currentSubSection" /></div>diff --git a/frontend/src/views/settings/SkillSettings.test.mjs b/frontend/src/views/settings/SkillSettings.test.mjsnew file mode 100644index 000000000..58084c736--- /dev/null+++ b/frontend/src/views/settings/SkillSettings.test.mjs@@ -0,0 +1,59 @@+import assert from 'node:assert/strict'+import { readFileSync } from 'node:fs'+import test from 'node:test'++const source = readFileSync(new URL('./SkillSettings.vue', import.meta.url), 'utf8')++test('skill settings lists the catalog instead of switching sandboxes', () => {+ assert.match(source, /listSkillCatalog/)+ assert.match(source, /settings\.skills\.addSkill/)+ assert.match(source, /settings\.skills\.emptyDesc/)+ assert.doesNotMatch(source, /sandbox-switcher/)+ assert.doesNotMatch(source, /noConfigsDesc/)+})++test('catalog cards can install onto sandboxes and manage one install', () => {+ assert.match(source, /installSkillCatalog/)+ assert.match(source, /openManage/)+ assert.match(source, /hide-add/)+ assert.match(source, /focus-skill-id/)+ assert.match(source, /deleteSkillCatalog/)+ assert.match(source, /askDelete/)+ assert.match(source, /skill-card__chip/)+ assert.match(source, /skill-card__chip--add/)+ assert.match(source, /skill-card__installs/)+ assert.match(source, /settings\.skills\.installedOn/)+ assert.match(source, /skill-card__icon-btn/)+ assert.match(source, /openCatalogFiles/)+ assert.match(source, /SkillFilesDrawer/)+ assert.match(source, /skill-card__chip-status/)+ assert.match(source, /chevron-right/)+ assert.match(source, /skill-card__heading/)+ assert.match(source, /align-items: center/)+ assert.doesNotMatch(source, /sandbox-pick__desc/)+ assert.doesNotMatch(source, /skill-card__bar/)+ assert.doesNotMatch(source, /skill-card__sandbox/)+ assert.doesNotMatch(source, /skill-card__more/)+ assert.doesNotMatch(source, /catalogMenu/)+ assert.doesNotMatch(source, /t-dropdown/)+ assert.doesNotMatch(source, /install-chip/)+})++test('adding a skill uses a two-step drawer like sandbox setup', () => {+ assert.match(source, /skill-add-steps/)+ assert.match(source, /settings\.skills\.addStepRegister/)+ assert.match(source, /settings\.skills\.addStepInstall/)+ assert.match(source, /header-extra/)+ assert.match(source, /addStep === 0/)+ assert.match(source, /handleAddPrimary/)+ assert.doesNotMatch(source, /addFromSource/)+})++test('install step shows parsed skill and sandbox backend details', () => {+ assert.match(source, /parsed-skill/)+ assert.match(source, /skill-card__badge/)+ assert.match(source, /sandboxMetaLine/)+ assert.match(source, /sandbox-pick-list/)+ assert.doesNotMatch(source, /t-alert/)+ assert.doesNotMatch(source, /registered-alert/)+})diff --git a/frontend/src/views/settings/SkillSettings.vue b/frontend/src/views/settings/SkillSettings.vueindex c46bef03b..144f72bdd 100644--- a/frontend/src/views/settings/SkillSettings.vue+++ b/frontend/src/views/settings/SkillSettings.vue@@ -22,72 +22,384 @@<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"+ <div v-if="catalog.length === 0" class="empty-state">+ <t-empty :description="$t('settings.skills.emptyDesc')" />+ <p v-if="skillConfigs.length === 0" class="empty-hint">+ {{ $t('settings.skills.emptyNoSandboxHint') }}+ </p>+ <div class="empty-actions">+ <t-button theme="primary" @click="openAdd">+ {{ $t('settings.skills.addSkill') }}+ </t-button>+ <t-button+ v-if="skillConfigs.length === 0"+ theme="default"+ variant="outline"+ @click="uiStore.openSettings('sandbox')"+ >+ {{ $t('settings.skills.goSandboxSettings') }}+ </t-button>+ </div>+ </div>++ <div v-else class="skill-list">+ <article+ v-for="item in catalog"+ :key="item.id"+ class="skill-card"+ :class="{ 'skill-card--focused': focusedCatalogId === item.id }">- <SandboxBackendBadge :type="cfg.sandbox_type" size="sm" class="sandbox-switcher__badge" />- <span class="sandbox-switcher__name" :title="cfg.name">{{ cfg.name }}</span>+ <div class="skill-card__main">+ <div class="skill-card__badge" aria-hidden="true">+ <t-icon :name="SKILL_ICON" size="16px" />+ </div>+ <div class="skill-card__body">+ <div class="skill-card__header">+ <div class="skill-card__heading">+ <h3 class="skill-card__title" :title="item.name">{{ item.name }}</h3>+ <span v-if="item.version" class="skill-card__type">{{ item.version }}</span>+ </div>+ <div class="skill-card__actions">+ <button+ type="button"+ class="skill-card__icon-btn"+ :title="$t('settings.sandbox.skillFiles')"+ :aria-label="$t('settings.sandbox.skillFiles')"+ @click="openCatalogFiles(item)"+ >+ <t-icon name="folder" size="16px" />+ </button>+ <button+ v-if="canDelete(item)"+ type="button"+ class="skill-card__icon-btn skill-card__icon-btn--danger"+ :disabled="deletingId === item.id"+ :title="$t('settings.skills.deleteCatalog')"+ :aria-label="$t('settings.skills.deleteCatalog')"+ @click="askDelete(item)"+ >+ <t-icon name="delete" size="16px" />+ </button>+ </div>+ </div>+ <p v-if="item.description" class="skill-card__desc" :title="item.description">+ {{ compactText(item.description) }}+ </p>+ <div class="skill-card__installs">+ <span class="skill-card__installs-label">+ {{+ liveInstalls(item).length > 0+ ? $t('settings.skills.installedOn')+ : $t('settings.skills.noInstalls')+ }}+ </span>+ <div class="skill-card__chips">+ <button+ v-for="inst in liveInstalls(item)"+ :key="inst.skill_id"+ type="button"+ class="skill-card__chip"+ :class="installChipClass(inst)"+ :disabled="!recordFor(inst.sandbox_config_id)"+ :title="installTooltip(inst)"+ :aria-label="$t('settings.skills.manageOnSandbox', { name: installName(inst) })"+ @click="openManage(item, inst)"+ >+ <span+ v-if="isInstallBusy(inst)"+ class="skill-card__chip-dot"+ aria-hidden="true"+ />+ <SandboxBackendBadge+ v-else-if="inst.sandbox_type"+ :type="inst.sandbox_type"+ size="xs"+ />+ <span class="skill-card__chip-name">{{ installName(inst) }}</span>+ <span v-if="installChipStatus(inst)" class="skill-card__chip-status">+ {{ installChipStatus(inst) }}+ </span>+ <t-icon+ v-else+ name="chevron-right"+ size="14px"+ class="skill-card__chip-go"+ />+ </button>+ <button+ v-if="targetsFor(item).length > 0"+ type="button"+ class="skill-card__chip skill-card__chip--add"+ :title="$t('settings.skills.installToSandbox')"+ :aria-label="$t('settings.skills.installToSandbox')"+ @click="openInstall(item)"+ >+ <t-icon name="add" size="14px" />+ </button>+ </div>+ </div>+ </div>+ </div>+ </article>+ <button type="button" class="skill-card skill-card--add" @click="openAdd">+ <span class="skill-card--add__icon" aria-hidden="true">+ <add-icon />+ </span>+ <span class="skill-card--add__label">{{ $t('settings.skills.addSkill') }}</span></button></div>-- <SandboxSkillsPanel- v-if="selectedRecord"- ref="listPanel"- :record="selectedRecord"- mode="list"- @updated="onPanelUpdated"- @install="openInstall"- /></template>+ <SettingDrawer+ v-model:visible="showAdd"+ :title="$t('settings.skills.addSkill')"+ :description="addStepDescription"+ :icon="SKILL_ICON"+ width="680px"+ :min-width="560"+ :max-width="920"+ storage-key="setting-drawer:width:skill-catalog-add"+ :confirm-loading="addPrimaryLoading"+ :confirm-disabled="addPrimaryDisabled"+ :confirm-text="addPrimaryText"+ @confirm="handleAddPrimary"+ >+ <template #header-extra>+ <nav class="skill-add-steps" :aria-label="$t('settings.skills.addProgress')">+ <component+ :is="canJumpAddStep(index) ? 'button' : 'div'"+ v-for="(item, index) in addSteps"+ :key="item.key"+ :type="canJumpAddStep(index) ? 'button' : undefined"+ :class="['skill-add-step', {+ 'is-active': addStep === index,+ 'is-done': addStep > index,+ 'is-clickable': canJumpAddStep(index),+ }]"+ :aria-current="addStep === index ? 'step' : undefined"+ @click="goToAddStep(index)"+ >+ <span class="skill-add-step__marker">+ <t-icon v-if="addStep > index" name="check" />+ <template v-else>{{ index + 1 }}</template>+ </span>+ <span class="skill-add-step__title">{{ item.title }}</span>+ <span v-if="index < addSteps.length - 1" class="skill-add-step__line" aria-hidden="true" />+ </component>+ </nav>+ </template>+ <template #footer-left>+ <t-button v-if="addStep > 0" variant="outline" @click="addPreviousStep">+ {{ $t('settings.sandbox.back') }}+ </t-button>+ </template>++ <article v-if="addStep > 0 && registeredCatalog" class="skill-card parsed-skill">+ <div class="skill-card__main">+ <div class="skill-card__badge" aria-hidden="true">+ <t-icon :name="SKILL_ICON" size="16px" />+ </div>+ <div class="skill-card__body">+ <div class="skill-card__header">+ <h3 class="skill-card__title" :title="registeredCatalog.name">{{ registeredCatalog.name }}</h3>+ <span v-if="registeredCatalog.version" class="skill-card__type">{{ registeredCatalog.version }}</span>+ </div>+ <p v-if="registeredCatalog.description" class="skill-card__desc" :title="registeredCatalog.description">+ {{ compactText(registeredCatalog.description) }}+ </p>+ </div>+ </div>+ </article>++ <template v-if="addStep === 0">+ <section class="setting-drawer__section">+ <h4 class="setting-drawer__section-title">{{ $t('settings.sandbox.skillSourceSection') }}</h4>+ <p class="installer-model-hint">{{ $t('settings.sandbox.skillSourceSectionHint') }}</p>+ <t-input+ v-model="sourceInput"+ :placeholder="$t('settings.sandbox.skillSourcePlaceholder')"+ :disabled="addBusy || !!registeredCatalog"+ @enter="handleAddPrimary"+ />+ </section>++ <section class="setting-drawer__section">+ <h4 class="setting-drawer__section-title">{{ $t('settings.sandbox.skillUploadSection') }}</h4>+ <p class="installer-model-hint">{{ $t('settings.sandbox.skillUploadSectionHint') }}</p>+ <input+ ref="fileInputRef"+ type="file"+ accept=".zip,application/zip"+ class="file-input-hidden"+ @change="onFileInputChange"+ />+ <div+ class="file-upload-area file-upload-area--large"+ :class="{ 'has-file': !!pendingFile, 'is-disabled': addBusy || !!registeredCatalog }"+ @click="!addBusy && !registeredCatalog && fileInputRef?.click()"+ @dragover.prevent+ @dragenter.prevent+ @drop.prevent="onFileDrop"+ >+ <div class="file-upload-content">+ <div class="file-upload-icon-wrap" aria-hidden="true">+ <t-icon name="cloud-upload" size="32px" class="upload-icon" />+ </div>+ <div class="upload-text">+ <span v-if="pendingFile" class="upload-file-name">+ {{ t('settings.skills.addFileSelected', { name: pendingFile.name }) }}+ </span>+ <template v-else>+ <span class="upload-primary-text">{{ $t('settings.sandbox.skillUploadClick') }}</span>+ <span class="upload-secondary-text">{{ $t('settings.sandbox.skillUploadDrag') }}</span>+ </template>+ </div>+ <t-progress v-if="uploading" :percentage="uploadPercent" size="small" />+ </div>+ </div>+ <t-button+ v-if="pendingFile && !registeredCatalog"+ variant="text"+ size="small"+ :disabled="addBusy"+ @click="pendingFile = null"+ >+ {{ $t('settings.skills.addClearFile') }}+ </t-button>+ </section>+ </template>++ <template v-else>+ <section v-if="skillConfigs.length > 0" class="setting-drawer__section">+ <h4 class="setting-drawer__section-title">{{ $t('settings.skills.pickSandboxes') }}</h4>+ <p class="installer-model-hint">{{ $t('settings.skills.pickSandboxesHint') }}</p>+ <t-checkbox-group v-model="addTargetIds" class="sandbox-pick-list">+ <t-checkbox v-for="cfg in skillConfigs" :key="cfg.id" :value="cfg.id" class="sandbox-pick">+ <span class="sandbox-pick__main">+ <SandboxBackendBadge :type="cfg.sandbox_type" size="xs" />+ <span class="sandbox-pick__text">+ <span class="sandbox-pick__name">{{ cfg.name }}</span>+ <span class="sandbox-pick__meta">{{ sandboxMetaLine(cfg) }}</span>+ </span>+ </span>+ </t-checkbox>+ </t-checkbox-group>+ </section>+ <p v-else class="installer-model-hint">{{ $t('settings.skills.emptyNoSandboxHint') }}</p>++ <section v-if="addTargetIds.length > 0" class="setting-drawer__section">+ <h4 class="setting-drawer__section-title">{{ $t('settings.sandbox.skillInstallerModel') }}</h4>+ <p class="installer-model-hint">{{ $t('settings.sandbox.skillInstallerModelHint') }}</p>+ <ModelSelector+ model-type="KnowledgeQA"+ :selected-model-id="installerModelId"+ :disabled="savingInstallerModel || installing"+ @update:selected-model-id="onInstallerModelChange"+ />+ </section>+ </template>+ </SettingDrawer>+<SettingDrawerv-model:visible="showInstall"- :title="$t('settings.skills.installSkill')"+ :title="$t('settings.skills.installToSandbox')":description="installDrawerDesc":icon="SKILL_ICON"+ width="560px"+ :min-width="480"+ :max-width="760"+ storage-key="setting-drawer:width:skill-catalog-install"+ :confirm-loading="installing"+ :confirm-disabled="installTargetIds.length === 0"+ :confirm-text="$t('settings.skills.installToSandbox')"+ @confirm="confirmInstall"+ >+ <p class="installer-model-hint">{{ $t('settings.skills.installToSandboxDesc') }}</p>+ <section v-if="installTargets.length > 0" class="setting-drawer__section">+ <t-checkbox-group v-model="installTargetIds" class="sandbox-pick-list">+ <t-checkbox v-for="cfg in installTargets" :key="cfg.id" :value="cfg.id" class="sandbox-pick">+ <span class="sandbox-pick__main">+ <SandboxBackendBadge :type="cfg.sandbox_type" size="xs" />+ <span class="sandbox-pick__text">+ <span class="sandbox-pick__name">{{ cfg.name }}</span>+ <span class="sandbox-pick__meta">{{ sandboxMetaLine(cfg) }}</span>+ </span>+ </span>+ </t-checkbox>+ </t-checkbox-group>+ </section>+ <p v-else class="installer-model-hint">{{ $t('settings.skills.noSandboxToInstall') }}</p>+ <section v-if="installTargetIds.length > 0" class="setting-drawer__section">+ <h4 class="setting-drawer__section-title">{{ $t('settings.sandbox.skillInstallerModel') }}</h4>+ <p class="installer-model-hint">{{ $t('settings.sandbox.skillInstallerModelHint') }}</p>+ <ModelSelector+ model-type="KnowledgeQA"+ :selected-model-id="installerModelId"+ :disabled="savingInstallerModel || installing"+ @update:selected-model-id="onInstallerModelChange"+ />+ </section>+ </SettingDrawer>++ <SettingDrawer+ v-model:visible="showManage"+ :title="manageTitle"+ :description="manageDesc"+ :icon="SKILL_ICON"width="680px":min-width="560":max-width="920"- storage-key="setting-drawer:width:skill-catalog"+ storage-key="setting-drawer:width:skill-catalog-manage":hide-footer="true"><SandboxSkillsPanel- v-if="showInstall && selectedRecord"- :record="selectedRecord"- mode="install"+ v-if="showManage && manageRecord && manageSkillId"+ :record="manageRecord"+ mode="list"+ hide-add+ :focus-skill-id="manageSkillId"@updated="onPanelUpdated"- @skills-changed="reloadList"- @installed="onInstalled"+ @skills-changed="loadCatalog"/></SettingDrawer>++ <SkillFilesDrawer+ v-model:visible="filesDrawerVisible"+ :catalog-id="filesCatalogId"+ :skill-name="filesCatalogName"+ /></div></template><script setup lang="ts">-import { computed, nextTick, onMounted, ref, watch } from 'vue'+import { computed, onMounted, onUnmounted, ref, watch } from 'vue'import { MessagePlugin } from 'tdesign-vue-next'+import { AddIcon } from 'tdesign-icons-vue-next'import { useI18n } from 'vue-i18n'import SandboxSkillsPanel from '@/components/SandboxSkillsPanel.vue'+import SkillFilesDrawer from '@/components/SkillFilesDrawer.vue'import SandboxBackendBadge from '@/components/settings/SandboxBackendBadge.vue'import SettingDrawer from '@/components/settings/SettingDrawer.vue'+import ModelSelector from '@/components/ModelSelector.vue'+import { useConfirmDelete } from '@/components/settings/useConfirmDelete'import { SKILL_ICON } from '@/types/mention'import { useUIStore } from '@/stores/ui'+import {+ deleteSkillCatalog,+ installSkillCatalog,+ listSkillCatalog,+ registerSkillCatalogFromFile,+ registerSkillCatalogFromSource,+ type SkillCatalogInstall,+ type SkillCatalogItem,+ type SkillCatalogRegisterResult,+} from '@/api/skill'+import {+ getAgentById,+ updateAgent,+ type CustomAgent,+} from '@/api/agent'import {isNamedSandboxBackend,listSandboxConfigs,@@ -100,72 +412,528 @@ const props = defineProps<{const { t } = useI18n()const uiStore = useUIStore()+const confirmDelete = useConfirmDelete()const loading = ref(false)const records = ref<SandboxConfigRecord[]>([])-const selectedId = ref('')+const catalog = ref<SkillCatalogItem[]>([])+const focusedCatalogId = ref('')+const deletingId = ref('')+const showAdd = ref(false)const showInstall = ref(false)-const listPanel = ref<{- reload: () => Promise<unknown>- revealSkill: (skillId: string) => void-} | null>(null)+const showManage = ref(false)+const addStep = ref(0)+const registeredCatalog = ref<SkillCatalogRegisterResult | null>(null)+const pendingFile = ref<File | null>(null)+const addTargetIds = ref<string[]>([])+const installTargetIds = ref<string[]>([])+const installCatalog = ref<SkillCatalogItem | null>(null)+const manageRecord = ref<SandboxConfigRecord | null>(null)+const manageSkillId = ref('')+const manageTitle = ref('')+const filesDrawerVisible = ref(false)+const filesCatalogId = ref('')+const filesCatalogName = ref('')+const sourceInput = ref('')+const uploading = ref(false)+const addingFromSource = ref(false)+const installing = ref(false)+const uploadPercent = ref(0)+const fileInputRef = ref<HTMLInputElement | null>(null)+const installerAgent = ref<CustomAgent | null>(null)+const installerModelId = ref('')+const savingInstallerModel = ref(false)++const INSTALLER_AGENT_ID = 'builtin-skill-installer'+const LAST_CHAT_MODEL_KEY = 'weknora_last_chat_model_id'++let pollTimer: number | null = null+let focusTimer: number | null = nullconst skillConfigs = computed(() =>records.value.filter((record) => isNamedSandboxBackend(record.sandbox_type)),)-const selectedRecord = computed(() =>- skillConfigs.value.find((record) => record.id === selectedId.value) || null,+const addBusy = computed(() => uploading.value || addingFromSource.value)++const addSteps = computed(() => [+ { key: 'register', title: t('settings.skills.addStepRegister') },+ { key: 'install', title: t('settings.skills.addStepInstall') },+])++const addStepDescription = computed(() =>+ addStep.value === 0+ ? t('settings.skills.addStepRegisterDesc')+ : t('settings.skills.addStepInstallDesc'),+)++const addPrimaryLoading = computed(() =>+ addStep.value === 0 ? addBusy.value : installing.value,)+const addPrimaryDisabled = computed(() => {+ if (addBusy.value || installing.value) return true+ if (addStep.value === 0) {+ if (registeredCatalog.value) return false+ return !sourceInput.value.trim() && !pendingFile.value+ }+ return addTargetIds.value.length > 0 && !installerModelId.value+})++const addPrimaryText = computed(() => {+ if (addStep.value === 0) return t('common.next')+ if (addTargetIds.value.length > 0) return t('settings.skills.installToSandbox')+ return t('settings.skills.addFinish')+})++const installTargets = computed(() => {+ const item = installCatalog.value+ if (!item) return skillConfigs.value+ return targetsFor(item)+})+const installDrawerDesc = computed(() => {- const record = selectedRecord.value+ const item = installCatalog.value+ if (!item) return t('settings.skills.installToSandboxDesc')+ return t('settings.skills.installDrawerDesc', { name: item.name })+})++const manageDesc = computed(() => {+ const record = manageRecord.valueif (!record) return ''- return t('settings.skills.installDrawerDesc', { name: record.name })+ return t('settings.skills.manageDrawerDesc', { name: record.name })})-function applyPreferredSelection() {- const preferred = (props.initialSandboxId || '').trim()- if (preferred && skillConfigs.value.some((record) => record.id === preferred)) {- selectedId.value = preferred+function liveInstalls(item: SkillCatalogItem): SkillCatalogInstall[] {+ return (item.installations || []).filter((inst) => inst.status && inst.status !== 'removed')+}++function canDelete(item: SkillCatalogItem): boolean {+ return liveInstalls(item).length === 0+}++function targetsFor(item: SkillCatalogItem): SandboxConfigRecord[] {+ const taken = new Set(+ liveInstalls(item)+ .filter((inst) => inst.status === 'installing' || inst.status === 'ready' || inst.status === 'removing')+ .map((inst) => inst.sandbox_config_id),+ )+ return skillConfigs.value.filter((cfg) => !taken.has(cfg.id))+}++function recordFor(id: string): SandboxConfigRecord | undefined {+ return records.value.find((record) => record.id === id)+}++function backendLabel(type: string): string {+ return t(`settings.sandbox.backends.${type}`)+}++function sandboxTargetLine(record: SandboxConfigRecord): string {+ if (record.sandbox_type === 'docker') {+ return record.config?.docker?.image?.trim() || ''+ }+ const remote = record.config?.e2b || record.config?.cube+ const raw = remote?.api_url?.trim() || ''+ if (!raw) return ''+ try {+ return new URL(raw).host+ } catch {+ return raw+ }+}++function sandboxMetaLine(record: SandboxConfigRecord): string {+ const type = backendLabel(record.sandbox_type)+ const target = sandboxTargetLine(record)+ return target ? `${type} · ${target}` : type+}++function catalogFromRegister(data: SkillCatalogRegisterResult | undefined, fallbackName: string): SkillCatalogRegisterResult | null {+ const id = data?.id || ''+ if (!id) return null+ return {+ id,+ name: data?.name || fallbackName,+ version: data?.version,+ description: data?.description,+ }+}++function syncRegisteredFromCatalog() {+ const current = registeredCatalog.value+ if (!current?.id) return+ const item = catalog.value.find((row) => row.id === current.id)+ if (!item) return+ registeredCatalog.value = {+ id: item.id,+ name: item.name,+ version: item.version,+ description: item.description,+ }+}++function compactText(value: string): string {+ return value.replace(/\s+/g, ' ').trim()+}++function installStatusText(inst: SkillCatalogInstall): string {+ if (inst.status === 'installing') return t('settings.sandbox.skillStatusInstalling')+ if (inst.status === 'removing') return t('settings.sandbox.skillStatusRemoving')+ if (inst.status === 'failed') return t('settings.sandbox.skillStatusFailed')+ if (inst.status === 'ready' && !inst.enabled) return t('common.off')+ if (inst.status === 'ready') return t('settings.sandbox.skillStatusReady')+ return inst.status+}++function installChipStatus(inst: SkillCatalogInstall): string {+ if (inst.status === 'ready' && inst.enabled) return ''+ return installStatusText(inst)+}++function isInstallBusy(inst: SkillCatalogInstall): boolean {+ return inst.status === 'installing' || inst.status === 'removing'+}++function installChipClass(inst: SkillCatalogInstall): string {+ if (inst.status === 'failed') return 'skill-card__chip--failed'+ if (isInstallBusy(inst)) return 'skill-card__chip--busy'+ if (inst.status === 'ready' && !inst.enabled) return 'skill-card__chip--off'+ return 'skill-card__chip--ready'+}++function installName(inst: SkillCatalogInstall): string {+ return inst.sandbox_config_name || inst.sandbox_config_id+}++function installTooltip(inst: SkillCatalogInstall): string {+ const parts = [+ inst.sandbox_config_name || inst.sandbox_config_id,+ inst.sandbox_type ? backendLabel(inst.sandbox_type) : '',+ installStatusText(inst),+ ].filter(Boolean)+ return parts.join(' · ')+}++function openCatalogFiles(item: SkillCatalogItem) {+ filesCatalogId.value = item.id+ filesCatalogName.value = item.name+ filesDrawerVisible.value = true+}++function askDelete(item: SkillCatalogItem) {+ if (!canDelete(item)) {+ MessagePlugin.warning(t('settings.skills.deleteCatalogBlocked'))return}- if (selectedId.value && skillConfigs.value.some((record) => record.id === selectedId.value)) return- selectedId.value = skillConfigs.value[0]?.id || ''+ confirmDelete({+ body: t('settings.skills.deleteCatalogConfirm', { name: item.name }),+ onConfirm: () => removeCatalog(item),+ })+}++function defaultAddTargets(): string[] {+ const preferred = (props.initialSandboxId || '').trim()+ if (preferred && skillConfigs.value.some((cfg) => cfg.id === preferred)) return [preferred]+ if (skillConfigs.value.length === 1) return [skillConfigs.value[0].id]+ return []+}++function revealCatalog(id: string) {+ focusedCatalogId.value = id+ if (focusTimer != null) window.clearTimeout(focusTimer)+ focusTimer = window.setTimeout(() => {+ if (focusedCatalogId.value === id) focusedCatalogId.value = ''+ focusTimer = null+ }, 2400)+}++function resetAddWizard() {+ addStep.value = 0+ registeredCatalog.value = null+ pendingFile.value = null+ sourceInput.value = ''+ addTargetIds.value = []+ uploadPercent.value = 0+ if (fileInputRef.value) fileInputRef.value.value = ''+}++async function openAdd() {+ resetAddWizard()+ await loadInstallerModel()+ showAdd.value = true}-function openInstall() {- if (!selectedRecord.value) return+function canJumpAddStep(index: number) {+ if (index === addStep.value) return false+ return Boolean(registeredCatalog.value) || index < addStep.value+}++function goToAddStep(index: number) {+ if (!canJumpAddStep(index) && index !== addStep.value) return+ addStep.value = index+}++function addPreviousStep() {+ if (addStep.value <= 0) return+ addStep.value -= 1+}++function openInstall(item: SkillCatalogItem) {+ installCatalog.value = item+ const remaining = targetsFor(item)+ installTargetIds.value = remaining.length === 1 ? [remaining[0].id] : []+ void loadInstallerModel()showInstall.value = true}+function openManage(item: SkillCatalogItem, inst: SkillCatalogInstall) {+ const record = recordFor(inst.sandbox_config_id)+ if (!record) return+ manageRecord.value = record+ manageSkillId.value = inst.skill_id+ manageTitle.value = item.name+ showManage.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()+function readLastChatModelID(): string {+ try {+ return localStorage.getItem(LAST_CHAT_MODEL_KEY) || ''+ } catch {+ return ''+ }+}++async function loadInstallerModel() {+ try {+ const res = await getAgentById(INSTALLER_AGENT_ID)+ installerAgent.value = res?.data || null+ const configured = installerAgent.value?.config?.model_id?.trim() || ''+ installerModelId.value = configured || readLastChatModelID()+ } catch {+ installerAgent.value = null+ installerModelId.value = readLastChatModelID()+ }+}++async function persistInstallerModel(modelId: string) {+ const id = modelId.trim()+ if (!id) {+ throw new Error(t('settings.sandbox.skillInstallerModelRequired'))+ }+ const current = installerAgent.value+ const config = { ...(current?.config || {}), model_id: id }+ const res = await updateAgent(INSTALLER_AGENT_ID, {+ name: current?.name || '',+ description: current?.description || '',+ avatar: current?.avatar || '',+ config,+ })+ installerAgent.value = res?.data || { ...(current as CustomAgent), config }+ installerModelId.value = id+}++async function onInstallerModelChange(modelId: string) {+ if (!modelId || modelId === '__add_model__') return+ installerModelId.value = modelId+ savingInstallerModel.value = true+ try {+ await persistInstallerModel(modelId)+ } catch (e: any) {+ MessagePlugin.error(e?.message || t('settings.sandbox.skillInstallerModelSaveFailed'))+ } finally {+ savingInstallerModel.value = false+ }+}++async function ensureInstallerModelIfNeeded(configIds: string[]) {+ if (configIds.length === 0) return+ if (!installerModelId.value) {+ throw new Error(t('settings.sandbox.skillInstallerModelRequired'))+ }+ await persistInstallerModel(installerModelId.value)+}++function isZipFile(file: File): boolean {+ return file.name.toLowerCase().endsWith('.zip') || file.type === 'application/zip'+}++function acceptPendingFile(file: File) {+ if (addBusy.value || registeredCatalog.value) return+ if (!isZipFile(file)) {+ MessagePlugin.error(t('settings.sandbox.skillUploadFailed'))+ return+ }+ pendingFile.value = file+}++async function registerThenAdvance() {+ if (registeredCatalog.value) {+ addTargetIds.value = defaultAddTargets()+ addStep.value = 1+ return+ }+ const source = sourceInput.value.trim()+ if (!pendingFile.value && !source) return++ try {+ let registered: SkillCatalogRegisterResult | null = null+ if (pendingFile.value) {+ uploading.value = true+ uploadPercent.value = 0+ const res = await registerSkillCatalogFromFile(pendingFile.value, (percent) => {+ uploadPercent.value = percent+ })+ registered = catalogFromRegister(res?.data, pendingFile.value.name)+ } else {+ addingFromSource.value = true+ const res = await registerSkillCatalogFromSource(source)+ registered = catalogFromRegister(res?.data, source)+ }+ if (!registered) {+ await loadCatalog()+ return+ }+ registeredCatalog.value = registered+ addTargetIds.value = defaultAddTargets()+ addStep.value = 1+ MessagePlugin.success(t('settings.skills.registerAccepted'))+ await loadCatalog()+ syncRegisteredFromCatalog()+ } catch (e: any) {+ MessagePlugin.error(+ e?.message || (pendingFile.value+ ? t('settings.sandbox.skillUploadFailed')+ : t('settings.sandbox.skillSourceFailed')),+ )+ } finally {+ uploading.value = false+ addingFromSource.value = false+ uploadPercent.value = 0+ if (fileInputRef.value) fileInputRef.value.value = ''+ }+}++async function handleAddPrimary() {+ if (addPrimaryLoading.value || addPrimaryDisabled.value) return+ if (addStep.value === 0) {+ await registerThenAdvance()+ return+ }+ const catalogId = registeredCatalog.value?.id+ if (!catalogId) return+ const targets = [...addTargetIds.value]+ if (targets.length === 0) {+ showAdd.value = false+ revealCatalog(catalogId)+ return+ }+ installing.value = true+ try {+ await ensureInstallerModelIfNeeded(targets)+ await installSkillCatalog(catalogId, targets)+ MessagePlugin.success(t('settings.skills.installAccepted'))+ showAdd.value = false+ await loadCatalog()+ revealCatalog(catalogId)+ } catch (e: any) {+ MessagePlugin.error(e?.message || t('settings.sandbox.skillUploadFailed'))+ } finally {+ installing.value = false+ }+}++function onFileInputChange(event: Event) {+ const input = event.target as HTMLInputElement+ const file = input.files?.[0]+ if (file) acceptPendingFile(file)}-// 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)+function onFileDrop(event: DragEvent) {+ if (addBusy.value || registeredCatalog.value) return+ const file = event.dataTransfer?.files?.[0]+ if (file) acceptPendingFile(file)+}++async function confirmInstall() {+ const item = installCatalog.value+ if (!item || installTargetIds.value.length === 0) return+ installing.value = true+ try {+ await ensureInstallerModelIfNeeded(installTargetIds.value)+ await installSkillCatalog(item.id, [...installTargetIds.value])+ MessagePlugin.success(t('settings.skills.installAccepted'))+ showInstall.value = false+ await loadCatalog()+ revealCatalog(item.id)+ } catch (e: any) {+ MessagePlugin.error(e?.message || t('settings.sandbox.skillUploadFailed'))+ } finally {+ installing.value = false+ }+}++async function removeCatalog(item: SkillCatalogItem) {+ if (!canDelete(item)) {+ MessagePlugin.warning(t('settings.skills.deleteCatalogBlocked'))+ return+ }+ deletingId.value = item.id+ try {+ await deleteSkillCatalog(item.id)+ MessagePlugin.success(t('settings.skills.deleteSuccess'))+ await loadCatalog()+ } catch (e: any) {+ MessagePlugin.error(e?.message || t('common.deleteFailed'))+ } finally {+ deletingId.value = ''+ }+}++function catalogBusy(): boolean {+ return catalog.value.some((item) =>+ liveInstalls(item).some((inst) => inst.status === 'installing' || inst.status === 'removing'),+ )+}++function stopPoll() {+ if (pollTimer != null) {+ window.clearInterval(pollTimer)+ pollTimer = null+ }+}++function ensurePoll() {+ if (!catalogBusy()) {+ stopPoll()+ return+ }+ if (pollTimer != null) return+ pollTimer = window.setInterval(() => {+ void loadCatalog(true)+ }, 2500)+}++async function loadCatalog(silent = false) {+ try {+ const res = await listSkillCatalog()+ catalog.value = res?.data || []+ } catch (e: any) {+ if (!silent) MessagePlugin.error(e?.message || t('settings.skills.loadFailed'))+ } finally {+ ensurePoll()}}async function load() {loading.value = truetry {- const res = await listSandboxConfigs()- records.value = res?.data || []- applyPreferredSelection()+ const [configRes] = await Promise.all([listSandboxConfigs(), loadCatalog()])+ records.value = configRes?.data || []} catch (e: any) {MessagePlugin.error(e?.message || t('settings.skills.loadFailed'))} finally {@@ -173,20 +941,27 @@ async function load() {}}-watch(() => props.initialSandboxId, () => {- applyPreferredSelection()-})--watch(selectedId, () => {- if (loading.value) return- showInstall.value = false+watch(showManage, (open) => {+ if (!open) {+ void loadCatalog()+ manageSkillId.value = ''+ manageRecord.value = null+ }})-watch(showInstall, (open) => {- if (!open) reloadList()+watch(showAdd, (open) => {+ if (open) return+ const catalogId = registeredCatalog.value?.id+ resetAddWizard()+ void loadCatalog()+ if (catalogId) revealCatalog(catalogId)})onMounted(load)+onUnmounted(() => {+ stopPoll()+ if (focusTimer != null) window.clearTimeout(focusTimer)+})</script><style lang="less" scoped>@@ -251,61 +1026,566 @@ onMounted(load)}}-.sandbox-switcher {+.empty-hint {+ margin: 0 0 16px;+ font-size: 13px;+ color: var(--td-text-color-placeholder);+}++.empty-actions {+ display: flex;+ justify-content: center;+ gap: 8px;+}++.skill-list {+ display: grid;+ grid-template-columns: repeat(auto-fill, minmax(320px, 1fr));+ gap: 10px;+ align-items: start;+}++.skill-card {+ position: relative;+ display: flex;+ flex-direction: column;+ padding: 0;+ overflow: hidden;+ border: 1px solid var(--td-component-stroke);+ border-radius: 10px;+ background: var(--td-bg-color-container);+ transition: border-color 0.18s ease, box-shadow 0.18s ease;+ min-width: 0;++ &--focused {+ border-color: var(--td-brand-color);+ box-shadow: 0 0 0 2px var(--td-brand-color-focus, rgba(0, 168, 112, 0.18));+ }++ &--add {+ flex-direction: column;+ align-items: center;+ justify-content: center;+ gap: 6px;+ min-height: 88px;+ padding: 16px 12px;+ border-style: dashed;+ background: transparent;+ color: var(--td-text-color-placeholder);+ cursor: pointer;+ font: inherit;+ text-align: center;++ &:hover,+ &:focus-visible {+ color: var(--td-brand-color);+ border-color: var(--td-brand-color);+ background: color-mix(in srgb, var(--td-brand-color) 6%, transparent);+ box-shadow: none;+ }++ &__icon {+ display: flex;+ align-items: center;+ justify-content: center;+ width: 32px;+ height: 32px;+ border-radius: 8px;+ background: color-mix(in srgb, var(--td-brand-color) 10%, transparent);+ color: var(--td-brand-color);+ font-size: 18px;+ }++ &__label {+ font-size: 13px;+ font-weight: 500;+ line-height: 1.4;+ }+ }+}++.skill-card__main {+ display: flex;+ align-items: flex-start;+ gap: 10px;+ padding: 10px 12px 10px 10px;+ min-width: 0;+}++.skill-card__badge {+ flex-shrink: 0;+ width: 28px;+ height: 28px;+ border-radius: 7px;+ display: flex;+ align-items: center;+ justify-content: center;+ background: color-mix(in srgb, var(--td-brand-color) 12%, transparent);+ color: var(--td-brand-color);+}++.skill-card__body {+ flex: 1;+ min-width: 0;+ display: flex;+ flex-direction: column;+ gap: 6px;+}++.skill-card__header {+ display: flex;+ align-items: center;+ gap: 8px;+ min-width: 0;+ min-height: 28px;+}++.skill-card__heading {+ flex: 1;+ min-width: 0;+ display: flex;+ align-items: baseline;+ gap: 6px;+}++.skill-card__title {+ flex: 0 1 auto;+ min-width: 0;+ margin: 0;+ font-size: 14px;+ font-weight: 600;+ line-height: 1.35;+ color: var(--td-text-color-primary);+ overflow: hidden;+ text-overflow: ellipsis;+ white-space: nowrap;+}++.skill-card__actions {+ flex-shrink: 0;+ display: flex;+ align-items: center;+ gap: 2px;+}++.skill-card__icon-btn {+ flex-shrink: 0;display: inline-flex;align-items: center;- gap: 4px;- max-width: 100%;- margin-bottom: 16px;- overflow-x: auto;- scrollbar-width: none;+ justify-content: center;+ width: 24px;+ height: 24px;+ margin: 0;+ padding: 0;+ border: 0;+ border-radius: 6px;+ background: none;+ color: var(--td-text-color-placeholder);+ cursor: pointer;++ &:hover:not(:disabled) {+ color: var(--td-text-color-primary);+ background: var(--td-bg-color-container-hover);+ }- &::-webkit-scrollbar {- display: none;+ &--danger:hover:not(:disabled) {+ color: var(--td-error-color);+ background: color-mix(in srgb, var(--td-error-color) 8%, transparent);+ }++ &:disabled {+ cursor: not-allowed;+ opacity: 0.4;}}-.sandbox-switcher__item {- flex: 0 0 auto;- display: inline-flex;+.skill-card__type {+ flex-shrink: 0;+ font-size: 12px;+ font-weight: 500;+ line-height: 1.35;+ color: var(--td-text-color-placeholder);+}++.skill-card__desc {+ display: -webkit-box;+ -webkit-box-orient: vertical;+ -webkit-line-clamp: 2;+ line-clamp: 2;+ margin: 0;+ overflow: hidden;+ font-size: 12px;+ line-height: 1.45;+ color: var(--td-text-color-secondary);+ word-break: break-word;+}++.skill-card__installs {+ display: flex;+ flex-direction: column;+ align-items: flex-start;+ gap: 6px;+}++.skill-card__installs-label {+ font-size: 12px;+ line-height: 18px;+ color: var(--td-text-color-placeholder);+}++.skill-card__chips {+ display: flex;+ flex-wrap: wrap;align-items: center;gap: 6px;- max-width: 220px;- padding: 4px 10px 4px 4px;- background: transparent;+}++.skill-card__chip {+ display: inline-flex;+ align-items: center;+ gap: 5px;+ max-width: 100%;+ margin: 0;+ padding: 3px 6px 3px 5px;border: 1px solid transparent;border-radius: 999px;+ background: var(--td-bg-color-secondarycontainer);+ color: var(--td-text-color-secondary);cursor: pointer;font: inherit;- color: var(--td-text-color-secondary);+ font-size: 12px;+ line-height: 18px;text-align: left;- transition: background 0.15s ease, border-color 0.15s ease, color 0.15s ease;- &:hover:not(.is-active) {+ &:hover:not(:disabled) {color: var(--td-text-color-primary);- background: var(--td-bg-color-container-hover);+ border-color: var(--td-brand-color);+ background: color-mix(in srgb, var(--td-brand-color) 8%, transparent);+ }++ &:disabled {+ cursor: default;+ opacity: 0.6;+ }++ &--busy {+ color: var(--td-warning-color);+ background: color-mix(in srgb, var(--td-warning-color) 12%, transparent);+ border-color: color-mix(in srgb, var(--td-warning-color) 28%, transparent);+ }++ &--failed {+ color: var(--td-error-color);+ background: color-mix(in srgb, var(--td-error-color) 10%, transparent);+ border-color: color-mix(in srgb, var(--td-error-color) 28%, transparent);+ }++ &--off {+ color: var(--td-text-color-placeholder);+ }++ &--add {+ padding: 3px 7px;+ border: 1px dashed var(--td-component-stroke);+ background: transparent;+ color: var(--td-text-color-placeholder);++ &:hover:not(:disabled) {+ color: var(--td-brand-color);+ border-color: var(--td-brand-color);+ background: color-mix(in srgb, var(--td-brand-color) 6%, transparent);+ }+ }+}++.skill-card__chip-status {+ flex-shrink: 0;+ font-size: 11px;+ font-weight: 500;+}++.skill-card__chip-go {+ flex-shrink: 0;+ color: var(--td-text-color-placeholder);+}++.skill-card__chip:hover:not(:disabled) .skill-card__chip-go {+ color: var(--td-brand-color);+}++.skill-card__chip-dot {+ width: 6px;+ height: 6px;+ border-radius: 50%;+ background: currentColor;+ animation: skill-chip-dot 1.2s ease-in-out infinite;+}++@keyframes skill-chip-dot {+ 0%,+ 100% { opacity: 1; }+ 50% { opacity: 0.35; }+}++.skill-card__chip-name {+ min-width: 0;+ overflow: hidden;+ text-overflow: ellipsis;+ white-space: nowrap;+}++.installer-model-hint {+ margin: 0 0 10px;+ font-size: 12px;+ line-height: 1.55;+ color: var(--td-text-color-secondary);+}++.parsed-skill {+ margin: 0 0 16px;+}++.skill-add-steps {+ display: flex;+ align-items: center;+ gap: 8px;+ margin: 0;+}++.skill-add-step {+ display: flex;+ align-items: center;+ gap: 8px;+ min-width: 0;+ color: var(--td-text-color-placeholder);+ transition: color 0.15s ease;++ &:not(:last-child) {+ flex: 1;}&.is-active {- background: var(--td-bg-color-secondarycontainer);- color: var(--td-text-color-primary);+ color: var(--td-brand-color);+ }++ &.is-done {+ color: var(--td-text-color-secondary);+ }++ &.is-clickable {+ padding: 0;+ font: inherit;+ text-align: left;+ background: none;+ border: 0;+ cursor: pointer;++ &:hover:not(.is-active) {+ color: var(--td-brand-color);+ }++ &:focus-visible {+ outline: 2px solid var(--td-brand-color);+ outline-offset: 2px;+ border-radius: 4px;+ }}}-.sandbox-switcher__badge {- transform: scale(0.82);- transform-origin: center;+.skill-add-step__marker {+ display: inline-flex;+ align-items: center;+ justify-content: center;+ width: 22px;+ height: 22px;+ flex-shrink: 0;+ border: 1px solid currentColor;+ border-radius: 50%;+ font-size: 11px;+ font-weight: 600;+ line-height: 1;++ .is-active & {+ background: var(--td-brand-color);+ border-color: var(--td-brand-color);+ color: #fff;+ }++ .is-done & {+ background: color-mix(in srgb, var(--td-brand-color) 12%, transparent);+ border-color: color-mix(in srgb, var(--td-brand-color) 35%, transparent);+ color: var(--td-brand-color);+ }}-.sandbox-switcher__name {+.skill-add-step__title {+ overflow: hidden;font-size: 13px;font-weight: 500;- line-height: 1.2;- color: inherit;- overflow: hidden;text-overflow: ellipsis;white-space: nowrap;}-</style>+.skill-add-step__line {+ flex: 1;+ min-width: 16px;+ height: 1px;+ margin: 0 4px;+ background: var(--td-component-stroke);++ .is-done & {+ background: color-mix(in srgb, var(--td-brand-color) 35%, transparent);+ }+}++.setting-drawer__section {+ margin-bottom: 20px;+}++.setting-drawer__section-title {+ margin: 0 0 8px;+ font-size: 13px;+ font-weight: 600;+ color: var(--td-text-color-primary);+}++.sandbox-pick-list {+ display: flex;+ flex-direction: column;+ gap: 8px;+ width: 100%;++ :deep(.t-checkbox) {+ width: 100%;+ margin: 0;+ align-items: center;+ padding: 8px 10px;+ border: 1px solid var(--td-component-stroke);+ border-radius: 10px;+ background: var(--td-bg-color-container);+ cursor: pointer;++ &:hover:not(.t-is-disabled) {+ border-color: color-mix(in srgb, var(--td-brand-color) 40%, transparent);+ background: color-mix(in srgb, var(--td-brand-color) 4%, transparent);+ }++ &.t-is-checked {+ border-color: color-mix(in srgb, var(--td-brand-color) 40%, transparent);+ background: color-mix(in srgb, var(--td-brand-color) 5%, transparent);+ }+ }++ :deep(.t-checkbox__label) {+ width: 100%;+ margin: 0;+ padding-left: 8px;+ white-space: normal;+ }+ :deep(.t-checkbox__former),+ :deep(.t-checkbox__input) {+ flex-shrink: 0;+ margin-top: 0;+ align-self: center;+ }+}++.sandbox-pick__main {+ display: flex;+ align-items: center;+ gap: 8px;+ min-width: 0;+}++.sandbox-pick__text {+ display: flex;+ flex-direction: column;+ gap: 1px;+ min-width: 0;+}++.sandbox-pick__name {+ font-size: 13px;+ font-weight: 500;+ color: var(--td-text-color-primary);+ line-height: 1.3;+}++.sandbox-pick__meta {+ font-size: 12px;+ color: var(--td-text-color-secondary);+ line-height: 1.3;+}++.skill-source-row {+ width: 100%;+}++.file-input-hidden {+ display: none;+}++.file-upload-area {+ border: 1px dashed var(--td-component-stroke);+ border-radius: 10px;+ cursor: pointer;+ transition: border-color 0.15s ease, background 0.15s ease;++ &:hover:not(.is-disabled) {+ border-color: var(--td-brand-color);+ background: color-mix(in srgb, var(--td-brand-color) 4%, transparent);+ }++ &.is-disabled {+ cursor: not-allowed;+ opacity: 0.6;+ }+}++.file-upload-content {+ display: flex;+ flex-direction: column;+ align-items: center;+ gap: 12px;+ padding: 24px 20px;+}++.file-upload-icon-wrap {+ display: flex;+ align-items: center;+ justify-content: center;+ width: 56px;+ height: 56px;+ border-radius: 50%;+ background: color-mix(in srgb, var(--td-brand-color) 12%, transparent);+}++.upload-icon {+ color: var(--td-brand-color);+}++.upload-text {+ display: flex;+ flex-direction: column;+ align-items: center;+ gap: 4px;+}++.upload-primary-text {+ font-size: 15px;+ font-weight: 500;+ color: var(--td-text-color-primary);+}++.upload-secondary-text {+ font-size: 13px;+ color: var(--td-text-color-secondary);+}++.upload-file-name {+ font-size: 14px;+ font-weight: 500;+ color: var(--td-brand-color);+}+</style>diff --git a/internal/application/repository/tenant_skill.go b/internal/application/repository/tenant_skill.goindex 6fc39e90d..547a86052 100644--- a/internal/application/repository/tenant_skill.go+++ b/internal/application/repository/tenant_skill.go@@ -81,6 +81,21 @@ type TenantSkillRepository interface {// DeleteUserEnvVarsByConfig removes every principal's values for a config,// including the config-wide ones DeleteSkill never sees.DeleteUserEnvVarsByConfig(ctx context.Context, tenantID uint64, configID string) error++ // CreateCatalog inserts a tenant-level skill definition.+ CreateCatalog(ctx context.Context, e *types.TenantSkillCatalogEntity) error+ // GetCatalog returns nil when the row is missing or belongs to another workspace.+ GetCatalog(ctx context.Context, tenantID uint64, catalogID string) (*types.TenantSkillCatalogEntity, error)+ // GetCatalogByName scopes lookup by workspace because names are unique per tenant.+ GetCatalogByName(ctx context.Context, tenantID uint64, name string) (*types.TenantSkillCatalogEntity, error)+ // ListCatalogsByTenant returns every live catalog row of one workspace.+ ListCatalogsByTenant(ctx context.Context, tenantID uint64) ([]*types.TenantSkillCatalogEntity, error)+ // UpdateCatalog writes mutable definition fields (bundle, description, version).+ UpdateCatalog(ctx context.Context, e *types.TenantSkillCatalogEntity) error+ // DeleteCatalog soft-deletes a definition. Install rows are not touched.+ DeleteCatalog(ctx context.Context, tenantID uint64, catalogID string) error+ // ListSkillsByCatalog returns installations of one catalog skill.+ ListSkillsByCatalog(ctx context.Context, tenantID uint64, catalogID string) ([]*types.TenantSkillEntity, error)}type tenantSkillRepository struct{ db *gorm.DB }@@ -178,6 +193,7 @@ func (r *tenantSkillRepository) UpdateSkill(ctx context.Context, e *types.Tenant"installed_snapshot_id": e.InstalledSnapshotID,"install_session_id": e.InstallSessionID,"install_message_id": e.InstallMessageID,+ "catalog_id": e.CatalogID,"status": e.Status,"error": e.Error,"installing_since": e.InstallingSince,@@ -388,3 +404,88 @@ func (r *tenantSkillRepository) DeleteUserEnvVarsByConfig(Where("tenant_id = ? AND sandbox_config_id = ?", tenantID, configID).Delete(&types.TenantUserEnvVar{}).Error}++func (r *tenantSkillRepository) CreateCatalog(ctx context.Context, e *types.TenantSkillCatalogEntity) error {+ return r.db.WithContext(ctx).Create(e).Error+}++func (r *tenantSkillRepository) GetCatalog(+ ctx context.Context, tenantID uint64, catalogID string,+) (*types.TenantSkillCatalogEntity, error) {+ var e types.TenantSkillCatalogEntity+ err := r.db.WithContext(ctx).+ Where("tenant_id = ? AND id = ?", tenantID, catalogID).+ First(&e).Error+ if errors.Is(err, gorm.ErrRecordNotFound) {+ return nil, nil+ }+ if err != nil {+ return nil, err+ }+ return &e, nil+}++func (r *tenantSkillRepository) GetCatalogByName(+ ctx context.Context, tenantID uint64, name string,+) (*types.TenantSkillCatalogEntity, error) {+ var e types.TenantSkillCatalogEntity+ err := r.db.WithContext(ctx).+ Where("tenant_id = ? AND name = ?", tenantID, name).+ First(&e).Error+ if errors.Is(err, gorm.ErrRecordNotFound) {+ return nil, nil+ }+ if err != nil {+ return nil, err+ }+ return &e, nil+}++func (r *tenantSkillRepository) ListCatalogsByTenant(+ ctx context.Context, tenantID uint64,+) ([]*types.TenantSkillCatalogEntity, error) {+ var list []*types.TenantSkillCatalogEntity+ err := r.db.WithContext(ctx).+ Where("tenant_id = ?", tenantID).+ Order("created_at ASC").+ Find(&list).Error+ if err != nil {+ return nil, err+ }+ return list, nil+}++func (r *tenantSkillRepository) UpdateCatalog(ctx context.Context, e *types.TenantSkillCatalogEntity) error {+ return r.db.WithContext(ctx).+ Model(&types.TenantSkillCatalogEntity{}).+ Where("tenant_id = ? AND id = ?", e.TenantID, e.ID).+ Updates(map[string]any{+ "name": e.Name,+ "version": e.Version,+ "description": e.Description,+ "instructions": e.Instructions,+ "bundle_ref": e.BundleRef,+ "bundle_sha256": e.BundleSHA256,+ "updated_at": time.Now(),+ }).Error+}++func (r *tenantSkillRepository) DeleteCatalog(ctx context.Context, tenantID uint64, catalogID string) error {+ return r.db.WithContext(ctx).+ Where("tenant_id = ? AND id = ?", tenantID, catalogID).+ Delete(&types.TenantSkillCatalogEntity{}).Error+}++func (r *tenantSkillRepository) ListSkillsByCatalog(+ ctx context.Context, tenantID uint64, catalogID string,+) ([]*types.TenantSkillEntity, error) {+ var list []*types.TenantSkillEntity+ err := r.db.WithContext(ctx).+ Where("tenant_id = ? AND catalog_id = ?", tenantID, catalogID).+ Order("created_at ASC").+ Find(&list).Error+ if err != nil {+ return nil, err+ }+ return list, nil+}diff --git a/internal/application/repository/tenant_skill_test.go b/internal/application/repository/tenant_skill_test.goindex 3beb3e697..2661141e9 100644--- a/internal/application/repository/tenant_skill_test.go+++ b/internal/application/repository/tenant_skill_test.go@@ -26,13 +26,16 @@ func newSkillTestRepoWithDB(t *testing.T) (TenantSkillRepository, *gorm.DB) {require.NoError(t, err)require.NoError(t, db.AutoMigrate(&types.TenantSkillEntity{}, &types.TenantSkillSnapshotEntity{},- &types.TenantUserEnvVar{},+ &types.TenantUserEnvVar{}, &types.TenantSkillCatalogEntity{},))// AutoMigrate cannot express the partial unique index, so add it here to// match the production migration.require.NoError(t, db.Exec(`CREATE UNIQUE INDEX IF NOT EXISTS uq_tenant_skills_config_nameON tenant_skills (sandbox_config_id, name) WHERE deleted_at IS NULL`).Error)+ require.NoError(t, db.Exec(+ `CREATE UNIQUE INDEX IF NOT EXISTS uq_tenant_skill_catalog_name+ ON tenant_skill_catalog (tenant_id, name) WHERE deleted_at IS NULL`).Error)return NewTenantSkillRepository(db), db}@@ -442,3 +445,31 @@ func TestListSkillsByTenantSpansConfigsAndStopsAtTheTenant(t *testing.T) {require.ElementsMatch(t, []string{"sk-a", "sk-b"}, ids,"every config of the tenant, and nothing from another tenant")}++func TestCatalogNameIsUniquePerTenant(t *testing.T) {+ repo := newSkillTestRepo(t)+ ctx := context.Background()++ require.NoError(t, repo.CreateCatalog(ctx, &types.TenantSkillCatalogEntity{+ ID: "cat-a", TenantID: 7, Name: "pdf",+ }))+ got, err := repo.GetCatalogByName(ctx, 7, "pdf")+ require.NoError(t, err)+ require.Equal(t, "cat-a", got.ID)++ err = repo.CreateCatalog(ctx, &types.TenantSkillCatalogEntity{+ ID: "cat-b", TenantID: 7, Name: "pdf",+ })+ require.Error(t, err, "same tenant cannot hold two catalog rows of one name")++ require.NoError(t, repo.CreateCatalog(ctx, &types.TenantSkillCatalogEntity{+ ID: "cat-other", TenantID: 8, Name: "pdf",+ }))++ install := skillRow("sk-a", "cfg-1", "pdf")+ install.CatalogID = "cat-a"+ require.NoError(t, repo.CreateSkill(ctx, install))+ list, err := repo.ListSkillsByCatalog(ctx, 7, "cat-a")+ require.NoError(t, err)+ require.Len(t, list, 1)+}diff --git a/internal/application/service/tenant_skill_catalog.go b/internal/application/service/tenant_skill_catalog.gonew file mode 100644index 000000000..a83dfddca--- /dev/null+++ b/internal/application/service/tenant_skill_catalog.go@@ -0,0 +1,463 @@+package service++import (+ "context"+ "errors"+ "fmt"+ "strings"+ "time"++ "github.com/google/uuid"++ apperrors "github.com/Tencent/WeKnora/internal/errors"+ "github.com/Tencent/WeKnora/internal/logger"+ "github.com/Tencent/WeKnora/internal/types"+)++// SkillCatalogInstallView is one installation of a catalog skill onto a sandbox.+type SkillCatalogInstallView struct {+ SkillID string `json:"skill_id"`+ SandboxConfigID string `json:"sandbox_config_id"`+ SandboxConfigName string `json:"sandbox_config_name,omitempty"`+ SandboxType string `json:"sandbox_type,omitempty"`+ Status string `json:"status"`+ Enabled bool `json:"enabled"`+ Error string `json:"error,omitempty"`+ UpdatedAt time.Time `json:"updated_at"`+}++// SkillCatalogView is a tenant skill definition plus its sandbox installations.+type SkillCatalogView struct {+ ID string `json:"id"`+ Name string `json:"name"`+ Version string `json:"version,omitempty"`+ Description string `json:"description,omitempty"`+ BundleSHA256 string `json:"bundle_sha256,omitempty"`+ CreatedAt time.Time `json:"created_at"`+ UpdatedAt time.Time `json:"updated_at"`+ Installations []SkillCatalogInstallView `json:"installations"`+}++// ListCatalog returns every workspace skill definition and which sandbox+// configs currently carry an installation of it.+func (s *TenantSkillService) ListCatalog(+ ctx context.Context, tenantID uint64,+) ([]SkillCatalogView, error) {+ catalogs, err := s.skills.ListCatalogsByTenant(ctx, tenantID)+ if err != nil {+ return nil, err+ }+ installs, err := s.skills.ListSkillsByTenant(ctx, tenantID)+ if err != nil {+ return nil, err+ }+ var configs []*types.TenantSandboxConfigEntity+ if s.configs != nil {+ var cfgErr error+ configs, cfgErr = s.configs.ListByTenant(ctx, tenantID)+ if cfgErr != nil {+ return nil, cfgErr+ }+ }+ configByID := make(map[string]*types.TenantSandboxConfigEntity, len(configs))+ for _, cfg := range configs {+ if cfg != nil {+ configByID[cfg.ID] = cfg+ }+ }++ byCatalog := make(map[string][]*types.TenantSkillEntity, len(catalogs))+ unattached := make([]*types.TenantSkillEntity, 0)+ for _, row := range installs {+ if row == nil {+ continue+ }+ if row.CatalogID != "" {+ byCatalog[row.CatalogID] = append(byCatalog[row.CatalogID], row)+ continue+ }+ unattached = append(unattached, row)+ }++ out := make([]SkillCatalogView, 0, len(catalogs)+len(unattached))+ seenName := make(map[string]struct{}, len(catalogs))+ for _, cat := range catalogs {+ if cat == nil {+ continue+ }+ seenName[cat.Name] = struct{}{}+ out = append(out, catalogView(cat, byCatalog[cat.ID], configByID))+ }+ // Rows that predate catalog_id (or tests that insert installs directly)+ // still need to show up as definitions so the settings page is complete.+ for _, row := range unattached {+ if _, exists := seenName[row.Name]; exists {+ for i := range out {+ if out[i].Name != row.Name {+ continue+ }+ out[i].Installations = append(out[i].Installations, installView(row, configByID))+ }+ continue+ }+ seenName[row.Name] = struct{}{}+ synthetic := &types.TenantSkillCatalogEntity{+ ID: row.ID, TenantID: row.TenantID, Name: row.Name, Version: row.Version,+ Description: row.Description, BundleSHA256: row.BundleSHA256,+ CreatedAt: row.CreatedAt, UpdatedAt: row.UpdatedAt,+ }+ out = append(out, catalogView(synthetic, []*types.TenantSkillEntity{row}, configByID))+ }+ return out, nil+}++func catalogView(+ cat *types.TenantSkillCatalogEntity,+ installs []*types.TenantSkillEntity,+ configByID map[string]*types.TenantSandboxConfigEntity,+) SkillCatalogView {+ view := SkillCatalogView{+ ID: cat.ID,+ Name: cat.Name,+ Version: cat.Version,+ Description: cat.Description,+ BundleSHA256: cat.BundleSHA256,+ CreatedAt: cat.CreatedAt,+ UpdatedAt: cat.UpdatedAt,+ Installations: make([]SkillCatalogInstallView, 0, len(installs)),+ }+ for _, row := range installs {+ view.Installations = append(view.Installations, installView(row, configByID))+ }+ return view+}++func installView(+ row *types.TenantSkillEntity,+ configByID map[string]*types.TenantSandboxConfigEntity,+) SkillCatalogInstallView {+ v := SkillCatalogInstallView{+ SkillID: row.ID,+ SandboxConfigID: row.SandboxConfigID,+ Status: row.Status,+ Enabled: row.Enabled,+ Error: row.Error,+ UpdatedAt: row.UpdatedAt,+ }+ if cfg := configByID[row.SandboxConfigID]; cfg != nil {+ v.SandboxConfigName = cfg.Name+ v.SandboxType = cfg.SandboxType+ }+ return v+}++// RegisterCatalogFromArchive records a skill definition without installing it+// onto any sandbox. Re-uploading the same name updates the stored bundle.+func (s *TenantSkillService) RegisterCatalogFromArchive(+ ctx context.Context, tenantID uint64, archive []byte,+) (*types.TenantSkillCatalogEntity, error) {+ bundle, err := ParseSkillBundle(archive)+ if err != nil {+ return nil, err+ }+ return s.upsertCatalogFromBundle(ctx, tenantID, bundle, archive, true)+}++// RegisterCatalogFromSource fetches a public skill and records it in the catalog.+func (s *TenantSkillService) RegisterCatalogFromSource(+ ctx context.Context, tenantID uint64, source string,+) (*types.TenantSkillCatalogEntity, error) {+ archive, err := fetchSkillArchive(ctx, source, s.sourceHTTP)+ if err != nil {+ return nil, err+ }+ return s.RegisterCatalogFromArchive(ctx, tenantID, archive)+}++// InstallCatalogToConfigs copies a catalog skill onto each named sandbox using+// the existing image-install pipeline. Missing configs are skipped with an+// error; partial success is returned so the caller can show per-config status.+func (s *TenantSkillService) InstallCatalogToConfigs(+ ctx context.Context, tenantID uint64, catalogID string, configIDs []string,+) (map[string]string, error) {+ catalog, err := s.resolveCatalog(ctx, tenantID, catalogID)+ if err != nil {+ return nil, err+ }+ archive, err := s.catalogBundleArchive(ctx, tenantID, catalog)+ if err != nil {+ return nil, err+ }++ ids := uniqueNonEmptyStrings(configIDs)+ if len(ids) == 0 {+ return nil, apperrors.NewBadRequestError("at least one sandbox is required")+ }++ accepted := make(map[string]string, len(ids))+ var firstErr error+ for _, configID := range ids {+ skillID, installErr := s.InstallSkill(ctx, tenantID, configID, archive)+ if installErr != nil {+ logger.Warnf(ctx, "[skill] install catalog %s onto config %s failed: %v",+ catalogID, configID, installErr)+ if firstErr == nil {+ firstErr = installErr+ }+ continue+ }+ accepted[configID] = skillID+ }+ if len(accepted) == 0 {+ return nil, firstErr+ }+ return accepted, nil+}++// DeleteCatalog removes a definition that has no remaining installations.+func (s *TenantSkillService) DeleteCatalog(+ ctx context.Context, tenantID uint64, catalogID string,+) error {+ catalog, err := s.skills.GetCatalog(ctx, tenantID, catalogID)+ if err != nil {+ return err+ }+ if catalog == nil {+ return apperrors.NewNotFoundError("skill not found")+ }+ installs, err := s.skills.ListSkillsByCatalog(ctx, tenantID, catalogID)+ if err != nil {+ return err+ }+ live := 0+ for _, row := range installs {+ if row != nil && row.Status != types.SkillStatusRemoving {+ live+++ }+ }+ if live > 0 {+ return apperrors.NewConflictError(+ "remove this skill from every sandbox before deleting it from the catalog")+ }+ return s.skills.DeleteCatalog(ctx, tenantID, catalogID)+}++func (s *TenantSkillService) upsertCatalogFromBundle(+ ctx context.Context, tenantID uint64, bundle *SkillBundle, archive []byte, requireStore bool,+) (*types.TenantSkillCatalogEntity, error) {+ existing, err := s.skills.GetCatalogByName(ctx, tenantID, bundle.Name)+ if err != nil {+ return nil, err+ }+ now := s.now()+ if existing != nil {+ existing.Version = bundle.Version+ existing.Description = bundle.Description+ existing.Instructions = bundle.Instructions+ existing.BundleSHA256 = bundle.SHA256+ existing.UpdatedAt = now+ if err := s.storeCatalogBundle(ctx, tenantID, existing, archive, requireStore); err != nil {+ return nil, err+ }+ if err := s.skills.UpdateCatalog(ctx, existing); err != nil {+ return nil, err+ }+ return existing, nil+ }++ row := &types.TenantSkillCatalogEntity{+ ID: uuid.NewString(), TenantID: tenantID, Name: bundle.Name,+ Version: bundle.Version, Description: bundle.Description,+ Instructions: bundle.Instructions, BundleSHA256: bundle.SHA256,+ CreatedAt: now, UpdatedAt: now,+ }+ if err := s.storeCatalogBundle(ctx, tenantID, row, archive, requireStore); err != nil {+ return nil, err+ }+ if err := s.skills.CreateCatalog(ctx, row); err != nil {+ if !isSkillNameConflict(err) {+ return nil, err+ }+ winner, lookupErr := s.skills.GetCatalogByName(ctx, tenantID, bundle.Name)+ if lookupErr != nil {+ return nil, lookupErr+ }+ if winner == nil {+ return nil, err+ }+ return s.upsertCatalogFromBundle(ctx, tenantID, bundle, archive, requireStore)+ }+ return row, nil+}++func (s *TenantSkillService) storeCatalogBundle(+ ctx context.Context, tenantID uint64, catalog *types.TenantSkillCatalogEntity, archive []byte, requireStore bool,+) error {+ if catalog == nil || len(archive) == 0 {+ return nil+ }+ fs, err := s.fileServiceForTenant(ctx, tenantID)+ if err != nil {+ if requireStore {+ return err+ }+ logger.Warnf(ctx, "[skill] catalog bundle storage unavailable: %v", err)+ return nil+ }+ ref, err := fs.SaveBytes(ctx, archive, tenantID,+ fmt.Sprintf("tenant-skills/catalog/%s.zip", catalog.ID), false)+ if err != nil {+ if requireStore {+ return fmt.Errorf("store catalog bundle: %w", err)+ }+ logger.Warnf(ctx, "[skill] catalog bundle store failed: %v", err)+ return nil+ }+ catalog.BundleRef = ref+ return nil+}++func (s *TenantSkillService) resolveCatalog(+ ctx context.Context, tenantID uint64, id string,+) (*types.TenantSkillCatalogEntity, error) {+ id = strings.TrimSpace(id)+ if id == "" {+ return nil, apperrors.NewNotFoundError("skill not found")+ }+ cat, err := s.skills.GetCatalog(ctx, tenantID, id)+ if err != nil {+ return nil, err+ }+ if cat != nil {+ return cat, nil+ }+ installs, err := s.skills.ListSkillsByTenant(ctx, tenantID)+ if err != nil {+ return nil, err+ }+ var match *types.TenantSkillEntity+ for _, row := range installs {+ if row == nil {+ continue+ }+ if row.ID == id || row.CatalogID == id {+ match = row+ break+ }+ }+ if match == nil {+ return nil, apperrors.NewNotFoundError("skill not found")+ }+ if cid := strings.TrimSpace(match.CatalogID); cid != "" && cid != id {+ cat, err = s.skills.GetCatalog(ctx, tenantID, cid)+ if err != nil {+ return nil, err+ }+ if cat != nil {+ return cat, nil+ }+ }+ return catalogProjectionFromSkill(match), nil+}++func catalogProjectionFromSkill(row *types.TenantSkillEntity) *types.TenantSkillCatalogEntity {+ return &types.TenantSkillCatalogEntity{+ ID: row.ID, TenantID: row.TenantID, Name: row.Name, Version: row.Version,+ Description: row.Description, Instructions: row.Instructions,+ BundleRef: row.BundleRef, BundleSHA256: row.BundleSHA256,+ CreatedAt: row.CreatedAt, UpdatedAt: row.UpdatedAt,+ }+}++func (s *TenantSkillService) ListCatalogFiles(+ ctx context.Context, tenantID uint64, catalogID string,+) ([]SkillFileEntry, error) {+ archive, err := s.loadCatalogArchive(ctx, tenantID, catalogID)+ if err != nil {+ return nil, err+ }+ return listSkillZipFiles(archive)+}++func (s *TenantSkillService) ReadCatalogFile(+ ctx context.Context, tenantID uint64, catalogID, relativePath string,+) (*SkillFileContent, error) {+ clean, err := safeSkillFilePath(relativePath)+ if err != nil {+ return nil, apperrors.NewBadRequestError(err.Error())+ }+ archive, err := s.loadCatalogArchive(ctx, tenantID, catalogID)+ if err != nil {+ return nil, err+ }+ body, err := readSkillZipFile(archive, clean)+ if err != nil {+ if errors.Is(err, errSkillFileMissing) {+ return nil, apperrors.NewNotFoundError("skill file not found")+ }+ return nil, err+ }+ return projectSkillFileContent(clean, body), nil+}++func (s *TenantSkillService) loadCatalogArchive(+ ctx context.Context, tenantID uint64, catalogID string,+) ([]byte, error) {+ catalog, err := s.resolveCatalog(ctx, tenantID, catalogID)+ if err != nil {+ return nil, err+ }+ return s.catalogBundleArchive(ctx, tenantID, catalog)+}++func (s *TenantSkillService) catalogBundleArchive(+ ctx context.Context, tenantID uint64, catalog *types.TenantSkillCatalogEntity,+) ([]byte, error) {+ if catalog == nil {+ return nil, apperrors.NewNotFoundError("skill not found")+ }+ tryRow := func(row *types.TenantSkillEntity) ([]byte, bool) {+ if row == nil || strings.TrimSpace(row.BundleRef) == "" {+ return nil, false+ }+ archive, err := s.downloadSkillBundle(ctx, tenantID, row)+ if err != nil || len(archive) == 0 {+ return nil, false+ }+ return archive, true+ }++ if ref := strings.TrimSpace(catalog.BundleRef); ref != "" {+ if archive, ok := tryRow(&types.TenantSkillEntity{+ Name: catalog.Name, BundleRef: catalog.BundleRef, BundleSHA256: catalog.BundleSHA256,+ }); ok {+ return archive, nil+ }+ }+ installs, err := s.skills.ListSkillsByCatalog(ctx, tenantID, catalog.ID)+ if err != nil {+ return nil, err+ }+ for _, row := range installs {+ if archive, ok := tryRow(row); ok {+ return archive, nil+ }+ }+ all, err := s.skills.ListSkillsByTenant(ctx, tenantID)+ if err != nil {+ return nil, err+ }+ for _, row := range all {+ if row == nil {+ continue+ }+ if row.ID != catalog.ID && row.Name != catalog.Name {+ continue+ }+ if archive, ok := tryRow(row); ok {+ return archive, nil+ }+ }+ return nil, apperrors.NewBadRequestError(+ "the archive of this skill is no longer stored; add it again from the original bundle")+}diff --git a/internal/application/service/tenant_skill_catalog_test.go b/internal/application/service/tenant_skill_catalog_test.gonew file mode 100644index 000000000..ffa825d69--- /dev/null+++ b/internal/application/service/tenant_skill_catalog_test.go@@ -0,0 +1,65 @@+package service++import (+ "context"+ "testing"++ "github.com/Tencent/WeKnora/internal/application/repository"+ "github.com/Tencent/WeKnora/internal/types"+ "github.com/stretchr/testify/require"+ "gorm.io/driver/sqlite"+ "gorm.io/gorm"+)++func TestListCatalogGroupsInstallsByDefinition(t *testing.T) {+ db, err := gorm.Open(sqlite.Open("file:catalog-list?mode=memory&cache=shared"), &gorm.Config{})+ require.NoError(t, err)+ require.NoError(t, db.AutoMigrate(+ &types.TenantSkillEntity{}, &types.TenantSkillCatalogEntity{},+ &types.TenantSkillSnapshotEntity{}, &types.TenantUserEnvVar{},+ ))+ repo := repository.NewTenantSkillRepository(db)+ ctx := context.Background()++ require.NoError(t, repo.CreateCatalog(ctx, &types.TenantSkillCatalogEntity{+ ID: "cat-pdf", TenantID: 7, Name: "pdf", Description: "extract",+ }))+ require.NoError(t, repo.CreateSkill(ctx, &types.TenantSkillEntity{+ ID: "sk-1", TenantID: 7, SandboxConfigID: "cfg-a", CatalogID: "cat-pdf",+ Name: "pdf", Status: types.SkillStatusReady, Enabled: true,+ }))+ require.NoError(t, repo.CreateSkill(ctx, &types.TenantSkillEntity{+ ID: "sk-2", TenantID: 7, SandboxConfigID: "cfg-b", CatalogID: "cat-pdf",+ Name: "pdf", Status: types.SkillStatusInstalling, Enabled: true,+ }))++ svc := NewTenantSkillService(repo, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil)+ list, err := svc.ListCatalog(ctx, 7)+ require.NoError(t, err)+ require.Len(t, list, 1)+ require.Equal(t, "pdf", list[0].Name)+ require.Len(t, list[0].Installations, 2)+}++func TestResolveCatalogFindsLegacySkillID(t *testing.T) {+ db, err := gorm.Open(sqlite.Open("file:catalog-legacy?mode=memory&cache=shared"), &gorm.Config{})+ require.NoError(t, err)+ require.NoError(t, db.AutoMigrate(+ &types.TenantSkillEntity{}, &types.TenantSkillCatalogEntity{},+ &types.TenantSkillSnapshotEntity{}, &types.TenantUserEnvVar{},+ ))+ repo := repository.NewTenantSkillRepository(db)+ ctx := context.Background()+ require.NoError(t, repo.CreateSkill(ctx, &types.TenantSkillEntity{+ ID: "sk-old", TenantID: 7, SandboxConfigID: "cfg-a",+ Name: "pdf", BundleRef: "local://7/tenant-skills/sk-old.zip",+ Status: types.SkillStatusReady, Enabled: true,+ }))++ svc := NewTenantSkillService(repo, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil)+ cat, err := svc.resolveCatalog(ctx, 7, "sk-old")+ require.NoError(t, err)+ require.NotNil(t, cat)+ require.Equal(t, "pdf", cat.Name)+ require.Equal(t, "local://7/tenant-skills/sk-old.zip", cat.BundleRef)+}diff --git a/internal/application/service/tenant_skill_files.go b/internal/application/service/tenant_skill_files.goindex b564cbc25..c1875c609 100644--- a/internal/application/service/tenant_skill_files.go+++ b/internal/application/service/tenant_skill_files.go@@ -100,15 +100,30 @@ func (s *TenantSkillService) skillBundleArchive(if skill == nil {return nil, apperrors.NewNotFoundError("skill not found")}- ref := strings.TrimSpace(skill.BundleRef)- if ref == "" {- return nil, apperrors.NewNotFoundError("skill files are not available")+ if archive, ok := s.trySkillBundle(ctx, tenantID, skill); ok {+ return archive, nil+ }+ if cid := strings.TrimSpace(skill.CatalogID); cid != "" {+ if archive, err := s.loadCatalogArchive(ctx, tenantID, cid); err == nil && len(archive) > 0 {+ return archive, nil+ }+ }+ if archive, err := s.loadCatalogArchive(ctx, tenantID, skill.ID); err == nil && len(archive) > 0 {+ return archive, nil+ }+ return nil, apperrors.NewNotFoundError("skill files are not available")+}++func (s *TenantSkillService) trySkillBundle(+ ctx context.Context, tenantID uint64, skill *types.TenantSkillEntity,+) ([]byte, bool) {+ if skill == nil || strings.TrimSpace(skill.BundleRef) == "" {+ return nil, false}key := skillBundleCacheKey(tenantID, skill)if cached := s.cachedSkillBundle(key); cached != nil {- return cached, nil+ return cached, true}-v, err, _ := s.bundleLoad.Do(key, func() (interface{}, error) {if cached := s.cachedSkillBundle(key); cached != nil {return cached, nil@@ -121,13 +136,13 @@ func (s *TenantSkillService) skillBundleArchive(return archive, nil})if err != nil {- return nil, err+ return nil, false}archive, ok := v.([]byte)- if !ok {- return nil, fmt.Errorf("download bundle of skill %s: unexpected cache result", skill.Name)+ if !ok || len(archive) == 0 {+ return nil, false}- return archive, nil+ return archive, true}func (s *TenantSkillService) downloadSkillBundle(diff --git a/internal/application/service/tenant_skill_install.go b/internal/application/service/tenant_skill_install.goindex faaf3add2..792534ad4 100644--- a/internal/application/service/tenant_skill_install.go+++ b/internal/application/service/tenant_skill_install.go@@ -78,17 +78,28 @@ func (s *TenantSkillService) InstallSkill(return existing.ID, nil}+ catalog, err := s.upsertCatalogFromBundle(ctx, tenantID, bundle, archive, false)+ if err != nil {+ return "", fmt.Errorf("record skill catalog: %w", err)+ }+ catalogID := ""+ if catalog != nil {+ catalogID = catalog.ID+ }+skillID := uuid.NewString()now := s.now()if existing != nil {skillID = existing.IDtakeSkillRowForInstall(existing, bundle, now)+ existing.CatalogID = catalogIDif err := s.skills.UpdateSkill(ctx, existing); err != nil {return "", err}} else {if err := s.skills.CreateSkill(ctx, &types.TenantSkillEntity{ID: skillID, TenantID: tenantID, SandboxConfigID: configID,+ CatalogID: catalogID,Name: bundle.Name, Version: bundle.Version,Description: bundle.Description, Instructions: bundle.Instructions,BundleSHA256: bundle.SHA256, Enabled: true,@@ -108,6 +119,7 @@ func (s *TenantSkillService) InstallSkill(}skillID = winner.IDtakeSkillRowForInstall(winner, bundle, now)+ winner.CatalogID = catalogIDif err := s.skills.UpdateSkill(ctx, winner); err != nil {return "", err}diff --git a/internal/application/service/tenant_skill_install_test.go b/internal/application/service/tenant_skill_install_test.goindex d1c31a3d3..635df9acd 100644--- a/internal/application/service/tenant_skill_install_test.go+++ b/internal/application/service/tenant_skill_install_test.go@@ -1858,6 +1858,7 @@ type installSkillRepo struct {mu sync.Mutexskills map[string]*types.TenantSkillEntitysnapshots map[string]*types.TenantSkillSnapshotEntity+ catalogs map[string]*types.TenantSkillCatalogEntity// updateFailsWhen models a transient write failure for one kind of row// state, so a test can fail the terminal bookkeeping write without// disabling every other write the run makes.@@ -1890,6 +1891,7 @@ func newInstallSkillRepo() *installSkillRepo {return &installSkillRepo{skills: map[string]*types.TenantSkillEntity{},snapshots: map[string]*types.TenantSkillSnapshotEntity{},+ catalogs: map[string]*types.TenantSkillCatalogEntity{},}}@@ -2254,6 +2256,84 @@ func (r *installSkillRepo) DeleteUserEnvVarsByConfig(return nil}+func (r *installSkillRepo) CreateCatalog(_ context.Context, e *types.TenantSkillCatalogEntity) error {+ r.mu.Lock()+ defer r.mu.Unlock()+ if r.catalogs == nil {+ r.catalogs = map[string]*types.TenantSkillCatalogEntity{}+ }+ cp := *e+ r.catalogs[e.ID] = &cp+ return nil+}++func (r *installSkillRepo) GetCatalog(_ context.Context, _ uint64, catalogID string) (*types.TenantSkillCatalogEntity, error) {+ r.mu.Lock()+ defer r.mu.Unlock()+ stored := r.catalogs[catalogID]+ if stored == nil {+ return nil, nil+ }+ cp := *stored+ return &cp, nil+}++func (r *installSkillRepo) GetCatalogByName(_ context.Context, tenantID uint64, name string) (*types.TenantSkillCatalogEntity, error) {+ r.mu.Lock()+ defer r.mu.Unlock()+ for _, row := range r.catalogs {+ if row.TenantID == tenantID && row.Name == name {+ cp := *row+ return &cp, nil+ }+ }+ return nil, nil+}++func (r *installSkillRepo) ListCatalogsByTenant(_ context.Context, tenantID uint64) ([]*types.TenantSkillCatalogEntity, error) {+ r.mu.Lock()+ defer r.mu.Unlock()+ var out []*types.TenantSkillCatalogEntity+ for _, row := range r.catalogs {+ if row.TenantID == tenantID {+ cp := *row+ out = append(out, &cp)+ }+ }+ return out, nil+}++func (r *installSkillRepo) UpdateCatalog(_ context.Context, e *types.TenantSkillCatalogEntity) error {+ r.mu.Lock()+ defer r.mu.Unlock()+ if r.catalogs == nil {+ r.catalogs = map[string]*types.TenantSkillCatalogEntity{}+ }+ cp := *e+ r.catalogs[e.ID] = &cp+ return nil+}++func (r *installSkillRepo) DeleteCatalog(_ context.Context, _ uint64, catalogID string) error {+ r.mu.Lock()+ defer r.mu.Unlock()+ delete(r.catalogs, catalogID)+ return nil+}++func (r *installSkillRepo) ListSkillsByCatalog(_ context.Context, tenantID uint64, catalogID string) ([]*types.TenantSkillEntity, error) {+ r.mu.Lock()+ defer r.mu.Unlock()+ var out []*types.TenantSkillEntity+ for _, row := range r.skills {+ if row.TenantID == tenantID && row.CatalogID == catalogID {+ cp := *row+ out = append(out, &cp)+ }+ }+ return out, nil+}+var _ repository.TenantSkillRepository = (*installSkillRepo)(nil)type installSandboxResolver struct {diff --git a/internal/application/service/tenant_skill_reaper_test.go b/internal/application/service/tenant_skill_reaper_test.goindex 0029ea724..f69657517 100644--- a/internal/application/service/tenant_skill_reaper_test.go+++ b/internal/application/service/tenant_skill_reaper_test.go@@ -906,6 +906,28 @@ func (r *reaperSkillStore) DeleteUserEnvVarsByConfig(context.Context, uint64, stpanic("DeleteUserEnvVarsByConfig is outside the reaper surface")}+func (r *reaperSkillStore) CreateCatalog(context.Context, *types.TenantSkillCatalogEntity) error {+ panic("CreateCatalog is outside the reaper surface")+}+func (r *reaperSkillStore) GetCatalog(context.Context, uint64, string) (*types.TenantSkillCatalogEntity, error) {+ panic("GetCatalog is outside the reaper surface")+}+func (r *reaperSkillStore) GetCatalogByName(context.Context, uint64, string) (*types.TenantSkillCatalogEntity, error) {+ panic("GetCatalogByName is outside the reaper surface")+}+func (r *reaperSkillStore) ListCatalogsByTenant(context.Context, uint64) ([]*types.TenantSkillCatalogEntity, error) {+ panic("ListCatalogsByTenant is outside the reaper surface")+}+func (r *reaperSkillStore) UpdateCatalog(context.Context, *types.TenantSkillCatalogEntity) error {+ panic("UpdateCatalog is outside the reaper surface")+}+func (r *reaperSkillStore) DeleteCatalog(context.Context, uint64, string) error {+ panic("DeleteCatalog is outside the reaper surface")+}+func (r *reaperSkillStore) ListSkillsByCatalog(context.Context, uint64, string) ([]*types.TenantSkillEntity, error) {+ panic("ListSkillsByCatalog is outside the reaper surface")+}+type reaperConfigStore struct {entity *types.TenantSandboxConfigEntity}diff --git a/internal/container/container.go b/internal/container/container.goindex b22b07054..19230a14a 100644--- a/internal/container/container.go+++ b/internal/container/container.go@@ -429,7 +429,7 @@ func BuildContainer(container *dig.Container) *dig.Container {must(container.Provide(handler.NewUserResourceFavoriteHandler))must(container.Provide(service.NewSkillService))must(container.Provide(func(s *service.TenantSkillService) *handler.SkillHandler {- return handler.NewSkillHandler(s)+ return handler.NewSkillHandler(s, s)}))must(container.Provide(handler.NewOrganizationHandler))must(container.Provide(handler.NewMemoryHandler))diff --git a/internal/handler/skill_catalog.go b/internal/handler/skill_catalog.gonew file mode 100644index 000000000..89100dadc--- /dev/null+++ b/internal/handler/skill_catalog.go@@ -0,0 +1,231 @@+package handler++import (+ stderrors "errors"+ "io"+ "net/http"+ "strings"++ "github.com/gin-gonic/gin"++ apperrors "github.com/Tencent/WeKnora/internal/errors"+ "github.com/Tencent/WeKnora/internal/types"+ secutils "github.com/Tencent/WeKnora/internal/utils"+)++// ListCatalog godoc+// @Summary List workspace skills+// @Description Returns every skill definition in this workspace and which sandbox configs it is installed on.+// @Tags Skills+// @Produce json+// @Success 200 {object} map[string]interface{}+// @Security Bearer+// @Security ApiKeyAuth+// @Router /skills/catalog [get]+func (h *SkillHandler) ListCatalog(c *gin.Context) {+ if h.catalog == nil {+ c.JSON(http.StatusOK, gin.H{"success": true, "data": []any{}})+ return+ }+ rows, err := h.catalog.ListCatalog(c.Request.Context(), sandboxConfigTenantID(c))+ if err != nil {+ _ = c.Error(err)+ return+ }+ c.JSON(http.StatusOK, gin.H{"success": true, "data": rows})+}++// RegisterCatalog godoc+// @Summary Add a skill to the workspace catalog+// @Description Records a skill without installing it. Send a zip as multipart field "file", or JSON {"source":"..."}.+// @Tags Skills+// @Accept json+// @Accept multipart/form-data+// @Produce json+// @Success 201 {object} map[string]interface{}+// @Router /skills/catalog [post]+func (h *SkillHandler) RegisterCatalog(c *gin.Context) {+ if h.catalog == nil {+ _ = c.Error(apperrors.NewInternalServerError("skill catalog is not configured"))+ return+ }+ maxBytes := secutils.GetMaxFileSize()+ c.Request.Body = http.MaxBytesReader(c.Writer, c.Request.Body, maxBytes+skillUploadEnvelopeSlack)++ if strings.HasPrefix(c.ContentType(), "application/json") {+ h.registerCatalogFromSource(c)+ return+ }++ file, header, err := c.Request.FormFile("file")+ if err != nil {+ var tooLarge *http.MaxBytesError+ if stderrors.As(err, &tooLarge) {+ _ = c.Error(skillTooLargeError())+ return+ }+ _ = c.Error(apperrors.NewBadRequestError("file is required"))+ return+ }+ defer func() { _ = file.Close() }()+ if header.Size > maxBytes {+ _ = c.Error(skillTooLargeError())+ return+ }+ archive, err := io.ReadAll(io.LimitReader(file, maxBytes+1))+ if err != nil {+ _ = c.Error(apperrors.NewBadRequestError("failed to read the uploaded skill bundle"))+ return+ }+ if int64(len(archive)) > maxBytes {+ _ = c.Error(skillTooLargeError())+ return+ }++ cat, err := h.catalog.RegisterCatalogFromArchive(+ c.Request.Context(), sandboxConfigTenantID(c), archive,+ )+ if err != nil {+ respondSkillServiceError(c, err)+ return+ }+ c.JSON(http.StatusCreated, gin.H{"success": true, "data": catalogIDResponse(cat)})+}++func (h *SkillHandler) registerCatalogFromSource(c *gin.Context) {+ var req skillSourceRequest+ if err := c.ShouldBindJSON(&req); err != nil {+ var tooLarge *http.MaxBytesError+ if stderrors.As(err, &tooLarge) {+ _ = c.Error(skillTooLargeError())+ return+ }+ _ = c.Error(apperrors.NewBadRequestError("invalid skill source request"))+ return+ }+ source := strings.TrimSpace(req.Source)+ if source == "" {+ _ = c.Error(apperrors.NewBadRequestError("source is required"))+ return+ }+ cat, err := h.catalog.RegisterCatalogFromSource(+ c.Request.Context(), sandboxConfigTenantID(c), source,+ )+ if err != nil {+ respondSkillServiceError(c, err)+ return+ }+ c.JSON(http.StatusCreated, gin.H{"success": true, "data": catalogIDResponse(cat)})+}++type catalogInstallRequest struct {+ SandboxConfigIDs []string `json:"sandbox_config_ids"`+}++// InstallCatalog godoc+// @Summary Install a catalog skill onto sandboxes+// @Description Runs the existing snapshot install onto each named sandbox config.+// @Tags Skills+// @Accept json+// @Produce json+// @Param id path string true "Catalog skill ID"+// @Success 202 {object} map[string]interface{}+// @Router /skills/catalog/{id}/install [post]+func (h *SkillHandler) InstallCatalog(c *gin.Context) {+ if h.catalog == nil {+ _ = c.Error(apperrors.NewInternalServerError("skill catalog is not configured"))+ return+ }+ var req catalogInstallRequest+ if err := c.ShouldBindJSON(&req); err != nil {+ _ = c.Error(apperrors.NewBadRequestError("invalid install request"))+ return+ }+ accepted, err := h.catalog.InstallCatalogToConfigs(+ c.Request.Context(), sandboxConfigTenantID(c), c.Param("id"), req.SandboxConfigIDs,+ )+ if err != nil {+ respondSkillServiceError(c, err)+ return+ }+ c.JSON(http.StatusAccepted, gin.H{"success": true, "data": gin.H{"installs": accepted}})+}++// DeleteCatalog godoc+// @Summary Delete a catalog skill+// @Description Refused while any sandbox still has an installation of this skill.+// @Tags Skills+// @Param id path string true "Catalog skill ID"+// @Success 200 {object} map[string]interface{}+// @Router /skills/catalog/{id} [delete]+func (h *SkillHandler) DeleteCatalog(c *gin.Context) {+ if h.catalog == nil {+ _ = c.Error(apperrors.NewInternalServerError("skill catalog is not configured"))+ return+ }+ if err := h.catalog.DeleteCatalog(+ c.Request.Context(), sandboxConfigTenantID(c), c.Param("id"),+ ); err != nil {+ _ = c.Error(err)+ return+ }+ c.JSON(http.StatusOK, gin.H{"success": true})+}++// ListCatalogFiles godoc+// @Summary List files of a catalog skill+// @Description Lists the stored catalog bundle. Files belong to the skill definition, not a sandbox install.+// @Tags Skills+// @Produce json+// @Param id path string true "Catalog skill ID"+// @Success 200 {object} map[string]interface{}+// @Router /skills/catalog/{id}/files [get]+func (h *SkillHandler) ListCatalogFiles(c *gin.Context) {+ if h.catalog == nil {+ _ = c.Error(apperrors.NewInternalServerError("skill catalog is not configured"))+ return+ }+ files, err := h.catalog.ListCatalogFiles(+ c.Request.Context(), sandboxConfigTenantID(c), c.Param("id"),+ )+ if err != nil {+ respondSkillServiceError(c, err)+ return+ }+ c.JSON(http.StatusOK, gin.H{"success": true, "data": files})+}++// GetCatalogFile godoc+// @Summary Read one file of a catalog skill+// @Tags Skills+// @Produce json+// @Param id path string true "Catalog skill ID"+// @Param path query string true "Skill-root-relative file path"+// @Success 200 {object} map[string]interface{}+// @Router /skills/catalog/{id}/files/content [get]+func (h *SkillHandler) GetCatalogFile(c *gin.Context) {+ if h.catalog == nil {+ _ = c.Error(apperrors.NewInternalServerError("skill catalog is not configured"))+ return+ }+ file, err := h.catalog.ReadCatalogFile(+ c.Request.Context(), sandboxConfigTenantID(c), c.Param("id"), c.Query("path"),+ )+ if err != nil {+ respondSkillServiceError(c, err)+ return+ }+ c.JSON(http.StatusOK, gin.H{"success": true, "data": file})+}++func catalogIDResponse(cat *types.TenantSkillCatalogEntity) gin.H {+ if cat == nil {+ return gin.H{}+ }+ return gin.H{+ "id": cat.ID,+ "name": cat.Name,+ "version": cat.Version,+ "description": cat.Description,+ }+}diff --git a/internal/handler/skill_catalog_test.go b/internal/handler/skill_catalog_test.gonew file mode 100644index 000000000..cb1d54f72--- /dev/null+++ b/internal/handler/skill_catalog_test.go@@ -0,0 +1,143 @@+package handler++import (+ "bytes"+ "context"+ "encoding/json"+ "net/http"+ "net/http/httptest"+ "testing"+ "time"++ "github.com/gin-gonic/gin"+ "github.com/stretchr/testify/require"++ "github.com/Tencent/WeKnora/internal/application/service"+ apperrors "github.com/Tencent/WeKnora/internal/errors"+ "github.com/Tencent/WeKnora/internal/middleware"+ "github.com/Tencent/WeKnora/internal/types"+)++type fakeSkillCatalog struct {+ list []service.SkillCatalogView+ registerID string+ installs map[string]string+ deleteErr error+ source string+}++func (f *fakeSkillCatalog) ListCatalog(context.Context, uint64) ([]service.SkillCatalogView, error) {+ return f.list, nil+}++func (f *fakeSkillCatalog) RegisterCatalogFromArchive(+ context.Context, uint64, []byte,+) (*types.TenantSkillCatalogEntity, error) {+ return &types.TenantSkillCatalogEntity{ID: f.registerID, Name: "pdf"}, nil+}++func (f *fakeSkillCatalog) RegisterCatalogFromSource(+ _ context.Context, _ uint64, source string,+) (*types.TenantSkillCatalogEntity, error) {+ f.source = source+ return &types.TenantSkillCatalogEntity{ID: f.registerID, Name: "pdf"}, nil+}++func (f *fakeSkillCatalog) InstallCatalogToConfigs(+ context.Context, uint64, string, []string,+) (map[string]string, error) {+ return f.installs, nil+}++func (f *fakeSkillCatalog) DeleteCatalog(context.Context, uint64, string) error {+ return f.deleteErr+}++func (f *fakeSkillCatalog) ListCatalogFiles(context.Context, uint64, string) ([]service.SkillFileEntry, error) {+ return nil, nil+}++func (f *fakeSkillCatalog) ReadCatalogFile(context.Context, uint64, string, string) (*service.SkillFileContent, error) {+ return nil, nil+}++func newCatalogRouter(h *SkillHandler) *gin.Engine {+ gin.SetMode(gin.TestMode)+ r := gin.New()+ r.Use(middleware.ErrorHandler())+ r.Use(func(c *gin.Context) {+ c.Set(types.TenantIDContextKey.String(), testSkillTenantID)+ c.Next()+ })+ r.GET("/skills/catalog", h.ListCatalog)+ r.POST("/skills/catalog", h.RegisterCatalog)+ r.POST("/skills/catalog/:id/install", h.InstallCatalog)+ r.DELETE("/skills/catalog/:id", h.DeleteCatalog)+ return r+}++func TestListCatalogReturnsDefinitionsAndInstallations(t *testing.T) {+ now := time.Now()+ catalog := &fakeSkillCatalog{+ list: []service.SkillCatalogView{{+ ID: "cat-1", Name: "pdf", Description: "extract", CreatedAt: now, UpdatedAt: now,+ Installations: []service.SkillCatalogInstallView{{+ SkillID: "sk-1", SandboxConfigID: "cfg-1", SandboxConfigName: "prod",+ Status: types.SkillStatusReady, Enabled: true, UpdatedAt: now,+ }},+ }},+ }+ router := newCatalogRouter(NewSkillHandler(&fakeUsableSkillLister{}, catalog))++ w := httptest.NewRecorder()+ router.ServeHTTP(w, httptest.NewRequest(http.MethodGet, "/skills/catalog", nil))+ require.Equal(t, http.StatusOK, w.Code)++ var body struct {+ Success bool+ Data []service.SkillCatalogView+ }+ require.NoError(t, json.Unmarshal(w.Body.Bytes(), &body))+ require.True(t, body.Success)+ require.Len(t, body.Data, 1)+ require.Equal(t, "pdf", body.Data[0].Name)+ require.Equal(t, "cfg-1", body.Data[0].Installations[0].SandboxConfigID)+}++func TestRegisterCatalogFromSource(t *testing.T) {+ catalog := &fakeSkillCatalog{registerID: "cat-9"}+ router := newCatalogRouter(NewSkillHandler(&fakeUsableSkillLister{}, catalog))++ body, err := json.Marshal(map[string]string{"source": "@owner/pdf"})+ require.NoError(t, err)+ req := httptest.NewRequest(http.MethodPost, "/skills/catalog", bytes.NewReader(body))+ req.Header.Set("Content-Type", "application/json")+ w := httptest.NewRecorder()+ router.ServeHTTP(w, req)+ require.Equal(t, http.StatusCreated, w.Code)+ require.Equal(t, "@owner/pdf", catalog.source)+}++func TestInstallCatalogAcceptsPerConfigIDs(t *testing.T) {+ catalog := &fakeSkillCatalog{installs: map[string]string{"cfg-1": "sk-1"}}+ router := newCatalogRouter(NewSkillHandler(&fakeUsableSkillLister{}, catalog))++ body, err := json.Marshal(map[string][]string{"sandbox_config_ids": {"cfg-1"}})+ require.NoError(t, err)+ req := httptest.NewRequest(http.MethodPost, "/skills/catalog/cat-1/install", bytes.NewReader(body))+ req.Header.Set("Content-Type", "application/json")+ w := httptest.NewRecorder()+ router.ServeHTTP(w, req)+ require.Equal(t, http.StatusAccepted, w.Code)+}++func TestDeleteCatalogRefusesWhileInstalled(t *testing.T) {+ catalog := &fakeSkillCatalog{+ deleteErr: apperrors.NewConflictError("remove this skill from every sandbox"),+ }+ router := newCatalogRouter(NewSkillHandler(&fakeUsableSkillLister{}, catalog))++ w := httptest.NewRecorder()+ router.ServeHTTP(w, httptest.NewRequest(http.MethodDelete, "/skills/catalog/cat-1", nil))+ require.Equal(t, http.StatusConflict, w.Code)+}diff --git a/internal/handler/skill_handler.go b/internal/handler/skill_handler.goindex 221cd6ffa..53db4e974 100644--- a/internal/handler/skill_handler.go+++ b/internal/handler/skill_handler.go@@ -4,6 +4,7 @@ import ("context""net/http"+ "github.com/Tencent/WeKnora/internal/application/service""github.com/Tencent/WeKnora/internal/types""github.com/gin-gonic/gin")@@ -18,12 +19,25 @@ type usableSkillLister interface {// SkillHandler handles skill-related HTTP requeststype SkillHandler struct {usableSkills usableSkillLister+ catalog skillCatalogService}-// NewSkillHandler creates a new skill handler-func NewSkillHandler(usableSkills usableSkillLister) *SkillHandler {+type skillCatalogService interface {+ ListCatalog(ctx context.Context, tenantID uint64) ([]service.SkillCatalogView, error)+ RegisterCatalogFromArchive(ctx context.Context, tenantID uint64, archive []byte) (*types.TenantSkillCatalogEntity, error)+ RegisterCatalogFromSource(ctx context.Context, tenantID uint64, source string) (*types.TenantSkillCatalogEntity, error)+ InstallCatalogToConfigs(ctx context.Context, tenantID uint64, catalogID string, configIDs []string) (map[string]string, error)+ DeleteCatalog(ctx context.Context, tenantID uint64, catalogID string) error+ ListCatalogFiles(ctx context.Context, tenantID uint64, catalogID string) ([]service.SkillFileEntry, error)+ ReadCatalogFile(ctx context.Context, tenantID uint64, catalogID, relativePath string) (*service.SkillFileContent, error)+}++// NewSkillHandler creates a new skill handler. catalog may be nil in tests+// that only exercise the chat picker.+func NewSkillHandler(usableSkills usableSkillLister, catalog skillCatalogService) *SkillHandler {return &SkillHandler{usableSkills: usableSkills,+ catalog: catalog,}}diff --git a/internal/handler/skill_handler_test.go b/internal/handler/skill_handler_test.goindex 45dcb7330..7ffaba133 100644--- a/internal/handler/skill_handler_test.go+++ b/internal/handler/skill_handler_test.go@@ -47,7 +47,7 @@ func TestListSkillsHidesThePickerWhenNoSandboxConfigIsSelected(t *testing.T) {lister := &fakeUsableSkillLister{skills: []*types.TenantSkillEntity{{Name: "ppt-generator", Description: "make ppt"}},}- router := newChatSkillRouter(NewSkillHandler(lister))+ router := newChatSkillRouter(NewSkillHandler(lister, nil))w := httptest.NewRecorder()router.ServeHTTP(w, httptest.NewRequest(http.MethodGet, "/skills", nil))@@ -71,7 +71,7 @@ func TestListSkillsReturnsUsableInstalledSkillsForTheSelectedConfig(t *testing.T{Name: "ppt-generator", Description: "make ppt"},},}- router := newChatSkillRouter(NewSkillHandler(lister))+ router := newChatSkillRouter(NewSkillHandler(lister, nil))w := httptest.NewRecorder()router.ServeHTTP(w, httptest.NewRequest(diff --git a/internal/router/router_api_key_capabilities_test.go b/internal/router/router_api_key_capabilities_test.goindex e2b970be7..c9b9c421d 100644--- a/internal/router/router_api_key_capabilities_test.go+++ b/internal/router/router_api_key_capabilities_test.go@@ -429,6 +429,35 @@ func TestSandboxConfigRoutesRequireFullAccessOnly(t *testing.T) {}}+func TestSkillCatalogWriteRoutesRequireFullAccess(t *testing.T) {+ gin.SetMode(gin.TestMode)+ g := &rbacGuards{}+ v1 := gin.New().Group("/api/v1")+ RegisterSkillRoutes(v1, &handler.SkillHandler{}, g)++ cases := []struct {+ method string+ path string+ }{+ {http.MethodPost, "/api/v1/skills/catalog"},+ {http.MethodPost, "/api/v1/skills/catalog/:id/install"},+ {http.MethodGet, "/api/v1/skills/catalog/:id/files"},+ {http.MethodGet, "/api/v1/skills/catalog/:id/files/content"},+ {http.MethodDelete, "/api/v1/skills/catalog/:id"},+ }+ for _, tc := range cases {+ t.Run(tc.method+" "+tc.path, func(t *testing.T) {+ policy := mustLookupAPIKeyPolicy(t, g, tc.method, tc.path)+ if !policy.RequireFullAccess {+ t.Fatal("catalog writes bake into sandbox images and must require full access")+ }+ if len(policy.Capabilities) != 0 {+ t.Fatalf("catalog writes must not be granted by a scoped capability: %#v", policy.Capabilities)+ }+ })+ }+}+func TestTenantMemberRoutesDeclareManageMembersCapability(t *testing.T) {gin.SetMode(gin.TestMode)g := &rbacGuards{}diff --git a/internal/router/routes_agent.go b/internal/router/routes_agent.goindex 37a9158db..e1157b85c 100644--- a/internal/router/routes_agent.go+++ b/internal/router/routes_agent.go@@ -75,8 +75,19 @@ func RegisterUserFavoriteRoutes(r *gin.RouterGroup, h *handler.UserResourceFavorfunc RegisterSkillRoutes(r *gin.RouterGroup, skillHandler *handler.SkillHandler, g *rbacGuards) {skills := r.Group("/skills"){- // List all preloaded skills — Viewer++ // Usable skills for @ mention / chat — Viewer+skills.GET("", g.Viewer(), skillHandler.ListSkills)+ // Catalog reads are Viewer+ so the agent editor can show uninstalled skills.+ skills.GET("/catalog", g.Viewer(), skillHandler.ListCatalog)+ }+ // Catalog writes bake into sandbox images; scoped API keys cannot hold them.+ catalogWrite := g.apiKeyGroup(r.Group("/skills/catalog"), apiKeyFullAccess())+ {+ catalogWrite.POST("", g.Admin(), skillHandler.RegisterCatalog)+ catalogWrite.POST("/:id/install", g.Admin(), skillHandler.InstallCatalog)+ catalogWrite.GET("/:id/files", g.Admin(), skillHandler.ListCatalogFiles)+ catalogWrite.GET("/:id/files/content", g.Admin(), skillHandler.GetCatalogFile)+ catalogWrite.DELETE("/:id", g.Admin(), skillHandler.DeleteCatalog)}}diff --git a/internal/types/tenant_skill.go b/internal/types/tenant_skill.goindex d308e9ba7..25af15d8a 100644--- a/internal/types/tenant_skill.go+++ b/internal/types/tenant_skill.go@@ -50,6 +50,10 @@ type TenantSkillEntity struct {ID string `gorm:"type:varchar(36);primaryKey"`TenantID uint64SandboxConfigID string `gorm:"type:varchar(36)"`+ // CatalogID points at the tenant-level skill definition this install+ // was created from. Empty on rows that predate the catalog migration+ // and have not been backfilled yet.+ CatalogID string `gorm:"type:varchar(36);index"`// Name is the SKILL.md frontmatter name and the directory under// /opt/weknora/tenant/skills. Same-name reinstalls keep this value so the@@ -130,3 +134,23 @@ type TenantSkillSnapshotEntity struct {// TableName pins the table so GORM's pluralizer cannot drift.func (e *TenantSkillSnapshotEntity) TableName() string { return "tenant_skill_snapshots" }++// TenantSkillCatalogEntity is one workspace skill definition. It does not+// belong to a sandbox: installations onto a config's image are TenantSkillEntity+// rows that point back here.+type TenantSkillCatalogEntity struct {+ ID string `gorm:"type:varchar(36);primaryKey"`+ TenantID uint64+ Name string `gorm:"type:varchar(255);not null"`+ Version string `gorm:"type:varchar(64)"`+ Description string `gorm:"type:text"`+ Instructions string `gorm:"type:text"`+ BundleRef string `gorm:"type:varchar(1024)"`+ BundleSHA256 string `gorm:"type:varchar(64)"`+ CreatedAt time.Time+ UpdatedAt time.Time+ DeletedAt gorm.DeletedAt+}++// TableName pins the table so GORM's pluralizer cannot drift.+func (e *TenantSkillCatalogEntity) TableName() string { return "tenant_skill_catalog" }diff --git a/migrations/versioned/000090_skill_catalog.down.sql b/migrations/versioned/000090_skill_catalog.down.sqlnew file mode 100644index 000000000..f6d3c3972--- /dev/null+++ b/migrations/versioned/000090_skill_catalog.down.sql@@ -0,0 +1,5 @@+DO $$ BEGIN RAISE NOTICE '[Migration 000090 down] Dropping skill catalog'; END $$;++DROP INDEX IF EXISTS idx_tenant_skills_catalog;+ALTER TABLE tenant_skills DROP COLUMN IF EXISTS catalog_id;+DROP TABLE IF EXISTS tenant_skill_catalog;diff --git a/migrations/versioned/000090_skill_catalog.up.sql b/migrations/versioned/000090_skill_catalog.up.sqlnew file mode 100644index 000000000..bdb3da657--- /dev/null+++ b/migrations/versioned/000090_skill_catalog.up.sql@@ -0,0 +1,54 @@+-- Description: Tenant-level skill catalog. A skill exists independently of any+-- sandbox; tenant_skills rows become installations onto one config's image.+DO $$ BEGIN RAISE NOTICE '[Migration 000090] Creating tenant_skill_catalog'; END $$;++CREATE TABLE IF NOT EXISTS tenant_skill_catalog (+ id VARCHAR(36) PRIMARY KEY,+ tenant_id BIGINT NOT NULL,+ name VARCHAR(255) NOT NULL,+ version VARCHAR(64),+ description TEXT,+ instructions TEXT,+ bundle_ref VARCHAR(1024),+ bundle_sha256 VARCHAR(64),+ created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),+ updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),+ deleted_at TIMESTAMPTZ+);++COMMENT ON TABLE tenant_skill_catalog IS+ 'Workspace skill definition. Installations onto sandbox configs live in tenant_skills.';++CREATE UNIQUE INDEX IF NOT EXISTS uq_tenant_skill_catalog_name+ ON tenant_skill_catalog (tenant_id, name) WHERE deleted_at IS NULL;++DO $$ BEGIN RAISE NOTICE '[Migration 000090] Linking tenant_skills to catalog'; END $$;++ALTER TABLE tenant_skills ADD COLUMN IF NOT EXISTS catalog_id VARCHAR(36);++CREATE INDEX IF NOT EXISTS idx_tenant_skills_catalog+ ON tenant_skills (catalog_id);++-- One catalog row per (tenant, name), using the oldest live install as the id+-- so existing rows keep a stable identity. Later installs of the same name+-- point at it via catalog_id.+INSERT INTO tenant_skill_catalog (+ id, tenant_id, name, version, description, instructions,+ bundle_ref, bundle_sha256, created_at, updated_at+)+SELECT DISTINCT ON (tenant_id, name)+ id, tenant_id, name, version, description, instructions,+ bundle_ref, bundle_sha256, created_at, updated_at+FROM tenant_skills+WHERE deleted_at IS NULL+ORDER BY tenant_id, name, created_at ASC+ON CONFLICT (id) DO NOTHING;++UPDATE tenant_skills AS s+SET catalog_id = c.id+FROM tenant_skill_catalog AS c+WHERE s.deleted_at IS NULL+ AND c.deleted_at IS NULL+ AND s.tenant_id = c.tenant_id+ AND s.name = c.name+ AND (s.catalog_id IS NULL OR s.catalog_id = '');