feat(sync): 添加 Vault 所有的用户 Skill 记录

This commit is contained in:
2026-09-09 08:39:14 +08:00
parent bdd1543a4d
commit b0783c9356
25 changed files with 1507 additions and 29 deletions
+35
View File
@@ -253,6 +253,41 @@ export interface Skill {
enabled: boolean
}
export type UserSkillStatus = 'ready' | 'dependency_missing' | 'permission_required'
export interface UserSkillData {
version: number
name: string
description: string
prompt: string
tools: string[]
permissions: string[]
retrieval: { top_k: number; rerank: boolean; citation: boolean }
required_capabilities: string[]
created_at_ms: number
updated_at_ms: number
}
export interface UserSkill {
skill_id: string
revision: string
data: UserSkillData
status: UserSkillStatus
missing_dependencies: string[]
undeclared_permissions: string[]
}
export interface UserSkillWriteRequest {
revision: string
name: string
description: string
prompt: string
tools: string[]
permissions: string[]
retrieval: { top_k: number; rerank: boolean; citation: boolean }
required_capabilities: string[]
}
// ============ Plugin ============
export type PluginStatus =
+1 -1
View File
@@ -97,7 +97,7 @@ async function handleOpenCitation(data: Record<string, unknown>) {
<div class="form-grid">
<div class="field"><label>{{ t('模型提供商', 'Model provider') }}</label><select v-model="form.provider_id" class="select"><option v-for="p in providerStore.enabledProviders" :key="p.provider_id" :value="p.provider_id">{{ p.name }}</option></select></div>
<div class="field"><label>{{ t('模型', 'Model') }}</label><input v-model="form.model" class="input" list="agent-models" :placeholder="t('填写模型 ID', 'Enter model ID')" required /><datalist id="agent-models"><option v-for="m in models" :key="m.model_id" :value="m.model_id">{{ m.name }}</option></datalist></div>
<div class="field"><label>{{ t('技能', 'Skill') }}</label><select v-model="form.skill_id" class="select"><option value="">{{ t('不使用技能', 'No skill') }}</option><option v-for="s in skillStore.readySkills" :key="s.skill_id" :value="s.skill_id">{{ s.name }}</option></select></div>
<div class="field"><label>{{ t('技能', 'Skill') }}</label><select v-model="form.skill_id" class="select"><option value="">{{ t('不使用技能', 'No skill') }}</option><optgroup :label="t('已安装 Skill', 'Installed Skills')"><option v-for="s in skillStore.readySkills" :key="s.skill_id" :value="s.skill_id">{{ s.name }}</option></optgroup><optgroup :label="t('当前库的用户 Skill', 'User Skills in this Vault')"><option v-for="s in skillStore.readyUserSkills" :key="s.skill_id" :value="s.skill_id">{{ s.data.name }}</option></optgroup></select></div>
<div class="field"><label>{{ t('最大步骤', 'Maximum steps') }}</label><input v-model.number="form.max_steps" class="input" type="number" min="1" max="100" /></div>
<div class="field"><label>{{ t('工具超时(秒)', 'Tool timeout (seconds)') }}</label><input v-model.number="form.tool_timeout_seconds" class="input" type="number" min="1" /></div>
<div class="field"><label>{{ t('运行超时(秒)', 'Run timeout (seconds)') }}</label><input v-model.number="form.run_timeout_seconds" class="input" type="number" min="1" /></div>
@@ -9,6 +9,7 @@ import ExtensionInstallDialog from '@/components/common/ExtensionInstallDialog.v
import { onMounted, ref } from 'vue'
import { useSkillStore } from '@/stores/skill'
import { t } from '@/i18n'
import UserSkillEditor from './UserSkillEditor.vue'
const skillStore = useSkillStore()
const actionError = ref('')
@@ -31,6 +32,7 @@ async function uninstall(skillId: string, name: string) {
<ActionDialog v-if="actionDialog" v-bind="actionDialog" @resolve="resolveAction" />
<ExtensionInstallDialog v-if="showInstall" kind="Skill" :install="skillStore.installSkill" @close="showInstall = false" @installed="showInstall = false; actionError = ''" />
<header class="feature-header"><div><h1>{{ t('Skill 管理', 'Skill Management') }}</h1><p>{{ t('查看工作流使用的 Tool、权限、检索配置和模型要求。', 'Review the tools, permissions, retrieval settings, and model requirements used by workflows.') }}</p></div><button class="button-primary" @click="showInstall = true">{{ t('安装 Skill', 'Install Skill') }}</button></header>
<UserSkillEditor />
<div v-if="skillStore.error || actionError" class="error-banner">{{ skillStore.error || actionError }}</div>
<div v-if="skillStore.selectedSkill" class="panel detail-panel">
<div class="detail-head"><div><span class="badge" :class="{ success: skillStore.selectedSkill.status === 'ready', error: skillStore.selectedSkill.status === 'error', warning: skillStore.selectedSkill.status.includes('missing') }">{{ skillStore.selectedSkill.status }}</span><h2>{{ skillStore.selectedSkill.icon }} {{ skillStore.selectedSkill.name }}</h2><p class="muted">v{{ skillStore.selectedSkill.version }} · {{ skillStore.selectedSkill.author || t('未知作者', 'Unknown author') }}</p></div><div class="inline-actions"><button class="button-secondary" @click="toggle(skillStore.selectedSkill.skill_id, skillStore.selectedSkill.enabled)">{{ skillStore.selectedSkill.enabled ? t('停用', 'Disable') : t('启用', 'Enable') }}</button><button class="button-danger" @click="uninstall(skillStore.selectedSkill.skill_id, skillStore.selectedSkill.name)">{{ t('卸载', 'Uninstall') }}</button></div></div>
@@ -0,0 +1,97 @@
// @vitest-environment happy-dom
import { beforeEach, expect, it, vi } from 'vitest'
import { flushPromises, mount } from '@vue/test-utils'
import { createPinia, setActivePinia } from 'pinia'
import UserSkillEditor from './UserSkillEditor.vue'
import { useWorkspaceStore } from '@/stores/workspace'
import { useSkillStore } from '@/stores/skill'
import * as service from '@/services/skillService'
import type { UserSkill } from '@/contracts'
vi.mock('@/services/skillService', () => ({
listSkills: vi.fn(), listUserSkills: vi.fn(), createUserSkill: vi.fn(), updateUserSkill: vi.fn(), deleteUserSkill: vi.fn(),
}))
const saved: UserSkill = {
skill_id: 'user_skill_' + '1'.repeat(32), revision: 'a'.repeat(64), status: 'ready',
missing_dependencies: [], undeclared_permissions: [],
data: { version: 1, name: 'Review', description: '', prompt: 'Review carefully', tools: ['notes.read'], permissions: ['notes.read'], retrieval: { top_k: 10, rerank: true, citation: true }, required_capabilities: ['chat'], created_at_ms: 1, updated_at_ms: 1 },
}
beforeEach(() => {
vi.clearAllMocks()
setActivePinia(createPinia())
useWorkspaceStore().vaultId = 'vault-one'
vi.mocked(service.listSkills).mockResolvedValue([])
vi.mocked(service.listUserSkills).mockResolvedValue([])
vi.mocked(service.createUserSkill).mockResolvedValue(saved)
vi.mocked(service.updateUserSkill).mockResolvedValue({ ...saved, revision: 'b'.repeat(64), data: { ...saved.data, version: 2 } })
vi.mocked(service.deleteUserSkill).mockResolvedValue({ status: 'completed' })
})
it('creates a complete declarative record and labels declarations as non-grants', async () => {
const wrapper = mount(UserSkillEditor)
await wrapper.findAll('input.input')[0]!.setValue('Review')
await wrapper.findAll('input.input')[1]!.setValue('notes.read')
await wrapper.get('textarea').setValue('Review carefully')
await wrapper.get('input[value="notes.read"]').setValue(true)
await wrapper.get('input[value="chat"]').setValue(true)
await wrapper.get('form').trigger('submit')
await flushPromises()
expect(service.createUserSkill).toHaveBeenCalledWith(expect.objectContaining({
revision: '', name: 'Review', prompt: 'Review carefully', tools: ['notes.read'],
permissions: ['notes.read'], required_capabilities: ['chat'],
retrieval: { top_k: 10, rerank: true, citation: true },
}), expect.stringMatching(/^[0-9a-f-]{36}$/))
expect(wrapper.text()).toContain('不是设备授权')
expect(useSkillStore().userSkills).toHaveLength(1)
wrapper.unmount()
})
it('does not publish a late save response into a different Vault', async () => {
let finish!: (value: UserSkill) => void
vi.mocked(service.createUserSkill).mockImplementation(() => new Promise(resolve => { finish = resolve }))
const wrapper = mount(UserSkillEditor)
await wrapper.findAll('input.input')[0]!.setValue('Review')
await wrapper.get('form').trigger('submit')
useWorkspaceStore().vaultId = 'vault-two'
await wrapper.vm.$nextTick()
finish(saved)
await flushPromises()
expect(useSkillStore().userSkills).toEqual([])
expect(wrapper.text()).toContain('WORKSPACE_CHANGED')
wrapper.unmount()
})
it('does not publish a late list response into a different Vault', async () => {
let finish!: (value: UserSkill[]) => void
vi.mocked(service.listUserSkills).mockImplementation(() => new Promise(resolve => { finish = resolve }))
const store = useSkillStore()
const loading = store.loadSkills()
useWorkspaceStore().vaultId = 'vault-two'
finish([saved])
await loading
expect(store.userSkills).toEqual([])
})
it('reuses the operation UUID after an ambiguous save failure and changes it with the payload', async () => {
vi.mocked(service.createUserSkill)
.mockRejectedValueOnce(new Error('HOST_TIMEOUT'))
.mockResolvedValueOnce(saved)
.mockRejectedValueOnce(new Error('HOST_TIMEOUT'))
const wrapper = mount(UserSkillEditor)
const name = wrapper.findAll('input.input')[0]!
await name.setValue('Review')
await wrapper.get('form').trigger('submit')
await flushPromises()
const firstOperation = vi.mocked(service.createUserSkill).mock.calls[0]![1]
await wrapper.get('form').trigger('submit')
await flushPromises()
expect(vi.mocked(service.createUserSkill).mock.calls[1]![1]).toBe(firstOperation)
await wrapper.findAll('button').find(button => button.text().includes('清空表单'))!.trigger('click')
await name.setValue('Changed')
await wrapper.get('form').trigger('submit')
await flushPromises()
expect(vi.mocked(service.createUserSkill).mock.calls[2]![1]).not.toBe(firstOperation)
wrapper.unmount()
})
@@ -0,0 +1,168 @@
<script setup lang="ts">
import ActionDialog from '@/components/common/ActionDialog.vue'
import { useActionDialog } from '@/composables/useActionDialog'
import { t } from '@/i18n'
import { useSkillStore } from '@/stores/skill'
import { useWorkspaceStore } from '@/stores/workspace'
import type { UserSkill, UserSkillWriteRequest } from '@/contracts'
import { computed, reactive, ref, watch } from 'vue'
const permissions = [
'notes.read', 'notes.search', 'notes.write', 'notes.delete', 'tasks.read', 'tasks.write',
'attachments.read', 'network.request', 'secrets.use', 'ui.command', 'ui.settings', 'ui.sidebar',
]
const capabilities = [
'chat', 'vision', 'tool_calling', 'reasoning', 'streaming', 'structured_output',
'embedding', 'transcription', 'speaker_matching',
]
const skillStore = useSkillStore()
const workspace = useWorkspaceStore()
const { actionDialog, resolveAction, askConfirm } = useActionDialog()
const editingId = ref<string | null>(null)
const loadedVault = ref(workspace.vaultId)
const busy = ref(false)
const error = ref('')
let pendingSave: { fingerprint: string; operationId: string } | null = null
const pendingDeletes = new Map<string, { revision: string; operationId: string }>()
const editingSkill = computed(() => skillStore.userSkills.find(skill => skill.skill_id === editingId.value) ?? null)
const form = reactive({
revision: '', name: '', description: '', prompt: '', tools: '', permissions: [] as string[],
capabilities: [] as string[], topK: 10, rerank: true, citation: true,
})
function reset() {
editingId.value = null
Object.assign(form, { revision: '', name: '', description: '', prompt: '', tools: '', permissions: [], capabilities: [], topK: 10, rerank: true, citation: true })
error.value = ''
pendingSave = null
}
function edit(skill: UserSkill) {
editingId.value = skill.skill_id
Object.assign(form, {
revision: skill.revision,
name: skill.data.name,
description: skill.data.description,
prompt: skill.data.prompt,
tools: skill.data.tools.join(', '),
permissions: [...skill.data.permissions],
capabilities: [...skill.data.required_capabilities],
topK: skill.data.retrieval.top_k,
rerank: skill.data.retrieval.rerank,
citation: skill.data.retrieval.citation,
})
error.value = ''
pendingSave = null
}
function payload(): UserSkillWriteRequest {
return {
revision: form.revision,
name: form.name,
description: form.description,
prompt: form.prompt,
tools: [...new Set(form.tools.split(',').map(value => value.trim()).filter(Boolean))],
permissions: [...form.permissions],
retrieval: { top_k: form.topK, rerank: form.rerank, citation: form.citation },
required_capabilities: [...form.capabilities],
}
}
async function save() {
const vault = loadedVault.value
if (!vault || workspace.vaultId !== vault) { error.value = t('工作区已切换,请重新加载。', 'The workspace changed; reload the form.'); return }
busy.value = true; error.value = ''
try {
const request = payload()
const fingerprint = JSON.stringify({ vault, skillId: editingId.value, request })
if (pendingSave?.fingerprint !== fingerprint) pendingSave = { fingerprint, operationId: crypto.randomUUID() }
const saved = editingId.value
? await skillStore.updateUserSkill(editingId.value, request, vault, pendingSave.operationId)
: await skillStore.createUserSkill(request, vault, pendingSave.operationId)
if (workspace.vaultId === vault) { pendingSave = null; edit(saved) }
} catch (reason) {
error.value = reason instanceof Error ? reason.message : t('用户 Skill 保存失败', 'Failed to save user Skill')
} finally { busy.value = false }
}
async function remove(skill: UserSkill) {
if (!(await askConfirm(`${t('确定删除用户 Skill', 'Delete user Skill')}${skill.data.name}”?`))) return
const vault = loadedVault.value
if (!vault || workspace.vaultId !== vault) return
busy.value = true; error.value = ''
try {
let pending = pendingDeletes.get(skill.skill_id)
if (!pending || pending.revision !== skill.revision) {
pending = { revision: skill.revision, operationId: crypto.randomUUID() }
pendingDeletes.set(skill.skill_id, pending)
}
await skillStore.deleteUserSkill(skill.skill_id, skill.revision, vault, pending.operationId)
pendingDeletes.delete(skill.skill_id)
if (editingId.value === skill.skill_id) reset()
} catch (reason) {
error.value = reason instanceof Error ? reason.message : t('用户 Skill 删除失败', 'Failed to delete user Skill')
} finally { busy.value = false }
}
watch(() => workspace.vaultId, async vault => {
loadedVault.value = vault; pendingDeletes.clear(); reset()
if (vault) await skillStore.loadSkills()
}, { flush: 'sync' })
</script>
<template>
<section class="panel user-skills">
<ActionDialog v-if="actionDialog" v-bind="actionDialog" @resolve="resolveAction" />
<header class="section-head">
<div><h2>{{ t('当前库的用户 Skill', 'User Skills in this Vault') }}</h2><p class="muted">{{ t('提示词和声明式配置会随当前库同步。设备授权、密钥、安装目录和运行状态不会同步;同步到新设备后仍按该设备的权限策略确认。', 'Prompts and declarative settings sync with this Vault. Device grants, secrets, package paths, and runtime state stay local; the destination device still applies its own permission policy.') }}</p></div>
<button class="button-secondary" :disabled="!workspace.vaultId || busy" @click="reset">{{ t('新建用户 Skill', 'New user Skill') }}</button>
</header>
<div v-if="skillStore.userSkillError || error" class="error-banner">{{ error || skillStore.userSkillError }}</div>
<div v-if="!workspace.vaultId" class="empty-state"><strong>{{ t('请先打开工作区', 'Open a workspace first') }}</strong></div>
<template v-else>
<div class="user-skill-grid">
<button v-for="skill in skillStore.userSkills" :key="skill.skill_id" class="user-skill-card" :class="{ active: editingId === skill.skill_id }" @click="edit(skill)">
<span><strong>{{ skill.data.name }}</strong><small>v{{ skill.data.version }} · {{ skill.status }}</small></span>
<span v-if="skill.missing_dependencies.length" class="badge warning">{{ t('缺少工具', 'Missing tools') }}</span>
<span v-else-if="skill.undeclared_permissions.length" class="badge warning">{{ t('权限声明不足', 'Permission declaration required') }}</span>
<span v-else class="badge success">{{ t('可选择运行', 'Ready to select') }}</span>
</button>
</div>
<form class="user-skill-form" @submit.prevent="save">
<div class="form-grid">
<label class="field"><span>{{ t('名称', 'Name') }}</span><input v-model="form.name" class="input" maxlength="128" required /></label>
<label class="field"><span>{{ t('工具 ID(逗号分隔)', 'Tool IDs (comma-separated)') }}</span><input v-model="form.tools" class="input" maxlength="8256" placeholder="notes.read, notes.search" /></label>
<label class="field wide"><span>{{ t('说明', 'Description') }}</span><input v-model="form.description" class="input" maxlength="2000" /></label>
<label class="field wide"><span>{{ t('系统提示词', 'System prompt') }}</span><textarea v-model="form.prompt" class="textarea prompt" maxlength="64000" rows="8" /></label>
<label class="field"><span>Top K</span><input v-model.number="form.topK" class="input" type="number" min="1" max="100" required /></label>
<div class="field checks"><span>{{ t('检索行为', 'Retrieval behavior') }}</span><label><input v-model="form.rerank" type="checkbox" />{{ t('重排', 'Rerank') }}</label><label><input v-model="form.citation" type="checkbox" />{{ t('引用', 'Citations') }}</label></div>
</div>
<fieldset><legend>{{ t('权限声明(不是设备授权)', 'Permission declarations (not device grants)') }}</legend><label v-for="permission in permissions" :key="permission" class="check"><input v-model="form.permissions" type="checkbox" :value="permission" />{{ permission }}</label></fieldset>
<fieldset><legend>{{ t('模型能力要求', 'Required model capabilities') }}</legend><label v-for="capability in capabilities" :key="capability" class="check"><input v-model="form.capabilities" type="checkbox" :value="capability" />{{ capability }}</label></fieldset>
<div class="inline-actions"><button class="button-primary" :disabled="busy">{{ busy ? t('保存中…', 'Saving…') : t('保存', 'Save') }}</button><button v-if="editingSkill" type="button" class="button-danger" :disabled="busy" @click="remove(editingSkill)">{{ t('删除', 'Delete') }}</button><button type="button" class="button-secondary" :disabled="busy" @click="reset">{{ t('清空表单', 'Clear form') }}</button></div>
</form>
</template>
</section>
</template>
<style scoped>
.user-skills { margin-bottom: var(--space-xl); }
.section-head { display: flex; align-items: flex-start; justify-content: space-between; gap: var(--space-lg); margin-bottom: var(--space-lg); }
.section-head p { max-width: 820px; margin-top: var(--space-xs); line-height: 1.5; }
.user-skill-grid { display: grid; grid-template-columns: repeat(auto-fit, minmax(240px, 1fr)); gap: var(--space-sm); margin-bottom: var(--space-lg); }
.user-skill-card { display: flex; justify-content: space-between; gap: var(--space-sm); align-items: center; padding: var(--space-md); border: 1px solid var(--color-border-default); border-radius: var(--radius-md); background: var(--color-background-secondary); color: inherit; text-align: left; cursor: pointer; }
.user-skill-card.active { border-color: var(--color-accent-primary); box-shadow: 0 0 0 2px var(--color-accent-soft); }
.user-skill-card span:first-child { display: grid; gap: 4px; }
.user-skill-card small { color: var(--color-text-tertiary); }
.form-grid { display: grid; grid-template-columns: repeat(2, minmax(0, 1fr)); gap: var(--space-md); }
.wide { grid-column: 1 / -1; }
.prompt { min-height: 180px; }
.checks { display: flex; flex-wrap: wrap; align-content: start; gap: var(--space-sm); }
.checks > span { flex-basis: 100%; }
.checks label, .check { display: inline-flex; align-items: center; gap: 6px; }
fieldset { margin: var(--space-lg) 0 0; padding: var(--space-md); border: 1px solid var(--color-border-default); border-radius: var(--radius-md); }
legend { padding: 0 var(--space-xs); color: var(--color-text-secondary); }
.check { margin: 6px var(--space-md) 6px 0; }
.inline-actions { margin-top: var(--space-lg); }
@media (max-width: 760px) { .section-head { display: grid; } .form-grid { grid-template-columns: 1fr; } .wide { grid-column: auto; } }
</style>
@@ -0,0 +1,42 @@
import { beforeEach, expect, it, vi } from 'vitest'
import { apiClient } from './apiClient'
import * as service from './skillService'
vi.mock('./apiClient', () => {
const client = { get: vi.fn(), post: vi.fn(), put: vi.fn(), delete: vi.fn(), postBinary: vi.fn() }
return { apiClient: client, default: client }
})
const request = {
revision: '', name: 'Review', description: '', prompt: 'Review carefully', tools: ['notes.read'],
permissions: ['notes.read'], retrieval: { top_k: 10, rerank: true, citation: true }, required_capabilities: ['chat'],
}
beforeEach(() => vi.clearAllMocks())
it('uses dedicated user Skill routes and stable idempotency keys', async () => {
const createOperation = '00000000-0000-4000-8000-000000000001'
const updateOperation = '00000000-0000-4000-8000-000000000002'
const deleteOperation = '00000000-0000-4000-8000-000000000003'
vi.mocked(apiClient.get).mockResolvedValue({ items: [] })
vi.mocked(apiClient.post).mockResolvedValue({})
vi.mocked(apiClient.put).mockResolvedValue({})
vi.mocked(apiClient.delete).mockResolvedValue({ status: 'completed' })
await service.listUserSkills()
await service.createUserSkill(request, createOperation)
await service.updateUserSkill('user_skill_' + '1'.repeat(32), { ...request, revision: 'a'.repeat(64) }, updateOperation)
await service.deleteUserSkill('user_skill_' + '1'.repeat(32), 'b'.repeat(64), deleteOperation)
expect(apiClient.get).toHaveBeenCalledWith('/api/user-skills', { params: { limit: 100, offset: 0 } })
expect(apiClient.post).toHaveBeenCalledWith('/api/user-skills', request, { headers: { 'Idempotency-Key': createOperation } })
expect(apiClient.put).toHaveBeenCalledWith('/api/user-skills/user_skill_' + '1'.repeat(32), expect.objectContaining({ revision: 'a'.repeat(64) }), { headers: { 'Idempotency-Key': updateOperation } })
expect(apiClient.delete).toHaveBeenCalledWith('/api/user-skills/user_skill_' + '1'.repeat(32), { params: { revision: 'b'.repeat(64) }, headers: { 'Idempotency-Key': deleteOperation } })
})
it('loads every bounded Host page instead of silently truncating user Skills', async () => {
const items = Array.from({ length: 101 }, (_, index) => ({ skill_id: `user_skill_${String(index).padStart(32, '0')}` }))
vi.mocked(apiClient.get)
.mockResolvedValueOnce({ items: items.slice(0, 100), page: { total: 101 } })
.mockResolvedValueOnce({ items: items.slice(100), page: { total: 101 } })
expect(await service.listUserSkills()).toHaveLength(101)
expect(apiClient.get).toHaveBeenNthCalledWith(2, '/api/user-skills', { params: { limit: 100, offset: 100 } })
})
+25 -1
View File
@@ -1,5 +1,5 @@
import apiClient from './apiClient'
import type { ApiSkill, OperationResponse, Skill } from '@/contracts'
import type { ApiSkill, OperationResponse, Skill, UserSkill, UserSkillWriteRequest } from '@/contracts'
function toSkill(skill: ApiSkill): Skill {
const { manifest } = skill
@@ -45,3 +45,27 @@ export async function disableSkill(skillId: string): Promise<Skill> {
export async function uninstallSkill(skillId: string): Promise<OperationResponse> {
return apiClient.delete(`/api/skills/${skillId}`)
}
export async function listUserSkills(): Promise<UserSkill[]> {
const items: UserSkill[] = []
for (let page = 0; page < 100; page += 1) {
const response = await apiClient.get<{ items: UserSkill[]; page?: { total: number } }>('/api/user-skills', { params: { limit: 100, offset: items.length } })
items.push(...response.items)
if (!response.items.length || items.length >= (response.page?.total ?? items.length)) return items
}
throw new Error('USER_SKILL_LIST_LIMIT_EXCEEDED')
}
export async function createUserSkill(request: UserSkillWriteRequest, operationId: string = crypto.randomUUID()): Promise<UserSkill> {
return apiClient.post('/api/user-skills', request, { headers: { 'Idempotency-Key': operationId } })
}
export async function updateUserSkill(skillId: string, request: UserSkillWriteRequest, operationId: string = crypto.randomUUID()): Promise<UserSkill> {
return apiClient.put(`/api/user-skills/${skillId}`, request, { headers: { 'Idempotency-Key': operationId } })
}
export async function deleteUserSkill(skillId: string, revision: string, operationId: string = crypto.randomUUID()): Promise<OperationResponse> {
return apiClient.delete(`/api/user-skills/${skillId}`, {
params: { revision }, headers: { 'Idempotency-Key': operationId },
})
}
+51 -5
View File
@@ -1,14 +1,18 @@
import { defineStore } from 'pinia'
import { ref, computed } from 'vue'
import type { Skill } from '@/contracts'
import type { Skill, UserSkill, UserSkillWriteRequest } from '@/contracts'
import * as skillService from '@/services/skillService'
import { t } from '@/i18n'
import { useWorkspaceStore } from '@/stores/workspace'
export const useSkillStore = defineStore('skill', () => {
const workspace = useWorkspaceStore()
const skills = ref<Skill[]>([])
const selectedSkillId = ref<string | null>(null)
const isLoading = ref(false)
const error = ref<string | null>(null)
const userSkills = ref<UserSkill[]>([])
const userSkillError = ref<string | null>(null)
const selectedSkill = computed(() =>
skills.value.find((s) => s.skill_id === selectedSkillId.value) || null
@@ -17,19 +21,55 @@ export const useSkillStore = defineStore('skill', () => {
const enabledSkills = computed(() => skills.value.filter((s) => s.enabled))
const installedSkills = computed(() => skills.value.filter((s) => s.status !== 'error'))
const readySkills = computed(() => skills.value.filter((s) => s.status === 'ready'))
const readyUserSkills = computed(() => userSkills.value.filter((skill) => skill.status === 'ready'))
async function loadSkills() {
isLoading.value = true
const vault = workspace.vaultId
try {
skills.value = await skillService.listSkills()
error.value = null
} catch (reason) {
error.value = reason instanceof Error ? reason.message : t('Skill 加载失败', 'Failed to load Skills')
const [installed, user] = await Promise.allSettled([
skillService.listSkills(), vault ? skillService.listUserSkills() : Promise.resolve([]),
])
if (installed.status === 'fulfilled') { skills.value = installed.value; error.value = null }
else error.value = installed.reason instanceof Error ? installed.reason.message : t('Skill 加载失败', 'Failed to load Skills')
if (workspace.vaultId !== vault) return
if (user.status === 'fulfilled') { userSkills.value = user.value; userSkillError.value = null }
else { userSkills.value = []; userSkillError.value = user.reason instanceof Error ? user.reason.message : t('用户 Skill 加载失败', 'Failed to load user Skills') }
} finally {
isLoading.value = false
}
}
function assertVault(vaultId: string) {
if (!vaultId || workspace.vaultId !== vaultId) throw new Error('WORKSPACE_CHANGED')
}
async function createUserSkill(request: UserSkillWriteRequest, vaultId: string, operationId?: string) {
assertVault(vaultId)
const created = await skillService.createUserSkill(request, operationId)
assertVault(vaultId)
userSkills.value.unshift(created); userSkillError.value = null
return created
}
async function updateUserSkill(skillId: string, request: UserSkillWriteRequest, vaultId: string, operationId?: string) {
assertVault(vaultId)
const updated = await skillService.updateUserSkill(skillId, request, operationId)
assertVault(vaultId)
const index = userSkills.value.findIndex(skill => skill.skill_id === skillId)
if (index >= 0) userSkills.value[index] = updated
userSkillError.value = null
return updated
}
async function deleteUserSkill(skillId: string, revision: string, vaultId: string, operationId?: string) {
assertVault(vaultId)
await skillService.deleteUserSkill(skillId, revision, operationId)
assertVault(vaultId)
userSkills.value = userSkills.value.filter(skill => skill.skill_id !== skillId)
userSkillError.value = null
}
function selectSkill(skillId: string | null) {
selectedSkillId.value = skillId
}
@@ -68,6 +108,9 @@ export const useSkillStore = defineStore('skill', () => {
enabledSkills,
installedSkills,
readySkills,
userSkills,
readyUserSkills,
userSkillError,
isLoading,
error,
loadSkills,
@@ -76,5 +119,8 @@ export const useSkillStore = defineStore('skill', () => {
enableSkill,
disableSkill,
uninstallSkill,
createUserSkill,
updateUserSkill,
deleteUserSkill,
}
})