diff --git a/docs/code-slimming-audit.md b/docs/code-slimming-audit.md index bbb4a518..21d5d508 100644 --- a/docs/code-slimming-audit.md +++ b/docs/code-slimming-audit.md @@ -1,4 +1,4 @@ -# 代码瘦身审计与第一批改动 +# 代码瘦身审计与实施记录 审计日期:2026-09-16。基线:`d5efe5ced`。目标:保留现有功能,减少重复维护和理解成本。 @@ -54,11 +54,22 @@ 第一批生产源码净减少 **3,819 行**,已计入新增共享逻辑,未把新增测试和本文档计入生产源码。 +## 第二批已实施:Skill 安装模型配置 + +基于第一批合并后的 `bfa7f0ed6`,将 `SandboxSkillsPanel.vue` 和 `SkillSettings.vue` 的重复配置逻辑收敛到 `composables/useSkillInstallerModel.ts`。生产源码净减少 40 行。 + +- 两个页面复用模型读取、最近聊天模型回退、保存、选择器错误通知和 loading 处理;每个实例仍保持独立状态。 +- 保存只替换配置中的 `model_id`,保留现有 Agent 元数据与其他配置;读取失败、返回缺少 data、localStorage 不可用时沿用原有回退行为。 +- 面板清空配置时调用 `resetInstallerModel`,继续清除已加载 Agent 与模型选择。此方法不增加异步请求取消语义。 +- 页面继续控制何时加载、何时安装以及安装前的保存。进度订阅、安装/卸载流程、模板和样式未修改。 +- 新增 10 项行为测试,覆盖优先级、回退、配置保留、响应缺省、保存失败重试、错误传播与实例隔离。 +- `scripts/verify_frontend_pr.sh` 通过:917 项前端测试、类型检查和生产构建。两个页面的 template/style 与本批基线逐字节一致。未做浏览器视觉验收;未修改或测试后端。 + ## 后续优先级 | 优先级 | 证据 | 建议边界 | 验证重点 | | --- | --- | --- | --- | -| P1 | `SandboxSkillsPanel.vue:1240` 与 `SkillSettings.vue:891` 重复安装模型读取、持久化、错误处理;面板最近 200 个非 merge commit 中变更 10 次 | 提取安装模型配置 composable;先统一这一块,再让面板复用已有 `useConfigSkillInstallProgress` | 默认模型回退、保存失败、同 skill 重试、卸载进度、配置切换与取消订阅 | +| P1 | 安装模型配置已在第二批收敛;面板的进度订阅仍与 `useConfigSkillInstallProgress` 重复 | 让面板复用已有进度 composable,保留各页面完成事件的处理 | 同 skill 重试、卸载进度、配置切换与取消订阅 | | P1 | `useChatCitationPopover.ts` 与 `useEmbedCitationPopover.ts` 重复浮层状态、定位、计时和事件绑定 | 共享交互状态;通过参数提供内容加载、缓存作用域和点击行为 | 普通/嵌入鉴权、缓存隔离、根节点替换、悬停竞争与卸载 | | P2 | `AgentEditorModal.vue` 6,756 行,其中 script 3,023 行;近期变更 9 次 | 按提示词编辑、知识库选择、工具配置分离状态和表单序列化责任 | 编辑回填、模式切换、保存 payload 保持兼容 | | P2 | `WikiBrowser.vue` 6,592 行,其中 script 4,086 行;`FAQEntryManager.vue` 5,650 行,其中 style 2,780 行 | 分开文档导航/编辑状态、批量动作与可复用展示区域 | 页面切换后的异步结果、选中项、保存与批量操作 | @@ -110,4 +121,4 @@ - 构建仍报告大 chunk 提示;本轮未以 bundle 体积为目标,也没有测量构建前后的体积差异。 - 未修改后端,未运行后端测试;未做浏览器视觉验收。 -下一批优先处理 Skill 安装模型配置与进度重复。涉及聊天、任务重试、权限或共享状态的改动应单独成批,以可验证的行为等价为边界。 +下一批优先处理 Skill 安装进度订阅的重复。涉及聊天、任务重试、权限或共享状态的改动应单独成批,以可验证的行为等价为边界。 diff --git a/frontend/src/components/SandboxSkillsPanel.vue b/frontend/src/components/SandboxSkillsPanel.vue index a1ca1210..f3d8995d 100644 --- a/frontend/src/components/SandboxSkillsPanel.vue +++ b/frontend/src/components/SandboxSkillsPanel.vue @@ -612,11 +612,7 @@ import ModelSelector from '@/components/ModelSelector.vue' import SkillInstallTimeline from '@/components/SkillInstallTimeline.vue' import { SETTING_DRAWER_HEADER_ACTIONS_ID } from '@/components/settings/SettingDrawer.vue' import { SKILL_ICON } from '@/types/mention' -import { - getAgentById, - updateAgent, - type CustomAgent, -} from '@/api/agent' +import { useSkillInstallerModel } from '@/composables/useSkillInstallerModel' import { configSkillInstallEventsUrl, deleteConfigSkill, @@ -710,12 +706,10 @@ const progressById = ref>({}) const abortBySkill = new Map() let pollTimer: number | null = null -const INSTALLER_AGENT_ID = 'builtin-skill-installer' -const LAST_CHAT_MODEL_KEY = 'weknora_last_chat_model_id' - -const installerAgent = ref(null) -const installerModelId = ref('') -const savingInstallerModel = ref(false) +const { + installerModelId, savingInstallerModel, loadInstallerModel, persistInstallerModel, + onInstallerModelChange, resetInstallerModel, +} = useSkillInstallerModel() function normalizeSkillRollout(value?: string): 'next_turn' | 'new_session' { return value === 'new_session' ? 'new_session' : 'next_turn' @@ -735,14 +729,6 @@ const deleteHint = computed(() => : t('settings.sandbox.skillDeleteHint'), ) -function readLastChatModelID(): string { - try { - return localStorage.getItem(LAST_CHAT_MODEL_KEY) || '' - } catch { - return '' - } -} - const STATUS_I18N: Record = { installing: 'settings.sandbox.skillStatusInstalling', ready: 'settings.sandbox.skillStatusReady', @@ -1237,48 +1223,6 @@ defineExpose({ revealSkill, }) -async function loadInstallerModel() { - try { - const res = await getAgentById(INSTALLER_AGENT_ID) - installerAgent.value = res?.data || null - const configured = installerAgent.value?.config?.model_id?.trim() || '' - installerModelId.value = configured || readLastChatModelID() - } catch { - installerAgent.value = null - installerModelId.value = readLastChatModelID() - } -} - -async function persistInstallerModel(modelId: string) { - const id = modelId.trim() - if (!id) { - throw new Error(t('settings.sandbox.skillInstallerModelRequired')) - } - const current = installerAgent.value - const config = { ...(current?.config || {}), model_id: id } - const res = await updateAgent(INSTALLER_AGENT_ID, { - name: current?.name || '', - description: current?.description || '', - avatar: current?.avatar || '', - config, - }) - installerAgent.value = res?.data || { ...(current as CustomAgent), config } - installerModelId.value = id -} - -async function onInstallerModelChange(modelId: string) { - if (!modelId || modelId === '__add_model__') return - installerModelId.value = modelId - savingInstallerModel.value = true - try { - await persistInstallerModel(modelId) - } catch (e: any) { - MessagePlugin.error(e?.message || t('settings.sandbox.skillInstallerModelSaveFailed')) - } finally { - savingInstallerModel.value = false - } -} - function isZipFile(file: File): boolean { return file.name.toLowerCase().endsWith('.zip') || file.type === 'application/zip' } @@ -1474,8 +1418,7 @@ watch( stopPoll() skills.value = [] progressById.value = {} - installerAgent.value = null - installerModelId.value = '' + resetInstallerModel() }, { immediate: true }, ) diff --git a/frontend/src/composables/useSkillInstallerModel.test.ts b/frontend/src/composables/useSkillInstallerModel.test.ts new file mode 100644 index 00000000..6e8bce6b --- /dev/null +++ b/frontend/src/composables/useSkillInstallerModel.test.ts @@ -0,0 +1,200 @@ +import assert from 'node:assert/strict' +import { readFileSync } from 'node:fs' +import { createRequire } from 'node:module' +import { runInNewContext } from 'node:vm' +import test from 'node:test' +import ts from 'typescript' +import type { CustomAgent, UpdateAgentRequest } from '../api/agent/index.ts' +import type { useSkillInstallerModel } from './useSkillInstallerModel.ts' + +const require = createRequire(import.meta.url) +const compiled = ts.transpileModule( + readFileSync(new URL('./useSkillInstallerModel.ts', import.meta.url), 'utf8'), + { compilerOptions: { module: ts.ModuleKind.CommonJS, target: ts.ScriptTarget.ES2022 } }, +).outputText + +function agent(config: CustomAgent['config'] = {}): CustomAgent { + return { id: 'builtin-skill-installer', name: 'Installer', is_builtin: true, config } +} + +function fixture(options: { + load?: () => Promise<{ data?: CustomAgent | null }> + save?: (data: UpdateAgentRequest) => Promise<{ data?: CustomAgent | null } | undefined> + readStorage?: (key: string) => string | null +} = {}) { + const reads: string[] = [] + const writes: Array<{ id: string; data: UpdateAgentRequest }> = [] + const errors: string[] = [] + const exports: { useSkillInstallerModel?: typeof useSkillInstallerModel } = {} + runInNewContext(compiled, { + exports, + localStorage: { getItem: (key: string) => options.readStorage?.(key) ?? null }, + require(name: string) { + if (name === 'vue') return require('vue') + if (name === 'vue-i18n') return { useI18n: () => ({ t: (key: string) => key }) } + if (name === 'tdesign-vue-next') return { MessagePlugin: { error: (message: string) => errors.push(message) } } + if (name === '@/api/agent') return { + getAgentById: async (id: string) => { + reads.push(id) + return options.load ? options.load() : { data: agent() } + }, + updateAgent: async (id: string, data: UpdateAgentRequest) => { + writes.push({ id, data: JSON.parse(JSON.stringify(data)) }) + return options.save ? options.save(data) : { data: { ...agent(), ...data } } + }, + } + throw new Error(`Unexpected import: ${name}`) + }, + }) + const create = exports.useSkillInstallerModel! + return { model: create(), create, reads, writes, errors } +} + +test('configured installer model takes precedence over the last chat model', async () => { + const f = fixture({ + load: async () => ({ data: agent({ model_id: ' configured ' }) }), + readStorage: () => { throw new Error('configured model must not read storage') }, + }) + await f.model.loadInstallerModel() + assert.equal(f.model.installerModelId.value, 'configured') + assert.deepEqual(f.reads, ['builtin-skill-installer']) + assert.equal(f.writes.length, 0) + assert.deepEqual(f.errors, []) +}) + +test('missing, empty and failed agent loads fall back to the last chat model without writing', async () => { + const loads = [ + async () => ({ data: null }), + async () => ({ data: agent() }), + async () => ({ data: agent({ model_id: ' ' }) }), + async () => { throw new Error('unavailable') }, + ] + for (const load of loads) { + const keys: string[] = [] + const f = fixture({ load, readStorage: key => { keys.push(key); return 'last-chat' } }) + await f.model.loadInstallerModel() + assert.equal(f.model.installerModelId.value, 'last-chat') + assert.deepEqual(keys, ['weknora_last_chat_model_id']) + assert.equal(f.writes.length, 0) + assert.deepEqual(f.errors, []) + } +}) + +test('unavailable storage or missing preference leaves an empty selection', async () => { + for (const readStorage of [() => null, () => { throw new Error('storage blocked') }]) { + const f = fixture({ readStorage }) + await f.model.loadInstallerModel() + assert.equal(f.model.installerModelId.value, '') + assert.deepEqual(f.errors, []) + } +}) + +test('saving trims the model ID and preserves agent metadata and unrelated config', async () => { + const original = { + ...agent({ model_id: 'old', temperature: 0.4, allowed_tools: ['shell_exec'], system_prompt: 'Keep this prompt' }), + description: 'Description', avatar: 'avatar.png', + } + const f = fixture({ load: async () => ({ data: original }) }) + await f.model.loadInstallerModel() + await f.model.persistInstallerModel(' new ') + assert.deepEqual(f.writes, [{ + id: 'builtin-skill-installer', + data: { + name: 'Installer', description: 'Description', avatar: 'avatar.png', + config: { ...original.config, model_id: 'new' }, + }, + }]) + assert.equal(f.model.installerModelId.value, 'new') + assert.equal(original.config.model_id, 'old', 'saving must not mutate the loaded response') +}) + +test('subsequent saves use returned agent config, or retain the previous config when data is absent', async () => { + for (const hasResponse of [true, false]) { + const f = fixture({ + load: async () => ({ data: agent({ temperature: 0.4 }) }), + save: async () => hasResponse ? { data: { ...agent({ temperature: 0.7 }), name: 'Returned name' } } : {}, + }) + await f.model.loadInstallerModel() + await f.model.persistInstallerModel('first') + await f.model.persistInstallerModel('second') + assert.equal(f.writes[1]?.data.name, hasResponse ? 'Returned name' : 'Installer') + assert.deepEqual(f.writes[1]?.data.config, { temperature: hasResponse ? 0.7 : 0.4, model_id: 'second' }) + assert.equal(f.model.installerModelId.value, 'second') + } +}) + +test('a load failure clears stale agent metadata before persisting a fallback selection', async () => { + let fail = false + const f = fixture({ + load: async () => { + if (fail) throw new Error('unavailable') + return { data: agent({ model_id: 'old', system_prompt: 'old metadata' }) } + }, + readStorage: () => 'last-chat', + save: async () => undefined, + }) + await f.model.loadInstallerModel() + fail = true + await f.model.loadInstallerModel() + await f.model.persistInstallerModel(f.model.installerModelId.value) + assert.deepEqual(f.writes[0]?.data, { name: '', description: '', avatar: '', config: { model_id: 'last-chat' } }) + await f.model.persistInstallerModel('next') + assert.equal(f.writes[1]?.data.config?.model_id, 'next') +}) + +test('blank persistence rejects, while empty and add-model selector events do not save', async () => { + const f = fixture() + f.model.installerModelId.value = 'current' + await assert.rejects(f.model.persistInstallerModel(' '), /settings.sandbox.skillInstallerModelRequired/) + await f.model.onInstallerModelChange('') + await f.model.onInstallerModelChange('__add_model__') + assert.equal(f.model.installerModelId.value, 'current') + assert.equal(f.model.savingInstallerModel.value, false) + assert.equal(f.writes.length, 0) + assert.deepEqual(f.errors, []) +}) + +test('selector save exposes loading until completion and preserves a failed draft for retry', async () => { + let fail!: (reason: Error) => void + let succeed!: (value: { data: CustomAgent }) => void + const f = fixture({ save: () => new Promise((resolve, reject) => { succeed = resolve; fail = reject }) }) + const first = f.model.onInstallerModelChange('next') + assert.equal(f.model.installerModelId.value, 'next') + assert.equal(f.model.savingInstallerModel.value, true) + fail(new Error('permission denied')) + await first + assert.equal(f.model.installerModelId.value, 'next') + assert.equal(f.model.savingInstallerModel.value, false) + assert.deepEqual(f.errors, ['permission denied']) + const retry = f.model.onInstallerModelChange('next') + assert.equal(f.model.savingInstallerModel.value, true) + succeed({ data: agent({ model_id: 'next' }) }) + await retry + assert.equal(f.writes.length, 2) + assert.equal(f.model.savingInstallerModel.value, false) +}) + +test('selector reports a localized fallback error, while persistence propagates failure to the install caller', async () => { + const f = fixture({ save: async () => { throw null } }) + await f.model.onInstallerModelChange('selected') + assert.deepEqual(f.errors, ['settings.sandbox.skillInstallerModelSaveFailed']) + const failure = new Error('save failed') + const direct = fixture({ save: async () => { throw failure } }) + direct.model.installerModelId.value = 'old' + await assert.rejects(direct.model.persistInstallerModel('new'), error => error === failure) + assert.equal(direct.model.installerModelId.value, 'old') + assert.deepEqual(direct.errors, []) +}) + +test('reset clears the panel selection and cached metadata without affecting a sibling instance', async () => { + const f = fixture({ load: async () => ({ data: agent({ model_id: 'configured', temperature: 0.4 }) }) }) + const sibling = f.create() + await f.model.loadInstallerModel() + await sibling.loadInstallerModel() + f.model.resetInstallerModel() + assert.equal(f.model.installerModelId.value, '') + assert.equal(sibling.installerModelId.value, 'configured') + await f.model.persistInstallerModel('after-reset') + assert.deepEqual(f.writes[0]?.data, { name: '', description: '', avatar: '', config: { model_id: 'after-reset' } }) + assert.equal(sibling.installerModelId.value, 'configured') +}) diff --git a/frontend/src/composables/useSkillInstallerModel.ts b/frontend/src/composables/useSkillInstallerModel.ts new file mode 100644 index 00000000..d906bc0f --- /dev/null +++ b/frontend/src/composables/useSkillInstallerModel.ts @@ -0,0 +1,73 @@ +import { ref } from 'vue' +import { useI18n } from 'vue-i18n' +import { MessagePlugin } from 'tdesign-vue-next' +import { getAgentById, updateAgent, type CustomAgent } from '@/api/agent' + +const INSTALLER_AGENT_ID = 'builtin-skill-installer' +const LAST_CHAT_MODEL_KEY = 'weknora_last_chat_model_id' + +function readLastChatModelID(): string { + try { + return localStorage.getItem(LAST_CHAT_MODEL_KEY) || '' + } catch { + return '' + } +} + +/** Each panel keeps its own draft while persisting to the same installer agent. */ +export function useSkillInstallerModel() { + const { t } = useI18n() + const installerAgent = ref | null>(null) + const installerModelId = ref('') + const savingInstallerModel = ref(false) + + async function loadInstallerModel() { + try { + const res = await getAgentById(INSTALLER_AGENT_ID) + installerAgent.value = res?.data || null + const configured = installerAgent.value?.config?.model_id?.trim() || '' + installerModelId.value = configured || readLastChatModelID() + } catch { + installerAgent.value = null + installerModelId.value = readLastChatModelID() + } + } + + async function persistInstallerModel(modelId: string) { + const id = modelId.trim() + if (!id) throw new Error(t('settings.sandbox.skillInstallerModelRequired')) + const current = installerAgent.value + const config = { ...(current?.config || {}), model_id: id } + const res = await updateAgent(INSTALLER_AGENT_ID, { + name: current?.name || '', + description: current?.description || '', + avatar: current?.avatar || '', + config, + }) + installerAgent.value = res?.data || { ...current, config } + installerModelId.value = id + } + + async function onInstallerModelChange(modelId: string) { + if (!modelId || modelId === '__add_model__') return + installerModelId.value = modelId + savingInstallerModel.value = true + try { + await persistInstallerModel(modelId) + } catch (error: any) { + MessagePlugin.error(error?.message || t('settings.sandbox.skillInstallerModelSaveFailed')) + } finally { + savingInstallerModel.value = false + } + } + + function resetInstallerModel() { + installerAgent.value = null + installerModelId.value = '' + } + + return { + installerModelId, savingInstallerModel, loadInstallerModel, persistInstallerModel, + onInstallerModelChange, resetInstallerModel, + } +} diff --git a/frontend/src/views/settings/SkillSettings.vue b/frontend/src/views/settings/SkillSettings.vue index 84c970e3..44efc5bf 100644 --- a/frontend/src/views/settings/SkillSettings.vue +++ b/frontend/src/views/settings/SkillSettings.vue @@ -350,11 +350,7 @@ import { type SkillCatalogItem, type SkillCatalogRegisterResult, } from '@/api/skill' -import { - getAgentById, - updateAgent, - type CustomAgent, -} from '@/api/agent' +import { useSkillInstallerModel } from '@/composables/useSkillInstallerModel' import { isNamedSandboxBackend, listSandboxConfigs, @@ -398,12 +394,10 @@ const addingFromSource = ref(false) const installing = ref(false) const uploadPercent = ref(0) const fileInputRef = ref(null) -const installerAgent = ref(null) -const installerModelId = ref('') -const savingInstallerModel = ref(false) - -const INSTALLER_AGENT_ID = 'builtin-skill-installer' -const LAST_CHAT_MODEL_KEY = 'weknora_last_chat_model_id' +const { + installerModelId, savingInstallerModel, loadInstallerModel, persistInstallerModel, + onInstallerModelChange, +} = useSkillInstallerModel() const { percentOf: installEventPercent, @@ -880,56 +874,6 @@ function onPanelUpdated(record: SandboxConfigRecord) { records.value = records.value.map((item) => (item.id === record.id ? { ...item, ...record } : item)) } -function readLastChatModelID(): string { - try { - return localStorage.getItem(LAST_CHAT_MODEL_KEY) || '' - } catch { - return '' - } -} - -async function loadInstallerModel() { - try { - const res = await getAgentById(INSTALLER_AGENT_ID) - installerAgent.value = res?.data || null - const configured = installerAgent.value?.config?.model_id?.trim() || '' - installerModelId.value = configured || readLastChatModelID() - } catch { - installerAgent.value = null - installerModelId.value = readLastChatModelID() - } -} - -async function persistInstallerModel(modelId: string) { - const id = modelId.trim() - if (!id) { - throw new Error(t('settings.sandbox.skillInstallerModelRequired')) - } - const current = installerAgent.value - const config = { ...(current?.config || {}), model_id: id } - const res = await updateAgent(INSTALLER_AGENT_ID, { - name: current?.name || '', - description: current?.description || '', - avatar: current?.avatar || '', - config, - }) - installerAgent.value = res?.data || { ...(current as CustomAgent), config } - installerModelId.value = id -} - -async function onInstallerModelChange(modelId: string) { - if (!modelId || modelId === '__add_model__') return - installerModelId.value = modelId - savingInstallerModel.value = true - try { - await persistInstallerModel(modelId) - } catch (e: any) { - MessagePlugin.error(e?.message || t('settings.sandbox.skillInstallerModelSaveFailed')) - } finally { - savingInstallerModel.value = false - } -} - async function ensureInstallerModelIfNeeded(configIds: string[]) { if (configIds.length === 0) return if (!installerModelId.value) {