feat(frontend): 第二阶段前端 Agent Trace / 主题包 / Mermaid 能力

实现第二阶段分工表中吉海燕负责的 P0/P1 前端能力。

- Agent Trace 可视化:新增 traceService 将扁平事件流折叠为树
  (ModelCallStarted 区间内的工具/文本事件挂为子节点,运行级事件保持顶层),
  TraceTimeline 支持时间线/树两种视图、耗时统计与引用跳转。
- 主题包:新增 themePackageService(Web Mock Adapter),
  校验 manifest 必填字段与 theme_id 格式,拒绝远程 css_entry;
  CSS 侧拒绝 @import / expression() / javascript:,
  未通过校验的 CSS 不会注入页面。内置主题走 data-theme=light|dark|sepia,
  自定义主题走 data-theme={theme_id} + 独立 style 节点。
  ThemesView 增加“已安装/社区主题”两个标签页与导入、预览、卸载流程。
- Mermaid:新增 mermaidService(securityLevel: strict)与 MermaidBlock,
  markdown 渲染管线识别 mermaid 代码块;MarkdownContent 随亮/暗主题重渲染
  (SVG 配色在渲染时烘焙,无法靠 CSS 变量事后调整)。
- 插件贡献 UI:PluginsView 增加“概览/命令/设置”标签页,
  PluginSettingsPanel 按 Schema 动态生成表单;
  secret 字段只写不读,仅展示 configured 状态,不进 store 也不回显。

与 main 上队友成果的整合(rebase 时处理):
- 命令面板保留队友基于真实后端的实现(when 条件求值、效果白名单、
  参数命令跳详情页),仅叠加我新增的主题/任务两条内置命令。
- 删除我先前的 pluginContributionService(mock 版),
  统一改用队友已落地的 pluginService 真实接口;
  相应修正表单以匹配真实契约(options 为 string[]、min/max 可空、无 placeholder)。
- 移除 contracts 中与队友重复的 PluginHostStatus / PluginCommand /
  PluginSettingField / PluginSettingsSchema 声明,以队友版本为准。
- PluginsView 概览页保留队友的 PluginMcpPanel,并补回被我改写时丢掉的空状态。

顺带修复:
- 开启 skipLibCheck —— mermaid 11.17 把 type-fest 泄漏进了发布产物的
  .d.ts,但只声明为自身 devDependency,vue-tsc -b 会因此报错。

