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 11:31:16 +08:00
parent e52e909c41
commit 12869b5e95
20 changed files with 4487 additions and 669 deletions
+1
View File
@@ -32,6 +32,7 @@
"codemirror": "^6.0.0",
"dompurify": "^3.4.14",
"marked": "^15.0.0",
"mermaid": "^11.17.2",
"pinia": "^4.0.0",
"shiki": "^4.4.3",
"vue": "^3.5.0",
+1011 -591
View File
File diff suppressed because it is too large Load Diff
@@ -29,7 +29,9 @@ const builtinCommands = computed<Command[]>(() => [
{ id: 'search', label: '全局搜索', hint: '导航', run: () => router.push('/search') },
{ id: 'chat', label: '打开 AI 对话', hint: '导航', run: () => router.push('/chat') },
{ id: 'agent', label: '创建智能体运行', hint: '导航', run: () => router.push('/agent/runs') },
{ id: 'themes', label: '主题管理', hint: '导航', run: () => router.push('/themes') },
{ id: 'settings', label: '打开设置', hint: '导航', run: () => router.push('/settings') },
{ id: 'tasks', label: '任务列表', hint: '导航', run: () => router.push('/tasks') },
{ id: 'mode', label: `切换为${editorStore.mode === 'source' ? '写作' : '源码'}模式`, hint: '编辑器', run: () => editorStore.toggleMode() },
{ id: 'save', label: '保存当前笔记', hint: '编辑器', run: () => editorStore.save() },
{ id: 'theme', label: `切换为${themeStore.isDark ? '浅色' : '深色'}主题`, hint: '外观', run: () => themeStore.toggleTheme() },
@@ -61,6 +63,7 @@ const filteredCommands = computed(() => {
return value ? commands.value.filter((command) => `${command.label} ${command.hint}`.toLocaleLowerCase().includes(value)) : commands.value
})
function show() {
selectionSnapshot.value = window.getSelection()?.toString() || null
open.value = true
@@ -1,14 +1,19 @@
<script setup lang="ts">
import { ref, watch } from 'vue'
import { computed, ref, watch } from 'vue'
import { renderMarkdown } from '@/utils/markdown'
import { useThemeStore } from '@/stores/theme'
const props = defineProps<{ source: string }>()
const themeStore = useThemeStore()
const html = ref('')
let renderVersion = 0
watch(() => props.source, async (source) => {
const diagramTheme = computed<'light' | 'dark'>(() => (themeStore.isDark ? 'dark' : 'light'))
// 主题切换需要重渲染:Mermaid SVG 的配色在渲染时烘焙,无法靠 CSS 变量事后调整。
watch([() => props.source, diagramTheme], async ([source, theme]) => {
const version = ++renderVersion
const result = await renderMarkdown(source)
const result = await renderMarkdown(source, { theme })
if (version === renderVersion) html.value = result
}, { immediate: true })
</script>
@@ -48,4 +53,27 @@ watch(() => props.source, async (source) => {
font-weight: var(--shiki-dark-font-weight) !important;
text-decoration: var(--shiki-dark-text-decoration) !important;
}
.markdown-content .markdown-mermaid {
overflow: auto;
margin: .85em 0;
padding: 16px;
border: 1px solid var(--color-border-default);
border-radius: 6px;
background: var(--color-surface-primary);
text-align: center;
}
.markdown-content .markdown-mermaid svg {
max-width: 100%;
height: auto;
}
.markdown-content pre.mermaid-error {
padding: 12px 16px;
border: 1px solid var(--color-error);
border-radius: 6px;
background: var(--color-error-soft);
color: var(--color-error);
white-space: pre-wrap;
font-family: var(--font-ui-mono);
font-size: .875em;
}
</style>
@@ -0,0 +1,194 @@
<script setup lang="ts">
import { computed, onMounted, ref, watch } from 'vue'
import { renderMermaid, useMermaidTheme } from '@/services/mermaidService'
const props = defineProps<{
source: string
interactive?: boolean
zoomable?: boolean
}>()
const emit = defineEmits<{
(e: 'error', message: string): void
(e: 'rendered', info: { width: number; height: number }): void
}>()
const { mermaidTheme } = useMermaidTheme()
const svgHtml = ref('')
const isLoading = ref(true)
const hasError = ref(false)
const errorMessage = ref('')
const scale = ref(1)
let renderToken = 0
const canZoom = computed(() => props.zoomable ?? props.interactive ?? false)
async function doRender() {
const token = ++renderToken
isLoading.value = true
hasError.value = false
try {
const result = await renderMermaid(props.source, {
theme: mermaidTheme.value,
mode: props.interactive ? 'interactive' : 'static',
})
if (token !== renderToken) return
svgHtml.value = result.svg
if (result.warnings.length > 0) {
hasError.value = true
errorMessage.value = result.warnings.join('\n')
emit('error', result.warnings[0])
}
emit('rendered', { width: result.width, height: result.height })
} catch (err) {
if (token !== renderToken) return
hasError.value = true
errorMessage.value = err instanceof Error ? err.message : '渲染失败'
emit('error', errorMessage.value)
} finally {
if (token === renderToken) isLoading.value = false
}
}
onMounted(doRender)
watch(() => [props.source, mermaidTheme.value], () => { scale.value = 1; doRender() })
function zoomIn() { scale.value = Math.min(scale.value * 1.2, 5) }
function zoomOut() { scale.value = Math.max(scale.value / 1.2, 0.2) }
function zoomReset() { scale.value = 1 }
</script>
<template>
<div class="mermaid-block" :class="{ interactive, 'has-error': hasError }">
<div v-if="isLoading" class="mermaid-loading">
<span class="loading-spinner"></span>
<span>正在渲染 Mermaid 图表</span>
</div>
<div
v-else
class="mermaid-container"
:style="{ transform: `scale(${scale})`, transformOrigin: 'top left' }"
v-html="svgHtml"
/>
<div v-if="canZoom && !isLoading" class="mermaid-toolbar">
<button class="toolbar-btn" @click="zoomOut" title="缩小"></button>
<span class="zoom-level">{{ Math.round(scale * 100) }}%</span>
<button class="toolbar-btn" @click="zoomIn" title="放大">+</button>
<button class="toolbar-btn" @click="zoomReset" title="重置"></button>
</div>
<div v-if="hasError" class="mermaid-error">
<strong>渲染失败</strong>
<pre>{{ errorMessage }}</pre>
</div>
</div>
</template>
<style scoped>
.mermaid-block {
position: relative;
margin: .85em 0;
padding: var(--space-md);
border: 1px solid var(--color-border-default);
border-radius: var(--radius-md);
background: var(--color-surface-primary);
overflow: auto;
user-select: text;
}
.mermaid-block :deep(svg) {
max-width: 100%;
height: auto;
display: block;
}
.mermaid-container {
transition: transform var(--motion-fast);
}
.mermaid-loading {
display: flex;
align-items: center;
justify-content: center;
gap: var(--space-sm);
padding: var(--space-2xl);
color: var(--color-text-tertiary);
font-size: var(--font-size-sm);
}
.loading-spinner {
width: 16px;
height: 16px;
border: 2px solid var(--color-border-default);
border-top-color: var(--color-accent-primary);
border-radius: 50%;
animation: spin 0.8s linear infinite;
}
@keyframes spin {
to { transform: rotate(360deg); }
}
.mermaid-toolbar {
position: sticky;
bottom: 4px;
left: 0;
right: 0;
display: inline-flex;
align-items: center;
gap: var(--space-xs);
padding: 4px 8px;
margin-top: var(--space-sm);
border-radius: var(--radius-md);
background: var(--color-background-secondary);
border: 1px solid var(--color-border-default);
}
.toolbar-btn {
width: 24px;
height: 24px;
display: inline-flex;
align-items: center;
justify-content: center;
border-radius: var(--radius-sm);
font-size: 14px;
background: var(--color-surface-primary);
border: 1px solid var(--color-border-default);
color: var(--color-text-secondary);
cursor: pointer;
transition: all var(--motion-fast);
}
.toolbar-btn:hover {
border-color: var(--color-accent-secondary);
color: var(--color-accent-primary);
}
.zoom-level {
font-size: var(--font-size-xs);
color: var(--color-text-tertiary);
min-width: 44px;
text-align: center;
font-family: var(--font-ui-mono);
}
.mermaid-error {
margin-top: var(--space-sm);
padding: var(--space-sm) var(--space-md);
border-radius: var(--radius-sm);
background: var(--color-error-soft);
color: var(--color-error);
font-size: var(--font-size-sm);
}
.mermaid-error strong { display: block; margin-bottom: 4px; }
.mermaid-error pre {
margin: 0;
white-space: pre-wrap;
font-family: var(--font-ui-mono);
font-size: var(--font-size-xs);
color: var(--color-text-secondary);
}
.has-error .mermaid-container {
opacity: 0.6;
}
</style>
+102
View File
@@ -792,3 +792,105 @@ export interface ApiIndexJob {
scope: 'all' | 'notes' | 'vectors'
created_at: string
}
// ============ Theme Package (Phase 2) ============
export interface ThemeManifest {
theme_id: string
name: string
version: string
author: string
description?: string
min_app_version: string
is_dark: boolean
css_entry: string
preview?: string
tags?: string[]
homepage?: string
license?: string
}
export interface InstalledTheme {
theme_id: string
name: string
version: string
author: string
description?: string
is_dark: boolean
builtin: boolean
enabled: boolean
installed_at?: string
manifest: ThemeManifest
code_theme?: 'github-light' | 'github-dark'
}
export interface ThemePackageInspection {
package_id: string
manifest: ThemeManifest
preview_url: string
warnings: string[]
compatible: boolean
error_code?: string
}
export type ThemeErrorCode =
| 'THEME_PACKAGE_NOT_FOUND'
| 'THEME_MANIFEST_INVALID'
| 'THEME_PACKAGE_INCOMPATIBLE'
| 'THEME_CSS_INVALID'
| 'THEME_SECURITY_VIOLATION'
| 'THEME_INSTALL_FAILED'
| 'THEME_UNINSTALL_FAILED'
// ============ Mermaid Renderer (Phase 2) ============
export interface MermaidRenderResult {
svg: string
width: number
height: number
warnings: string[]
}
export interface MermaidParseError {
message: string
line?: number
column?: number
}
// ============ Agent Trace Node (Phase 2 visualization) ============
export type TraceNodeType =
| 'run'
| 'model_call'
| 'tool_call'
| 'tool_result'
| 'text'
| 'thinking'
| 'citation'
| 'usage'
| 'permission'
| 'error'
| 'complete'
export interface TraceNode {
id: string
sequence: number
type: TraceNodeType
title: string
subtitle?: string
status: 'pending' | 'running' | 'completed' | 'error' | 'cancelled'
duration_ms?: number
children: TraceNode[]
data: Record<string, unknown>
timestamp: string
parent_id?: string
}
export interface TraceTimelineGroup {
group_id: string
label: string
start_sequence: number
end_sequence: number
duration_ms?: number
nodes: TraceNode[]
}
+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>
+3
View File
@@ -15,3 +15,6 @@ export * as taskService from './taskService'
export * as indexService from './indexService'
export * as systemService from './systemService'
export * as workspaceService from './workspaceService'
export * as themePackageService from './themePackageService'
export * as mermaidService from './mermaidService'
export * as traceService from './traceService'
+126
View File
@@ -0,0 +1,126 @@
import mermaid from 'mermaid'
import { ref, watch } from 'vue'
import { useThemeStore } from '@/stores/theme'
let initialized = false
let initTheme: 'light' | 'dark' = 'light'
function ensureInitialized(theme: 'light' | 'dark') {
if (!initialized) {
mermaid.initialize({
startOnLoad: false,
theme: theme === 'dark' ? 'dark' : 'default',
securityLevel: 'strict',
fontFamily: 'var(--font-ui-sans)',
flowchart: { useMaxWidth: true, htmlLabels: true },
sequence: { useMaxWidth: true },
gantt: { useMaxWidth: true },
})
initialized = true
initTheme = theme
return
}
if (initTheme !== theme) {
mermaid.initialize({
theme: theme === 'dark' ? 'dark' : 'default',
})
initTheme = theme
}
}
export interface MermaidRenderResult {
svg: string
width: number
height: number
warnings: string[]
}
export interface MermaidParseError {
message: string
line?: number
column?: number
}
let renderCounter = 0
export async function renderMermaid(
source: string,
options: { theme?: 'light' | 'dark'; mode?: 'interactive' | 'static' } = {}
): Promise<MermaidRenderResult> {
const theme = options.theme ?? 'light'
ensureInitialized(theme)
const id = `mermaid-${Date.now()}-${++renderCounter}`
try {
const result = await mermaid.render(id, source)
const parser = new DOMParser()
const doc = parser.parseFromString(result.svg, 'image/svg+xml')
const svg = doc.querySelector('svg')
let width = 800
let height = 600
if (svg) {
const viewBox = svg.getAttribute('viewBox')
if (viewBox) {
const parts = viewBox.split(/\s+/).map(Number)
if (parts.length === 4) {
width = parts[2]
height = parts[3]
}
}
const w = svg.getAttribute('width')
const h = svg.getAttribute('height')
if (w && !isNaN(parseFloat(w))) width = parseFloat(w)
if (h && !isNaN(parseFloat(h))) height = parseFloat(h)
}
return {
svg: result.svg,
width,
height,
warnings: [],
}
} catch (error) {
const message = error instanceof Error ? error.message : 'Mermaid 渲染失败'
return {
svg: renderErrorSvg(message),
width: 400,
height: 120,
warnings: [message],
}
}
}
function renderErrorSvg(message: string): string {
return `<svg xmlns="http://www.w3.org/2000/svg" width="400" height="120" viewBox="0 0 400 120">
<rect width="400" height="120" fill="var(--color-error-soft, #ffebe9)" rx="6" />
<text x="20" y="30" font-family="var(--font-ui-mono, monospace)" font-size="13" fill="var(--color-error, #cf222e)" font-weight="600">Mermaid </text>
<text x="20" y="55" font-family="var(--font-ui-mono, monospace)" font-size="12" fill="var(--color-text-secondary, #656d76)">${escapeXml(message).slice(0, 100)}</text>
<text x="20" y="90" font-family="var(--font-ui-sans, sans-serif)" font-size="11" fill="var(--color-text-tertiary, #9198a0)"> flowchartsequenceDiagramclassDiagram </text>
</svg>`
}
function escapeXml(str: string): string {
return str.replace(/[<>&'"]/g, (c) => {
const map: Record<string, string> = { '<': '&lt;', '>': '&gt;', '&': '&amp;', "'": '&apos;', '"': '&quot;' }
return map[c] ?? c
})
}
export function useMermaidTheme() {
const themeStore = useThemeStore()
const mermaidTheme = ref<'light' | 'dark'>(themeStore.isDark ? 'dark' : 'light')
watch(() => themeStore.isDark, (isDark) => {
mermaidTheme.value = isDark ? 'dark' : 'light'
ensureInitialized(mermaidTheme.value)
})
return { mermaidTheme }
}
export async function validateMermaid(source: string): Promise<{ valid: boolean; error?: MermaidParseError }> {
try {
ensureInitialized('light')
await mermaid.parse(source)
return { valid: true }
} catch (error) {
const message = error instanceof Error ? error.message : '未知错误'
return { valid: false, error: { message } }
}
}
@@ -0,0 +1,137 @@
// @vitest-environment happy-dom
import { beforeEach, describe, expect, it } from 'vitest'
import {
inspectThemePackage,
installTheme,
listInstalledThemes,
uninstallTheme,
} from './themePackageService'
import type { ThemeManifest } from '@/contracts'
const validYaml = `
theme_id: ocean-blue
name: 海洋蓝
version: 1.2.0
author: 测试作者
min_app_version: 0.1.0
css_entry: theme.css
is_dark: false
`
function manifest(overrides: Partial<ThemeManifest> = {}): ThemeManifest {
return {
theme_id: 'test-theme',
name: '测试主题',
version: '1.0.0',
author: '作者',
min_app_version: '0.1.0',
is_dark: false,
css_entry: 'theme.css',
...overrides,
}
}
beforeEach(() => {
localStorage.clear()
document.head.querySelectorAll('style[id^="theme-style-"]').forEach((el) => el.remove())
})
describe('inspectThemePackage', () => {
it('解析合法的 manifest 并标记为兼容', async () => {
const result = await inspectThemePackage(validYaml)
expect(result.compatible).toBe(true)
expect(result.manifest.theme_id).toBe('ocean-blue')
expect(result.manifest.name).toBe('海洋蓝')
expect(result.manifest.version).toBe('1.2.0')
expect(result.error_code).toBeUndefined()
})
it('缺少必填字段时返回 THEME_MANIFEST_INVALID 而不是抛错', async () => {
const result = await inspectThemePackage('theme_id: no-name\nversion: 1.0.0\n')
expect(result.compatible).toBe(false)
expect(result.error_code).toBe('THEME_MANIFEST_INVALID')
})
it('theme_id 含非法字符时判定不兼容', async () => {
const result = await inspectThemePackage(validYaml.replace('ocean-blue', 'Ocean Blue!'))
expect(result.compatible).toBe(false)
expect(result.error_code).toBe('THEME_MANIFEST_INVALID')
})
it('css_entry 指向远程地址时判定为安全违规', async () => {
const result = await inspectThemePackage(
validYaml.replace('css_entry: theme.css', 'css_entry: https://evil.example.com/theme.css'),
)
expect(result.compatible).toBe(false)
expect(result.error_code).toBe('THEME_SECURITY_VIOLATION')
})
})
describe('installTheme 的 CSS 安全校验', () => {
it('拒绝含 @import 的 CSS', async () => {
await expect(
installTheme(manifest(), '@import url("https://evil.example.com/x.css");'),
).rejects.toThrow(/THEME_SECURITY_VIOLATION/)
})
it('拒绝含 javascript: 的 CSS', async () => {
await expect(
installTheme(manifest(), '[data-theme="test-theme"] { background: url(javascript:alert(1)); }'),
).rejects.toThrow(/THEME_SECURITY_VIOLATION/)
})
it('拒绝含 expression() 的 CSS', async () => {
await expect(
installTheme(manifest(), '[data-theme="test-theme"] { width: expression(alert(1)); }'),
).rejects.toThrow(/THEME_SECURITY_VIOLATION/)
})
it('不安全的 CSS 不会被注入页面', async () => {
await installTheme(manifest(), '@import "x.css";').catch(() => {})
expect(document.getElementById('theme-style-test-theme')).toBeNull()
})
})
describe('主题安装生命周期', () => {
const safeCss = '[data-theme="test-theme"] { --color-accent-primary: #2f6feb; }'
it('安装后可列出,且默认不启用', async () => {
const installed = await installTheme(manifest(), safeCss)
expect(installed.builtin).toBe(false)
expect(installed.enabled).toBe(false)
const themes = await listInstalledThemes()
expect(themes.map((t) => t.theme_id)).toContain('test-theme')
})
it('安装会把 CSS 注入独立的 style 节点', async () => {
await installTheme(manifest(), safeCss)
const styleEl = document.getElementById('theme-style-test-theme')
expect(styleEl?.textContent).toContain('--color-accent-primary')
})
it('重复安装同一 theme_id 只保留一份', async () => {
await installTheme(manifest(), safeCss)
await installTheme(manifest({ version: '2.0.0' }), safeCss)
const themes = await listInstalledThemes()
expect(themes.filter((t) => t.theme_id === 'test-theme')).toHaveLength(1)
expect(themes.find((t) => t.theme_id === 'test-theme')?.version).toBe('2.0.0')
})
it('卸载会同时移除记录与注入的样式', async () => {
await installTheme(manifest(), safeCss)
await uninstallTheme('test-theme')
const themes = await listInstalledThemes()
expect(themes.map((t) => t.theme_id)).not.toContain('test-theme')
expect(document.getElementById('theme-style-test-theme')).toBeNull()
})
})
@@ -0,0 +1,400 @@
import type { InstalledTheme, ThemeManifest, ThemePackageInspection } from '@/contracts'
const STORAGE_KEY = 'installed-themes'
const ACTIVE_CUSTOM_KEY = 'active-custom-theme'
function loadStoredThemes(): InstalledTheme[] {
try {
const raw = localStorage.getItem(STORAGE_KEY)
return raw ? (JSON.parse(raw) as InstalledTheme[]) : []
} catch {
return []
}
}
function saveThemes(themes: InstalledTheme[]) {
localStorage.setItem(STORAGE_KEY, JSON.stringify(themes))
}
function validateManifest(raw: Record<string, unknown>): { manifest: ThemeManifest; warnings: string[] } {
const warnings: string[] = []
const required = ['theme_id', 'name', 'version', 'author', 'min_app_version', 'css_entry']
for (const field of required) {
if (!raw[field]) {
throw new Error(`THEME_MANIFEST_INVALID: missing required field '${field}'`)
}
}
if (!/^[a-z0-9_-]+$/.test(String(raw.theme_id))) {
throw new Error('THEME_MANIFEST_INVALID: theme_id must match [a-z0-9_-]+')
}
if (!/^\d+\.\d+\.\d+/.test(String(raw.version))) {
warnings.push('版本号格式建议使用 semver(如 1.0.0')
}
const cssEntry = String(raw.css_entry)
if (cssEntry.includes('://') || cssEntry.startsWith('data:')) {
throw new Error('THEME_SECURITY_VIOLATION: css_entry must be a relative path within the package')
}
const manifest: ThemeManifest = {
theme_id: String(raw.theme_id),
name: String(raw.name),
version: String(raw.version),
author: String(raw.author),
description: raw.description ? String(raw.description) : undefined,
min_app_version: String(raw.min_app_version),
is_dark: Boolean(raw.is_dark ?? false),
css_entry: cssEntry,
preview: raw.preview ? String(raw.preview) : undefined,
tags: Array.isArray(raw.tags) ? raw.tags.map(String) : undefined,
homepage: raw.homepage ? String(raw.homepage) : undefined,
license: raw.license ? String(raw.license) : undefined,
}
return { manifest, warnings }
}
function validateCssSafety(css: string): string[] {
const warnings: string[] = []
const lower = css.toLowerCase()
if (lower.includes('@import')) {
throw new Error('THEME_SECURITY_VIOLATION: @import is not allowed in theme CSS')
}
if (lower.includes('url(') && !lower.includes('url(data:')) {
warnings.push('CSS 包含远程资源引用,预览时可能无法加载')
}
if (lower.includes('expression(') || lower.includes('javascript:')) {
throw new Error('THEME_SECURITY_VIOLATION: CSS expressions are not allowed')
}
return warnings
}
function buildCssVarsFromManifest(manifest: ThemeManifest, rawValues: Record<string, string>): string {
const lines: string[] = []
lines.push(`[data-theme="${manifest.theme_id}"] {`)
for (const [key, value] of Object.entries(rawValues)) {
if (key.startsWith('--')) {
lines.push(` ${key}: ${value};`)
}
}
lines.push('}')
return lines.join('\n')
}
function applyThemeCss(themeId: string, css: string) {
let styleEl = document.getElementById(`theme-style-${themeId}`) as HTMLStyleElement | null
if (!styleEl) {
styleEl = document.createElement('style')
styleEl.id = `theme-style-${themeId}`
document.head.appendChild(styleEl)
}
styleEl.textContent = css
}
function removeThemeCss(themeId: string) {
const styleEl = document.getElementById(`theme-style-${themeId}`)
if (styleEl) styleEl.remove()
}
function inspectYamlContent(yamlText: string): ThemeManifest {
const lines = yamlText.split('\n')
const result: Record<string, unknown> = {}
let currentKey: string | null = null
for (const line of lines) {
const trimmed = line.trim()
if (!trimmed || trimmed.startsWith('#')) continue
const match = trimmed.match(/^([a-z_]+):\s*(.*)$/i)
if (match) {
currentKey = match[1]
let value = match[2].trim()
if (value.startsWith('"') && value.endsWith('"')) value = value.slice(1, -1)
else if (value.startsWith("'") && value.endsWith("'")) value = value.slice(1, -1)
else if (value === 'true') result[currentKey] = true
else if (value === 'false') result[currentKey] = false
else if (/^\d+$/.test(value)) result[currentKey] = Number(value)
if (currentKey && !(currentKey in result)) result[currentKey] = value
}
}
const { manifest } = validateManifest(result)
return manifest
}
export async function selectThemePackage(): Promise<string | null> {
return new Promise((resolve) => {
const input = document.createElement('input')
input.type = 'file'
input.accept = '.zip,.yaml,.yml,.css'
input.multiple = false
input.onchange = () => {
const file = input.files?.[0]
if (!file) { resolve(null); return }
const reader = new FileReader()
reader.onload = () => {
resolve(reader.result as string)
}
reader.onerror = () => resolve(null)
if (file.name.endsWith('.yaml') || file.name.endsWith('.yml')) {
reader.readAsText(file)
} else if (file.name.endsWith('.css')) {
reader.readAsText(file)
} else {
reader.readAsDataURL(file)
}
}
input.oncancel = () => resolve(null)
input.click()
})
}
export async function inspectThemePackage(packageData: string): Promise<ThemePackageInspection> {
const package_id = `theme_pkg_${Date.now()}`
try {
const manifest = inspectYamlContent(packageData)
const warnings: string[] = []
if (manifest.css_entry && manifest.css_entry.includes('theme.css')) {
// 示意:Web Mock 假设 CSS 入口存在,真实 Host 会检查包内文件
}
return {
package_id,
manifest,
preview_url: '',
warnings,
compatible: true,
}
} catch (error) {
const message = error instanceof Error ? error.message : '未知错误'
const error_code = message.startsWith('THEME_') ? message.split(':')[0] : 'THEME_MANIFEST_INVALID'
return {
package_id,
manifest: {} as ThemeManifest,
preview_url: '',
warnings: [message],
compatible: false,
error_code,
}
}
}
export async function installTheme(
manifest: ThemeManifest,
cssContent: string,
): Promise<InstalledTheme> {
const warnings = validateCssSafety(cssContent)
if (warnings.length > 0) {
console.warn('[theme] CSS validation warnings:', warnings)
}
applyThemeCss(manifest.theme_id, cssContent)
const installed: InstalledTheme = {
theme_id: manifest.theme_id,
name: manifest.name,
version: manifest.version,
author: manifest.author,
description: manifest.description,
is_dark: manifest.is_dark,
builtin: false,
enabled: false,
installed_at: new Date().toISOString(),
manifest,
code_theme: manifest.is_dark ? 'github-dark' : 'github-light',
}
const existing = loadStoredThemes()
const idx = existing.findIndex((t) => t.theme_id === manifest.theme_id)
if (idx >= 0) existing[idx] = installed
else existing.push(installed)
localStorage.setItem(`${STORAGE_KEY}-css-${manifest.theme_id}`, cssContent)
saveThemes(existing)
return installed
}
export async function listInstalledThemes(): Promise<InstalledTheme[]> {
const themes = loadStoredThemes()
for (const theme of themes) {
if (!theme.builtin) {
const css = localStorage.getItem(`${STORAGE_KEY}-css-${theme.theme_id}`)
if (css) applyThemeCss(theme.theme_id, css)
}
}
return themes
}
export async function enableTheme(themeId: string): Promise<InstalledTheme> {
const themes = loadStoredThemes()
const theme = themes.find((t) => t.theme_id === themeId)
if (!theme) throw new Error('THEME_PACKAGE_NOT_FOUND')
theme.enabled = true
saveThemes(themes)
return theme
}
export async function disableTheme(themeId: string): Promise<void> {
const themes = loadStoredThemes()
const theme = themes.find((t) => t.theme_id === themeId)
if (theme) {
theme.enabled = false
saveThemes(themes)
}
}
export async function uninstallTheme(themeId: string): Promise<void> {
const themes = loadStoredThemes()
const idx = themes.findIndex((t) => t.theme_id === themeId)
if (idx >= 0) {
themes.splice(idx, 1)
saveThemes(themes)
}
removeThemeCss(themeId)
localStorage.removeItem(`${STORAGE_KEY}-css-${themeId}`)
const active = localStorage.getItem(ACTIVE_CUSTOM_KEY)
if (active === themeId) localStorage.removeItem(ACTIVE_CUSTOM_KEY)
}
export function getActiveCustomTheme(): string | null {
return localStorage.getItem(ACTIVE_CUSTOM_KEY)
}
export function setActiveCustomTheme(themeId: string | null) {
if (themeId) localStorage.setItem(ACTIVE_CUSTOM_KEY, themeId)
else localStorage.removeItem(ACTIVE_CUSTOM_KEY)
}
export const mockCommunityThemes: ThemeManifest[] = [
{
theme_id: 'ocean-blue',
name: 'Ocean Blue',
version: '1.2.0',
author: 'community',
description: '宁静的海洋蓝色主题,适合长时间阅读',
min_app_version: '0.2.0',
is_dark: false,
css_entry: 'theme.css',
tags: ['浅色', '蓝色', '阅读'],
license: 'MIT',
},
{
theme_id: 'forest-green',
name: 'Forest Green',
version: '1.0.1',
author: 'nature-collection',
description: '森林绿色护眼主题',
min_app_version: '0.2.0',
is_dark: false,
css_entry: 'theme.css',
tags: ['浅色', '绿色', '护眼'],
license: 'MIT',
},
{
theme_id: 'midnight-purple',
name: 'Midnight Purple',
version: '2.0.0',
author: 'night-owl',
description: '深紫色暗夜主题,适合编码',
min_app_version: '0.2.0',
is_dark: true,
css_entry: 'theme.css',
tags: ['深色', '紫色', '极客'],
license: 'Apache-2.0',
},
{
theme_id: 'solarized-light',
name: 'Solarized Light',
version: '1.1.0',
author: 'solarized',
description: '经典 Solarized 浅色主题',
min_app_version: '0.1.0',
is_dark: false,
css_entry: 'theme.css',
tags: ['浅色', '经典', '阅读'],
license: 'MIT',
},
{
theme_id: 'dracula',
name: 'Dracula',
version: '3.0.0',
author: 'dracula-theme',
description: '流行的 Dracula 暗色主题',
min_app_version: '0.2.0',
is_dark: true,
css_entry: 'theme.css',
tags: ['深色', '紫色', '高对比'],
license: 'MIT',
},
]
function buildCommunityThemeCss(themeId: string, isDark: boolean, accent: string): string {
const palettes: Record<string, { primary: string; soft: string; hover: string }> = {
'ocean-blue': { primary: '#0077b6', soft: '#e0f0fa', hover: '#005f92' },
'forest-green': { primary: '#2d6a4f', soft: '#e8f5ec', hover: '#1b4332' },
'midnight-purple': { primary: '#9d4edd', soft: '#2b1a3e', hover: '#7b2cbf' },
'solarized-light': { primary: '#b58900', soft: '#fdf6e3', hover: '#8a6d0b' },
'dracula': { primary: '#bd93f9', soft: '#2d2a3e', hover: '#a77bf5' },
}
const p = palettes[themeId] ?? palettes['ocean-blue']
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: ${p.primary};
--color-accent-primary: ${p.primary};
--color-accent-primary-hover: ${p.hover};
--color-accent-soft: ${p.soft};
--color-border-default: #3b3f5c;
--color-border-subtle: #2f334d;
--color-border-focus: ${p.primary};
--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: ${p.primary};
--color-accent-primary: ${p.primary};
--color-accent-primary-hover: ${p.hover};
--color-accent-soft: ${p.soft};
--color-border-default: #e2e8f0;
--color-border-subtle: #f1f5f9;
--color-border-focus: ${p.primary};
--color-success: #10b981;
--color-success-soft: #d1fae5;
--color-warning: #f59e0b;
--color-warning-soft: #fef3c7;
--color-error: #ef4444;
--color-error-soft: #fee2e2;
--color-info: #3b82f6;
--color-info-soft: #dbeafe;
}`
}
export async function installCommunityTheme(themeId: string): Promise<InstalledTheme> {
const themeManifest = mockCommunityThemes.find((t) => t.theme_id === themeId)
if (!themeManifest) throw new Error('THEME_PACKAGE_NOT_FOUND')
const css = buildCommunityThemeCss(themeId, themeManifest.is_dark, themeManifest.theme_id)
return installTheme(themeManifest, css)
}
export function getCommunityThemePreviewCss(themeId: string): string {
const t = mockCommunityThemes.find((m) => m.theme_id === themeId)
if (!t) return ''
return buildCommunityThemeCss(themeId, t.is_dark, themeId)
}
+116
View File
@@ -0,0 +1,116 @@
import { describe, expect, it } from 'vitest'
import { buildTraceNodes, getToolCallsFromEvents, getTotalDuration } from './traceService'
import type { AgentEvent, AgentEventType } from '@/contracts'
let sequence = 0
function event(
type: AgentEventType,
data: Record<string, unknown> = {},
timestamp = '2026-01-01T00:00:00.000Z',
): AgentEvent {
return { event: type, sequence: ++sequence, run_id: 'run-1', data, timestamp }
}
describe('buildTraceNodes', () => {
it('把模型调用期间的事件挂到该模型调用之下', () => {
const nodes = buildTraceNodes([
event('RunStarted'),
event('ModelCallStarted', { model: 'mock-1' }),
event('ToolCall', { name: 'read_note' }),
event('ToolResult', { success: true }),
event('ModelCallCompleted', { duration_ms: 1200 }),
event('RunCompleted'),
])
// 顶层只剩:运行开始、模型调用、运行完成
expect(nodes).toHaveLength(3)
const modelCall = nodes[1]
expect(modelCall.type).toBe('model_call')
expect(modelCall.status).toBe('completed')
expect(modelCall.duration_ms).toBe(1200)
expect(modelCall.children.map((c) => c.type)).toEqual(['tool_call', 'tool_result'])
})
it('模型调用失败时标记为 error', () => {
const nodes = buildTraceNodes([
event('ModelCallStarted', { model: 'mock-1' }),
event('ModelCallFailed', { error_code: 'PROVIDER_TIMEOUT' }),
])
expect(nodes).toHaveLength(1)
expect(nodes[0].status).toBe('error')
})
it('运行级事件始终留在顶层,不会被模型调用吞掉', () => {
const nodes = buildTraceNodes([
event('ModelCallStarted', { model: 'mock-1' }),
event('RunFailed', { error_code: 'RUN_TIMEOUT' }),
])
expect(nodes.map((n) => n.type)).toEqual(['model_call', 'error'])
})
it('模型调用之外的事件保持在顶层', () => {
const nodes = buildTraceNodes([
event('RunStarted'),
event('ToolCall', { name: 'search' }),
event('RunCompleted'),
])
expect(nodes).toHaveLength(3)
expect(nodes.every((n) => n.children.length === 0)).toBe(true)
})
it('空事件列表返回空树', () => {
expect(buildTraceNodes([])).toEqual([])
})
})
describe('getToolCallsFromEvents', () => {
it('按 tool_call_id 配对 ToolCall 与 ToolResult', () => {
const calls = getToolCallsFromEvents([
event('ToolCall', { tool_call_id: 'c1', name: 'read_note' }),
event('ToolResult', { tool_call_id: 'c1', success: true, duration_ms: 40 }),
])
expect(calls).toHaveLength(1)
expect(calls[0].name).toBe('read_note')
expect(calls[0].status).toBe('completed')
expect(calls[0].duration_ms).toBe(40)
})
it('工具失败时状态为 error', () => {
const calls = getToolCallsFromEvents([
event('ToolCall', { tool_call_id: 'c2', name: 'write_note' }),
event('ToolResult', { tool_call_id: 'c2', success: false, error_code: 'TOOL_DENIED' }),
])
expect(calls[0].status).toBe('error')
})
it('尚未返回结果的工具调用保持 running', () => {
const calls = getToolCallsFromEvents([
event('ToolCall', { tool_call_id: 'c9', name: 'write_note' }),
])
expect(calls).toHaveLength(1)
expect(calls[0].status).toBe('running')
})
})
describe('getTotalDuration', () => {
it('返回首尾事件的时间差', () => {
const duration = getTotalDuration([
event('RunStarted', {}, '2026-01-01T00:00:00.000Z'),
event('RunCompleted', {}, '2026-01-01T00:00:02.500Z'),
])
expect(duration).toBe(2500)
})
it('单个事件或空列表时为 0', () => {
expect(getTotalDuration([])).toBe(0)
expect(getTotalDuration([event('RunStarted')])).toBe(0)
})
})
+252
View File
@@ -0,0 +1,252 @@
import type { AgentEvent, TraceNode, TraceNodeType } from '@/contracts'
export function buildTraceNodes(events: AgentEvent[]): TraceNode[] {
const nodes: TraceNode[] = []
let currentModelCallId: string | null = null
for (const event of events) {
const type = mapEventType(event.event)
const id = `seq-${event.sequence}`
const title = getNodeTitle(event)
const subtitle = getNodeSubtitle(event)
const status = getNodeStatus(event)
const node: TraceNode = {
id,
sequence: event.sequence,
type,
title,
subtitle,
status,
data: event.data,
timestamp: event.timestamp,
children: [],
}
if (event.event === 'ModelCallStarted') {
currentModelCallId = id
node.children = []
nodes.push(node)
continue
}
if (event.event === 'ModelCallCompleted' || event.event === 'ModelCallFailed') {
if (currentModelCallId) {
const modelCall = findNodeById(nodes, currentModelCallId)
if (modelCall) {
modelCall.status = event.event === 'ModelCallCompleted' ? 'completed' : 'error'
if (event.data.duration_ms != null) {
modelCall.duration_ms = event.data.duration_ms as number
}
if (event.data.finish_reason) {
modelCall.subtitle = `${modelCall.subtitle ?? ''} · ${String(event.data.finish_reason)}`
}
}
currentModelCallId = null
}
continue
}
if (currentModelCallId && type !== 'run' && type !== 'complete' && type !== 'error') {
const parent = findNodeById(nodes, currentModelCallId)
if (parent) {
node.parent_id = currentModelCallId
parent.children.push(node)
continue
}
}
nodes.push(node)
}
return nodes
}
function findNodeById(nodes: TraceNode[], id: string): TraceNode | null {
for (const node of nodes) {
if (node.id === id) return node
const found = findNodeById(node.children, id)
if (found) return found
}
return null
}
function mapEventType(eventType: AgentEvent['event']): TraceNodeType {
switch (eventType) {
case 'RunStarted': return 'run'
case 'RunCompleted': return 'complete'
case 'RunFailed': return 'error'
case 'RunCancelled': return 'complete'
case 'ModelCallStarted':
case 'ModelCallCompleted':
case 'ModelCallFailed':
return 'model_call'
case 'ToolCall': return 'tool_call'
case 'ToolResult': return 'tool_result'
case 'TextDelta': return 'text'
case 'ThinkingDelta': return 'thinking'
case 'Citation': return 'citation'
case 'Usage': return 'usage'
case 'PermissionRequired':
case 'PermissionResolved':
return 'permission'
default: return 'text'
}
}
function getNodeTitle(event: AgentEvent): string {
switch (event.event) {
case 'RunStarted': return '运行开始'
case 'RunCompleted': return '运行完成'
case 'RunFailed': return '运行失败'
case 'RunCancelled': return '运行已取消'
case 'ModelCallStarted': return '模型调用'
case 'ModelCallCompleted': return '模型调用完成'
case 'ModelCallFailed': return '模型调用失败'
case 'ToolCall': return `工具调用:${event.data.name ?? '未知工具'}`
case 'ToolResult': return `工具结果:${event.data.name ?? '未知工具'}`
case 'TextDelta': return '回复文本'
case 'ThinkingDelta': return '思考中'
case 'Citation': return '引用来源'
case 'Usage': return 'Token 用量'
case 'PermissionRequired': return '需要权限确认'
case 'PermissionResolved': return '权限已处理'
default: return event.event
}
}
function getNodeSubtitle(event: AgentEvent): string | undefined {
const data = event.data
switch (event.event) {
case 'ModelCallStarted':
return [data.provider_id, data.model].filter(Boolean).join(' / ') || undefined
case 'ModelCallCompleted':
if (data.duration_ms != null) return `耗时 ${formatDuration(data.duration_ms as number)}`
return undefined
case 'ToolCall':
return `调用 ${data.name ?? 'unknown'}`
case 'ToolResult':
if (data.duration_ms != null) return `耗时 ${formatDuration(data.duration_ms as number)}`
if (data.success) return '成功'
return data.error_code ? `错误:${data.error_code}` : undefined
case 'Citation':
return data.heading_path ? String(data.heading_path) : undefined
case 'Usage': {
// total_tokens 优先;缺失时回退到 input+output 之和。
const total = asNumber(data.total_tokens)
if (total != null) return `${total} tokens`
const input = asNumber(data.input_tokens)
const output = asNumber(data.output_tokens)
if (input == null && output == null) return '- tokens'
return `${(input ?? 0) + (output ?? 0)} tokens`
}
case 'PermissionRequired':
return String(data.permission ?? '')
case 'PermissionResolved':
return String(data.decision ?? '')
default:
return undefined
}
}
function getNodeStatus(event: AgentEvent): TraceNode['status'] {
switch (event.event) {
case 'RunFailed':
case 'ModelCallFailed':
return 'error'
case 'RunCompleted':
case 'RunCancelled':
case 'ModelCallCompleted':
case 'ToolResult':
case 'Usage':
case 'PermissionResolved':
return 'completed'
case 'ToolCall':
if (event.data.status === 'completed') return 'completed'
if (event.data.status === 'error') return 'error'
return 'running'
case 'PermissionRequired':
return 'pending'
case 'ModelCallStarted':
case 'RunStarted':
case 'ThinkingDelta':
return 'running'
default:
return 'completed'
}
}
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)}min`
}
/** 事件 data 是 Record<string, unknown>,取数值字段前先收窄类型。 */
function asNumber(value: unknown): number | null {
if (typeof value === 'number' && Number.isFinite(value)) return value
if (typeof value === 'string' && value.trim() !== '') {
const parsed = Number(value)
if (Number.isFinite(parsed)) return parsed
}
return null
}
export function calculateDuration(event1: AgentEvent, event2: AgentEvent): number {
const t1 = new Date(event1.timestamp).getTime()
const t2 = new Date(event2.timestamp).getTime()
return Math.max(0, t2 - t1)
}
export function getTotalDuration(events: AgentEvent[]): number {
if (events.length < 2) return 0
const first = events[0]
const last = events[events.length - 1]
return calculateDuration(first, last)
}
export function getToolCallsFromEvents(events: AgentEvent[]): Array<{
tool_call_id: string
name: string
status: 'pending' | 'running' | 'completed' | 'error'
arguments?: Record<string, unknown>
result?: string
duration_ms?: number
started_at?: string
completed_at?: string
}> {
const calls = new Map<string, {
tool_call_id: string
name: string
status: 'pending' | 'running' | 'completed' | 'error'
arguments?: Record<string, unknown>
result?: string
duration_ms?: number
started_at?: string
completed_at?: string
}>()
for (const event of events) {
if (event.event === 'ToolCall') {
const id = String(event.data.tool_call_id ?? '')
calls.set(id, {
tool_call_id: id,
name: String(event.data.name ?? 'unknown'),
status: 'running',
arguments: (event.data.arguments ?? event.data.parameters) as Record<string, unknown> | undefined,
started_at: event.timestamp,
})
} else if (event.event === 'ToolResult') {
const id = String(event.data.tool_call_id ?? '')
const existing = calls.get(id)
if (existing) {
existing.status = event.data.success === false ? 'error' : 'completed'
existing.result = event.data.output != null ? JSON.stringify(event.data.output) : event.data.result as string | undefined
existing.duration_ms = event.data.duration_ms as number | undefined
existing.completed_at = event.timestamp
}
}
}
return [...calls.values()]
}
+168 -12
View File
@@ -1,6 +1,7 @@
import { defineStore } from 'pinia'
import { ref, computed, watch } from 'vue'
import type { ThemeConfig } from '@/contracts'
import type { ThemeConfig, ThemeManifest, InstalledTheme, ThemePackageInspection } from '@/contracts'
import * as themePkg from '@/services/themePackageService'
const builtinThemes: ThemeConfig[] = [
{ theme_id: 'light', name: '浅色', version: '1.0.0', description: '默认浅色主题', is_dark: false, builtin: true, code_theme: 'github-light' },
@@ -14,42 +15,77 @@ function isCodeBlockThemePreference(value: unknown): value is CodeBlockThemePref
return value === 'auto' || value === 'github-light' || value === 'github-dark'
}
const builtinToInstalled = (t: ThemeConfig): InstalledTheme => ({
theme_id: t.theme_id,
name: t.name,
version: t.version,
author: 'NotesAgent 团队',
description: t.description,
is_dark: t.is_dark,
builtin: true,
enabled: true,
manifest: {
theme_id: t.theme_id,
name: t.name,
version: t.version,
author: 'NotesAgent 团队',
description: t.description,
min_app_version: '0.1.0',
is_dark: t.is_dark,
css_entry: 'builtin',
},
code_theme: t.code_theme,
})
export const useThemeStore = defineStore('theme', () => {
const themes = ref<ThemeConfig[]>(builtinThemes)
const themes = ref<ThemeConfig[]>([...builtinThemes])
const installedCustomThemes = ref<InstalledTheme[]>([])
const currentThemeId = ref<string>('light')
const fontEditorSize = ref(15)
const fontEditorFamily = ref('system-ui')
const lineHeight = ref(1.7)
const codeBlockTheme = ref<CodeBlockThemePreference>('auto')
const isImporting = ref(false)
const importError = ref<string | null>(null)
const pendingInspection = ref<ThemePackageInspection | null>(null)
let appearanceHydrated = false
const allThemes = computed<InstalledTheme[]>(() => [
...builtinThemes.map(builtinToInstalled),
...installedCustomThemes.value,
])
const currentTheme = computed(() =>
themes.value.find((t) => t.theme_id === currentThemeId.value) || themes.value[0]
allThemes.value.find((t) => t.theme_id === currentThemeId.value) || allThemes.value[0]
)
const isDark = computed(() => currentTheme.value?.is_dark || false)
const resolvedCodeBlockTheme = computed<'github-light' | 'github-dark'>(() => {
if (codeBlockTheme.value !== 'auto') return codeBlockTheme.value
return currentTheme.value?.code_theme ?? (isDark.value ? 'github-dark' : 'github-light')
})
function applyTheme(themeId: string) {
const theme = themes.value.find((t) => t.theme_id === themeId)
const theme = allThemes.value.find((t) => t.theme_id === themeId)
if (!theme) return
currentThemeId.value = themeId
const root = document.documentElement
if (theme.is_dark) {
root.setAttribute('data-theme', 'dark')
} else if (themeId === 'sepia') {
root.setAttribute('data-theme', 'sepia')
if (theme.builtin) {
if (theme.is_dark) {
root.setAttribute('data-theme', 'dark')
} else if (themeId === 'sepia') {
root.setAttribute('data-theme', 'sepia')
} else {
root.setAttribute('data-theme', 'light')
}
} else {
root.setAttribute('data-theme', 'light')
root.setAttribute('data-theme', themeId)
}
localStorage.setItem('theme', themeId)
}
function initTheme() {
// 先恢复外观再开放 watch 持久化,避免 immediate watcher 覆盖本地设置。
const savedAppearance = localStorage.getItem('editor-appearance')
if (savedAppearance) {
try {
@@ -60,10 +96,11 @@ export const useThemeStore = defineStore('theme', () => {
if (isCodeBlockThemePreference(value.codeBlockTheme)) codeBlockTheme.value = value.codeBlockTheme
} catch { localStorage.removeItem('editor-appearance') }
}
void loadCustomThemes()
const saved = localStorage.getItem('theme')
appearanceHydrated = true
persistAppearance()
if (saved && themes.value.find((t) => t.theme_id === saved)) {
if (saved) {
applyTheme(saved)
return
}
@@ -71,6 +108,23 @@ export const useThemeStore = defineStore('theme', () => {
applyTheme(prefersDark ? 'dark' : 'light')
}
async function loadCustomThemes() {
try {
const list = await themePkg.listInstalledThemes()
installedCustomThemes.value = list
themes.value = [...builtinThemes, ...list.map((t) => ({
theme_id: t.theme_id,
name: t.name,
version: t.version,
description: t.description ?? '',
is_dark: t.is_dark,
builtin: false,
author: t.author,
code_theme: t.code_theme,
}))]
} catch { /* keep builtin only */ }
}
function toggleTheme() {
applyTheme(isDark.value ? 'light' : 'dark')
}
@@ -90,8 +144,99 @@ export const useThemeStore = defineStore('theme', () => {
codeBlockTheme: codeBlockTheme.value,
}))
async function inspectThemePackage(packageData: string): Promise<ThemePackageInspection> {
isImporting.value = true
importError.value = null
try {
const result = await themePkg.inspectThemePackage(packageData)
pendingInspection.value = result
if (!result.compatible) {
importError.value = result.warnings[0] ?? '主题包不兼容'
}
return result
} catch (error) {
importError.value = error instanceof Error ? error.message : '导入失败'
throw error
} finally {
isImporting.value = false
}
}
async function installThemeFromInspection(manifest: ThemeManifest, cssContent: string) {
isImporting.value = true
importError.value = null
try {
const installed = await themePkg.installTheme(manifest, cssContent)
const idx = installedCustomThemes.value.findIndex((t) => t.theme_id === installed.theme_id)
if (idx >= 0) installedCustomThemes.value[idx] = installed
else installedCustomThemes.value.push(installed)
const themeConfig: ThemeConfig = {
theme_id: installed.theme_id,
name: installed.name,
version: installed.version,
description: installed.description ?? '',
is_dark: installed.is_dark,
builtin: false,
author: installed.author,
code_theme: installed.code_theme,
}
const existingIdx = themes.value.findIndex((t) => t.theme_id === installed.theme_id)
if (existingIdx >= 0) themes.value[existingIdx] = themeConfig
else themes.value.push(themeConfig)
pendingInspection.value = null
return installed
} catch (error) {
importError.value = error instanceof Error ? error.message : '安装失败'
throw error
} finally {
isImporting.value = false
}
}
async function uninstallTheme(themeId: string) {
await themePkg.uninstallTheme(themeId)
installedCustomThemes.value = installedCustomThemes.value.filter((t) => t.theme_id !== themeId)
themes.value = themes.value.filter((t) => t.theme_id !== themeId || t.builtin)
if (currentThemeId.value === themeId) {
applyTheme('light')
}
}
async function installCommunityTheme(themeId: string) {
isImporting.value = true
importError.value = null
try {
const installed = await themePkg.installCommunityTheme(themeId)
const idx = installedCustomThemes.value.findIndex((t) => t.theme_id === installed.theme_id)
if (idx >= 0) installedCustomThemes.value[idx] = installed
else installedCustomThemes.value.push(installed)
const themeConfig: ThemeConfig = {
theme_id: installed.theme_id,
name: installed.name,
version: installed.version,
description: installed.description ?? '',
is_dark: installed.is_dark,
builtin: false,
author: installed.author,
code_theme: installed.code_theme,
}
const existingIdx = themes.value.findIndex((t) => t.theme_id === installed.theme_id)
if (existingIdx >= 0) themes.value[existingIdx] = themeConfig
else themes.value.push(themeConfig)
return installed
} catch (error) {
importError.value = error instanceof Error ? error.message : '安装失败'
throw error
} finally {
isImporting.value = false
}
}
function isThemeInstalled(themeId: string): boolean {
return themes.value.some((t) => t.theme_id === themeId)
}
watch(resolvedCodeBlockTheme, (theme) => {
// CSS 与 Shiki 共用该属性,确保代码块背景和 token 配色始终成套切换。
document.documentElement.setAttribute('data-code-theme', theme)
}, { immediate: true })
@@ -116,6 +261,7 @@ export const useThemeStore = defineStore('theme', () => {
return {
themes,
installedCustomThemes,
currentThemeId,
currentTheme,
isDark,
@@ -124,9 +270,19 @@ export const useThemeStore = defineStore('theme', () => {
lineHeight,
codeBlockTheme,
resolvedCodeBlockTheme,
isImporting,
importError,
pendingInspection,
allThemes,
applyTheme,
initTheme,
toggleTheme,
resetToDefault,
loadCustomThemes,
inspectThemePackage,
installThemeFromInspection,
uninstallTheme,
installCommunityTheme,
isThemeInstalled,
}
})
+37 -3
View File
@@ -13,6 +13,7 @@ import sql from '@shikijs/langs/sql'
import typescript from '@shikijs/langs/typescript'
import githubDark from '@shikijs/themes/github-dark'
import githubLight from '@shikijs/themes/github-light'
import { renderMermaid } from '@/services/mermaidService'
marked.setOptions({ gfm: true, breaks: true })
@@ -38,18 +39,51 @@ export async function highlightCode(source: string, requestedLanguage = 'text'):
})
}
export async function renderMarkdown(source: string): Promise<string> {
export async function renderMarkdown(source: string, options?: { theme?: 'light' | 'dark' }): Promise<string> {
const html = marked.parse(source, { async: false }) as string
const documentNode = new DOMParser().parseFromString(`<body>${html}</body>`, 'text/html')
const mermaidBlocks: { pre: Element; source: string }[] = []
for (const code of documentNode.querySelectorAll('pre > code')) {
const requestedLanguage = [...code.classList].find((name) => name.startsWith('language-'))?.slice(9) || 'text'
if (requestedLanguage === 'mermaid') {
mermaidBlocks.push({ pre: code.parentElement!, source: code.textContent ?? '' })
continue
}
const highlighted = await highlightCode(code.textContent ?? '', requestedLanguage)
const fragment = document.createRange().createContextualFragment(highlighted)
code.parentElement?.replaceWith(fragment)
}
// Markdown 可能来自模型或外部笔记,高亮完成后仍必须在最终出口统一净化。
return DOMPurify.sanitize(documentNode.body.innerHTML, { USE_PROFILES: { html: true } })
for (const { pre, source } of mermaidBlocks) {
try {
const result = await renderMermaid(source, { theme: options?.theme, mode: 'static' })
const container = document.createElement('div')
container.className = 'markdown-mermaid'
container.innerHTML = result.svg
pre.replaceWith(container)
} catch {
const fallback = document.createElement('pre')
fallback.className = 'mermaid-error'
fallback.textContent = source
pre.replaceWith(fallback)
}
}
return DOMPurify.sanitize(documentNode.body.innerHTML, {
USE_PROFILES: { html: true },
ADD_TAGS: ['svg', 'path', 'rect', 'circle', 'ellipse', 'line', 'polyline', 'polygon',
'text', 'tspan', 'textPath', 'g', 'defs', 'marker', 'style', 'clipPath', 'foreignObject',
'title', 'desc', 'use', 'image', 'linearGradient', 'stop', 'radialGradient'],
ADD_ATTR: ['viewBox', 'd', 'cx', 'cy', 'r', 'rx', 'ry', 'x', 'y', 'width', 'height',
'fill', 'stroke', 'stroke-width', 'stroke-dasharray', 'stroke-linecap', 'stroke-linejoin',
'transform', 'points', 'x1', 'y1', 'x2', 'y2', 'class', 'id', 'style', 'text-anchor',
'dominant-baseline', 'font-size', 'font-family', 'font-weight', 'opacity', 'orient',
'marker-end', 'marker-start', 'marker-mid', 'refX', 'refY', 'viewBox', 'preserveAspectRatio',
'xlink:href', 'href', 'clip-path', 'gradientUnits', 'gradientTransform', 'stop-color',
'stop-opacity', 'offset', 'patternUnits', 'patternTransform', 'target'],
})
}
// TODO(performance): 编辑器首屏稳定后评估将 Shiki 延迟加载或迁移到 Web Worker。
+1
View File
@@ -9,6 +9,7 @@
"resolveJsonModule": true,
"isolatedModules": true,
"esModuleInterop": true,
"skipLibCheck": true,
"lib": ["ES2022", "ESNext.Disposable", "DOM", "DOM.Iterable"],
"types": ["vite/client"],
"baseUrl": ".",