fix(frontend): 修复 PR #18 审阅问题并补充回归测试

审阅意见逐项修复:

1. 主题包安装丢弃用户 CSS
   inspectThemePackage 之前只解析 YAML 清单,ThemesView 安装时另外
   生成一套硬编码调色板,用户提供的 CSS 被整份丢掉。现在定义单文件
   格式(YAML 清单 + `---` + CSS),parseThemePackage 取出真实 CSS
   并原样安装;CSS 安全校验提前到预览阶段;按内容识别并拒绝 ZIP。

2. 主题恢复竞态导致页面无 data-theme
   initTheme 之前没有 await loadCustomThemes,自定义主题还没进
   allThemes,applyTheme 找不到主题直接 return。现在先同步落一个
   内置主题兜底(不写 localStorage,避免冲掉用户存的自定义主题 id),
   加载完成后再切到真正保存的那个;主题失效或列表加载失败时回退并
   通过 themeLoadWarning 告知用户,不再静默。

3. Trace 建树依赖事件相邻顺序
   后端真实顺序是 ModelCallStarted → ModelCallCompleted → Usage →
   ToolCall/ToolResult,工具在模型调用完成后才执行且并发跑,相邻性
   不可用。改为按 model_call_id / parent_model_call_id / tool_call_id
   关联;ToolResult 回填 ToolCall 的状态与耗时,结束后不再显示
   running;SSE 断点恢复的孤立事件退回顶层而不是丢弃。

4. Trace 叶子节点无法查看数据
   行的 click 是 `children.length && toggleExpand`,而详情 v-if 又
   要求 `children.length === 0`,两个条件互斥。拆成 expandedNodes
   与 detailNodes 两个状态集合;展开箭头改为独立按钮,行支持键盘
   与 aria-expanded;引用节点补「定位」按钮。同时修正 Usage 卡片
   字段(后端只发累计 token_usage)。

5. 引用定位逻辑三处重复且各自有缺陷
   抽出 navigateToCitation(依赖注入,可独立测试)+ useCitationNavigation。
   调用顺序固化:必须先 await loadFile 再 highlightBlock,否则
   editor store 的 loadFile 末尾会把高亮清掉;loadFile 失败时不跳转。
   AgentView / ChatView / AppShell 统一走这一处。

6. 插件命令 UI 重复实现
   抽出 PluginCommandPanel 复用 PluginMcpPanel 的 schema 驱动表单,
   删除 PluginsView 里的劣化副本。effect 现在真的执行 navigate /
   refresh(此前只拼成文本显示);补上必填校验与布尔字段初始值,
   修正「显示否但不提交该键」的不一致。

补充回归测试 91 项(含对上述缺陷的变异验证):
traceService / theme store / themePackageService / pluginCommandForm /
useCitationNavigation / TraceTimeline。

