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(此前只拼成文本显示);补上必填校验与布尔字段初始值,
   修正「显示否但不提交该键」的不一致。

补充回归测试 64 项(相关 spec 由 25 项增至 89 项),并对 2、3、4 三项
缺陷做了变异验证:把修复回退成原写法后对应测试确实失败。
涉及 traceService / theme store / themePackageService / pluginCommandForm /
useCitationNavigation / TraceTimeline,其中后三个为新增文件。

vue-tsc -b、vitest(32 文件 182 项)、vite build 全部通过。
This commit is contained in:
2026-09-05 10:04:17 +08:00
parent e70c0b198c
commit f21c7861e4
22 changed files with 1573 additions and 390 deletions
@@ -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>