验证:pnpm test 26 文件 / 113 测试通过(新增 traceService、
themePackageService 两个测试文件共 22 项);pnpm build 通过。
This commit is contained in:
2026-09-04 21:36:47 +08:00
parent 6bdba2c7f9
commit 639f38c1fc
20 changed files with 4487 additions and 669 deletions
+43 -18
View File
@@ -4,8 +4,9 @@ import { useRoute, useRouter } from 'vue-router'
import { useAgentStore } from '@/stores/agent'
import { useProviderStore } from '@/stores/provider'
import { useSkillStore } from '@/stores/skill'
import TraceTimeline from './TraceTimeline.vue'
import type { AgentEvent } from '@/contracts'
import { eventLabel, localizeDetails, permissionLabel, runStatusLabel, toolLabel } from './labels'
import { localizeDetails, permissionLabel, runStatusLabel, toolLabel } from './labels'
import ToolOption from './ToolOption.vue'
const route = useRoute()
@@ -95,15 +96,29 @@ function eventText(event: AgentEvent) {
</form>
<div v-else class="trace-layout">
<div class="panel run-summary"><div><span class="badge info">{{ runStatusLabel(agentStore.activeRun?.status) }}</span><h2>{{ agentStore.activeRunId }}</h2></div><div class="inline-actions"><span>步骤 {{ agentStore.currentStep }} / {{ agentStore.activeRun?.max_steps }}</span><button v-if="agentStore.isRunning" class="button-danger" @click="agentStore.cancelRun(agentStore.activeRunId!)">取消运行</button></div></div>
<div class="timeline">
<article v-for="event in agentStore.events" :key="event.sequence" class="event-card item-card">
<div class="event-head"><span class="badge" :class="{ success: event.event === 'RunCompleted', error: event.event === 'RunFailed', warning: event.event === 'PermissionRequired' }">{{ eventLabel(event.event) }}</span><span> {{ event.sequence }} · {{ new Date(event.timestamp).toLocaleTimeString() }}</span></div>
<p v-if="eventText(event)" class="event-text">{{ eventText(event) }}</p>
<pre v-if="['ToolCall', 'ToolResult', 'Citation', 'Usage'].includes(event.event)">{{ JSON.stringify(localizeDetails(event.data), null, 2) }}</pre>
</article>
<div v-if="!agentStore.events.length" class="empty-state"><div><strong>等待执行轨迹</strong><p>事件连接建立后将在这里实时显示</p></div></div>
<div class="panel run-summary">
<div>
<span class="badge" :class="{
success: agentStore.activeRun?.status === 'completed',
error: agentStore.activeRun?.status === 'failed',
warning: agentStore.activeRun?.status === 'waiting_permission',
info: agentStore.activeRun?.status === 'running' || agentStore.activeRun?.status === 'queued',
}">{{ runStatusLabel(agentStore.activeRun?.status) }}</span>
<h2>{{ agentStore.activeRun?.run_id ?? agentStore.activeRunId }}</h2>
<p v-if="agentStore.activeRun" class="run-meta">
<span>步骤 {{ agentStore.currentStep }} / {{ agentStore.activeRun.max_steps }}</span>
<span>·</span>
<span>Token: {{ agentStore.activeRun.token_usage?.total_tokens ?? 0 }}</span>
<span v-if="agentStore.activeRun.started_at">·</span>
<span v-if="agentStore.activeRun.started_at">开始: {{ new Date(agentStore.activeRun.started_at).toLocaleString() }}</span>
</p>
</div>
<div class="inline-actions">
<button v-if="agentStore.isRunning" class="button-danger" @click="agentStore.cancelRun(agentStore.activeRunId!)">取消运行</button>
<button class="button-secondary" @click="agentStore.loadRun(agentStore.activeRunId!)">重新加载</button>
</div>
</div>
<TraceTimeline :events="agentStore.events" :run-status="agentStore.activeRun?.status" />
</div>
<div v-if="agentStore.permissionRequest" class="modal-backdrop">
@@ -118,14 +133,24 @@ function eventText(event: AgentEvent) {
.tool-grid { display: grid; align-items: start; grid-template-columns: repeat(auto-fit, minmax(230px, 1fr)); gap: var(--space-sm); }
.network { display: flex; gap: var(--space-sm); }
.trace-layout { display: grid; gap: var(--space-lg); }
.run-summary, .event-head { display: flex; align-items: center; justify-content: space-between; gap: var(--space-md); }
.run-summary h2 { margin-top: var(--space-sm); font-family: var(--font-ui-mono); font-size: var(--font-size-lg); }
.timeline { position: relative; display: grid; gap: var(--space-md); padding-left: var(--space-md); }
.timeline::before { content: ''; position: absolute; top: 10px; bottom: 10px; left: 1px; width: 2px; border-radius: var(--radius-full); background: var(--color-border-default); }
.event-card { position: relative; }
.event-card::before { content: ''; position: absolute; top: 20px; left: calc(-1 * var(--space-md) - 5px); width: 8px; height: 8px; border: 2px solid var(--color-surface-primary); border-radius: var(--radius-full); background: var(--color-accent-primary); box-shadow: 0 0 0 1px var(--color-accent-secondary); }
.event-head { color: var(--color-text-tertiary); font-size: var(--font-size-xs); }
.event-text { margin-top: var(--space-md); white-space: pre-wrap; line-height: var(--line-height-relaxed); }
pre { margin-top: var(--space-md); max-height: 260px; overflow: auto; padding: var(--space-md); border-radius: var(--radius-md); background: var(--color-background-secondary); font-family: var(--font-ui-mono); font-size: var(--font-size-xs); white-space: pre-wrap; user-select: text; }
.run-summary {
display: flex;
align-items: flex-start;
justify-content: space-between;
gap: var(--space-md);
}
.run-summary h2 {
margin-top: var(--space-sm);
font-family: var(--font-ui-mono);
font-size: var(--font-size-lg);
word-break: break-all;
}
.run-meta {
display: flex;
gap: var(--space-sm);
margin-top: var(--space-xs);
font-size: var(--font-size-xs);
color: var(--color-text-tertiary);
}
.permission-actions { margin-top: var(--space-lg); }
</style>
@@ -0,0 +1,661 @@
<script setup lang="ts">
import { computed, ref } from 'vue'
import type { TraceNode, AgentEvent } from '@/contracts'
import { buildTraceNodes, getToolCallsFromEvents, getTotalDuration } from '@/services/traceService'
import { eventLabel } from './labels'
const props = defineProps<{
events: AgentEvent[]
runStatus?: string
}>()
const emit = defineEmits<{
(e: 'open-citation', data: Record<string, unknown>): void
}>()
const expandedNodes = ref<Set<string>>(new Set())
const viewMode = ref<'timeline' | 'tree'>('timeline')
const showDetails = ref(true)
const traceNodes = computed(() => buildTraceNodes(props.events))
const toolCalls = computed(() => getToolCallsFromEvents(props.events))
const totalDuration = computed(() => getTotalDuration(props.events))
const summaryStats = computed(() => {
const events = props.events
return {
totalEvents: events.length,
modelCalls: events.filter((e) => e.event === 'ModelCallStarted').length,
toolCalls: events.filter((e) => e.event === 'ToolCall').length,
citations: events.filter((e) => e.event === 'Citation').length,
errors: events.filter((e) => e.event.endsWith('Failed') || e.event === 'RunFailed').length,
}
})
function toggleExpand(nodeId: string) {
if (expandedNodes.value.has(nodeId)) {
expandedNodes.value.delete(nodeId)
} else {
expandedNodes.value.add(nodeId)
}
}
function isExpanded(nodeId: string): boolean {
return expandedNodes.value.has(nodeId)
}
function formatTime(iso: string): string {
const d = new Date(iso)
return d.toLocaleTimeString('zh-CN', { hour12: false }) + '.' + String(d.getMilliseconds()).padStart(3, '0')
}
function formatDuration(ms: number): string {
if (ms < 1000) return `${ms}ms`
if (ms < 60000) return `${(ms / 1000).toFixed(1)}s`
return `${(ms / 60000).toFixed(1)}m`
}
function getNodeIcon(type: TraceNode['type']): string {
const icons: Record<TraceNode['type'], string> = {
run: '▶',
model_call: '🤖',
tool_call: '🔧',
tool_result: '✅',
text: '💬',
thinking: '🧠',
citation: '📚',
usage: '📊',
permission: '🔒',
error: '❌',
complete: '🏁',
}
return icons[type] ?? '•'
}
function getNodeStatusClass(node: TraceNode): string {
switch (node.status) {
case 'running': return 'status-running'
case 'completed': return 'status-completed'
case 'error': return 'status-error'
case 'pending': return 'status-pending'
case 'cancelled': return 'status-cancelled'
default: return 'status-completed'
}
}
function prettyData(data: Record<string, unknown>): string {
const filtered = { ...data }
if (typeof filtered.output === 'string' && filtered.output.length > 500) {
filtered.output = filtered.output.slice(0, 500) + '...'
}
return JSON.stringify(filtered, null, 2)
}
function flatNodes(nodes: TraceNode[], depth = 0): Array<{ node: TraceNode; depth: number }> {
const result: Array<{ node: TraceNode; depth: number }> = []
for (const node of nodes) {
result.push({ node, depth })
if (node.children.length > 0 && isExpanded(node.id)) {
result.push(...flatNodes(node.children, depth + 1))
}
}
return result
}
const flatTrace = computed(() => flatNodes(traceNodes.value))
</script>
<template>
<div class="trace-visualization">
<div class="trace-header">
<div class="trace-stats">
<div class="stat-item">
<span class="stat-value">{{ summaryStats.totalEvents }}</span>
<span class="stat-label">事件</span>
</div>
<div class="stat-item">
<span class="stat-value">{{ summaryStats.modelCalls }}</span>
<span class="stat-label">模型调用</span>
</div>
<div class="stat-item">
<span class="stat-value">{{ summaryStats.toolCalls }}</span>
<span class="stat-label">工具调用</span>
</div>
<div class="stat-item">
<span class="stat-value">{{ summaryStats.citations }}</span>
<span class="stat-label">引用</span>
</div>
<div class="stat-item">
<span class="stat-value duration">{{ totalDuration > 0 ? formatDuration(totalDuration) : '-' }}</span>
<span class="stat-label">总耗时</span>
</div>
</div>
<div class="trace-controls">
<div class="view-toggle">
<button :class="{ active: viewMode === 'timeline' }" @click="viewMode = 'timeline'">时间线</button>
<button :class="{ active: viewMode === 'tree' }" @click="viewMode = 'tree'">树形</button>
</div>
<button class="detail-toggle" @click="showDetails = !showDetails">
{{ showDetails ? '隐藏详情' : '显示详情' }}
</button>
</div>
</div>
<div v-if="viewMode === 'timeline'" class="timeline-view">
<div class="timeline">
<article
v-for="event in events"
:key="event.sequence"
class="event-card"
:class="{ expanded: isExpanded(`event-${event.sequence}`) }"
>
<div class="event-dot" :class="`dot-${event.event}`"></div>
<div class="event-content" @click="toggleExpand(`event-${event.sequence}`)">
<div class="event-header">
<span class="event-badge" :class="{
success: event.event === 'RunCompleted' || event.event === 'ModelCallCompleted',
error: event.event.endsWith('Failed') || event.event === 'RunFailed',
warning: event.event === 'PermissionRequired',
info: event.event === 'ToolCall' || event.event === 'ModelCallStarted',
}">{{ eventLabel(event.event as any) }}</span>
<span class="event-time">{{ formatTime(event.timestamp) }}</span>
</div>
<div v-if="event.data.text || event.data.message" class="event-text">
{{ (event.data.text || event.data.message) as string }}
</div>
<div v-else-if="event.data.name" class="event-name">
<code>{{ event.data.name as string }}</code>
<span v-if="event.data.duration_ms != null" class="event-duration">
{{ formatDuration(event.data.duration_ms as number) }}
</span>
</div>
<div v-if="event.event === 'Usage'" class="event-usage">
<span>输入: {{ event.data.input_tokens ?? '-' }} tokens</span>
<span>输出: {{ event.data.output_tokens ?? '-' }} tokens</span>
<span class="total">总计: {{ event.data.total_tokens ?? '-' }} tokens</span>
</div>
<div v-if="event.event === 'Citation'" class="event-citation" @click.stop="emit('open-citation', event.data)">
<span class="cite-icon">📎</span>
<span>{{ (event.data.heading_path || event.data.note_title || event.data.file_path) as string }}</span>
</div>
<div v-if="event.event === 'PermissionRequired'" class="event-permission">
<span class="perm-label">权限:</span>
<code>{{ event.data.permission as string }}</code>
</div>
</div>
<div v-if="isExpanded(`event-${event.sequence}`) && showDetails" class="event-detail">
<details open>
<summary>完整数据</summary>
<pre>{{ prettyData(event.data) }}</pre>
</details>
</div>
</article>
<div v-if="!events.length" class="empty-state">
<div><strong>等待执行轨迹</strong><p>事件连接建立后将在这里实时显示</p></div>
</div>
</div>
</div>
<div v-else class="tree-view">
<div v-for="item in flatTrace" :key="item.node.id" class="tree-node" :style="{ paddingLeft: `${item.depth * 24 + 8}px` }">
<div class="node-row" :class="getNodeStatusClass(item.node)" @click="item.node.children.length && toggleExpand(item.node.id)">
<span v-if="item.node.children.length" class="expand-icon">
{{ isExpanded(item.node.id) ? '' : '' }}
</span>
<span v-else class="expand-icon placeholder"></span>
<span class="node-icon">{{ getNodeIcon(item.node.type) }}</span>
<span class="node-title">{{ item.node.title }}</span>
<span v-if="item.node.subtitle" class="node-subtitle">{{ item.node.subtitle }}</span>
<span v-if="item.node.duration_ms != null" class="node-duration">
{{ formatDuration(item.node.duration_ms) }}
</span>
</div>
<div v-if="isExpanded(item.node.id) && item.node.children.length === 0 && showDetails" class="node-detail">
<pre>{{ prettyData(item.node.data) }}</pre>
</div>
</div>
<div v-if="!traceNodes.length" class="empty-state">
<div><strong>暂无树形数据</strong><p>运行开始后将展示调用树</p></div>
</div>
</div>
<div v-if="toolCalls.length > 0 && viewMode === 'timeline'" class="tool-calls-summary panel">
<h3 class="panel-title">工具调用统计</h3>
<div class="tool-call-list">
<div v-for="call in toolCalls" :key="call.tool_call_id" class="tool-call-item" :class="call.status">
<span class="tool-status-dot"></span>
<code class="tool-name">{{ call.name }}</code>
<span v-if="call.duration_ms != null" class="tool-duration">
{{ formatDuration(call.duration_ms) }}
</span>
<span class="tool-status-badge" :class="call.status">
{{ call.status === 'completed' ? '成功' : call.status === 'error' ? '失败' : call.status }}
</span>
</div>
</div>
</div>
</div>
</template>
<style scoped>
.trace-visualization {
display: grid;
gap: var(--space-lg);
}
.trace-header {
display: flex;
justify-content: space-between;
align-items: flex-start;
gap: var(--space-md);
flex-wrap: wrap;
}
.trace-stats {
display: flex;
gap: var(--space-lg);
flex-wrap: wrap;
}
.stat-item {
display: flex;
flex-direction: column;
gap: 2px;
}
.stat-value {
font-size: var(--font-size-xl);
font-weight: 600;
color: var(--color-text-primary);
font-variant-numeric: tabular-nums;
}
.stat-value.duration {
color: var(--color-accent-primary);
}
.stat-label {
font-size: var(--font-size-xs);
color: var(--color-text-tertiary);
}
.trace-controls {
display: flex;
gap: var(--space-sm);
align-items: center;
}
.view-toggle {
display: flex;
border: 1px solid var(--color-border-default);
border-radius: var(--radius-md);
overflow: hidden;
}
.view-toggle button {
padding: 4px 12px;
background: var(--color-surface-primary);
border: none;
border-right: 1px solid var(--color-border-default);
color: var(--color-text-secondary);
font-size: var(--font-size-sm);
cursor: pointer;
transition: all var(--motion-fast);
}
.view-toggle button:last-child { border-right: none; }
.view-toggle button.active {
background: var(--color-accent-primary);
color: var(--color-text-inverse);
}
.detail-toggle {
padding: 4px 12px;
background: var(--color-surface-primary);
border: 1px solid var(--color-border-default);
border-radius: var(--radius-md);
color: var(--color-text-secondary);
font-size: var(--font-size-sm);
cursor: pointer;
}
.detail-toggle:hover { border-color: var(--color-accent-secondary); }
.timeline {
position: relative;
display: grid;
gap: var(--space-sm);
padding-left: var(--space-md);
}
.timeline::before {
content: '';
position: absolute;
top: 10px;
bottom: 10px;
left: 7px;
width: 2px;
border-radius: var(--radius-full);
background: var(--color-border-default);
}
.event-card {
position: relative;
padding: var(--space-md);
background: var(--color-surface-primary);
border: 1px solid var(--color-border-default);
border-radius: var(--radius-md);
transition: border-color var(--motion-fast), box-shadow var(--motion-fast);
}
.event-card:hover {
border-color: var(--color-accent-secondary);
box-shadow: var(--shadow-sm);
}
.event-dot {
position: absolute;
top: 18px;
left: -22px;
width: 10px;
height: 10px;
border-radius: 50%;
background: var(--color-accent-primary);
border: 2px solid var(--color-surface-primary);
box-shadow: 0 0 0 1px var(--color-border-default);
}
.dot-RunStarted, .dot-ModelCallStarted { background: var(--color-accent-primary); }
.dot-RunCompleted, .dot-ModelCallCompleted, .dot-ToolResult { background: var(--color-success); }
.dot-RunFailed, .dot-ModelCallFailed { background: var(--color-error); }
.dot-ToolCall { background: var(--color-info); }
.dot-PermissionRequired { background: var(--color-warning); }
.dot-ThinkingDelta { background: var(--color-text-tertiary); }
.dot-TextDelta { background: var(--color-text-secondary); }
.dot-Citation { background: var(--color-accent-secondary); }
.dot-Usage { background: var(--color-text-tertiary); }
.event-content {
cursor: pointer;
}
.event-header {
display: flex;
justify-content: space-between;
align-items: center;
gap: var(--space-sm);
margin-bottom: var(--space-xs);
}
.event-badge {
padding: 2px 8px;
border-radius: var(--radius-full);
font-size: var(--font-size-xs);
font-weight: 500;
background: var(--color-background-tertiary);
color: var(--color-text-secondary);
}
.event-badge.success {
background: var(--color-success-soft);
color: var(--color-success);
}
.event-badge.error {
background: var(--color-error-soft);
color: var(--color-error);
}
.event-badge.warning {
background: var(--color-warning-soft);
color: var(--color-warning);
}
.event-badge.info {
background: var(--color-info-soft);
color: var(--color-info);
}
.event-time {
font-size: var(--font-size-xs);
color: var(--color-text-tertiary);
font-family: var(--font-ui-mono);
}
.event-text {
white-space: pre-wrap;
line-height: var(--line-height-relaxed);
color: var(--color-text-primary);
max-height: 120px;
overflow: hidden;
text-overflow: ellipsis;
}
.event-name {
display: flex;
align-items: center;
gap: var(--space-sm);
}
.event-name code {
padding: 2px 6px;
background: var(--color-background-secondary);
border-radius: var(--radius-sm);
font-family: var(--font-ui-mono);
font-size: var(--font-size-sm);
}
.event-duration {
font-size: var(--font-size-xs);
color: var(--color-text-tertiary);
font-family: var(--font-ui-mono);
}
.event-usage {
display: flex;
gap: var(--space-md);
font-size: var(--font-size-sm);
color: var(--color-text-secondary);
font-family: var(--font-ui-mono);
}
.event-usage .total {
color: var(--color-accent-primary);
font-weight: 500;
}
.event-citation {
display: flex;
align-items: center;
gap: var(--space-xs);
padding: var(--space-xs) var(--space-sm);
background: var(--color-accent-soft);
border-radius: var(--radius-sm);
font-size: var(--font-size-sm);
color: var(--color-accent-primary);
cursor: pointer;
}
.event-citation:hover { text-decoration: underline; }
.event-permission {
display: flex;
align-items: center;
gap: var(--space-sm);
font-size: var(--font-size-sm);
}
.event-permission code {
padding: 2px 6px;
background: var(--color-warning-soft);
color: var(--color-warning);
border-radius: var(--radius-sm);
font-family: var(--font-ui-mono);
}
.event-detail {
margin-top: var(--space-sm);
padding-top: var(--space-sm);
border-top: 1px solid var(--color-border-subtle);
}
.event-detail details summary {
cursor: pointer;
font-size: var(--font-size-sm);
color: var(--color-text-secondary);
}
.event-detail pre {
margin-top: var(--space-sm);
max-height: 300px;
overflow: auto;
padding: var(--space-sm);
border-radius: var(--radius-sm);
background: var(--color-background-secondary);
font-family: var(--font-ui-mono);
font-size: var(--font-size-xs);
white-space: pre-wrap;
word-break: break-all;
}
.tree-view {
padding: var(--space-sm) 0;
border: 1px solid var(--color-border-default);
border-radius: var(--radius-md);
background: var(--color-surface-primary);
}
.tree-node {
border-bottom: 1px solid var(--color-border-subtle);
}
.tree-node:last-child { border-bottom: none; }
.node-row {
display: flex;
align-items: center;
gap: var(--space-xs);
padding: 8px 12px;
cursor: default;
font-size: var(--font-size-sm);
transition: background-color var(--motion-fast);
}
.node-row:hover { background: var(--color-background-hover); }
.node-row.status-running {
background: var(--color-info-soft);
}
.node-row.status-error {
background: var(--color-error-soft);
}
.expand-icon {
width: 16px;
font-size: 10px;
color: var(--color-text-tertiary);
cursor: pointer;
flex-shrink: 0;
}
.expand-icon.placeholder { visibility: hidden; }
.node-icon {
font-size: 14px;
width: 20px;
text-align: center;
flex-shrink: 0;
}
.node-title {
flex: 1;
color: var(--color-text-primary);
font-weight: 500;
}
.node-subtitle {
color: var(--color-text-tertiary);
font-size: var(--font-size-xs);
}
.node-duration {
color: var(--color-text-tertiary);
font-family: var(--font-ui-mono);
font-size: var(--font-size-xs);
}
.node-detail {
padding: 8px 12px 12px 36px;
}
.node-detail pre {
margin: 0;
max-height: 200px;
overflow: auto;
padding: var(--space-sm);
border-radius: var(--radius-sm);
background: var(--color-background-secondary);
font-family: var(--font-ui-mono);
font-size: var(--font-size-xs);
white-space: pre-wrap;
}
.tool-calls-summary { margin-top: var(--space-md); }
.tool-call-list {
display: grid;
gap: var(--space-xs);
}
.tool-call-item {
display: flex;
align-items: center;
gap: var(--space-sm);
padding: 6px 10px;
border-radius: var(--radius-sm);
background: var(--color-background-secondary);
font-size: var(--font-size-sm);
}
.tool-status-dot {
width: 8px;
height: 8px;
border-radius: 50%;
background: var(--color-text-tertiary);
}
.tool-call-item.completed .tool-status-dot { background: var(--color-success); }
.tool-call-item.error .tool-status-dot { background: var(--color-error); }
.tool-call-item.running .tool-status-dot { background: var(--color-info); }
.tool-name {
flex: 1;
font-family: var(--font-ui-mono);
font-size: var(--font-size-xs);
}
.tool-duration {
color: var(--color-text-tertiary);
font-family: var(--font-ui-mono);
font-size: var(--font-size-xs);
}
.tool-status-badge {
padding: 1px 6px;
border-radius: var(--radius-full);
font-size: 11px;
}
.tool-status-badge.completed { background: var(--color-success-soft); color: var(--color-success); }
.tool-status-badge.error { background: var(--color-error-soft); color: var(--color-error); }
.tool-status-badge.running { background: var(--color-info-soft); color: var(--color-info); }
.empty-state {
padding: var(--space-3xl);
text-align: center;
color: var(--color-text-tertiary);
}
.empty-state strong {
display: block;
color: var(--color-text-secondary);
margin-bottom: var(--space-xs);
}
</style>
@@ -0,0 +1,404 @@
<script setup lang="ts">
import { computed, onMounted, reactive, ref, watch } from 'vue'
import type { PluginSettingsSchema, PluginSettingField } from '@/contracts'
import {
getPluginSettings,
updatePluginSettings,
putPluginSecret,
deletePluginSecret,
} from '@/services/pluginService'
const props = defineProps<{
pluginId: string
}>()
const emit = defineEmits<{
(e: 'saved'): void
(e: 'error', message: string): void
}>()
const schema = ref<PluginSettingsSchema | null>(null)
const values = reactive<Record<string, unknown>>({})
const secrets = reactive<Record<string, string>>({})
const isLoading = ref(false)
const isSaving = ref(false)
const saveError = ref('')
const hasChanges = ref(false)
const nonSecretFields = computed(() =>
schema.value?.fields.filter((f) => f.type !== 'secret') ?? []
)
const secretFields = computed(() =>
schema.value?.fields.filter((f) => f.type === 'secret') ?? []
)
async function load() {
isLoading.value = true
saveError.value = ''
try {
schema.value = await getPluginSettings(props.pluginId)
Object.keys(values).forEach((k) => delete values[k])
Object.assign(values, schema.value.values)
hasChanges.value = false
} catch (error) {
emit('error', error instanceof Error ? error.message : '设置加载失败')
} finally {
isLoading.value = false
}
}
async function save() {
if (!schema.value) return
isSaving.value = true
saveError.value = ''
try {
schema.value = await updatePluginSettings(
props.pluginId,
schema.value.schema_version,
{ ...values }
)
hasChanges.value = false
emit('saved')
} catch (error) {
saveError.value = error instanceof Error ? error.message : '保存失败'
} finally {
isSaving.value = false
}
}
async function saveSecret(key: string) {
if (!secrets[key]) return
isSaving.value = true
saveError.value = ''
try {
const result = await putPluginSecret(props.pluginId, key, secrets[key])
if (schema.value) {
schema.value.secrets[key] = { configured: result.configured }
}
secrets[key] = ''
emit('saved')
} catch (error) {
saveError.value = error instanceof Error ? error.message : '密钥保存失败'
} finally {
isSaving.value = false
}
}
async function clearSecret(key: string) {
if (!confirm(`确认删除 " ${key} " 的配置?`)) return
try {
await deletePluginSecret(props.pluginId, key)
if (schema.value) {
schema.value.secrets[key] = { configured: false }
}
emit('saved')
} catch (error) {
saveError.value = error instanceof Error ? error.message : '删除失败'
}
}
function setFieldValue(key: string, value: unknown, field: PluginSettingField) {
if (field.type === 'number') {
const num = Number(value)
if (field.minimum != null && num < field.minimum) return
if (field.maximum != null && num > field.maximum) return
values[key] = num
} else {
values[key] = value
}
hasChanges.value = true
}
onMounted(load)
watch(() => props.pluginId, load)
</script>
<template>
<div class="plugin-settings-panel">
<div v-if="isLoading" class="loading">加载设置中</div>
<template v-else-if="schema && schema.fields.length > 0">
<div v-if="saveError" class="error-banner small">{{ saveError }}</div>
<div v-if="nonSecretFields.length" class="settings-section">
<h4>通用设置</h4>
<div class="form-grid">
<div v-for="field in nonSecretFields" :key="field.key" class="field">
<label>
{{ field.label }}
<span v-if="field.required" class="required">*</span>
</label>
<small v-if="field.description">{{ field.description }}</small>
<input
v-if="field.type === 'string'"
:value="values[field.key] ?? ''"
class="input"
@input="setFieldValue(field.key, ($event.target as HTMLInputElement).value, field)"
/>
<input
v-else-if="field.type === 'number'"
type="number"
:value="values[field.key] ?? field.default ?? 0"
:min="field.minimum ?? undefined"
:max="field.maximum ?? undefined"
class="input"
@input="setFieldValue(field.key, ($event.target as HTMLInputElement).value, field)"
/>
<label v-else-if="field.type === 'boolean'" class="switch-label">
<input
type="checkbox"
:checked="Boolean(values[field.key] ?? field.default)"
@change="setFieldValue(field.key, ($event.target as HTMLInputElement).checked, field)"
/>
<span class="switch-track"><span class="switch-thumb"></span></span>
<span class="switch-text">{{ values[field.key] ? '已启用' : '已禁用' }}</span>
</label>
<select
v-else-if="field.type === 'select'"
:value="String(values[field.key] ?? field.default ?? '')"
class="select"
@change="setFieldValue(field.key, ($event.target as HTMLSelectElement).value, field)"
>
<option v-for="opt in field.options" :key="opt" :value="opt">
{{ opt }}
</option>
</select>
</div>
</div>
<div class="form-actions">
<button
class="button-primary"
:disabled="!hasChanges || isSaving"
@click="save"
>
{{ isSaving ? '保存中…' : '保存设置' }}
</button>
<span v-if="hasChanges" class="unsaved-hint">有未保存的更改</span>
</div>
</div>
<div v-if="secretFields.length" class="settings-section">
<h4>密钥与凭据</h4>
<p class="section-hint">密钥加密存储前端不会回显明文</p>
<div class="form-grid">
<div v-for="field in secretFields" :key="field.key" class="field secret-field">
<label>{{ field.label }}</label>
<small v-if="field.description">{{ field.description }}</small>
<div class="secret-row">
<span
class="secret-status"
:class="schema.secrets[field.key]?.configured ? 'configured' : 'not-configured'"
>
{{ schema.secrets[field.key]?.configured ? '● 已配置' : '○ 未配置' }}
</span>
<template v-if="schema.secrets[field.key]?.configured">
<input
v-model="secrets[field.key]"
type="password"
placeholder="重新输入以更新"
class="input"
/>
<button class="button-secondary" :disabled="!secrets[field.key]" @click="saveSecret(field.key)">
更新
</button>
<button class="link-btn danger" @click="clearSecret(field.key)">清除</button>
</template>
<template v-else>
<input
v-model="secrets[field.key]"
type="password"
placeholder="请输入密钥"
class="input"
/>
<button
class="button-primary"
:disabled="!secrets[field.key]"
@click="saveSecret(field.key)"
>保存</button>
</template>
</div>
</div>
</div>
</div>
</template>
<div v-else class="empty-hint">
<p>此插件没有可配置项</p>
</div>
</div>
</template>
<style scoped>
.plugin-settings-panel {
display: grid;
gap: var(--space-lg);
}
.settings-section h4 {
margin-bottom: var(--space-sm);
font-size: var(--font-size-md);
}
.section-hint {
font-size: var(--font-size-sm);
color: var(--color-text-tertiary);
margin-bottom: var(--space-md);
}
.form-grid {
display: grid;
gap: var(--space-md);
}
.field {
display: grid;
gap: 4px;
}
.field label {
font-size: var(--font-size-sm);
color: var(--color-text-primary);
font-weight: 500;
}
.field small {
color: var(--color-text-tertiary);
font-size: var(--font-size-xs);
}
.required {
color: var(--color-error);
margin-left: 2px;
}
.input, .select {
padding: 6px 10px;
border: 1px solid var(--color-border-default);
border-radius: var(--radius-sm);
background: var(--color-surface-primary);
color: var(--color-text-primary);
font-size: var(--font-size-sm);
width: 100%;
transition: border-color var(--motion-fast);
}
.input:focus, .select:focus {
outline: none;
border-color: var(--color-border-focus);
box-shadow: 0 0 0 2px color-mix(in srgb, var(--color-accent-primary) 15%, transparent);
}
.switch-label {
display: flex;
align-items: center;
gap: var(--space-sm);
cursor: pointer;
font-weight: 400 !important;
}
.switch-label input { display: none; }
.switch-track {
position: relative;
width: 40px;
height: 22px;
border-radius: 11px;
background: var(--color-background-tertiary);
transition: background-color var(--motion-fast);
}
.switch-thumb {
position: absolute;
top: 2px;
left: 2px;
width: 18px;
height: 18px;
border-radius: 50%;
background: var(--color-text-inverse);
box-shadow: 0 1px 3px rgba(0, 0, 0, 0.2);
transition: transform var(--motion-fast);
}
.switch-label input:checked + .switch-track {
background: var(--color-accent-primary);
}
.switch-label input:checked + .switch-track .switch-thumb {
transform: translateX(18px);
}
.switch-text {
font-size: var(--font-size-sm);
color: var(--color-text-secondary);
}
.form-actions {
display: flex;
align-items: center;
gap: var(--space-md);
margin-top: var(--space-md);
}
.unsaved-hint {
font-size: var(--font-size-xs);
color: var(--color-warning);
}
.secret-field .secret-row {
display: flex;
align-items: center;
gap: var(--space-sm);
margin-top: 4px;
}
.secret-status {
font-size: var(--font-size-xs);
padding: 2px 8px;
border-radius: var(--radius-full);
white-space: nowrap;
}
.secret-status.configured {
background: var(--color-success-soft);
color: var(--color-success);
}
.secret-status.not-configured {
background: var(--color-background-tertiary);
color: var(--color-text-tertiary);
}
.secret-row .input {
flex: 1;
min-width: 0;
}
.error-banner.small {
padding: var(--space-sm) var(--space-md);
font-size: var(--font-size-sm);
}
.loading, .empty-hint {
padding: var(--space-xl);
text-align: center;
color: var(--color-text-tertiary);
font-size: var(--font-size-sm);
}
.link-btn {
background: none;
border: none;
color: var(--color-text-secondary);
cursor: pointer;
font-size: var(--font-size-sm);
padding: 0;
}
.link-btn.danger { color: var(--color-error); }
.link-btn:hover { text-decoration: underline; }
</style>
+373 -22
View File
@@ -2,49 +2,400 @@
import { Connection } from '@element-plus/icons-vue'
import AppIcon from '@/components/common/AppIcon.vue'
import PluginMcpPanel from './PluginMcpPanel.vue'
import { onMounted, ref } from 'vue'
import PluginSettingsPanel from './PluginSettingsPanel.vue'
import { computed, onMounted, ref, watch } from 'vue'
import { usePluginStore } from '@/stores/plugin'
import * as pluginService from '@/services/pluginService'
import type { PluginCommand, PluginCommandEffect } from '@/contracts'
const pluginStore = usePluginStore()
const actionError = ref('')
const activeTab = ref<'info' | 'settings' | 'commands'>('info')
const pluginCommands = ref<PluginCommand[]>([])
const commandOutput = ref<Record<string, string>>({})
const isExecutingCommand = ref<string | null>(null)
onMounted(() => { void pluginStore.loadPlugins() })
async function install() { const path = prompt('请输入 Plugin Package 路径')?.trim(); if (!path) return; try { await pluginStore.installPlugin(path) } catch (error) { actionError.value = error instanceof Error ? error.message : '安装失败' } }
async function toggle(id: string, enabled: boolean) { try { enabled ? await pluginStore.disablePlugin(id) : await pluginStore.enablePlugin(id) } catch (error) { actionError.value = error instanceof Error ? error.message : '状态更新失败' } }
async function grant(id: string, permissions: string[]) { if (!confirm(`将授权:${permissions.join('、')}。是否继续?`)) return; try { await pluginStore.grantPermissions(id, permissions) } catch (error) { actionError.value = error instanceof Error ? error.message : '授权失败' } }
async function uninstall(id: string, name: string) { if (!confirm(`卸载“${name}”将移除其全部 Contribution,是否继续?`)) return; try { await pluginStore.uninstallPlugin(id) } catch (error) { actionError.value = error instanceof Error ? error.message : '卸载失败' } }
watch(() => pluginStore.selectedPluginId, async (pluginId) => {
if (pluginId) {
activeTab.value = 'info'
pluginCommands.value = []
commandOutput.value = {}
try {
const allCommands = await pluginService.listPluginCommands()
pluginCommands.value = allCommands.filter((c) => c.plugin_id === pluginId)
} catch { /* 命令加载失败时忽略 */ }
}
})
async function install() {
const path = prompt('请输入 Plugin Package 路径')?.trim()
if (!path) return
try { await pluginStore.installPlugin(path) }
catch (error) { actionError.value = error instanceof Error ? error.message : '安装失败' }
}
async function toggle(id: string, enabled: boolean) {
try {
enabled ? await pluginStore.disablePlugin(id) : await pluginStore.enablePlugin(id)
} catch (error) { actionError.value = error instanceof Error ? error.message : '状态更新失败' }
}
async function grant(id: string, permissions: string[]) {
if (!confirm(`将授权:${permissions.join('、')}。是否继续?`)) return
try { await pluginStore.grantPermissions(id, permissions) }
catch (error) { actionError.value = error instanceof Error ? error.message : '授权失败' }
}
async function uninstall(id: string, name: string) {
if (!confirm(`卸载"${name}"将移除其全部 Contribution,是否继续?`)) return
try { await pluginStore.uninstallPlugin(id) }
catch (error) { actionError.value = error instanceof Error ? error.message : '卸载失败' }
}
async function runCommand(command: PluginCommand) {
isExecutingCommand.value = command.command_id
commandOutput.value[command.command_id] = ''
try {
// Plugin 详情页没有笔记/选区上下文,按契约传空上下文。
const result = await pluginService.executePluginCommand(command.command_id, {}, {})
commandOutput.value[command.command_id] = describeEffect(result.effect)
} catch (error) {
commandOutput.value[command.command_id] = error instanceof Error ? error.message : '执行失败'
} finally {
isExecutingCommand.value = null
}
}
/** 效果白名单:只渲染契约允许的类型,未知类型统一按“已完成”处理。 */
function describeEffect(effect: PluginCommandEffect): string {
switch (effect.type) {
case 'notification':
return effect.payload.message
case 'navigate':
return `命令请求跳转到「${effect.payload.route}`
case 'refresh':
return `命令请求刷新「${effect.payload.scope}`
case 'job':
return `已创建后台任务:${effect.payload.job_id}`
default:
return '命令执行成功'
}
}
const hasSettingsContribution = computed(() =>
pluginStore.selectedPlugin?.contributions.some((c) => c.type === 'settings_section') ?? false
)
const hasCommandContribution = computed(() =>
pluginStore.selectedPlugin?.contributions.some((c) => c.type === 'command') ?? false
)
</script>
<template>
<section class="feature-page">
<header class="feature-header"><div><h1>Plugin MCP</h1><p>管理插件生命周期MCP Host权限和受控 Contribution</p></div><button class="button-primary" @click="install">安装 Plugin</button></header>
<div v-if="pluginStore.error || actionError" class="error-banner">{{ pluginStore.error || actionError }}</div>
<div v-if="pluginStore.selectedPlugin" class="panel">
<div class="detail-head"><div><span class="badge" :class="{ success: pluginStore.selectedPlugin.status === 'ready', error: pluginStore.selectedPlugin.status === 'error', warning: pluginStore.selectedPlugin.status === 'permission_required' }">{{ pluginStore.selectedPlugin.status }}</span><h2>{{ pluginStore.selectedPlugin.icon }} {{ pluginStore.selectedPlugin.name }}</h2><p class="muted">v{{ pluginStore.selectedPlugin.version }} · {{ pluginStore.selectedPlugin.backend_type || 'none' }}/{{ pluginStore.selectedPlugin.transport || 'none' }}</p></div><div class="inline-actions"><button v-if="pluginStore.selectedPlugin.status === 'permission_required'" class="button-primary" @click="grant(pluginStore.selectedPlugin.plugin_id, pluginStore.selectedPlugin.permissions)">授权权限</button><button class="button-secondary" @click="toggle(pluginStore.selectedPlugin.plugin_id, pluginStore.selectedPlugin.enabled)">{{ pluginStore.selectedPlugin.enabled ? '停用' : '启用' }}</button><button class="button-danger" @click="uninstall(pluginStore.selectedPlugin.plugin_id, pluginStore.selectedPlugin.name)">卸载</button></div></div>
<p class="description">{{ pluginStore.selectedPlugin.description }}</p>
<div class="detail-grid"><div><h3>权限</h3><div class="tag-list"><span v-for="permission in pluginStore.selectedPlugin.permissions" :key="permission" class="badge warning">{{ permission }}</span></div></div><div><h3>Contribution</h3><div class="contribution-list"><div v-for="item in pluginStore.selectedPlugin.contributions" :key="item.id" class="item-card"><span class="badge info">{{ item.type }}</span><strong>{{ item.name }}</strong><p class="subtle">{{ item.description || item.id }}</p></div></div></div></div>
<div v-if="pluginStore.selectedPlugin.last_error" class="error-banner last-error">{{ pluginStore.selectedPlugin.last_error }}</div>
<div v-if="pluginStore.selectedPlugin.dependent_skills?.length" class="notice-banner last-error">依赖此插件的 Skill{{ pluginStore.selectedPlugin.dependent_skills.join('') }}</div>
<PluginMcpPanel :plugin="pluginStore.selectedPlugin" />
<header class="feature-header">
<div><h1>Plugin MCP</h1><p>管理插件生命周期MCP Host权限和受控 Contribution</p></div>
<button class="button-primary" @click="install">安装 Plugin</button>
</header>
<div v-if="pluginStore.error || actionError" class="error-banner">
{{ pluginStore.error || actionError }}
</div>
<div v-if="pluginStore.selectedPlugin" class="plugin-detail">
<div class="panel detail-panel">
<div class="detail-head">
<div>
<span class="badge" :class="{
success: pluginStore.selectedPlugin.status === 'ready',
error: pluginStore.selectedPlugin.status === 'error',
warning: pluginStore.selectedPlugin.status === 'permission_required',
info: pluginStore.selectedPlugin.status === 'starting',
}">{{ pluginStore.selectedPlugin.status }}</span>
<h2>{{ pluginStore.selectedPlugin.icon }} {{ pluginStore.selectedPlugin.name }}</h2>
<p class="muted">
v{{ pluginStore.selectedPlugin.version }}
· {{ pluginStore.selectedPlugin.backend_type || 'none' }}/{{ pluginStore.selectedPlugin.transport || 'none' }}
· {{ pluginStore.selectedPlugin.author || '未知作者' }}
</p>
</div>
<div class="inline-actions">
<button
v-if="pluginStore.selectedPlugin.status === 'permission_required'"
class="button-primary"
@click="grant(pluginStore.selectedPlugin.plugin_id, pluginStore.selectedPlugin.permissions)"
>授权权限</button>
<button
class="button-secondary"
@click="toggle(pluginStore.selectedPlugin.plugin_id, pluginStore.selectedPlugin.enabled)"
>{{ pluginStore.selectedPlugin.enabled ? '停用' : '启用' }}</button>
<button
class="button-danger"
@click="uninstall(pluginStore.selectedPlugin.plugin_id, pluginStore.selectedPlugin.name)"
>卸载</button>
</div>
</div>
<p class="description">{{ pluginStore.selectedPlugin.description }}</p>
<div class="detail-tabs">
<button
class="tab-btn"
:class="{ active: activeTab === 'info' }"
@click="activeTab = 'info'"
>概览</button>
<button
v-if="hasCommandContribution"
class="tab-btn"
:class="{ active: activeTab === 'commands' }"
@click="activeTab = 'commands'"
>命令 ({{ pluginCommands.length }})</button>
<button
v-if="hasSettingsContribution || pluginCommands.some(c => c.enabled)"
class="tab-btn"
:class="{ active: activeTab === 'settings' }"
@click="activeTab = 'settings'"
>设置</button>
</div>
<div v-if="activeTab === 'info'" class="tab-content">
<div class="detail-grid">
<div>
<h3>权限</h3>
<div class="tag-list">
<span v-for="permission in pluginStore.selectedPlugin.permissions" :key="permission" class="badge warning">
{{ permission }}
</span>
</div>
</div>
<div>
<h3>Contribution</h3>
<div class="contribution-list">
<div
v-for="item in pluginStore.selectedPlugin.contributions"
:key="item.id"
class="item-card"
>
<span class="badge info">{{ item.type }}</span>
<strong>{{ item.name }}</strong>
<p class="subtle">{{ item.description || item.id }}</p>
</div>
</div>
</div>
</div>
<div v-if="pluginStore.selectedPlugin.last_error" class="error-banner last-error">
{{ pluginStore.selectedPlugin.last_error }}
</div>
<div v-if="pluginStore.selectedPlugin.dependent_skills?.length" class="notice-banner">
依赖此插件的 Skill{{ pluginStore.selectedPlugin.dependent_skills.join('') }}
</div>
<PluginMcpPanel :plugin="pluginStore.selectedPlugin" />
</div>
<div v-else-if="activeTab === 'commands'" class="tab-content">
<div v-if="pluginCommands.length === 0" class="empty-hint">
<p>此插件暂无可执行命令</p>
</div>
<div v-else class="command-list">
<div v-for="cmd in pluginCommands" :key="cmd.command_id" class="command-item">
<div class="command-info">
<strong>{{ cmd.title }}</strong>
<p class="subtle">{{ cmd.description }}</p>
<div class="command-meta">
<code>{{ cmd.command_id }}</code>
<span class="locations">
挂载于: {{ cmd.locations.join(', ') }}
</span>
</div>
</div>
<div class="command-action">
<button
class="button-secondary"
:disabled="!cmd.enabled || isExecutingCommand === cmd.command_id"
@click="runCommand(cmd)"
>
{{ isExecutingCommand === cmd.command_id ? '执行中…' : '运行' }}
</button>
</div>
<div v-if="commandOutput[cmd.command_id]" class="command-output">
{{ commandOutput[cmd.command_id] }}
</div>
</div>
</div>
</div>
<div v-else-if="activeTab === 'settings'" class="tab-content">
<PluginSettingsPanel :plugin-id="pluginStore.selectedPlugin.plugin_id" />
</div>
</div>
</div>
<div v-else-if="!pluginStore.plugins.length" class="empty-state">
<div>
<strong>{{ pluginStore.isLoading ? '正在加载…' : pluginStore.error ? '加载失败' : '尚未安装' }}</strong>
<button class="button-secondary" @click="pluginStore.loadPlugins">重新加载</button>
</div>
</div>
<div v-else class="feature-grid">
<article
v-for="plugin in pluginStore.plugins"
:key="plugin.plugin_id"
class="item-card extension-card"
@click="pluginStore.selectPlugin(plugin.plugin_id)"
>
<div class="extension-title">
<AppIcon :icon="Connection" :size="22" />
<div>
<strong>{{ plugin.name }}</strong>
<p>v{{ plugin.version }}</p>
</div>
<span
class="badge"
:class="{
success: plugin.status === 'ready',
error: plugin.status === 'error',
warning: plugin.status === 'permission_required',
}"
>{{ plugin.status }}</span>
</div>
<p class="muted">{{ plugin.description }}</p>
<p class="subtle">
{{ plugin.permissions.length }} 项权限 · {{ plugin.contributions.length }} Contribution
</p>
</article>
</div>
<div v-else-if="!pluginStore.plugins.length" class="empty-state"><div><strong>{{ pluginStore.isLoading ? '正在加载…' : pluginStore.error ? '加载失败' : '尚未安装' }}</strong><button class="button-secondary" @click="pluginStore.loadPlugins">重新加载</button></div></div>
<div v-else class="feature-grid"><article v-for="plugin in pluginStore.plugins" :key="plugin.plugin_id" class="item-card extension-card" @click="pluginStore.selectPlugin(plugin.plugin_id)"><div class="extension-title"><AppIcon :icon="Connection" :size="22" /><div><strong>{{ plugin.name }}</strong><p>v{{ plugin.version }}</p></div><span class="badge" :class="{ success: plugin.status === 'ready', error: plugin.status === 'error', warning: plugin.status === 'permission_required' }">{{ plugin.status }}</span></div><p class="muted">{{ plugin.description }}</p><p class="subtle">{{ plugin.permissions.length }} 项权限 · {{ plugin.contributions.length }} Contribution</p></article></div>
</section>
</template>
<style scoped>
.detail-head, .extension-title { display: flex; align-items: flex-start; justify-content: space-between; gap: var(--space-md); }
.plugin-detail { display: grid; gap: var(--space-lg); }
.detail-head {
display: flex;
align-items: flex-start;
justify-content: space-between;
gap: var(--space-md);
}
.detail-head h2 { margin-top: var(--space-sm); }
.description { margin: var(--space-xl) 0; line-height: var(--line-height-relaxed); }
.detail-grid { display: grid; grid-template-columns: minmax(220px, .7fr) minmax(320px, 1.3fr); gap: var(--space-xl); }
.detail-head .muted {
color: var(--color-text-tertiary);
font-size: var(--font-size-sm);
margin-top: 4px;
}
.description {
margin: var(--space-xl) 0;
line-height: var(--line-height-relaxed);
}
.detail-tabs {
display: flex;
gap: var(--space-sm);
border-bottom: 1px solid var(--color-border-default);
margin-bottom: var(--space-lg);
}
.tab-btn {
padding: var(--space-sm) var(--space-md);
background: none;
border: none;
border-bottom: 2px solid transparent;
color: var(--color-text-secondary);
cursor: pointer;
font-size: var(--font-size-md);
margin-bottom: -1px;
transition: all var(--motion-fast);
}
.tab-btn:hover { color: var(--color-text-primary); }
.tab-btn.active {
color: var(--color-accent-primary);
border-bottom-color: var(--color-accent-primary);
font-weight: 500;
}
.tab-content { min-height: 200px; }
.detail-grid {
display: grid;
grid-template-columns: minmax(220px, .7fr) minmax(320px, 1.3fr);
gap: var(--space-xl);
}
.detail-grid h3 { margin-bottom: var(--space-sm); }
.contribution-list { display: grid; gap: var(--space-sm); }
.contribution-list .item-card { display: grid; gap: var(--space-xs); }
.tag-list { display: flex; flex-wrap: wrap; gap: 6px; }
.last-error { margin: var(--space-xl) 0 0; }
.notice-banner {
margin-top: var(--space-xl);
padding: var(--space-sm) var(--space-md);
border-radius: var(--radius-md);
background: var(--color-info-soft);
color: var(--color-info);
font-size: var(--font-size-sm);
}
.extension-card { cursor: pointer; }
.extension-card > p { margin-top: var(--space-md); }
.extension-title { align-items: center; }
.extension-title .icon { font-size: 28px; }
.extension-title { display: flex; align-items: center; gap: var(--space-sm); }
.extension-title div { flex: 1; }
.extension-title p { color: var(--color-text-tertiary); font-size: var(--font-size-xs); }
@media (max-width: 800px) { .detail-grid { grid-template-columns: 1fr; } }
.command-list { display: grid; gap: var(--space-sm); }
.command-item {
padding: var(--space-md);
border: 1px solid var(--color-border-default);
border-radius: var(--radius-md);
background: var(--color-surface-primary);
display: grid;
grid-template-columns: 1fr auto;
gap: var(--space-sm) var(--space-md);
align-items: start;
}
.command-info strong { display: block; margin-bottom: 2px; }
.command-info .subtle {
font-size: var(--font-size-sm);
color: var(--color-text-secondary);
margin-bottom: var(--space-xs);
}
.command-meta {
display: flex;
align-items: center;
gap: var(--space-md);
font-size: var(--font-size-xs);
color: var(--color-text-tertiary);
}
.command-meta code {
padding: 1px 6px;
background: var(--color-background-secondary);
border-radius: var(--radius-sm);
font-family: var(--font-ui-mono);
}
.command-output {
grid-column: 1 / -1;
padding: var(--space-sm) var(--space-md);
background: var(--color-background-secondary);
border-radius: var(--radius-sm);
font-size: var(--font-size-sm);
color: var(--color-text-secondary);
white-space: pre-wrap;
}
.empty-hint {
padding: var(--space-2xl);
text-align: center;
color: var(--color-text-tertiary);
font-size: var(--font-size-sm);
}
@media (max-width: 800px) {
.detail-grid { grid-template-columns: 1fr; }
.command-item { grid-template-columns: 1fr; }
}
</style>
+424 -20
View File
@@ -1,57 +1,461 @@
<script setup lang="ts">
import { computed } from 'vue'
import { computed, onMounted, ref } from 'vue'
import MarkdownContent from '@/components/common/MarkdownContent.vue'
import { useThemeStore } from '@/stores/theme'
import { mockCommunityThemes } from '@/services/themePackageService'
import type { ThemePackageInspection } from '@/contracts'
const themeStore = useThemeStore()
const activeTab = ref<'installed' | 'community'>('installed')
const showImportDialog = ref(false)
const previewThemeId = ref<string | null>(null)
const actionError = ref('')
const shikiPreview = `\`\`\`typescript
const notes = await search('本地优先')
\`\`\``
const codeThemeLabel = computed(() => themeStore.resolvedCodeBlockTheme === 'github-dark'
? 'Shiki · GitHub Dark'
: 'Shiki · GitHub Light')
const communityThemes = computed(() => mockCommunityThemes)
function handleFileImport(event: Event) {
const input = event.target as HTMLInputElement
const file = input.files?.[0]
if (!file) return
const reader = new FileReader()
reader.onload = async () => {
const content = reader.result as string
try {
const result = await themeStore.inspectThemePackage(content)
if (result.compatible) {
previewThemeId.value = result.manifest.theme_id
}
} catch (error) {
actionError.value = error instanceof Error ? error.message : '导入失败'
}
}
reader.readAsText(file)
input.value = ''
}
async function confirmInstall(inspection: ThemePackageInspection) {
try {
// Web Mock 模式:使用社区主题的 CSS 作为演示
const cssText = generateThemeCss(inspection.manifest.theme_id, inspection.manifest.is_dark)
await themeStore.installThemeFromInspection(inspection.manifest, cssText)
showImportDialog.value = false
previewThemeId.value = null
} catch (error) {
actionError.value = error instanceof Error ? error.message : '安装失败'
}
}
async function installFromCommunity(themeId: string) {
actionError.value = ''
try {
await themeStore.installCommunityTheme(themeId)
} catch (error) {
actionError.value = error instanceof Error ? error.message : '安装失败'
}
}
function generateThemeCss(themeId: string, isDark: boolean): string {
if (isDark) {
return `[data-theme="${themeId}"] {
--color-background-primary: #1a1b26;
--color-background-secondary: #24283b;
--color-background-tertiary: #2f334d;
--color-background-hover: #2d2f45;
--color-background-active: #3d4261;
--color-surface-primary: #24283b;
--color-surface-secondary: #1a1b26;
--color-surface-elevated: #2f334d;
--color-text-primary: #c0caf5;
--color-text-secondary: #9aa5ce;
--color-text-tertiary: #565f89;
--color-text-link: #7aa2f7;
--color-accent-primary: #7aa2f7;
--color-accent-primary-hover: #89b4fa;
--color-accent-soft: #1e2352;
--color-border-default: #3b3f5c;
--color-border-subtle: #2f334d;
--color-border-focus: #7aa2f7;
--color-success: #9ece6a;
--color-success-soft: #1f2a1a;
--color-warning: #e0af68;
--color-warning-soft: #2d2418;
--color-error: #f7768e;
--color-error-soft: #2d1a1f;
--color-info: #7aa2f7;
--color-info-soft: #1a2030;
}`
}
return `[data-theme="${themeId}"] {
--color-background-primary: #ffffff;
--color-background-secondary: #f8fafc;
--color-background-tertiary: #eef2f7;
--color-background-hover: #f1f5f9;
--color-background-active: #e2e8f0;
--color-surface-primary: #ffffff;
--color-surface-secondary: #fafbfc;
--color-surface-elevated: #ffffff;
--color-text-primary: #1e293b;
--color-text-secondary: #64748b;
--color-text-tertiary: #94a3b8;
--color-text-link: #3b82f6;
--color-accent-primary: #3b82f6;
--color-accent-primary-hover: #2563eb;
--color-accent-soft: #dbeafe;
--color-border-default: #e2e8f0;
--color-border-subtle: #f1f5f9;
--color-border-focus: #3b82f6;
}`
}
function previewCommunity(themeId: string) {
// 临时切换预览
const current = themeStore.currentThemeId
themeStore.applyTheme(themeId)
setTimeout(() => themeStore.applyTheme(current), 1500)
}
onMounted(() => {
themeStore.loadCustomThemes()
})
</script>
<template>
<section class="feature-page">
<header class="feature-header"><div><h1>主题</h1><p>预览并切换 Design Token编辑器偏好会即时生效</p></div><button class="button-secondary" @click="themeStore.resetToDefault">恢复默认</button></header>
<div class="feature-grid themes">
<button v-for="theme in themeStore.themes" :key="theme.theme_id" class="item-card theme-card" :class="{ selected: themeStore.currentThemeId === theme.theme_id }" @click="themeStore.applyTheme(theme.theme_id)">
<div class="theme-preview" :class="`preview-${theme.theme_id}`"><span></span><span></span><span></span><div></div></div>
<div class="theme-info"><div><strong>{{ theme.name }}</strong><p class="subtle">{{ theme.description }}</p></div><span v-if="themeStore.currentThemeId === theme.theme_id" class="badge success">使用中</span></div>
<p class="subtle">v{{ theme.version }} · {{ theme.builtin ? '内置主题' : theme.author }}</p>
<header class="feature-header">
<div>
<h1>主题</h1>
<p>浏览导入和管理主题打造你的知识工作流</p>
</div>
<div class="inline-actions">
<button class="button-secondary" @click="showImportDialog = true">导入主题</button>
<button class="button-secondary" @click="themeStore.resetToDefault()">恢复默认</button>
</div>
</header>
<div v-if="actionError || themeStore.importError" class="error-banner">
{{ actionError || themeStore.importError }}
</div>
<div class="tabs">
<button
class="tab-btn"
:class="{ active: activeTab === 'installed' }"
@click="activeTab = 'installed'"
>已安装</button>
<button
class="tab-btn"
:class="{ active: activeTab === 'community' }"
@click="activeTab = 'community'"
>社区主题</button>
</div>
<div v-if="activeTab === 'installed'" class="feature-grid themes">
<button
v-for="theme in themeStore.allThemes"
:key="theme.theme_id"
class="item-card theme-card"
:class="{ selected: themeStore.currentThemeId === theme.theme_id }"
@click="themeStore.applyTheme(theme.theme_id)"
>
<div class="theme-preview" :class="theme.is_dark ? 'preview-dark' : (theme.theme_id === 'sepia' ? 'preview-sepia' : 'preview-light')">
<span></span><span></span><span></span><div></div>
</div>
<div class="theme-info">
<div>
<strong>{{ theme.name }}</strong>
<p class="subtle">{{ theme.description }}</p>
</div>
<span v-if="themeStore.currentThemeId === theme.theme_id" class="badge success">使用中</span>
</div>
<p class="subtle">
v{{ theme.version }} · {{ theme.builtin ? '内置主题' : theme.author }}
<span v-if="!theme.builtin"> · 自定义</span>
</p>
<div v-if="!theme.builtin" class="theme-actions" @click.stop>
<button class="link-btn danger" @click="themeStore.uninstallTheme(theme.theme_id)">卸载</button>
</div>
</button>
</div>
<div v-else class="feature-grid themes">
<article
v-for="theme in communityThemes"
:key="theme.theme_id"
class="item-card theme-card"
>
<div class="theme-preview" :class="theme.is_dark ? 'preview-dark' : 'preview-light'">
<span></span><span></span><span></span><div></div>
</div>
<div class="theme-info">
<div>
<strong>{{ theme.name }}</strong>
<p class="subtle">{{ theme.description }}</p>
</div>
<span class="badge" :class="theme.is_dark ? 'info' : 'success'">{{ theme.is_dark ? '深色' : '浅色' }}</span>
</div>
<p class="subtle">v{{ theme.version }} · {{ theme.author }}</p>
<div class="theme-tags">
<span v-for="tag in theme.tags" :key="tag" class="tag">{{ tag }}</span>
</div>
<div class="theme-actions">
<button
v-if="themeStore.isThemeInstalled(theme.theme_id)"
class="button-secondary small"
@click="themeStore.applyTheme(theme.theme_id)"
>启用</button>
<template v-else>
<button class="button-secondary small" @click="previewCommunity(theme.theme_id)">预览</button>
<button class="button-primary small" @click="installFromCommunity(theme.theme_id)">安装</button>
</template>
</div>
</article>
</div>
<div class="panel preference-panel">
<h2 class="panel-title">编辑器外观</h2>
<div class="form-grid">
<div class="field"><label>字号{{ themeStore.fontEditorSize }}px</label><input v-model.number="themeStore.fontEditorSize" type="range" min="12" max="24" /></div>
<div class="field"><label>行高{{ themeStore.lineHeight }}</label><input v-model.number="themeStore.lineHeight" type="range" min="1.2" max="2.2" step="0.1" /></div>
<div class="field"><label>字体</label><select v-model="themeStore.fontEditorFamily" class="select"><option value="system-ui">系统字体</option><option value="serif">衬线字体</option><option value="var(--font-ui-mono)">等宽字体</option></select></div>
<div class="field"><label>代码块样式</label><select v-model="themeStore.codeBlockTheme" class="select"><option value="auto">跟随主题</option><option value="github-light">GitHub Light</option><option value="github-dark">GitHub Dark</option></select><small>Markdown 渲染使用对应的 Shiki GitHub 主题</small></div>
<div class="field">
<label>字号{{ themeStore.fontEditorSize }}px</label>
<input v-model.number="themeStore.fontEditorSize" type="range" min="12" max="24" />
</div>
<div class="field">
<label>行高{{ themeStore.lineHeight }}</label>
<input v-model.number="themeStore.lineHeight" type="range" min="1.2" max="2.2" step="0.1" />
</div>
<div class="field">
<label>字体</label>
<select v-model="themeStore.fontEditorFamily" class="select">
<option value="system-ui">系统字体</option>
<option value="serif">衬线字体</option>
<option value="var(--font-ui-mono)">等宽字体</option>
</select>
</div>
<div class="field">
<label>代码块样式</label>
<select v-model="themeStore.codeBlockTheme" class="select">
<option value="auto">跟随主题</option>
<option value="github-light">GitHub Light</option>
<option value="github-dark">GitHub Dark</option>
</select>
<small>Markdown 渲染使用对应的 Shiki GitHub 主题</small>
</div>
</div>
<div class="editor-preview" :style="{ fontSize: `${themeStore.fontEditorSize}px`, lineHeight: themeStore.lineHeight, fontFamily: themeStore.fontEditorFamily }">
<div class="preview-heading"><h3>主题预览</h3><span class="badge info">{{ codeThemeLabel }}</span></div>
<div
class="editor-preview"
:style="{
fontSize: `${themeStore.fontEditorSize}px`,
lineHeight: themeStore.lineHeight,
fontFamily: themeStore.fontEditorFamily,
}"
>
<div class="preview-heading">
<h3>主题预览</h3>
<span class="badge info">{{ codeThemeLabel }}</span>
</div>
<p>知识的价值不只在于保存更在于被重新发现和使用</p>
<MarkdownContent class="code-theme-preview" :source="shikiPreview" />
</div>
</div>
<div v-if="showImportDialog" class="modal-backdrop" @click.self="showImportDialog = false">
<div class="modal import-modal">
<span class="badge info">主题导入</span>
<h2>导入主题包</h2>
<p class="subtle">支持 YAML Manifest + CSS 主题包主题将在安全沙箱中验证后安装</p>
<div v-if="themeStore.pendingInspection?.compatible" class="inspection-result">
<div class="inspect-head">
<strong>{{ themeStore.pendingInspection.manifest.name }}</strong>
<span class="badge success">验证通过</span>
</div>
<div class="inspect-meta">
<span>作者{{ themeStore.pendingInspection.manifest.author }}</span>
<span>版本{{ themeStore.pendingInspection.manifest.version }}</span>
<span>{{ themeStore.pendingInspection.manifest.is_dark ? '深色主题' : '浅色主题' }}</span>
</div>
<p v-if="themeStore.pendingInspection.manifest.description" class="inspect-desc">
{{ themeStore.pendingInspection.manifest.description }}
</p>
<div v-if="themeStore.pendingInspection.warnings.length" class="warnings">
<p v-for="w in themeStore.pendingInspection.warnings" :key="w" class="warning-text"> {{ w }}</p>
</div>
</div>
<div v-else class="upload-area">
<input type="file" accept=".yaml,.yml,.css,.zip" @change="handleFileImport" />
<p>拖放主题包或点击选择文件</p>
<p class="subtle">支持 .yaml / .yml / .css / .zip</p>
</div>
<div class="inline-actions">
<button class="button-secondary" @click="showImportDialog = false">取消</button>
<button
v-if="themeStore.pendingInspection?.compatible"
class="button-primary"
@click="confirmInstall(themeStore.pendingInspection!)"
>安装主题</button>
</div>
</div>
</div>
</section>
</template>
<style scoped>
.themes { margin-bottom: var(--space-xl); }
.theme-card { display: grid; gap: var(--space-md); text-align: left; }
.theme-preview { display: grid; grid-template-columns: 30px 1fr; grid-template-rows: repeat(3, 18px); gap: 6px; height: 120px; padding: var(--space-md); border-radius: var(--radius-md); background: #fff; border: 1px solid #ddd; }
.theme-card { display: grid; gap: var(--space-md); text-align: left; position: relative; }
.theme-preview {
display: grid;
grid-template-columns: 30px 1fr;
grid-template-rows: repeat(3, 18px);
gap: 6px;
height: 120px;
padding: var(--space-md);
border-radius: var(--radius-md);
background: #fff;
border: 1px solid #ddd;
}
.theme-preview span { grid-column: 1; border-radius: 4px; background: #dfe3eb; }
.theme-preview div { grid-column: 2; grid-row: 1 / 4; border-radius: 6px; background: #f4f5f7; }
.preview-dark { background: #0d1117; border-color: #30363d; }.preview-dark span { background: #30363d; }.preview-dark div { background: #161b22; }
.preview-sepia { background: #fbf3df; border-color: #ddcfad; }.preview-sepia span { background: #d8c69c; }.preview-sepia div { background: #f4e8ca; }
.theme-info { display: flex; justify-content: space-between; gap: var(--space-md); }
.preview-dark { background: #0d1117; border-color: #30363d; }
.preview-dark span { background: #30363d; }
.preview-dark div { background: #161b22; }
.preview-sepia { background: #fbf3df; border-color: #ddcfad; }
.preview-sepia span { background: #d8c69c; }
.preview-sepia div { background: #f4e8ca; }
.theme-info { display: flex; justify-content: space-between; gap: var(--space-md); align-items: flex-start; }
.theme-info strong { display: block; margin-bottom: 2px; }
.theme-tags { display: flex; flex-wrap: wrap; gap: 4px; }
.tag {
padding: 2px 8px;
border-radius: var(--radius-full);
background: var(--color-background-tertiary);
color: var(--color-text-secondary);
font-size: var(--font-size-xs);
}
.theme-actions { display: flex; gap: var(--space-sm); margin-top: 4px; }
.button-primary.small, .button-secondary.small {
padding: 4px 12px;
font-size: var(--font-size-sm);
}
.link-btn {
background: none;
border: none;
color: var(--color-text-secondary);
cursor: pointer;
font-size: var(--font-size-sm);
padding: 0;
}
.link-btn.danger { color: var(--color-error); }
.link-btn:hover { text-decoration: underline; }
.tabs {
display: flex;
gap: var(--space-sm);
margin-bottom: var(--space-lg);
border-bottom: 1px solid var(--color-border-default);
}
.tab-btn {
padding: var(--space-sm) var(--space-md);
background: none;
border: none;
border-bottom: 2px solid transparent;
color: var(--color-text-secondary);
cursor: pointer;
font-size: var(--font-size-md);
margin-bottom: -1px;
transition: all var(--motion-fast);
}
.tab-btn:hover { color: var(--color-text-primary); }
.tab-btn.active {
color: var(--color-accent-primary);
border-bottom-color: var(--color-accent-primary);
font-weight: 500;
}
.preference-panel { display: grid; gap: var(--space-xl); }
.editor-preview { padding: var(--space-xl); border: 1px solid var(--color-border-default); border-radius: var(--radius-md); background: var(--color-background-secondary); }
.editor-preview {
padding: var(--space-xl);
border: 1px solid var(--color-border-default);
border-radius: var(--radius-md);
background: var(--color-background-secondary);
}
.editor-preview p { margin: var(--space-sm) 0; }
.preview-heading { display: flex; align-items: center; justify-content: space-between; gap: var(--space-md); }
.preview-heading {
display: flex;
align-items: center;
justify-content: space-between;
gap: var(--space-md);
}
.field small { color: var(--color-text-tertiary); }
.code-theme-preview { margin-top: var(--space-md); }
.import-modal {
width: min(520px, 90vw);
max-height: 80vh;
overflow: auto;
}
.upload-area {
padding: var(--space-2xl);
border: 2px dashed var(--color-border-default);
border-radius: var(--radius-md);
text-align: center;
margin: var(--space-lg) 0;
transition: border-color var(--motion-fast);
}
.upload-area:hover { border-color: var(--color-accent-secondary); }
.upload-area input {
display: block;
margin: 0 auto var(--space-md);
}
.upload-area p { color: var(--color-text-secondary); }
.inspection-result {
padding: var(--space-lg);
border: 1px solid var(--color-border-default);
border-radius: var(--radius-md);
margin: var(--space-lg) 0;
background: var(--color-background-secondary);
}
.inspect-head {
display: flex;
justify-content: space-between;
align-items: center;
margin-bottom: var(--space-sm);
}
.inspect-meta {
display: flex;
flex-wrap: wrap;
gap: var(--space-md);
font-size: var(--font-size-sm);
color: var(--color-text-secondary);
margin-bottom: var(--space-sm);
}
.inspect-desc {
color: var(--color-text-primary);
line-height: var(--line-height-relaxed);
}
.warnings {
margin-top: var(--space-md);
padding-top: var(--space-sm);
border-top: 1px solid var(--color-border-default);
}
.warning-text {
color: var(--color-warning);
font-size: var(--font-size-sm);
}
.inline-actions { margin-top: var(--space-lg); justify-content: flex-end; gap: var(--space-sm); }
</style>