vue-tsc -b、vitest(32 文件 182 项)、vite build 全部通过。
This commit is contained in:
2026-09-04 23:15:53 +08:00
parent 639f38c1fc
commit ab9ce58051
22 changed files with 1573 additions and 390 deletions
+13 -4
View File
@@ -10,6 +10,7 @@ import SecondarySidebar from './SecondarySidebar.vue'
import StatusBar from './StatusBar.vue'
import TitleBar from './TitleBar.vue'
import CommandPalette from './CommandPalette.vue'
import { navigateToCitation } from '@/composables/useCitationNavigation'
defineProps<{
showSecondarySidebar?: boolean
@@ -43,10 +44,18 @@ const secondaryComponent = computed(() => {
}
})
function openCitation(noteId: string, blockId: string, filePath: string) {
workspaceStore.openFile(filePath)
editorStore.highlightBlock(blockId)
router.push('/workspace')
function openCitation(_noteId: string, blockId: string, filePath: string) {
// 走统一的定位流程:必须先 loadFile 再 highlightBlock
// 否则 editor store 的 loadFile 会把刚设好的高亮清掉。
return navigateToCitation(
{ file_path: filePath, block_id: blockId },
{
loadFile: (path) => editorStore.loadFile(path),
openFile: (path) => workspaceStore.openFile(path),
highlightBlock: (id) => editorStore.highlightBlock(id),
navigate: (path) => router.push(path),
},
)
}
defineExpose({ openCitation })
@@ -0,0 +1,84 @@
import { describe, expect, it, vi } from 'vitest'
import { navigateToCitation } from './useCitationNavigation'
import type { CitationNavigationDeps } from './useCitationNavigation'
function deps(overrides: Partial<CitationNavigationDeps> = {}) {
const calls: string[] = []
const base: CitationNavigationDeps = {
loadFile: vi.fn(async () => { calls.push('loadFile') }),
openFile: vi.fn(() => { calls.push('openFile') }),
highlightBlock: vi.fn(() => { calls.push('highlightBlock') }),
navigate: vi.fn(async () => { calls.push('navigate') }),
}
return { deps: { ...base, ...overrides }, calls }
}
describe('navigateToCitation', () => {
it('先加载文件再高亮,最后跳转到工作区', async () => {
// 顺序不能改:editor store 的 loadFile 末尾会把 highlightBlockId 清空
// stores/editor.ts),先 highlightBlock 会被自己冲掉。
const { deps: d, calls } = deps()
await navigateToCitation({ file_path: 'notes/a.md', block_id: 'blk-1' }, d)
expect(calls).toEqual(['loadFile', 'openFile', 'highlightBlock', 'navigate'])
expect(d.loadFile).toHaveBeenCalledWith('notes/a.md')
expect(d.highlightBlock).toHaveBeenCalledWith('blk-1')
expect(d.navigate).toHaveBeenCalledWith('/workspace')
})
it('等 loadFile 的 promise resolve 之后才高亮', async () => {
let loaded = false
const highlightBlock = vi.fn(() => {
// loadFile 还没完成就高亮,说明少了 await
expect(loaded).toBe(true)
})
const { deps: d } = deps({
loadFile: vi.fn(async () => {
await Promise.resolve()
loaded = true
}),
highlightBlock,
})
await navigateToCitation({ file_path: 'notes/a.md', block_id: 'blk-1' }, d)
expect(highlightBlock).toHaveBeenCalledTimes(1)
})
it('没有 block_id 时只打开文件,不调用高亮', async () => {
const { deps: d, calls } = deps()
await navigateToCitation({ file_path: 'notes/a.md' }, d)
expect(calls).toEqual(['loadFile', 'openFile', 'navigate'])
expect(d.highlightBlock).not.toHaveBeenCalled()
})
it('缺少 file_path 时抛出可展示的错误,且不做任何跳转', async () => {
const { deps: d } = deps()
await expect(navigateToCitation({ block_id: 'blk-1' }, d)).rejects.toThrow('该引用缺少文件路径,无法定位到笔记。')
expect(d.loadFile).not.toHaveBeenCalled()
expect(d.navigate).not.toHaveBeenCalled()
})
it('file_path 是空串或非字符串时同样拒绝', async () => {
const { deps: d } = deps()
await expect(navigateToCitation({ file_path: ' ' }, d)).rejects.toThrow(/缺少文件路径/)
await expect(navigateToCitation({ file_path: 42 }, d)).rejects.toThrow(/缺少文件路径/)
expect(d.loadFile).not.toHaveBeenCalled()
})
it('loadFile 失败时不跳转,避免把用户从未保存的编辑器里弹走', async () => {
const { deps: d } = deps({
loadFile: vi.fn(async () => { throw new Error('SAVE_CONFLICT: 当前文件有未解决的冲突') }),
})
await expect(navigateToCitation({ file_path: 'notes/a.md', block_id: 'b' }, d)).rejects.toThrow(/SAVE_CONFLICT/)
expect(d.openFile).not.toHaveBeenCalled()
expect(d.highlightBlock).not.toHaveBeenCalled()
expect(d.navigate).not.toHaveBeenCalled()
})
})
@@ -0,0 +1,64 @@
import { useRouter } from 'vue-router'
import { useEditorStore } from '@/stores/editor'
import { useWorkspaceStore } from '@/stores/workspace'
/**
* 引用目标。字段用 unknown 是因为 Agent 事件流里拿到的是
* Record<string, unknown>SSE 原始 data),不保证结构完整。
*/
export interface CitationTarget {
file_path?: unknown
block_id?: unknown
}
export interface CitationNavigationDeps {
loadFile: (filePath: string) => Promise<void>
openFile: (filePath: string) => void
highlightBlock: (blockId: string) => void
navigate: (path: string) => Promise<unknown> | unknown
}
function asPath(value: unknown): string {
return typeof value === 'string' && value.trim() !== '' ? value : ''
}
/**
* 定位到引用对应的笔记块。
*
* 调用顺序不能改:editor store 的 loadFile 在末尾会把 highlightBlockId 清空,
* 所以必须等它 resolve 之后再 highlightBlock,否则高亮会被自己冲掉。
* loadFile 失败(例如当前文件有未解决的保存冲突)时直接抛出,
* 不跳转,避免把用户从未保存的编辑器里弹走。
*/
export async function navigateToCitation(
target: CitationTarget,
deps: CitationNavigationDeps,
): Promise<void> {
const filePath = asPath(target.file_path)
if (!filePath) throw new Error('该引用缺少文件路径,无法定位到笔记。')
await deps.loadFile(filePath)
deps.openFile(filePath)
const blockId = asPath(target.block_id)
if (blockId) deps.highlightBlock(blockId)
await deps.navigate('/workspace')
}
/** 组件里用的封装:绑定真实的 store 与路由。 */
export function useCitationNavigation() {
const router = useRouter()
const editorStore = useEditorStore()
const workspaceStore = useWorkspaceStore()
return {
openCitation: (target: CitationTarget) =>
navigateToCitation(target, {
loadFile: (filePath) => editorStore.loadFile(filePath),
openFile: (filePath) => workspaceStore.openFile(filePath),
highlightBlock: (blockId) => editorStore.highlightBlock(blockId),
navigate: (path) => router.push(path),
}),
}
}
+4
View File
@@ -842,12 +842,16 @@ export interface ThemePackageInspection {
warnings: string[]
compatible: boolean
error_code?: string
/** 包内实际的主题 CSS。安装时必须用这份内容,不能另行生成。 */
css: string
}
export type ThemeErrorCode =
| 'THEME_PACKAGE_NOT_FOUND'
| 'THEME_MANIFEST_INVALID'
| 'THEME_PACKAGE_INCOMPATIBLE'
| 'THEME_PACKAGE_UNSUPPORTED_FORMAT'
| 'THEME_PACKAGE_INVALID'
| 'THEME_CSS_INVALID'
| 'THEME_SECURITY_VIOLATION'
| 'THEME_INSTALL_FAILED'
+17 -1
View File
@@ -8,12 +8,14 @@ import TraceTimeline from './TraceTimeline.vue'
import type { AgentEvent } from '@/contracts'
import { localizeDetails, permissionLabel, runStatusLabel, toolLabel } from './labels'
import ToolOption from './ToolOption.vue'
import { useCitationNavigation } from '@/composables/useCitationNavigation'
const route = useRoute()
const router = useRouter()
const agentStore = useAgentStore()
const providerStore = useProviderStore()
const skillStore = useSkillStore()
const { openCitation } = useCitationNavigation()
const pageError = ref('')
const form = reactive({
input: '', provider_id: '', model: '', skill_id: '', max_steps: 10,
@@ -71,6 +73,16 @@ function eventText(event: AgentEvent) {
if (text) return String(text)
return ''
}
/** Trace 里点引用 → 打开对应笔记块。失败原因要让用户看到,不能静默。 */
async function handleOpenCitation(data: Record<string, unknown>) {
pageError.value = ''
try {
await openCitation(data)
} catch (error) {
pageError.value = error instanceof Error ? error.message : '引用定位失败'
}
}
</script>
<template>
@@ -118,7 +130,11 @@ function eventText(event: AgentEvent) {
<button class="button-secondary" @click="agentStore.loadRun(agentStore.activeRunId!)">重新加载</button>
</div>
</div>
<TraceTimeline :events="agentStore.events" :run-status="agentStore.activeRun?.status" />
<TraceTimeline
:events="agentStore.events"
:run-status="agentStore.activeRun?.status"
@open-citation="handleOpenCitation"
/>
</div>
<div v-if="agentStore.permissionRequest" class="modal-backdrop">
@@ -0,0 +1,170 @@
// @vitest-environment happy-dom
import { mount } from '@vue/test-utils'
import { describe, expect, it } from 'vitest'
import type { AgentEvent, AgentEventType } from '@/contracts'
import TraceTimeline from './TraceTimeline.vue'
let sequence = 0
function event(type: AgentEventType, data: Record<string, unknown> = {}): AgentEvent {
return {
event: type,
sequence: ++sequence,
run_id: 'run-1',
data,
timestamp: '2026-01-01T00:00:00.000Z',
}
}
/** 一次带工具调用的运行:模型调用有子节点,Usage / 引用是叶子。 */
function sampleEvents(): AgentEvent[] {
return [
event('RunStarted'),
event('ModelCallStarted', { model_call_id: 'mc-1', model: 'mock-1' }),
event('ModelCallCompleted', { model_call_id: 'mc-1', duration_ms: 800 }),
event('ToolCall', { tool_call_id: 'tc-1', name: 'read_note', parent_model_call_id: 'mc-1' }),
event('ToolResult', { tool_call_id: 'tc-1', name: 'read_note', success: true, parent_model_call_id: 'mc-1' }),
event('Citation', { file_path: 'notes/a.md', block_id: 'blk-1', heading_path: 'A > B' }),
event('RunCompleted'),
]
}
function mountTree(events: AgentEvent[]) {
const wrapper = mount(TraceTimeline, { props: { events } })
return wrapper
}
async function switchToTree(wrapper: ReturnType<typeof mountTree>) {
const treeButton = wrapper.findAll('button').find((b) => b.text() === '树形')
await treeButton!.trigger('click')
return wrapper
}
describe('TraceTimeline 树形视图', () => {
it('叶子节点点击后能看到自己的数据', async () => {
// 回归:之前行的 click 是 `children.length && toggleExpand(id)`
// 而详情 v-if 又要求 children.length === 0 —— 两个条件互斥,
// 叶子节点永远打不开详情。
const wrapper = await switchToTree(mountTree(sampleEvents()))
const rows = wrapper.findAll('.node-row')
const citationRow = rows.find((row) => row.text().includes('引用来源'))
expect(citationRow).toBeTruthy()
expect(wrapper.find('.node-detail').exists()).toBe(false)
await citationRow!.trigger('click')
const detail = wrapper.find('.node-detail')
expect(detail.exists()).toBe(true)
expect(detail.text()).toContain('notes/a.md')
})
it('有子节点的节点也能查看自己的数据,不只是展开子树', async () => {
const wrapper = await switchToTree(mountTree(sampleEvents()))
const modelRow = wrapper.findAll('.node-row').find((row) => row.text().includes('模型调用'))
await modelRow!.trigger('click')
const detail = wrapper.find('.node-detail')
expect(detail.exists()).toBe(true)
expect(detail.text()).toContain('mc-1')
})
it('展开箭头只切子树,不会连带打开详情', async () => {
const wrapper = await switchToTree(mountTree(sampleEvents()))
// 初始只有顶层节点:运行开始、模型调用、引用、运行完成
expect(wrapper.findAll('.node-row')).toHaveLength(4)
const arrow = wrapper.find('.expand-icon:not(.placeholder)')
expect(arrow.exists()).toBe(true)
await arrow.trigger('click')
// 子节点出现,但没有任何详情面板被打开
expect(wrapper.findAll('.node-row')).toHaveLength(5)
expect(wrapper.text()).toContain('工具调用:read_note')
expect(wrapper.find('.node-detail').exists()).toBe(false)
})
it('键盘 Enter 与空格可以打开详情', async () => {
const wrapper = await switchToTree(mountTree(sampleEvents()))
const row = wrapper.findAll('.node-row').find((r) => r.text().includes('运行开始'))!
await row.trigger('keydown.enter')
expect(wrapper.find('.node-detail').exists()).toBe(true)
await row.trigger('keydown.space')
expect(wrapper.find('.node-detail').exists()).toBe(false)
})
it('行的 aria-expanded 跟随详情开合', async () => {
const wrapper = await switchToTree(mountTree(sampleEvents()))
const row = wrapper.findAll('.node-row').find((r) => r.text().includes('运行开始'))!
expect(row.attributes('aria-expanded')).toBe('false')
await row.trigger('click')
expect(row.attributes('aria-expanded')).toBe('true')
})
it('引用节点带「定位」按钮,点击后抛出 open-citation 且不打开详情', async () => {
const wrapper = await switchToTree(mountTree(sampleEvents()))
const locate = wrapper.find('.node-locate')
expect(locate.exists()).toBe(true)
await locate.trigger('click')
const emitted = wrapper.emitted('open-citation')
expect(emitted).toHaveLength(1)
expect((emitted![0][0] as Record<string, unknown>).file_path).toBe('notes/a.md')
// @click.stop 生效,行的详情不该被顺带打开
expect(wrapper.find('.node-detail').exists()).toBe(false)
})
it('引用缺少 file_path 时不显示定位按钮', async () => {
const wrapper = await switchToTree(mountTree([event('Citation', { heading_path: 'A' })]))
expect(wrapper.find('.node-locate').exists()).toBe(false)
})
})
describe('TraceTimeline 时间线视图', () => {
it('Usage 卡片读后端真实字段 token_usage', () => {
// 后端只发累计的 token_usageruntime.py),没有 input/output/total_tokens。
const wrapper = mountTree([event('Usage', { token_usage: 1024 })])
expect(wrapper.find('.event-usage').text()).toContain('1024')
})
it('Usage 缺字段时显示占位符而不是 undefined', () => {
const wrapper = mountTree([event('Usage', {})])
const text = wrapper.find('.event-usage').text()
expect(text).toContain('-')
expect(text).not.toContain('undefined')
})
it('点击引用卡片抛出 open-citation', async () => {
const wrapper = mountTree([event('Citation', { file_path: 'notes/a.md', heading_path: 'A' })])
await wrapper.find('.event-citation').trigger('click')
expect(wrapper.emitted('open-citation')).toHaveLength(1)
})
it('工具调用统计按 ToolResult 显示最终状态,不停在 running', () => {
const wrapper = mountTree([
event('ToolCall', { tool_call_id: 'tc-9', name: 'write_note' }),
event('ToolResult', { tool_call_id: 'tc-9', name: 'write_note', success: false, error_code: 'TOOL_DENIED' }),
])
const item = wrapper.find('.tool-call-item')
expect(item.classes()).toContain('error')
expect(item.text()).toContain('失败')
})
it('没有事件时显示等待态', () => {
const wrapper = mountTree([])
expect(wrapper.find('.empty-state').text()).toContain('等待执行轨迹')
})
})
+81 -15
View File
@@ -13,7 +13,11 @@ const emit = defineEmits<{
(e: 'open-citation', data: Record<string, unknown>): void
}>()
// 子树展开与「查看本节点数据」是两件事:
// 叶子节点没有子树,但依然需要能看自己的 data,
// 所以两个状态集合分开维护,不能共用一个 expanded。
const expandedNodes = ref<Set<string>>(new Set())
const detailNodes = ref<Set<string>>(new Set())
const viewMode = ref<'timeline' | 'tree'>('timeline')
const showDetails = ref(true)
@@ -32,18 +36,32 @@ const summaryStats = computed(() => {
}
})
function toggleExpand(nodeId: string) {
if (expandedNodes.value.has(nodeId)) {
expandedNodes.value.delete(nodeId)
function toggle(set: Set<string>, nodeId: string) {
if (set.has(nodeId)) {
set.delete(nodeId)
} else {
expandedNodes.value.add(nodeId)
set.add(nodeId)
}
}
/** 展开/收起子树,只对有 children 的节点有意义。 */
function toggleExpand(nodeId: string) {
toggle(expandedNodes.value, nodeId)
}
function isExpanded(nodeId: string): boolean {
return expandedNodes.value.has(nodeId)
}
/** 查看/隐藏本节点自身的数据,任何节点(含叶子)都可用。 */
function toggleDetail(nodeId: string) {
toggle(detailNodes.value, nodeId)
}
function isDetailOpen(nodeId: string): boolean {
return detailNodes.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')
@@ -83,6 +101,11 @@ function getNodeStatusClass(node: TraceNode): string {
}
}
/** 引用节点带 file_path 才能定位到笔记块。 */
function isCitationNode(node: TraceNode): boolean {
return node.type === 'citation' && typeof node.data.file_path === 'string'
}
function prettyData(data: Record<string, unknown>): string {
const filtered = { ...data }
if (typeof filtered.output === 'string' && filtered.output.length > 500) {
@@ -147,10 +170,10 @@ const flatTrace = computed(() => flatNodes(traceNodes.value))
v-for="event in events"
:key="event.sequence"
class="event-card"
:class="{ expanded: isExpanded(`event-${event.sequence}`) }"
:class="{ expanded: isDetailOpen(`event-${event.sequence}`) }"
>
<div class="event-dot" :class="`dot-${event.event}`"></div>
<div class="event-content" @click="toggleExpand(`event-${event.sequence}`)">
<div class="event-content" @click="toggleDetail(`event-${event.sequence}`)">
<div class="event-header">
<span class="event-badge" :class="{
success: event.event === 'RunCompleted' || event.event === 'ModelCallCompleted',
@@ -170,9 +193,7 @@ const flatTrace = computed(() => flatNodes(traceNodes.value))
</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>
<span class="total">累计: {{ event.data.token_usage ?? '-' }} tokens</span>
</div>
<div v-if="event.event === 'Citation'" class="event-citation" @click.stop="emit('open-citation', event.data)">
<span class="cite-icon">📎</span>
@@ -183,7 +204,7 @@ const flatTrace = computed(() => flatNodes(traceNodes.value))
<code>{{ event.data.permission as string }}</code>
</div>
</div>
<div v-if="isExpanded(`event-${event.sequence}`) && showDetails" class="event-detail">
<div v-if="isDetailOpen(`event-${event.sequence}`) && showDetails" class="event-detail">
<details open>
<summary>完整数据</summary>
<pre>{{ prettyData(event.data) }}</pre>
@@ -199,10 +220,25 @@ const flatTrace = computed(() => flatNodes(traceNodes.value))
<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">
<div
class="node-row"
:class="[getNodeStatusClass(item.node), { 'detail-open': isDetailOpen(item.node.id) }]"
role="button"
tabindex="0"
:aria-expanded="isDetailOpen(item.node.id)"
@click="toggleDetail(item.node.id)"
@keydown.enter.prevent="toggleDetail(item.node.id)"
@keydown.space.prevent="toggleDetail(item.node.id)"
>
<button
v-if="item.node.children.length"
type="button"
class="expand-icon"
:aria-label="isExpanded(item.node.id) ? '收起子调用' : `展开 ${item.node.children.length} 个子调用`"
@click.stop="toggleExpand(item.node.id)"
>
{{ isExpanded(item.node.id) ? '▼' : '▶' }}
</span>
</button>
<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>
@@ -210,8 +246,16 @@ const flatTrace = computed(() => flatNodes(traceNodes.value))
<span v-if="item.node.duration_ms != null" class="node-duration">
{{ formatDuration(item.node.duration_ms) }}
</span>
<button
v-if="isCitationNode(item.node)"
type="button"
class="node-locate"
@click.stop="emit('open-citation', item.node.data)"
>
定位
</button>
</div>
<div v-if="isExpanded(item.node.id) && item.node.children.length === 0 && showDetails" class="node-detail">
<div v-if="isDetailOpen(item.node.id) && showDetails" class="node-detail">
<pre>{{ prettyData(item.node.data) }}</pre>
</div>
</div>
@@ -533,12 +577,18 @@ const flatTrace = computed(() => flatNodes(traceNodes.value))
align-items: center;
gap: var(--space-xs);
padding: 8px 12px;
cursor: default;
cursor: pointer;
font-size: var(--font-size-sm);
transition: background-color var(--motion-fast);
}
.node-row:hover { background: var(--color-background-hover); }
.node-row:focus-visible {
outline: 2px solid var(--color-accent-primary);
outline-offset: -2px;
}
.node-row.detail-open { background: var(--color-background-secondary); }
.node-row.status-running {
background: var(--color-info-soft);
@@ -550,6 +600,9 @@ const flatTrace = computed(() => flatNodes(traceNodes.value))
.expand-icon {
width: 16px;
padding: 0;
background: none;
border: none;
font-size: 10px;
color: var(--color-text-tertiary);
cursor: pointer;
@@ -558,6 +611,19 @@ const flatTrace = computed(() => flatNodes(traceNodes.value))
.expand-icon.placeholder { visibility: hidden; }
.node-locate {
padding: 1px 8px;
border: 1px solid var(--color-border-default);
border-radius: var(--radius-full);
background: var(--color-surface-primary);
color: var(--color-accent-primary);
font-size: 11px;
cursor: pointer;
flex-shrink: 0;
}
.node-locate:hover { border-color: var(--color-accent-primary); }
.node-icon {
font-size: 14px;
width: 20px;
+10 -12
View File
@@ -1,20 +1,16 @@
<script setup lang="ts">
import { computed, onBeforeUnmount, onMounted, ref, watch } from 'vue'
import { useRouter } from 'vue-router'
import type { Citation } from '@/contracts'
import { useChatStore } from '@/stores/chat'
import { useEditorStore } from '@/stores/editor'
import { useProviderStore } from '@/stores/provider'
import { useSkillStore } from '@/stores/skill'
import { useWorkspaceStore } from '@/stores/workspace'
import MarkdownContent from '@/components/common/MarkdownContent.vue'
import { useCitationNavigation } from '@/composables/useCitationNavigation'
const chatStore = useChatStore()
const providerStore = useProviderStore()
const skillStore = useSkillStore()
const workspaceStore = useWorkspaceStore()
const editorStore = useEditorStore()
const router = useRouter()
const { openCitation } = useCitationNavigation()
const loadError = ref('')
let disposed = false
onBeforeUnmount(() => { disposed = true })
@@ -51,11 +47,13 @@ watch(() => chatStore.selectedProviderId, async (providerId) => {
function send() { void chatStore.sendMessage(chatStore.inputText) }
async function openCitation(citation: Citation) {
await editorStore.loadFile(citation.file_path)
workspaceStore.openFile(citation.file_path)
editorStore.highlightBlock(citation.block_id)
await router.push('/workspace')
async function openCitationCard(citation: Citation) {
loadError.value = ''
try {
await openCitation(citation)
} catch (error) {
loadError.value = error instanceof Error ? error.message : '引用定位失败'
}
}
</script>
@@ -80,7 +78,7 @@ async function openCitation(citation: Citation) {
<div v-else-if="chatStore.isStreaming" class="message-content">正在思考</div>
<div v-if="message.tool_calls?.length" class="tool-calls"><div v-for="call in message.tool_calls" :key="call.tool_call_id" class="item-card"><span class="badge info">{{ call.status }}</span><strong>{{ call.name }}</strong><pre>{{ JSON.stringify(call.parameters, null, 2) }}</pre></div></div>
<div v-if="message.citations?.length" class="citations">
<button v-for="(citation, index) in message.citations" :key="citation.block_id" class="citation-card" @click="openCitation(citation)">
<button v-for="(citation, index) in message.citations" :key="citation.block_id" class="citation-card" @click="openCitationCard(citation)">
<span class="badge info">{{ index + 1 }}</span><span><strong>{{ citation.heading_path || citation.file_path }}</strong><small>{{ citation.content }}</small></span>
</button>
</div>
@@ -0,0 +1,235 @@
<script setup lang="ts">
import { Refresh, VideoPlay } from '@element-plus/icons-vue'
import { ref, watch } from 'vue'
import { useRouter } from 'vue-router'
import AppIcon from '@/components/common/AppIcon.vue'
import type { Plugin, PluginCommand } from '@/contracts'
import * as pluginService from '@/services/pluginService'
import {
applyCommandEffect,
cleanArguments,
coerceArgument,
commandFields,
initialArguments,
missingRequiredFields,
type CommandField,
} from '@/services/pluginCommandForm'
import { useEditorStore } from '@/stores/editor'
import { usePluginStore } from '@/stores/plugin'
import { useWorkspaceStore } from '@/stores/workspace'
const props = defineProps<{ plugin: Plugin }>()
const emit = defineEmits<{ (e: 'refresh-settings'): void }>()
const router = useRouter()
const pluginStore = usePluginStore()
const editorStore = useEditorStore()
const workspaceStore = useWorkspaceStore()
const commands = ref<PluginCommand[]>([])
const argumentsByCommand = ref<Record<string, Record<string, unknown>>>({})
const loading = ref(false)
const busy = ref('')
const error = ref('')
const notice = ref('')
let loadVersion = 0
watch(() => props.plugin.plugin_id, () => { void load() }, { immediate: true })
async function load() {
const version = ++loadVersion
const pluginId = props.plugin.plugin_id
error.value = ''
loading.value = true
try {
const all = await pluginService.listPluginCommands()
if (version !== loadVersion) return
const mine = all.filter((command) => command.plugin_id === pluginId)
commands.value = mine
// 重新加载会重置表单:schema 可能已经变了,留着旧值会送出非法参数。
const next: Record<string, Record<string, unknown>> = {}
for (const command of mine) next[command.command_id] = initialArguments(command)
argumentsByCommand.value = next
} catch (reason) {
if (version === loadVersion) error.value = reason instanceof Error ? reason.message : '命令加载失败'
} finally {
if (version === loadVersion) loading.value = false
}
}
function argsOf(commandId: string): Record<string, unknown> {
return argumentsByCommand.value[commandId] ?? {}
}
function fieldValue(commandId: string, field: CommandField): string {
const value = argsOf(commandId)[field.key]
if (value === undefined || value === null) return ''
return String(value)
}
function updateArgument(commandId: string, field: CommandField, raw: string) {
const target = argumentsByCommand.value[commandId] ??= {}
target[field.key] = coerceArgument(field, raw)
}
/**
* when 条件求值。缺少上下文时禁用而不是硬跑 ——
* 插件详情页没有编辑器选区,不冒充。
*/
function commandAvailable(command: PluginCommand): boolean {
if (!command.enabled) return false
return command.when.every((condition) => {
if (condition === 'workspace.has_vault') return Boolean(workspaceStore.vaultId)
if (condition === 'editor.has_note') return Boolean(editorStore.currentNoteId)
if (condition === 'editor.has_selection') return false
return false
})
}
function missing(command: PluginCommand): CommandField[] {
return missingRequiredFields(command, argsOf(command.command_id))
}
function canRun(command: PluginCommand): boolean {
return commandAvailable(command) && missing(command).length === 0 && busy.value !== command.command_id
}
async function execute(command: PluginCommand) {
const unfilled = missing(command)
if (unfilled.length) {
error.value = `请先填写必填参数:${unfilled.map((f) => f.title).join('、')}`
return
}
busy.value = command.command_id
error.value = ''
notice.value = ''
try {
const result = await pluginService.executePluginCommand(
command.command_id,
cleanArguments(argsOf(command.command_id)),
{
vault_id: workspaceStore.hasVault ? workspaceStore.vaultId : null,
note_id: editorStore.currentNoteId,
file_path: editorStore.currentFilePath,
selection: null,
},
)
await applyCommandEffect(result.effect, {
navigate: (path) => router.push(path),
refresh: async (scope) => {
if (scope === 'commands') await load()
else if (scope === 'plugins') await pluginStore.loadPlugins()
else if (scope === 'workspace') await workspaceStore.refreshFileTree()
else emit('refresh-settings')
},
notify: (text) => { notice.value = text },
})
} catch (reason) {
error.value = reason instanceof Error ? reason.message : '命令执行失败'
} finally {
busy.value = ''
}
}
</script>
<template>
<div class="command-panel">
<div class="section-head">
<div>
<h3>Plugin 命令</h3>
<p>执行该 Plugin 注册的受控 Command Contribution参数表单由后端声明的 JSON Schema 生成</p>
</div>
<button class="button-secondary" :disabled="loading" @click="load">
<AppIcon :icon="Refresh" :size="15" />刷新
</button>
</div>
<div v-if="error" class="error-banner">{{ error }}</div>
<div v-if="notice" class="notice-banner">{{ notice }}</div>
<div v-if="commands.length" class="command-list">
<article v-for="command in commands" :key="command.command_id" class="item-card command-card">
<div class="command-head">
<div>
<strong>{{ command.title }}</strong>
<p>{{ command.description || command.command_id }}</p>
</div>
<span
class="badge"
:class="{
success: commandAvailable(command),
warning: command.enabled && !commandAvailable(command),
}"
>{{ commandAvailable(command) ? '可执行' : command.enabled ? '缺少上下文' : '不可用' }}</span>
</div>
<div v-if="commandFields(command).length" class="command-fields">
<label v-for="field in commandFields(command)" :key="field.key" class="field">
<span>
{{ field.title }}
<em v-if="field.required">必填</em>
</span>
<select
v-if="field.enum"
class="select"
:value="fieldValue(command.command_id, field)"
@change="updateArgument(command.command_id, field, ($event.target as HTMLSelectElement).value)"
>
<option value="">请选择</option>
<option v-for="option in field.enum" :key="option" :value="option">{{ option }}</option>
</select>
<select
v-else-if="field.type === 'boolean'"
class="select"
:value="fieldValue(command.command_id, field)"
@change="updateArgument(command.command_id, field, ($event.target as HTMLSelectElement).value)"
>
<option value="false"></option>
<option value="true"></option>
</select>
<input
v-else
class="input"
:type="field.type === 'number' || field.type === 'integer' ? 'number' : 'text'"
:required="field.required"
:value="fieldValue(command.command_id, field)"
@input="updateArgument(command.command_id, field, ($event.target as HTMLInputElement).value)"
/>
<small v-if="field.description">{{ field.description }}</small>
</label>
</div>
<p v-if="commandAvailable(command) && missing(command).length" class="missing-hint">
待填写{{ missing(command).map((f) => f.title).join('、') }}
</p>
<button
class="button-primary command-run"
:disabled="!canRun(command)"
@click="execute(command)"
>
<AppIcon :icon="VideoPlay" :size="15" />
{{ busy === command.command_id ? '执行中…' : '执行命令' }}
</button>
</article>
</div>
<div v-else-if="!loading" class="empty-state">
<div><strong>没有可用命令</strong><p>启用 Plugin 已注册的命令会出现在这里</p></div>
</div>
</div>
</template>
<style scoped>
.command-panel { min-height: 220px; }
.section-head, .command-head { display: flex; align-items: flex-start; justify-content: space-between; gap: var(--space-md); margin-bottom: var(--space-lg); }
.section-head p, .command-head p { margin-top: var(--space-xs); color: var(--color-text-tertiary); font-size: var(--font-size-sm); }
.section-head button, .command-run { display: inline-flex; align-items: center; gap: var(--space-xs); }
.command-list, .command-card { display: grid; gap: var(--space-sm); }
.command-card:hover { transform: none; }
.command-fields { display: grid; grid-template-columns: repeat(auto-fit, minmax(180px, 1fr)); gap: var(--space-md); }
.command-fields small { color: var(--color-text-tertiary); font-size: var(--font-size-xs); }
.command-run { justify-self: end; }
.missing-hint { color: var(--color-warning); font-size: var(--font-size-sm); }
em { margin-left: var(--space-xs); color: var(--color-error); font-size: var(--font-size-xs); font-style: normal; }
@media (max-width: 800px) { .command-fields { grid-template-columns: 1fr; } }
</style>
@@ -1,27 +1,20 @@
<script setup lang="ts">
import { Key, Refresh, VideoPlay } from '@element-plus/icons-vue'
import { Key, Refresh } from '@element-plus/icons-vue'
import { computed, ref, watch } from 'vue'
import { useRouter } from 'vue-router'
import AppIcon from '@/components/common/AppIcon.vue'
import type { Plugin, PluginCommand, PluginHostStatus, PluginSettingField, PluginSettingsSchema } from '@/contracts'
import PluginCommandPanel from './PluginCommandPanel.vue'
import type { Plugin, PluginHostStatus, PluginSettingField, PluginSettingsSchema } from '@/contracts'
import * as pluginService from '@/services/pluginService'
import { useEditorStore } from '@/stores/editor'
import { usePluginStore } from '@/stores/plugin'
import { useWorkspaceStore } from '@/stores/workspace'
const props = defineProps<{ plugin: Plugin }>()
const pluginStore = usePluginStore()
const editorStore = useEditorStore()
const workspaceStore = useWorkspaceStore()
const router = useRouter()
const activeTab = ref<'host' | 'settings' | 'commands'>('host')
const host = ref<PluginHostStatus | null>(null)
const schema = ref<PluginSettingsSchema | null>(null)
const values = ref<Record<string, unknown>>({})
// 明文只停留在组件内存,提交后立即清空。
const secrets = ref<Record<string, string>>({})
const commands = ref<PluginCommand[]>([])
const argumentsByCommand = ref<Record<string, Record<string, unknown>>>({})
const loading = ref(false)
const busy = ref('')
const error = ref('')
@@ -42,7 +35,6 @@ watch(() => props.plugin.plugin_id, () => {
schema.value = null
values.value = {}
secrets.value = {}
commands.value = []
void loadActive()
}, { immediate: true })
@@ -72,19 +64,20 @@ async function loadActive() {
values.value = { ...loadedSchema.values }
}
}
if (tab === 'commands') {
const loadedCommands = (await pluginService.listPluginCommands()).filter((command) => command.plugin_id === pluginId)
if (version === loadVersion) {
commands.value = loadedCommands
for (const command of loadedCommands) argumentsByCommand.value[command.command_id] = {}
}
}
// commands 由 PluginCommandPanel 自己加载。
} catch (reason) {
if (version === loadVersion) feedback(message(reason, 'MCP 数据加载失败'))
} finally {
if (version === loadVersion) loading.value = false
}
}
/** 命令返回 refresh:settings 时重新拉设置。 */
async function reloadSettings() {
const loadedSchema = await pluginService.getPluginSettings(props.plugin.plugin_id)
schema.value = loadedSchema
values.value = { ...loadedSchema.values }
}
async function restartHost() {
busy.value = 'host'
feedback()
@@ -131,54 +124,6 @@ async function deleteSecret(field: PluginSettingField) {
notice.value = field.label + '已删除。'
} catch (reason) { feedback(message(reason, '密钥删除失败')) } finally { busy.value = '' }
}
function properties(command: PluginCommand): Record<string, Record<string, unknown>> {
const result = command.parameters.properties
return result && typeof result === 'object' && !Array.isArray(result) ? result as Record<string, Record<string, unknown>> : {}
}
function required(command: PluginCommand, key: string) {
return Array.isArray(command.parameters.required) && command.parameters.required.includes(key)
}
function commandAvailable(command: PluginCommand) {
if (!command.enabled) return false
return command.when.every((condition) => {
if (condition === 'workspace.has_vault') return Boolean(workspaceStore.vaultId)
if (condition === 'editor.has_note') return Boolean(editorStore.currentNoteId)
// Plugin 详情页不冒充编辑器选区;选区命令应从命令面板或编辑器挂载点执行。
if (condition === 'editor.has_selection') return false
return false
})
}
function updateArgument(commandId: string, key: string, raw: string, definition: Record<string, unknown>) {
const target = argumentsByCommand.value[commandId] ??= {}
if (definition.type === 'number' || definition.type === 'integer') target[key] = raw === '' ? undefined : Number(raw)
else if (definition.type === 'boolean') target[key] = raw === 'true'
else target[key] = raw
}
async function execute(command: PluginCommand) {
busy.value = command.command_id
feedback()
try {
const result = await pluginService.executePluginCommand(command.command_id, argumentsByCommand.value[command.command_id] ?? {}, {
vault_id: workspaceStore.hasVault ? workspaceStore.vaultId : null,
note_id: editorStore.currentNoteId,
file_path: editorStore.currentFilePath,
selection: null,
})
if (result.effect.type === 'notification') notice.value = result.effect.payload.message
else if (result.effect.type === 'job') notice.value = '后台任务已创建:' + result.effect.payload.job_id
else if (result.effect.type === 'navigate') {
const routes: Record<string, string> = {
'vault-entry': '/', workspace: '/workspace', search: '/search', chat: '/chat',
agent: '/agent/runs', tasks: '/tasks', skills: '/extensions/skills',
plugins: '/extensions/plugins', themes: '/themes', settings: '/settings',
}
await router.push(routes[result.effect.payload.route])
} else if (result.effect.type === 'refresh') {
await loadActive()
notice.value = '相关数据已刷新。'
} else notice.value = '命令执行完成。'
} catch (reason) { feedback(message(reason, '命令执行失败')) } finally { busy.value = '' }
}
</script>
<template>
@@ -222,17 +167,7 @@ async function execute(command: PluginCommand) {
</div>
<div v-else class="mcp-section">
<div class="section-head"><div><h3>Plugin 命令</h3><p>执行该 Plugin 注册的受控 Command Contribution</p></div><button class="button-secondary" :disabled="loading" @click="loadActive"><AppIcon :icon="Refresh" :size="15" />刷新</button></div>
<div v-if="commands.length" class="command-list">
<article v-for="command in commands" :key="command.command_id" class="item-card command-card">
<div class="command-head"><div><strong>{{ command.title }}</strong><p>{{ command.description || command.command_id }}</p></div><span class="badge" :class="{ success: commandAvailable(command), warning: command.enabled && !commandAvailable(command) }">{{ commandAvailable(command) ? '可执行' : command.enabled ? '缺少上下文' : '不可用' }}</span></div>
<div v-if="Object.keys(properties(command)).length" class="command-fields">
<label v-for="(definition, key) in properties(command)" :key="key" class="field"><span>{{ String(definition.title || key) }}<em v-if="required(command, key)">必填</em></span><select v-if="Array.isArray(definition.enum)" class="select" @change="updateArgument(command.command_id, key, ($event.target as HTMLSelectElement).value, definition)"><option value="">请选择</option><option v-for="option in definition.enum" :key="String(option)" :value="String(option)">{{ option }}</option></select><select v-else-if="definition.type === 'boolean'" class="select" @change="updateArgument(command.command_id, key, ($event.target as HTMLSelectElement).value, definition)"><option value="false">否</option><option value="true">是</option></select><input v-else class="input" :type="definition.type === 'number' || definition.type === 'integer' ? 'number' : 'text'" @input="updateArgument(command.command_id, key, ($event.target as HTMLInputElement).value, definition)"></label>
</div>
<button class="button-primary command-run" :disabled="!commandAvailable(command) || busy === command.command_id" @click="execute(command)"><AppIcon :icon="VideoPlay" :size="15" />{{ busy === command.command_id ? '执行中…' : '执行命令' }}</button>
</article>
</div>
<div v-else-if="!loading" class="empty-state"><div><strong>没有可用命令</strong><p>启用 Plugin 已注册的命令会出现在这里</p></div></div>
<PluginCommandPanel :plugin="plugin" @refresh-settings="reloadSettings" />
</div>
</section>
</template>
+4 -104
View File
@@ -2,18 +2,17 @@
import { Connection } from '@element-plus/icons-vue'
import AppIcon from '@/components/common/AppIcon.vue'
import PluginMcpPanel from './PluginMcpPanel.vue'
import PluginCommandPanel from './PluginCommandPanel.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'
import type { PluginCommand } 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() })
@@ -21,8 +20,8 @@ watch(() => pluginStore.selectedPluginId, async (pluginId) => {
if (pluginId) {
activeTab.value = 'info'
pluginCommands.value = []
commandOutput.value = {}
try {
// 只为了标签上的命令数;执行逻辑在 PluginCommandPanel 里。
const allCommands = await pluginService.listPluginCommands()
pluginCommands.value = allCommands.filter((c) => c.plugin_id === pluginId)
} catch { /* 命令加载失败时忽略 */ }
@@ -54,36 +53,6 @@ async function uninstall(id: string, name: string) {
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
)
@@ -195,35 +164,7 @@ const hasCommandContribution = computed(() =>
</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>
<PluginCommandPanel :plugin="pluginStore.selectedPlugin" />
</div>
<div v-else-if="activeTab === 'settings'" class="tab-content">
@@ -347,46 +288,6 @@ const hasCommandContribution = computed(() =>
.extension-title div { flex: 1; }
.extension-title p { color: var(--color-text-tertiary); font-size: var(--font-size-xs); }
.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;
@@ -396,6 +297,5 @@ const hasCommandContribution = computed(() =>
@media (max-width: 800px) {
.detail-grid { grid-template-columns: 1fr; }
.command-item { grid-template-columns: 1fr; }
}
</style>
+54 -63
View File
@@ -25,28 +25,34 @@ const communityThemes = computed(() => mockCommunityThemes)
function handleFileImport(event: Event) {
const input = event.target as HTMLInputElement
const file = input.files?.[0]
input.value = ''
if (!file) return
actionError.value = ''
const reader = new FileReader()
reader.onload = async () => {
const content = reader.result as string
try {
const result = await themeStore.inspectThemePackage(content)
const result = await themeStore.inspectThemePackage(String(reader.result ?? ''))
if (result.compatible) {
previewThemeId.value = result.manifest.theme_id
} else {
actionError.value = result.warnings[0] ?? '主题包无法解析'
}
} catch (error) {
actionError.value = error instanceof Error ? error.message : '导入失败'
}
}
reader.onerror = () => { actionError.value = '文件读取失败' }
// 主题包是文本格式(YAML 清单 + --- + CSS),二进制包在解析阶段会被拒绝。
reader.readAsText(file)
input.value = ''
}
async function confirmInstall(inspection: ThemePackageInspection) {
actionError.value = ''
try {
// Web Mock 模式:使用社区主题的 CSS 作为演示
const cssText = generateThemeCss(inspection.manifest.theme_id, inspection.manifest.is_dark)
await themeStore.installThemeFromInspection(inspection.manifest, cssText)
// 装的必须是包里那份 CSS —— 之前这里是现场生成的假样式,
// 用户提供的内容被整份丢掉了。
if (!inspection.css.trim()) throw new Error('主题包内没有 CSS 内容,无法安装。')
await themeStore.installThemeFromInspection(inspection.manifest, inspection.css)
showImportDialog.value = false
previewThemeId.value = null
} catch (error) {
@@ -63,59 +69,6 @@ async function installFromCommunity(themeId: string) {
}
}
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
@@ -145,6 +98,10 @@ onMounted(() => {
{{ actionError || themeStore.importError }}
</div>
<div v-if="themeStore.themeLoadWarning" class="warning-banner">
{{ themeStore.themeLoadWarning }}
</div>
<div class="tabs">
<button
class="tab-btn"
@@ -270,7 +227,7 @@ onMounted(() => {
<div class="modal import-modal">
<span class="badge info">主题导入</span>
<h2>导入主题包</h2>
<p class="subtle">支持 YAML Manifest + CSS 主题主题将在安全沙箱中验证后安装</p>
<p class="subtle">单文件主题包YAML 清单 + 一行 <code>---</code> + 主题 CSS安装前会校验清单与 CSS 安全性</p>
<div v-if="themeStore.pendingInspection?.compatible" class="inspection-result">
<div class="inspect-head">
@@ -288,12 +245,16 @@ onMounted(() => {
<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>
<details class="css-preview">
<summary>将要安装的 CSS{{ themeStore.pendingInspection.css.length }} 字符</summary>
<pre>{{ themeStore.pendingInspection.css }}</pre>
</details>
</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>
<input type="file" accept=".yaml,.yml,.theme" @change="handleFileImport" />
<p>点击选择主题包文件</p>
<p class="subtle">支持 .yaml / .yml / .themeZIP 需要 Host 端解压暂不支持</p>
</div>
<div class="inline-actions">
@@ -457,5 +418,35 @@ onMounted(() => {
font-size: var(--font-size-sm);
}
.warning-banner {
padding: var(--space-sm) var(--space-md);
border: 1px solid var(--color-warning);
border-radius: var(--radius-md);
background: var(--color-warning-soft);
color: var(--color-warning);
font-size: var(--font-size-sm);
}
.css-preview {
margin-top: var(--space-md);
}
.css-preview summary {
cursor: pointer;
font-size: var(--font-size-sm);
color: var(--color-text-secondary);
}
.css-preview pre {
margin-top: var(--space-sm);
max-height: 220px;
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;
}
.inline-actions { margin-top: var(--space-lg); justify-content: flex-end; gap: var(--space-sm); }
</style>
+2 -1
View File
@@ -13,6 +13,7 @@ app.use(pinia)
app.use(router)
const themeStore = useThemeStore()
themeStore.initTheme()
// initTheme 先同步落内置主题兜底,自定义主题恢复是异步的,不阻塞挂载。
void themeStore.initTheme()
app.mount('#app')
@@ -0,0 +1,227 @@
import { describe, expect, it, vi } from 'vitest'
import {
applyCommandEffect,
cleanArguments,
coerceArgument,
commandFields,
EFFECT_ROUTES,
initialArguments,
missingRequiredFields,
} from './pluginCommandForm'
import type { PluginCommand, PluginCommandEffect } from '@/contracts'
function command(parameters: Record<string, unknown>): PluginCommand {
return {
command_id: 'demo.run',
plugin_id: 'demo',
title: '示例命令',
description: '',
locations: [],
when: [],
parameters,
enabled: true,
}
}
/** 后端只接受 type=object 的 JSON Schemacontributions.py 显式拒绝其他形态)。 */
const schema = command({
type: 'object',
properties: {
path: { type: 'string', title: '笔记路径', description: '相对于库根目录' },
count: { type: 'integer', default: 3 },
recursive: { type: 'boolean' },
mode: { type: 'string', enum: ['fast', 'full'] },
},
required: ['path', 'mode'],
})
describe('commandFields', () => {
it('摊平 properties 并标记 required', () => {
const fields = commandFields(schema)
expect(fields.map((f) => f.key)).toEqual(['path', 'count', 'recursive', 'mode'])
expect(fields[0]).toMatchObject({ title: '笔记路径', type: 'string', required: true })
expect(fields[1]).toMatchObject({ type: 'integer', required: false, default: 3 })
expect(fields[3].enum).toEqual(['fast', 'full'])
})
it('没有 title 时用字段名兜底,没有 type 时按 string 处理', () => {
const fields = commandFields(command({ type: 'object', properties: { raw: {} } }))
expect(fields[0]).toMatchObject({ key: 'raw', title: 'raw', type: 'string', required: false })
})
it('parameters 为空或形态异常时返回空数组而不是抛错', () => {
expect(commandFields(command({}))).toEqual([])
expect(commandFields(command({ type: 'object' }))).toEqual([])
// properties 被写成数组等非法形态时按空处理
expect(commandFields(command({ type: 'object', properties: ['nope'] as unknown as Record<string, unknown> }))).toEqual([])
})
})
describe('initialArguments', () => {
it('布尔字段显式初始化为 false,保证 UI 显示与提交值一致', () => {
// 回归:之前布尔下拉框显示「否」,但参数对象里没有这个键,
// 用户没手动切换过就会漏发这个参数。
const args = initialArguments(schema)
expect(args.recursive).toBe(false)
expect('recursive' in args).toBe(true)
})
it('有 default 的字段用 default,没有的不塞键', () => {
const args = initialArguments(schema)
expect(args.count).toBe(3)
expect('path' in args).toBe(false)
expect('mode' in args).toBe(false)
})
it('布尔字段的 default 优先于 false', () => {
const args = initialArguments(
command({ type: 'object', properties: { flag: { type: 'boolean', default: true } } }),
)
expect(args.flag).toBe(true)
})
})
describe('coerceArgument', () => {
const field = (type: string) => ({ key: 'k', title: 'k', type, required: false })
it('布尔只认字符串 "true"', () => {
expect(coerceArgument(field('boolean'), 'true')).toBe(true)
expect(coerceArgument(field('boolean'), 'false')).toBe(false)
})
it('数字字段转成 number,空串与非法输入转成 undefined', () => {
expect(coerceArgument(field('integer'), '42')).toBe(42)
expect(coerceArgument(field('number'), '1.5')).toBe(1.5)
expect(coerceArgument(field('number'), '')).toBeUndefined()
expect(coerceArgument(field('number'), 'abc')).toBeUndefined()
})
it('字符串原样保留(含空格)', () => {
expect(coerceArgument(field('string'), ' notes/a.md ')).toBe(' notes/a.md ')
})
})
describe('missingRequiredFields', () => {
it('列出未填的必填字段', () => {
const missing = missingRequiredFields(schema, initialArguments(schema))
expect(missing.map((f) => f.key)).toEqual(['path', 'mode'])
})
it('空白字符串算没填', () => {
const missing = missingRequiredFields(schema, { path: ' ', mode: 'fast' })
expect(missing.map((f) => f.key)).toEqual(['path'])
})
it('布尔 false 是合法值,不算缺失', () => {
const boolSchema = command({
type: 'object',
properties: { flag: { type: 'boolean' } },
required: ['flag'],
})
expect(missingRequiredFields(boolSchema, { flag: false })).toEqual([])
})
it('全部填好时返回空数组', () => {
expect(missingRequiredFields(schema, { path: 'a.md', mode: 'fast' })).toEqual([])
})
})
describe('cleanArguments', () => {
it('丢掉 undefined 的键,保留 false / 0 / 空串', () => {
const cleaned = cleanArguments({ a: undefined, b: false, c: 0, d: '', e: null })
expect(cleaned).toEqual({ b: false, c: 0, d: '', e: null })
expect('a' in cleaned).toBe(false)
})
})
describe('applyCommandEffect', () => {
function handlers() {
return { navigate: vi.fn(), refresh: vi.fn(), notify: vi.fn() }
}
it('navigate 真的触发跳转,而不是只提示一句话', async () => {
// 回归:之前只把 effect 拼成描述文本显示,命令等于没生效。
const h = handlers()
await applyCommandEffect({ type: 'navigate', payload: { route: 'workspace' } }, h)
expect(h.navigate).toHaveBeenCalledWith('/workspace')
expect(h.notify).not.toHaveBeenCalled()
})
it('每个白名单路由都能解析出路径', async () => {
for (const route of Object.keys(EFFECT_ROUTES)) {
const h = handlers()
await applyCommandEffect(
{ type: 'navigate', payload: { route } } as PluginCommandEffect,
h,
)
expect(h.navigate).toHaveBeenCalledWith(EFFECT_ROUTES[route])
}
})
it('未知路由只提示不跳转,避免 router.push(undefined)', async () => {
const h = handlers()
await applyCommandEffect(
{ type: 'navigate', payload: { route: 'nope' } } as unknown as PluginCommandEffect,
h,
)
expect(h.navigate).not.toHaveBeenCalled()
expect(h.notify.mock.calls[0][0]).toContain('nope')
})
it('refresh 真的触发对应 scope 的刷新', async () => {
const h = handlers()
await applyCommandEffect({ type: 'refresh', payload: { scope: 'workspace' } }, h)
expect(h.refresh).toHaveBeenCalledWith('workspace')
})
it('等待异步 refresh 完成后才返回', async () => {
const h = handlers()
let done = false
h.refresh.mockImplementation(async () => {
await Promise.resolve()
done = true
})
await applyCommandEffect({ type: 'refresh', payload: { scope: 'commands' } }, h)
expect(done).toBe(true)
})
it('notification 原样透出插件消息', async () => {
const h = handlers()
await applyCommandEffect(
{ type: 'notification', payload: { level: 'info', message: '索引已重建' } },
h,
)
expect(h.notify).toHaveBeenCalledWith('索引已重建')
})
it('job 提示任务 id', async () => {
const h = handlers()
await applyCommandEffect({ type: 'job', payload: { job_id: 'job_7' } }, h)
expect(h.notify.mock.calls[0][0]).toContain('job_7')
})
it('none 或未知 type 按「已完成」处理,不猜测语义', async () => {
const h = handlers()
await applyCommandEffect({ type: 'none', payload: {} }, h)
expect(h.notify).toHaveBeenCalledWith('命令执行完成。')
expect(h.navigate).not.toHaveBeenCalled()
expect(h.refresh).not.toHaveBeenCalled()
})
})
+152
View File
@@ -0,0 +1,152 @@
import type { PluginCommand, PluginCommandEffect } from '@/contracts'
/** 命令参数的 JSON Schema 字段定义(后端用 Draft 2020-12 校验)。 */
export interface CommandField {
key: string
title: string
type: string
required: boolean
enum?: string[]
default?: unknown
description?: string
}
function asRecord(value: unknown): Record<string, unknown> {
return value && typeof value === 'object' && !Array.isArray(value)
? (value as Record<string, unknown>)
: {}
}
/**
* 把命令的 parametersobject schema)摊平成表单字段。
*
* 后端只接受 type=object 的 schemacontributions.py 里显式拒绝其他形态),
* 所以这里只处理 properties + required 两个键,嵌套对象按文本输入兜底。
*/
export function commandFields(command: PluginCommand): CommandField[] {
const schema = asRecord(command.parameters)
const properties = asRecord(schema.properties)
const requiredKeys = Array.isArray(schema.required) ? schema.required.map(String) : []
return Object.entries(properties).map(([key, rawDefinition]) => {
const definition = asRecord(rawDefinition)
return {
key,
title: typeof definition.title === 'string' && definition.title ? definition.title : key,
type: typeof definition.type === 'string' ? definition.type : 'string',
required: requiredKeys.includes(key),
enum: Array.isArray(definition.enum) ? definition.enum.map(String) : undefined,
default: definition.default,
description: typeof definition.description === 'string' ? definition.description : undefined,
}
})
}
/**
* 表单初始值。
*
* 布尔字段必须显式给 false —— 下拉框默认显示「否」,如果参数对象里
* 没有这个键,用户看到的和实际提交的就不一致。
*/
export function initialArguments(command: PluginCommand): Record<string, unknown> {
const result: Record<string, unknown> = {}
for (const field of commandFields(command)) {
if (field.default !== undefined) result[field.key] = field.default
else if (field.type === 'boolean') result[field.key] = false
}
return result
}
/** 按字段类型把输入框的字符串转成 schema 期望的类型。 */
export function coerceArgument(field: CommandField, raw: string): unknown {
if (field.type === 'boolean') return raw === 'true'
if (field.type === 'number' || field.type === 'integer') {
if (raw.trim() === '') return undefined
const parsed = Number(raw)
return Number.isNaN(parsed) ? undefined : parsed
}
return raw
}
function isBlank(value: unknown): boolean {
if (value === undefined || value === null) return true
return typeof value === 'string' && value.trim() === ''
}
/**
* 找出还没填的必填字段。
*
* 后端会用 JSON Schema 再校验一次,这里做前置检查只为了别让用户
* 提交一次才知道少填了什么。布尔的 false 是合法值,不算缺失。
*/
export function missingRequiredFields(
command: PluginCommand,
args: Record<string, unknown>,
): CommandField[] {
return commandFields(command).filter((field) => field.required && isBlank(args[field.key]))
}
/** undefined 的键不该出现在请求体里。 */
export function cleanArguments(args: Record<string, unknown>): Record<string, unknown> {
const result: Record<string, unknown> = {}
for (const [key, value] of Object.entries(args)) {
if (value !== undefined) result[key] = value
}
return result
}
/** navigate effect 的路由白名单,与 router/index.ts 的路径一一对应。 */
export const EFFECT_ROUTES: Record<string, string> = {
'vault-entry': '/',
workspace: '/workspace',
search: '/search',
chat: '/chat',
agent: '/agent/runs',
tasks: '/tasks',
skills: '/extensions/skills',
plugins: '/extensions/plugins',
themes: '/themes',
settings: '/settings',
}
export interface EffectHandlers {
navigate: (path: string) => Promise<unknown> | unknown
refresh: (scope: 'workspace' | 'commands' | 'settings' | 'plugins') => Promise<unknown> | unknown
notify: (message: string) => void
}
/**
* 执行命令返回的 effect。
*
* navigate / refresh 必须真的发生 —— 之前这里只是把 effect 拼成一句话
* 显示给用户,命令等于没生效。未知 type 一律按「已完成」处理,
* 不猜测语义。
*/
export async function applyCommandEffect(
effect: PluginCommandEffect,
handlers: EffectHandlers,
): Promise<void> {
switch (effect.type) {
case 'notification':
handlers.notify(effect.payload.message)
return
case 'navigate': {
const path = EFFECT_ROUTES[effect.payload.route]
if (!path) {
handlers.notify(`命令请求跳转到未知路由「${effect.payload.route}」,已忽略。`)
return
}
await handlers.navigate(path)
return
}
case 'refresh':
await handlers.refresh(effect.payload.scope)
handlers.notify('相关数据已刷新。')
return
case 'job':
handlers.notify(`已创建后台任务:${effect.payload.job_id}`)
return
default:
handlers.notify('命令执行完成。')
}
}
Binary file not shown.
+56 -27
View File
@@ -66,18 +66,6 @@ function validateCssSafety(css: string): string[] {
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) {
@@ -116,27 +104,61 @@ function inspectYamlContent(yamlText: string): ThemeManifest {
return manifest
}
/**
* 主题包是单文件文本格式:YAML 清单 + 一行 `---` + 主题 CSS。
*
* theme_id: my-theme
* name: My Theme
* ...
* ---
* [data-theme="my-theme"] { --color-... }
*
* 浏览器端没有解压能力,所以不支持 ZIP —— 与其把二进制当文本解析出
* 一堆乱码再报「清单无效」,不如直接告诉用户格式不支持。
*/
export function parseThemePackage(packageData: string): { manifestText: string; css: string } {
if (looksLikeZip(packageData)) {
throw new Error(
'THEME_PACKAGE_UNSUPPORTED_FORMAT: 暂不支持 ZIP 主题包,请提供「YAML 清单 + --- + CSS」的单文件主题。',
)
}
const lines = packageData.split(/\r?\n/)
const separatorIndex = lines.findIndex((line) => line.trim() === '---')
if (separatorIndex < 0) {
throw new Error(
'THEME_PACKAGE_INVALID: 主题包缺少 `---` 分隔行,无法区分清单与 CSS。',
)
}
const manifestText = lines.slice(0, separatorIndex).join('\n')
const css = lines.slice(separatorIndex + 1).join('\n').trim()
if (!css) {
throw new Error('THEME_CSS_INVALID: 主题包内没有 CSS 内容。')
}
return { manifestText, css }
}
/** ZIP 的魔数是 PK\x03\x04base64 形式(readAsDataURL)开头是 UEsDB。 */
function looksLikeZip(data: string): boolean {
if (data.startsWith('PK')) return true
return /^data:.*;base64,UEsDB/.test(data) || data.startsWith('UEsDB')
}
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'
// 只接受能在浏览器里解析的单文件主题;ZIP 需要 Host 端解压,暂不支持。
input.accept = '.yaml,.yml,.theme'
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.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)
}
reader.readAsText(file)
}
input.oncancel = () => resolve(null)
input.click()
@@ -146,10 +168,13 @@ export async function selectThemePackage(): Promise<string | null> {
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 会检查包内文件
const { manifestText, css } = parseThemePackage(packageData)
const manifest = inspectYamlContent(manifestText)
// CSS 的安全校验放在这里,不合规的包在「预览」阶段就该被拒,
// 而不是等到用户点安装。
const warnings = validateCssSafety(css)
if (!css.includes(`[data-theme="${manifest.theme_id}"]`)) {
warnings.push(`CSS 未包含 [data-theme="${manifest.theme_id}"] 选择器,主题可能不会生效。`)
}
return {
package_id,
@@ -157,6 +182,7 @@ export async function inspectThemePackage(packageData: string): Promise<ThemePac
preview_url: '',
warnings,
compatible: true,
css,
}
} catch (error) {
const message = error instanceof Error ? error.message : '未知错误'
@@ -168,6 +194,7 @@ export async function inspectThemePackage(packageData: string): Promise<ThemePac
warnings: [message],
compatible: false,
error_code,
css: '',
}
}
}
@@ -176,6 +203,8 @@ export async function installTheme(
manifest: ThemeManifest,
cssContent: string,
): Promise<InstalledTheme> {
// validateCssSafety 会对 @import / expression() / javascript: 抛错,
// 必须在 applyThemeCss 之前调用 —— 未校验的 CSS 一律不许进入页面。
const warnings = validateCssSafety(cssContent)
if (warnings.length > 0) {
console.warn('[theme] CSS validation warnings:', warnings)
+94 -19
View File
@@ -12,54 +12,129 @@ function event(
return { event: type, sequence: ++sequence, run_id: 'run-1', data, timestamp }
}
/**
* 后端真实的事件顺序(backend/app/agent/runtime.py):
* ModelCallStarted → ModelCallCompleted → Usage → ToolCall → ToolResult
* 工具在模型调用「完成之后」才执行,而且多个工具并发跑(asyncio.gather +
* Semaphore),事件会交错到达。所以建树只能靠 id 关联,不能靠相邻顺序。
*/
describe('buildTraceNodes', () => {
it('把模型调用期间的事件挂到该模型调用之下', () => {
it('工具事件按 parent_model_call_id 归属,即使出现在 ModelCallCompleted 之后', () => {
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('ModelCallStarted', { model_call_id: 'mc-1', model: 'mock-1', provider_id: 'mock' }),
event('ModelCallCompleted', { model_call_id: 'mc-1', duration_ms: 1200, finish_reason: 'tool_calls' }),
event('Usage', { token_usage: 320 }),
event('ToolCall', { tool_call_id: 'tc-1', name: 'read_note', parent_model_call_id: 'mc-1' }),
event('ToolResult', { tool_call_id: 'tc-1', name: 'read_note', success: true, duration_ms: 40, parent_model_call_id: 'mc-1' }),
event('RunCompleted'),
])
// 顶层只剩:运行开始、模型调用、运行完成
expect(nodes).toHaveLength(3)
// 顶层:运行开始、模型调用、Usage、运行完成。工具挂在模型调用下面。
expect(nodes.map((n) => n.type)).toEqual(['run', 'model_call', 'usage', 'complete'])
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'])
expect(modelCall.children.map((c) => c.type)).toEqual(['tool_call'])
})
it('模型调用失败时标记为 error', () => {
it('ToolResult 回填对应 ToolCall 的状态,结束后不再显示 running', () => {
const nodes = buildTraceNodes([
event('ModelCallStarted', { model: 'mock-1' }),
event('ModelCallFailed', { error_code: 'PROVIDER_TIMEOUT' }),
event('ModelCallStarted', { model_call_id: 'mc-2' }),
event('ModelCallCompleted', { model_call_id: 'mc-2' }),
event('ToolCall', { tool_call_id: 'tc-2', name: 'read_note', parent_model_call_id: 'mc-2' }),
event('ToolResult', { tool_call_id: 'tc-2', name: 'read_note', success: true, duration_ms: 55, parent_model_call_id: 'mc-2' }),
])
const toolCall = nodes[0].children[0]
expect(toolCall.type).toBe('tool_call')
expect(toolCall.status).toBe('completed')
expect(toolCall.duration_ms).toBe(55)
// 结果数据合并进调用节点,展开详情时能看到 output。
expect((toolCall.data.result as Record<string, unknown>).success).toBe(true)
})
it('工具失败时把 ToolCall 标记为 error 并带上 error_code', () => {
const nodes = buildTraceNodes([
event('ModelCallStarted', { model_call_id: 'mc-3' }),
event('ToolCall', { tool_call_id: 'tc-3', name: 'write_note', parent_model_call_id: 'mc-3' }),
event('ToolResult', { tool_call_id: 'tc-3', name: 'write_note', success: false, error_code: 'TOOL_DENIED', parent_model_call_id: 'mc-3' }),
])
const toolCall = nodes[0].children[0]
expect(toolCall.status).toBe('error')
expect(toolCall.subtitle).toContain('TOOL_DENIED')
})
it('并发工具交错到达时各自归属到正确的模型调用', () => {
const nodes = buildTraceNodes([
event('ModelCallStarted', { model_call_id: 'mc-a' }),
event('ModelCallCompleted', { model_call_id: 'mc-a' }),
event('ToolCall', { tool_call_id: 'a1', name: 'toolA1', parent_model_call_id: 'mc-a' }),
event('ToolCall', { tool_call_id: 'a2', name: 'toolA2', parent_model_call_id: 'mc-a' }),
event('ModelCallStarted', { model_call_id: 'mc-b' }),
event('ModelCallCompleted', { model_call_id: 'mc-b' }),
event('ToolCall', { tool_call_id: 'b1', name: 'toolB1', parent_model_call_id: 'mc-b' }),
// 第一个模型调用的工具结果比第二轮的工具调用还晚到
event('ToolResult', { tool_call_id: 'a2', name: 'toolA2', success: true, parent_model_call_id: 'mc-a' }),
event('ToolResult', { tool_call_id: 'a1', name: 'toolA1', success: true, parent_model_call_id: 'mc-a' }),
event('ToolResult', { tool_call_id: 'b1', name: 'toolB1', success: true, parent_model_call_id: 'mc-b' }),
])
const [callA, callB] = nodes.filter((n) => n.type === 'model_call')
expect(callA.children.map((c) => c.title)).toEqual(['工具调用:toolA1', '工具调用:toolA2'])
expect(callB.children.map((c) => c.title)).toEqual(['工具调用:toolB1'])
expect(callA.children.every((c) => c.status === 'completed')).toBe(true)
})
it('模型调用失败时标记为 error 并附带 error_code', () => {
const nodes = buildTraceNodes([
event('ModelCallStarted', { model_call_id: 'mc-4', model: 'mock-1' }),
event('ModelCallFailed', { model_call_id: 'mc-4', error_code: 'PROVIDER_TIMEOUT', duration_ms: 900 }),
])
expect(nodes).toHaveLength(1)
expect(nodes[0].status).toBe('error')
expect(nodes[0].duration_ms).toBe(900)
expect(nodes[0].subtitle).toContain('PROVIDER_TIMEOUT')
})
it('PermissionRequired 不带父 id,留在顶层', () => {
const nodes = buildTraceNodes([
event('ModelCallStarted', { model_call_id: 'mc-5' }),
event('PermissionRequired', { request_id: 'r1', permission: 'notes.write' }),
])
expect(nodes.map((n) => n.type)).toEqual(['model_call', 'permission'])
expect(nodes[1].status).toBe('pending')
})
it('运行级事件始终留在顶层,不会被模型调用吞掉', () => {
const nodes = buildTraceNodes([
event('ModelCallStarted', { model: 'mock-1' }),
event('ModelCallStarted', { model_call_id: 'mc-6' }),
event('RunFailed', { error_code: 'RUN_TIMEOUT' }),
])
expect(nodes.map((n) => n.type)).toEqual(['model_call', 'error'])
})
it('模型调用之外的事件保持在顶层', () => {
it('SSE 断点恢复只拿到后半段时,孤立事件退回顶层而不是被丢弃', () => {
// 没有 ModelCallStarted,也没有对应的 ToolCall
const nodes = buildTraceNodes([
event('RunStarted'),
event('ToolCall', { name: 'search' }),
event('RunCompleted'),
event('ModelCallCompleted', { model_call_id: 'mc-lost', duration_ms: 10 }),
event('ToolResult', { tool_call_id: 'tc-lost', name: 'read_note', success: false, error_code: 'TOOL_FAILED' }),
])
expect(nodes).toHaveLength(3)
expect(nodes.every((n) => n.children.length === 0)).toBe(true)
expect(nodes).toHaveLength(2)
expect(nodes[0].type).toBe('model_call')
// 落单的失败结果不能显示成 completed
expect(nodes[1].status).toBe('error')
})
it('Usage 副标题读后端真实字段 token_usage', () => {
const nodes = buildTraceNodes([event('Usage', { token_usage: 1234 })])
expect(nodes[0].subtitle).toBe('1234 tokens')
})
it('空事件列表返回空树', () => {
+106 -54
View File
@@ -1,74 +1,121 @@
import type { AgentEvent, TraceNode, TraceNodeType } from '@/contracts'
/**
* 把扁平事件流折叠成调用树。
*
* 归属关系一律走 id,不依赖事件相邻顺序 —— 后端的真实顺序是
* ModelCallStarted → ModelCallCompleted → Usage → ToolCall/ToolResult
* 工具在模型调用「完成」之后才执行,并且多个工具是并发跑的
* runtime.py 里 asyncio.gather + Semaphore),事件会交错到达。
* 因此工具事件用 data.parent_model_call_id 找父节点,
* ToolResult 用 data.tool_call_id 回填对应 ToolCall 的状态。
*/
export function buildTraceNodes(events: AgentEvent[]): TraceNode[] {
const nodes: TraceNode[] = []
let currentModelCallId: string | null = null
const roots: TraceNode[] = []
/** model_call_id -> 模型调用节点 */
const modelCalls = new Map<string, TraceNode>()
/** tool_call_id -> 工具调用节点,供 ToolResult 回填状态 */
const toolCalls = new Map<string, TraceNode>()
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,
id: `seq-${event.sequence}`,
sequence: event.sequence,
type,
title,
subtitle,
status,
type: mapEventType(event.event),
title: getNodeTitle(event),
subtitle: getNodeSubtitle(event),
status: getNodeStatus(event),
data: event.data,
timestamp: event.timestamp,
children: [],
}
const modelCallId = asId(event.data.model_call_id)
const parentModelCallId = asId(event.data.parent_model_call_id)
const toolCallId = asId(event.data.tool_call_id)
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
switch (event.event) {
case 'ModelCallStarted': {
if (modelCallId) modelCalls.set(modelCallId, node)
roots.push(node)
continue
}
continue
}
if (currentModelCallId && type !== 'run' && type !== 'complete' && type !== 'error') {
const parent = findNodeById(nodes, currentModelCallId)
if (parent) {
node.parent_id = currentModelCallId
parent.children.push(node)
// 完成/失败事件不单独成节点,只更新对应模型调用的状态。
case 'ModelCallCompleted':
case 'ModelCallFailed': {
const target = modelCallId ? modelCalls.get(modelCallId) : undefined
if (!target) {
// 找不到配对的 Started(例如 SSE 断点恢复后只拿到后半段),保留为顶层节点。
roots.push(node)
continue
}
target.status = event.event === 'ModelCallCompleted' ? 'completed' : 'error'
const duration = asNumber(event.data.duration_ms)
if (duration != null) target.duration_ms = duration
const extra = event.event === 'ModelCallCompleted'
? asText(event.data.finish_reason)
: asText(event.data.error_code)
if (extra) target.subtitle = target.subtitle ? `${target.subtitle} · ${extra}` : extra
continue
}
// ToolResult 只回填对应 ToolCall,避免工具结束后仍显示 running。
case 'ToolResult': {
const target = toolCallId ? toolCalls.get(toolCallId) : undefined
if (!target) {
attach(node, parentModelCallId, modelCalls, roots)
continue
}
target.status = event.data.success === false ? 'error' : 'completed'
const duration = asNumber(event.data.duration_ms)
if (duration != null) target.duration_ms = duration
const detail = event.data.success === false
? asText(event.data.error_code) ?? '失败'
: undefined
if (detail) target.subtitle = target.subtitle ? `${target.subtitle} · ${detail}` : detail
// 结果数据合并到调用节点,展开详情时才能看到 output。
target.data = { ...target.data, result: event.data }
continue
}
case 'ToolCall': {
if (toolCallId) toolCalls.set(toolCallId, node)
attach(node, parentModelCallId, modelCalls, roots)
continue
}
default: {
attach(node, parentModelCallId, modelCalls, roots)
continue
}
}
nodes.push(node)
}
return nodes
return roots
}
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
/** 有已知父模型调用就挂进去,否则留在顶层。 */
function attach(
node: TraceNode,
parentModelCallId: string | null,
modelCalls: Map<string, TraceNode>,
roots: TraceNode[],
) {
const parent = parentModelCallId ? modelCalls.get(parentModelCallId) : undefined
if (parent) {
node.parent_id = parent.id
parent.children.push(node)
return
}
return null
roots.push(node)
}
function asId(value: unknown): string | null {
return typeof value === 'string' && value !== '' ? value : null
}
function asText(value: unknown): string | undefined {
return typeof value === 'string' && value !== '' ? value : undefined
}
function mapEventType(eventType: AgentEvent['event']): TraceNodeType {
@@ -132,12 +179,12 @@ function getNodeSubtitle(event: AgentEvent): string | 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`
// 后端发的是累计 token_usageruntime.py),其余字段仅作兼容回退
const usage = asNumber(data.token_usage) ?? asNumber(data.total_tokens)
if (usage != null) return `${usage} tokens`
const input = asNumber(data.input_tokens)
const output = asNumber(data.output_tokens)
if (input == null && output == null) return '- tokens'
if (input == null && output == null) return undefined
return `${(input ?? 0) + (output ?? 0)} tokens`
}
case 'PermissionRequired':
@@ -154,14 +201,19 @@ function getNodeStatus(event: AgentEvent): TraceNode['status'] {
case 'RunFailed':
case 'ModelCallFailed':
return 'error'
case 'ToolResult':
// 只在 ToolResult 没配上 ToolCall 时(SSE 断点恢复)才成为独立节点,
// 那时也要按 success 显示,不能一律算成功。
return event.data.success === false ? 'error' : 'completed'
case 'RunCompleted':
case 'RunCancelled':
case 'ModelCallCompleted':
case 'ToolResult':
case 'Usage':
case 'PermissionResolved':
return 'completed'
case 'ToolCall':
// 后端的 ToolCall 事件不带 status,起始一律 running
// 由后到的 ToolResult 回填最终状态。
if (event.data.status === 'completed') return 'completed'
if (event.data.status === 'error') return 'error'
return 'running'
+133 -2
View File
@@ -1,8 +1,41 @@
// @vitest-environment happy-dom
import { beforeEach, describe, expect, it } from 'vitest'
import { beforeEach, describe, expect, it, vi } from 'vitest'
import { createPinia, setActivePinia } from 'pinia'
import { nextTick } from 'vue'
import type { InstalledTheme } from '@/contracts'
import { useThemeStore } from './theme'
import * as themePkg from '@/services/themePackageService'
vi.mock('@/services/themePackageService', () => ({
listInstalledThemes: vi.fn(async () => []),
inspectThemePackage: vi.fn(),
installTheme: vi.fn(),
uninstallTheme: vi.fn(),
installCommunityTheme: vi.fn(),
}))
const listInstalledThemes = vi.mocked(themePkg.listInstalledThemes)
function customTheme(themeId: string, isDark = false): InstalledTheme {
return {
theme_id: themeId,
name: themeId,
version: '1.0.0',
author: '社区',
is_dark: isDark,
builtin: false,
enabled: true,
manifest: {
theme_id: themeId,
name: themeId,
version: '1.0.0',
author: '社区',
min_app_version: '0.1.0',
is_dark: isDark,
css_entry: 'theme.css',
},
}
}
beforeEach(() => {
localStorage.clear()
@@ -13,6 +46,8 @@ beforeEach(() => {
configurable: true,
value: () => ({ matches: false }),
})
listInstalledThemes.mockReset()
listInstalledThemes.mockResolvedValue([])
})
describe('代码块主题偏好', () => {
@@ -38,10 +73,106 @@ describe('代码块主题偏好', () => {
it('恢复持久化的代码块主题偏好', async () => {
localStorage.setItem('editor-appearance', JSON.stringify({ codeBlockTheme: 'github-dark' }))
const store = useThemeStore()
store.initTheme()
await store.initTheme()
await nextTick()
expect(store.codeBlockTheme).toBe('github-dark')
expect(document.documentElement.dataset.codeTheme).toBe('github-dark')
})
})
describe('initTheme 恢复已保存主题', () => {
it('等自定义主题加载完成后再恢复,不会停在没有 data-theme 的裸状态', async () => {
// 回归:之前这里是 `void loadCustomThemes()` 没有 await
// applyTheme('ocean') 在主题列表到达前找不到主题直接 return,
// 页面上一个 data-theme 都没有。
localStorage.setItem('theme', 'ocean')
listInstalledThemes.mockResolvedValue([customTheme('ocean', true)])
const store = useThemeStore()
await store.initTheme()
expect(document.documentElement.getAttribute('data-theme')).toBe('ocean')
expect(store.currentThemeId).toBe('ocean')
expect(store.themeLoadWarning).toBeNull()
})
it('首屏先同步落内置主题兜底,且不覆盖保存的自定义主题 id', async () => {
localStorage.setItem('theme', 'ocean')
let resolveList: (themes: InstalledTheme[]) => void = () => {}
listInstalledThemes.mockReturnValue(
new Promise<InstalledTheme[]>((resolve) => { resolveList = resolve }),
)
const store = useThemeStore()
const pending = store.initTheme()
// 接口还没回来:页面已经有兜底主题,不是裸的
expect(document.documentElement.getAttribute('data-theme')).toBe('light')
// 兜底不能把用户存的主题 id 冲掉,否则刷新后自定义主题就丢了
expect(localStorage.getItem('theme')).toBe('ocean')
resolveList([customTheme('ocean', true)])
await pending
expect(document.documentElement.getAttribute('data-theme')).toBe('ocean')
})
it('保存的主题已被卸载时回退到默认主题并给出提示', async () => {
localStorage.setItem('theme', 'removed-theme')
listInstalledThemes.mockResolvedValue([])
const store = useThemeStore()
await store.initTheme()
expect(document.documentElement.getAttribute('data-theme')).toBe('light')
expect(store.currentThemeId).toBe('light')
expect(store.themeLoadWarning).toContain('removed-theme')
// 失效记录要清掉,避免每次启动都报一遍
expect(localStorage.getItem('theme')).toBe('light')
})
it('主题列表加载失败时提示用户,而不是静默只剩内置主题', async () => {
localStorage.setItem('theme', 'dark')
listInstalledThemes.mockRejectedValue(new Error('网络不可用'))
const store = useThemeStore()
await store.initTheme()
expect(store.themeLoadWarning).toBe('自定义主题加载失败:网络不可用')
// 内置主题仍然要正常恢复
expect(document.documentElement.getAttribute('data-theme')).toBe('dark')
})
it('没有保存过主题时按系统偏好选择', async () => {
Object.defineProperty(window, 'matchMedia', {
configurable: true,
value: () => ({ matches: true }),
})
const store = useThemeStore()
await store.initTheme()
expect(document.documentElement.getAttribute('data-theme')).toBe('dark')
expect(localStorage.getItem('theme')).toBe('dark')
})
})
describe('applyTheme 返回值', () => {
it('主题不存在时返回 false 且不改动 data-theme', () => {
const store = useThemeStore()
store.applyTheme('light')
expect(store.applyTheme('not-installed')).toBe(false)
expect(document.documentElement.getAttribute('data-theme')).toBe('light')
expect(store.currentThemeId).toBe('light')
})
it('persist: false 时不写 localStorage', () => {
const store = useThemeStore()
expect(store.applyTheme('sepia', { persist: false })).toBe(true)
expect(document.documentElement.getAttribute('data-theme')).toBe('sepia')
expect(localStorage.getItem('theme')).toBeNull()
})
})
+48 -11
View File
@@ -47,6 +47,8 @@ export const useThemeStore = defineStore('theme', () => {
const codeBlockTheme = ref<CodeBlockThemePreference>('auto')
const isImporting = ref(false)
const importError = ref<string | null>(null)
// 主题恢复阶段的提示(保存的主题已卸载、主题列表加载失败等),与导入错误分开。
const themeLoadWarning = ref<string | null>(null)
const pendingInspection = ref<ThemePackageInspection | null>(null)
let appearanceHydrated = false
@@ -66,9 +68,10 @@ export const useThemeStore = defineStore('theme', () => {
return currentTheme.value?.code_theme ?? (isDark.value ? 'github-dark' : 'github-light')
})
function applyTheme(themeId: string) {
/** 应用主题;返回 false 表示该主题当前不存在(未安装或还没加载完)。 */
function applyTheme(themeId: string, options: { persist?: boolean } = {}): boolean {
const theme = allThemes.value.find((t) => t.theme_id === themeId)
if (!theme) return
if (!theme) return false
currentThemeId.value = themeId
const root = document.documentElement
if (theme.builtin) {
@@ -82,10 +85,28 @@ export const useThemeStore = defineStore('theme', () => {
} else {
root.setAttribute('data-theme', themeId)
}
localStorage.setItem('theme', themeId)
if (options.persist !== false) localStorage.setItem('theme', themeId)
return true
}
function initTheme() {
function isBuiltinThemeId(themeId: string): boolean {
return builtinThemes.some((t) => t.theme_id === themeId)
}
function systemThemeId(): string {
return window.matchMedia?.('(prefers-color-scheme: dark)').matches ? 'dark' : 'light'
}
/**
*
*
* listInstalledThemes allThemes
* loadCustomThemes applyTheme
* return data-theme
* localStorage
* id
*/
async function initTheme(): Promise<void> {
const savedAppearance = localStorage.getItem('editor-appearance')
if (savedAppearance) {
try {
@@ -96,16 +117,25 @@ 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) {
applyTheme(saved)
const saved = localStorage.getItem('theme')
const fallback = systemThemeId()
applyTheme(saved && isBuiltinThemeId(saved) ? saved : fallback, { persist: false })
await loadCustomThemes()
if (!saved) {
applyTheme(fallback)
return
}
const prefersDark = window.matchMedia('(prefers-color-scheme: dark)').matches
applyTheme(prefersDark ? 'dark' : 'light')
if (applyTheme(saved)) return
// 保存的主题已被卸载,或主题列表加载失败:回退并清掉失效记录。
themeLoadWarning.value = `主题「${saved}」已不可用,已回退到默认主题。`
localStorage.removeItem('theme')
applyTheme(fallback)
}
async function loadCustomThemes() {
@@ -122,7 +152,13 @@ export const useThemeStore = defineStore('theme', () => {
author: t.author,
code_theme: t.code_theme,
}))]
} catch { /* keep builtin only */ }
themeLoadWarning.value = null
} catch (error) {
// 只保留内置主题,但要让用户知道自定义主题这次没加载上。
themeLoadWarning.value = error instanceof Error
? `自定义主题加载失败:${error.message}`
: '自定义主题加载失败。'
}
}
function toggleTheme() {
@@ -272,6 +308,7 @@ export const useThemeStore = defineStore('theme', () => {
resolvedCodeBlockTheme,
isImporting,
importError,
themeLoadWarning,
pendingInspection,
allThemes,
applyTheme,
+7
View File
@@ -62,6 +62,12 @@ export const useWorkspaceStore = defineStore('workspace', () => {
recentVaults.value = await workspaceService.getRecentVaults()
}
/** 重新拉取文件树。插件命令返回 refresh:workspace 时需要。 */
async function refreshFileTree() {
if (!hasVault.value) return
fileTree.value = await workspaceService.getFileTree()
}
async function openVault(path: string) {
isLoading.value = true
try {
@@ -161,6 +167,7 @@ export const useWorkspaceStore = defineStore('workspace', () => {
closeFile,
setActiveFile,
loadRecentVaults,
refreshFileTree,
openVault,
createVault,
addFileToTree,