refactor(frontend): share skill install progress subscriptions

main
wizardchen 2026-09-16 21:06:06 +08:00 committed by lyingbug
parent 5bcc43d728
commit f2606629b3
5 changed files with 374 additions and 126 deletions

View File

@ -65,11 +65,20 @@
- 新增 10 项行为测试,覆盖优先级、回退、配置保留、响应缺省、保存失败重试、错误传播与实例隔离。
- `scripts/verify_frontend_pr.sh` 通过:917 项前端测试、类型检查和生产构建。两个页面的 template/style 与本批基线逐字节一致。未做浏览器视觉验收;未修改或测试后端。
## 第三批已实施:Skill 安装进度订阅
基于第二批合并后的 `5bcc43d72`,面板改为复用 `useConfigSkillInstallProgress`,统一 SSE 请求、配置/Skill 标识、连接去重、取消和完成事件处理。
- 目录页继续只保留所跟踪任务的进度;面板通过 `retainProgress` 保留完成事件与卸载失败原因,显式重试时清空。面板的百分比显示规则和卸载初始进度保持不变。
- 连接回调和 Promise 清理检查当前连接身份,避免旧事件、旧请求拒绝或结束回调覆盖/取消替代连接。正常 EOF 也释放订阅标记,允许后续轮询重新连接。
- 配置切换立即停止原订阅和轮询;面板读取、重试、停止和卸载请求的后续处理检查面板代次,避免迟到结果在另一配置或卸载后重新订阅。
- 新增 11 项行为测试,包含真实面板 setup 的配置切换、卸载失败展示、相同 Skill ID 重试、异步请求迟到和卸载清理;替换原有一项订阅源码正则断言。
- `scripts/verify_frontend_pr.sh` 通过:927 项前端测试、类型检查和生产构建。面板 template/style 与本批基线逐字节一致;未做浏览器视觉验收,未修改或测试后端。
## 后续优先级
| 优先级 | 证据 | 建议边界 | 验证重点 |
| --- | --- | --- | --- |
| 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 行 | 分开文档导航/编辑状态、批量动作与可复用展示区域 | 页面切换后的异步结果、选中项、保存与批量操作 |
@ -121,4 +130,4 @@
- 构建仍报告大 chunk 提示;本轮未以 bundle 体积为目标,也没有测量构建前后的体积差异。
- 未修改后端,未运行后端测试;未做浏览器视觉验收。
下一批优先处理 Skill 安装进度订阅的重复。涉及聊天、任务重试、权限或共享状态的改动应单独成批,以可验证的行为等价为边界。
下一批优先处理主聊天与嵌入聊天引用浮层的重复。涉及聊天、任务重试、权限或共享状态的改动应单独成批,以可验证的行为等价为边界。

View File

@ -607,14 +607,13 @@ import { computed, inject, nextTick, onUnmounted, reactive, ref, watch } from 'v
import { MessagePlugin } from 'tdesign-vue-next'
import { AddIcon } from 'tdesign-icons-vue-next'
import { useI18n } from 'vue-i18n'
import { fetchEventSource } from '@microsoft/fetch-event-source'
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 { useConfigSkillInstallProgress } from '@/composables/useConfigSkillInstallProgress'
import { useSkillInstallerModel } from '@/composables/useSkillInstallerModel'
import {
configSkillInstallEventsUrl,
deleteConfigSkill,
getSandboxConfigById,
listConfigSkills,
@ -624,12 +623,9 @@ import {
uploadConfigSkill,
installConfigSkillFromSource,
type ConfigSkill,
type ConfigSkillInstallEvent,
type SandboxConfigRecord,
} from '@/api/system'
import { getApiBaseUrl } from '@/utils/api-base'
import { generateRandomString, MAX_SKILL_BUNDLE_SIZE_BYTES, MAX_SKILL_BUNDLE_SIZE_MB } from '@/utils/index'
import i18n from '@/i18n'
import { MAX_SKILL_BUNDLE_SIZE_BYTES, MAX_SKILL_BUNDLE_SIZE_MB } from '@/utils/index'
import {
MAX_ENV_VALUE_BYTES,
addSkillEnvSaveInFlight,
@ -701,9 +697,18 @@ const envDrafts = reactive<Record<string, Record<string, string>>>({})
const envInputUnlocked = reactive<Record<string, boolean>>({})
const envSavesInFlight = ref<SkillEnvSavesInFlight>({})
const fileInputRef = ref<HTMLInputElement | null>(null)
const progressById = ref<Record<string, ConfigSkillInstallEvent>>({})
const abortBySkill = new Map<string, AbortController>()
const {
eventOf: installEventOf, follow: followInstallProgress, sync: syncInstallProgress,
stopAll: stopAllFollows, reset: resetInstallProgress, forget: forgetInstallProgress,
setEvent: setInstallEvent,
} = useConfigSkillInstallProgress({
retainProgress: true,
onDone() {
void loadSkills()
void refreshImage()
},
})
let panelGeneration = 0
let pollTimer: number | null = null
const {
@ -747,7 +752,7 @@ function isBusy(skill: ConfigSkill): boolean {
function isRemoving(skill: ConfigSkill): boolean {
if (uninstallingId.value === skill.id && !uninstallDone.value) {
if (progressById.value[skill.id]?.stage !== 'failed') return true
if (progressEvent(skill.id)?.stage !== 'failed') return true
}
return skill.status === 'removing' || deletingId.value === skill.id
}
@ -1001,7 +1006,7 @@ async function submitEnvs(
}
function progressOf(skill: ConfigSkill): number {
const percent = progressById.value[skill.id]?.percent
const percent = progressEvent(skill.id)?.percent
if (typeof percent === 'number' && Number.isFinite(percent)) {
return Math.max(0, Math.min(100, percent))
}
@ -1018,7 +1023,7 @@ const REMOVE_STAGE_I18N: Record<string, string> = {
}
function progressStageText(skill: ConfigSkill): string {
const ev = progressById.value[skill.id]
const ev = progressEvent(skill.id)
const stageKey = ev?.stage ? REMOVE_STAGE_I18N[ev.stage] : ''
if (stageKey) return t(stageKey)
if (skill.status === 'removing' || deletingId.value === skill.id) {
@ -1028,21 +1033,18 @@ function progressStageText(skill: ConfigSkill): string {
}
function progressLog(skill: ConfigSkill): string {
const ev = progressById.value[skill.id]
const ev = progressEvent(skill.id)
if (ev?.log) return ev.log
if (skill.status === 'removing') return progressStageText(skill)
return ''
}
// A re-run reuses the skill id, so the previous run's last event is still the
// one cached here. Left in place it renders as this run's state: a retry would
// open at 100% showing the failure it was started to fix, until the first new
// event lands.
function progressEvent(skillId: string) {
return installEventOf(props.record?.id || '', skillId)
}
function forgetProgress(skillId: string) {
if (!(skillId in progressById.value)) return
const next = { ...progressById.value }
delete next[skillId]
progressById.value = next
if (props.record) forgetInstallProgress(props.record.id, skillId)
}
function failedError(skill: ConfigSkill): string {
@ -1062,7 +1064,7 @@ function failedErrorLines(skill: ConfigSkill): string[] {
}
function removalErrorLines(skill: ConfigSkill): string[] {
const ev = progressById.value[skill.id]
const ev = progressEvent(skill.id)
const raw = ev?.stage === 'failed'
? (ev.log || skill.error || '')
: (uninstallingId.value === skill.id && skill.status !== 'removing' ? (skill.error || '') : '')
@ -1072,20 +1074,6 @@ function removalErrorLines(skill: ConfigSkill): string[] {
.filter(Boolean)
}
function stopFollow(skillId: string) {
const controller = abortBySkill.get(skillId)
if (controller) {
controller.abort()
abortBySkill.delete(skillId)
}
}
function stopAllFollows() {
for (const skillId of [...abortBySkill.keys()]) {
stopFollow(skillId)
}
}
function stopPoll() {
if (pollTimer != null) {
window.clearInterval(pollTimer)
@ -1105,67 +1093,25 @@ function ensurePoll() {
}
function followBusySkills() {
if (!props.record) return
const busyIds = new Set(skills.value.filter(isBusy).map((skill) => skill.id))
for (const skillId of [...abortBySkill.keys()]) {
if (!busyIds.has(skillId)) stopFollow(skillId)
}
for (const skill of skills.value) {
if (isBusy(skill)) followProgress(skill.id)
}
const configId = props.record?.id
syncInstallProgress(configId
? skills.value.filter(isBusy).map(skill => ({ configId, skillId: skill.id }))
: [])
}
function followProgress(skillId: string) {
if (!props.record || abortBySkill.has(skillId)) return
const configId = props.record.id
const controller = new AbortController()
abortBySkill.set(skillId, controller)
const token = localStorage.getItem('weknora_token')
const tenantId = localStorage.getItem('weknora_selected_tenant_id')
const url = `${getApiBaseUrl()}${configSkillInstallEventsUrl(configId, skillId)}`
void fetchEventSource(url, {
method: 'GET',
headers: {
Authorization: token ? `Bearer ${token}` : '',
'Accept-Language': i18n.global.locale?.value || localStorage.getItem('locale') || 'zh-CN',
'X-Request-ID': generateRandomString(12),
...(tenantId ? { 'X-Tenant-ID': tenantId } : {}),
},
signal: controller.signal,
openWhenHidden: true,
onmessage(ev) {
if (!ev.data) return
let parsed: ConfigSkillInstallEvent
try {
parsed = JSON.parse(ev.data) as ConfigSkillInstallEvent
} catch {
return
}
progressById.value = { ...progressById.value, [skillId]: parsed }
if (parsed.done) {
stopFollow(skillId)
void loadSkills()
void refreshImage()
}
},
onerror() {
stopFollow(skillId)
throw new Error('skill install stream closed')
},
}).catch(() => {
stopFollow(skillId)
})
if (props.record) followInstallProgress(props.record.id, skillId)
}
async function refreshImage() {
if (!props.record) return
const generation = panelGeneration
try {
const res = await getSandboxConfigById(props.record.id)
if (generation !== panelGeneration) return
if (res?.data) emit('updated', res.data)
} catch {
emit('skillsChanged')
if (generation === panelGeneration) emit('skillsChanged')
}
}
@ -1176,7 +1122,7 @@ function skillsSignature(list: ConfigSkill[]): string {
function overlayUninstallStatus(list: ConfigSkill[]): ConfigSkill[] {
const id = uninstallingId.value
if (!id || uninstallDone.value) return list
if (progressById.value[id]?.stage === 'failed') return list
if (progressEvent(id)?.stage === 'failed') return list
return list.map((item) => {
if (item.id !== id) return item
if (item.status === 'removed' || item.status === 'failed' || item.status === 'removing') {
@ -1188,11 +1134,13 @@ function overlayUninstallStatus(list: ConfigSkill[]): ConfigSkill[] {
async function loadSkills(silent = false) {
if (!props.record) return
const generation = panelGeneration
if (!silent) loading.value = true
const previous = skillsSignature(skills.value)
const wasBusy = skills.value.some(isBusy)
try {
const res = await listConfigSkills(props.record.id)
if (generation !== panelGeneration) return
skills.value = overlayUninstallStatus(res?.data || [])
followBusySkills()
ensurePoll()
@ -1204,11 +1152,11 @@ async function loadSkills(silent = false) {
void refreshImage()
}
} catch (e: any) {
if (!silent) {
if (!silent && generation === panelGeneration) {
MessagePlugin.error(e?.message || t('settings.sandbox.skillLoadFailed'))
}
} finally {
if (!silent) loading.value = false
if (!silent && generation === panelGeneration) loading.value = false
}
}
@ -1337,26 +1285,32 @@ async function toggleEnabled(skill: ConfigSkill, enabled: boolean) {
// re-attached under the id already on screen.
async function retrySkill(skill: ConfigSkill) {
if (!props.record) return
const generation = panelGeneration
retryingId.value = skill.id
forgetProgress(skill.id)
try {
await reinstallConfigSkill(props.record.id, skill.id)
if (generation !== panelGeneration) return
MessagePlugin.success(t('settings.sandbox.skillRetryAccepted'))
await loadSkills()
if (generation !== panelGeneration) return
followProgress(skill.id)
} catch (e: any) {
if (generation !== panelGeneration) return
MessagePlugin.error(e?.message || t('settings.sandbox.skillRetryFailed'))
} finally {
retryingId.value = ''
if (generation === panelGeneration) retryingId.value = ''
}
}
async function stopSkill(skill: ConfigSkill) {
if (!props.record) return
const generation = panelGeneration
stoppingId.value = skill.id
forgetProgress(skill.id)
try {
const res = await stopConfigSkill(props.record.id, skill.id)
if (generation !== panelGeneration) return
const updated = res?.data
if (updated) {
skills.value = skills.value.map((item) => (item.id === skill.id ? { ...item, ...updated } : item))
@ -1364,14 +1318,16 @@ async function stopSkill(skill: ConfigSkill) {
MessagePlugin.success(t('settings.sandbox.skillStopAccepted'))
await loadSkills()
} catch (e: any) {
if (generation !== panelGeneration) return
MessagePlugin.error(e?.message || t('settings.sandbox.skillStopFailed'))
} finally {
stoppingId.value = ''
if (generation === panelGeneration) stoppingId.value = ''
}
}
async function removeSkill(skill: ConfigSkill) {
if (!props.record || isBusy(skill) || deletingId.value) return
const generation = panelGeneration
deletingId.value = skill.id
uninstallingId.value = skill.id
uninstallingName.value = skill.name
@ -1379,25 +1335,26 @@ async function removeSkill(skill: ConfigSkill) {
forgetProgress(skill.id)
try {
await deleteConfigSkill(props.record.id, skill.id)
if (generation !== panelGeneration) return
MessagePlugin.success(t('settings.sandbox.skillDeleteAccepted'))
skills.value = skills.value.map((item) => (
item.id === skill.id ? { ...item, status: 'removing' } : item
))
sawRemoving.value = true
progressById.value = {
...progressById.value,
[skill.id]: { percent: 5, stage: 'accepted', done: false },
}
setInstallEvent(props.record.id, skill.id, { percent: 5, stage: 'accepted', done: false })
await loadSkills()
if (generation !== panelGeneration) return
await refreshImage()
if (generation !== panelGeneration) return
followProgress(skill.id)
} catch (e: any) {
if (generation !== panelGeneration) return
uninstallingId.value = ''
uninstallingName.value = ''
sawRemoving.value = false
MessagePlugin.error(e?.message || t('common.deleteFailed'))
} finally {
deletingId.value = ''
if (generation === panelGeneration) deletingId.value = ''
}
}
@ -1407,6 +1364,18 @@ watch(
() => props.record?.id,
(configID, previousConfigID) => {
if (configID !== previousConfigID) {
panelGeneration++
resetInstallProgress()
stopPoll()
skills.value = []
loading.value = false
retryingId.value = ''
stoppingId.value = ''
deletingId.value = ''
uninstallingId.value = ''
uninstallingName.value = ''
uninstallDone.value = false
sawRemoving.value = false
expandedEnvSkillId.value = ''
for (const skillId of Object.keys(envDrafts)) delete envDrafts[skillId]
}
@ -1417,7 +1386,6 @@ watch(
stopAllFollows()
stopPoll()
skills.value = []
progressById.value = {}
resetInstallerModel()
},
{ immediate: true },
@ -1431,6 +1399,7 @@ watch(
)
onUnmounted(() => {
panelGeneration++
stopAllFollows()
stopPoll()
if (focusTimer != null) window.clearTimeout(focusTimer)

View File

@ -1,5 +1,4 @@
import assert from 'node:assert/strict'
import { readFileSync } from 'node:fs'
import test from 'node:test'
import {
@ -9,20 +8,6 @@ import {
progressKey,
} from './skillInstallProgress.ts'
const source = readFileSync(new URL('./useConfigSkillInstallProgress.ts', import.meta.url), 'utf8')
test('catalog install progress follows the same SSE as the sandbox panel', () => {
assert.match(source, /fetchEventSource/)
assert.match(source, /configSkillInstallEventsUrl/)
assert.match(source, /openWhenHidden: true/)
assert.match(source, /if \(!configId \|\| !skillId \|\| abortByKey\.has\(key\)\) return/)
assert.doesNotMatch(
source,
/existing\?\.done && existing\.stage !== 'detached'/,
'a done event must not block reconnect: retry reuses the same skill id',
)
})
test('progress keys isolate one install per sandbox', () => {
assert.equal(progressKey('cfg-a', 'skill-1'), 'cfg-a:skill-1')
})

View File

@ -0,0 +1,265 @@
import assert from 'node:assert/strict'
import { readFileSync } from 'node:fs'
import { runInNewContext } from 'node:vm'
import test from 'node:test'
import ts from 'typescript'
import { compileScript, parse } from '@vue/compiler-sfc'
import * as vue from 'vue'
import * as progress from './skillInstallProgress.ts'
import type { useConfigSkillInstallProgress } from './useConfigSkillInstallProgress.ts'
const compile = (source: string) => ts.transpileModule(source, {
compilerOptions: { module: ts.ModuleKind.CommonJS, target: ts.ScriptTarget.ES2022 },
}).outputText
const compiled = compile(readFileSync(new URL('./useConfigSkillInstallProgress.ts', import.meta.url), 'utf8'))
function deferred<T = void>() {
let resolve!: (value: T) => void, reject!: (reason: unknown) => void
const promise = new Promise<T>((yes, no) => { resolve = yes; reject = no })
return { promise, resolve, reject }
}
const flush = async () => { await new Promise(resolve => setImmediate(resolve)); await vue.nextTick() }
function fixture() {
const requests: Array<{ url: string; options: any; pending: ReturnType<typeof deferred<void>> }> = []
const exports: { useConfigSkillInstallProgress?: typeof useConfigSkillInstallProgress } = {}
runInNewContext(compiled, {
exports, AbortController,
localStorage: { getItem: (key: string) => ({ weknora_token: 'token', weknora_selected_tenant_id: 'tenant' })[key] },
require(name: string) {
if (name === 'vue') return vue
if (name === './skillInstallProgress') return progress
if (name === '@/i18n') return { __esModule: true, default: { global: { locale: { value: 'en-US' } } } }
if (name === '@/utils') return { generateRandomString: () => 'request-id' }
if (name === '@/utils/api-base') return { getApiBaseUrl: () => '/prefix' }
if (name === '@/api/system') return { configSkillInstallEventsUrl: (config: string, skill: string) => `/configs/${config}/skills/${skill}/events` }
if (name === '@microsoft/fetch-event-source') return {
fetchEventSource: (url: string, options: any) => {
const pending = deferred()
requests.push({ url, options, pending })
// Real fetch-event-source also resolves when the caller aborts.
options.signal.addEventListener('abort', () => pending.resolve())
return pending.promise
},
}
throw new Error(`Unexpected import: ${name}`)
},
})
const send = (index: number, event: unknown) => requests[index]!.options.onmessage({ data: JSON.stringify(event) })
return { create: exports.useConfigSkillInstallProgress!, requests, send }
}
const running = { percent: 37.4, stage: 'installing', done: false }
const failed = { percent: 100, stage: 'failed', log: 'remove failed', done: true }
test('subscriptions deduplicate targets, isolate configurations and preserve request headers', () => {
const f = fixture(), state = f.create()
state.sync([{ configId: ' a ', skillId: 'same' }, { configId: 'a', skillId: 'same' }, { configId: 'b', skillId: 'same' }, { configId: '', skillId: 'x' }])
assert.equal(f.requests.length, 2)
assert.equal(f.requests[0]!.url, '/prefix/configs/a/skills/same/events')
const request = f.requests[0]!.options
assert.equal(request.headers.Authorization, 'Bearer token')
assert.equal(request.headers['X-Tenant-ID'], 'tenant')
assert.equal(request.headers['Accept-Language'], 'en-US')
assert.equal(request.headers['X-Request-ID'], 'request-id')
assert.equal(request.openWhenHidden, true)
f.send(0, running)
assert.equal(state.percentOf('a', 'same'), 37)
assert.equal(state.eventOf('b', 'same'), undefined)
state.stopAll()
assert.ok(f.requests.every(request => request.options.signal.aborted))
})
test('completion fires once and a reused skill ID clears the catalog progress before retry', () => {
const f = fixture(), done: unknown[] = []
const state = f.create({ onDone: (target, event) => done.push([target, event]) })
state.follow('a', 'skill')
f.send(0, failed)
f.send(0, failed)
assert.equal(done.length, 1)
assert.equal(state.eventOf('a', 'skill')?.log, 'remove failed')
state.follow('a', 'skill')
assert.equal(state.eventOf('a', 'skill'), undefined)
assert.equal(f.requests.length, 2)
state.sync([])
assert.equal(f.requests[1]!.options.signal.aborted, true)
})
test('detail panels keep seeded and terminal progress until explicit forget/reset', () => {
const f = fixture(), state = f.create({ retainProgress: true })
state.setEvent('a', 'skill', { percent: 5, stage: 'accepted', done: false })
state.follow('a', 'skill')
assert.equal(state.eventOf('a', 'skill')?.percent, 5)
f.send(0, failed)
state.sync([])
assert.equal(state.eventOf('a', 'skill')?.log, 'remove failed')
state.forget('a', 'skill')
state.follow('a', 'skill')
assert.equal(state.eventOf('a', 'skill'), undefined)
f.send(1, running)
state.reset()
assert.equal(f.requests[1]!.options.signal.aborted, true)
assert.equal(state.eventOf('a', 'skill'), undefined)
})
test('retired callbacks and promise cleanup cannot overwrite or cancel a replacement stream', async () => {
const f = fixture(), done: unknown[] = [], state = f.create({ onDone: event => done.push(event) })
state.follow('a', 'skill')
f.requests[0]!.pending.reject(new Error('old request failed'))
state.forget('a', 'skill')
state.follow('a', 'skill')
f.send(1, running)
f.send(0, failed)
assert.throws(() => f.requests[0]!.options.onerror(new Error('late failure')), /stream closed/)
await flush()
assert.equal(f.requests[1]!.options.signal.aborted, false)
assert.equal(state.eventOf('a', 'skill')?.percent, 37.4)
assert.equal(done.length, 0)
state.stopAll()
})
test('clean EOF and rejected requests release the subscription for later polling', async () => {
for (const reject of [false, true]) {
const f = fixture(), state = f.create()
state.follow('a', 'skill')
if (reject) f.requests[0]!.pending.reject(new Error('connection failed'))
else f.requests[0]!.pending.resolve()
await flush()
state.follow('a', 'skill')
assert.equal(f.requests.length, 2)
state.stopAll()
}
})
test('invalid events are ignored and catalog sync prunes inactive cached progress', () => {
const f = fixture(), state = f.create()
state.follow('a', 'skill')
for (const data of ['', '{', 'null', '42']) f.requests[0]!.options.onmessage({ data })
assert.equal(state.eventOf('a', 'skill'), undefined)
f.send(0, running)
state.sync([])
assert.equal(state.eventOf('a', 'skill'), undefined)
f.send(0, running)
assert.equal(state.eventOf('a', 'skill'), undefined)
})
const { descriptor } = parse(readFileSync(new URL('../components/SandboxSkillsPanel.vue', import.meta.url), 'utf8'))
const componentScript = compileScript(descriptor, { id: 'skill-progress-test' }).content
.replace(/__expose\(\{[\s\S]*?\}\);?/, '')
.replace('return __returned__', '__expose(__returned__); return __returned__')
const componentCompiled = compile(componentScript)
async function panelFixture(api: Record<string, (...args: any[]) => Promise<any>> = {}) {
const f = fixture(), exports: any = {}, intervals = new Set<number>(), emitted: any[] = []
let timer = 0
const record = vue.ref<any>({ id: 'a' }), panel = vue.ref<any>()
const row = { id: 'skill', name: 'Skill', status: 'installing', enabled: true }
runInNewContext(componentCompiled, {
exports,
window: { setInterval: () => { intervals.add(++timer); return timer }, clearInterval: (id: number) => intervals.delete(id), clearTimeout() {} },
require(name: string) {
if (name === 'vue') return vue
if (name === 'vue-i18n') return { useI18n: () => ({ t: (key: string) => key }) }
if (name === 'tdesign-vue-next') return { MessagePlugin: { success() {}, error() {}, warning() {} } }
if (name === '@/composables/useConfigSkillInstallProgress') return { useConfigSkillInstallProgress: f.create }
if (name === '@/composables/useSkillInstallerModel') return { useSkillInstallerModel: () => ({ resetInstallerModel() {} }) }
if (name === '@/api/system') return {
listConfigSkills: async () => ({ data: [{ ...row }] }), getSandboxConfigById: async (id: string) => ({ data: { id } }),
...api,
}
if (name === '@/views/settings/envVarState') return { skillHasDeclaredEnvs: () => false }
if (name.endsWith('.vue') || ['@/types/mention', '@/utils/index', 'tdesign-icons-vue-next'].includes(name)) return { default: {}, SETTING_DRAWER_HEADER_ACTIONS_ID: 'header' }
throw new Error(`Unexpected import: ${name}`)
},
})
exports.default.render = () => null
const renderer = vue.createRenderer<any, any>({
patchProp() {}, insert() {}, remove() {}, setText() {}, setElementText() {},
createElement: () => ({}), createText: () => ({}), createComment: () => ({}), parentNode: () => null, nextSibling: () => null,
})
const app = renderer.createApp({ setup: () => () => vue.h(exports.default, { record: record.value, ref: panel, onUpdated: (event: any) => emitted.push(event) }) })
app.mount({})
await flush()
return { ...f, record, panel, row, intervals, emitted, close: () => app.unmount() }
}
test('panel uses scoped progress and aborts subscriptions on config changes and unmount', async (t) => {
const f = await panelFixture()
t.after(f.close)
f.send(0, running)
assert.equal(f.panel.value.progressOf(f.row), 37.4, 'panel retains its unrounded display rule')
f.record.value = { id: 'b' }
await flush()
assert.equal(f.requests[0]!.options.signal.aborted, true)
assert.equal(f.requests[1]!.url, '/prefix/configs/b/skills/skill/events')
f.send(0, failed)
assert.equal(f.panel.value.progressLog(f.row), '')
f.close()
assert.equal(f.requests[1]!.options.signal.aborted, true)
assert.equal(f.intervals.size, 0)
})
test('panel retains uninstall failure details after list refresh stops following the skill', async (t) => {
const row = { id: 'skill', name: 'Skill', status: 'ready', enabled: true }
const f = await panelFixture({ listConfigSkills: async () => ({ data: [row] }), deleteConfigSkill: async () => {} })
t.after(f.close)
await f.panel.value.removeSkill(row)
assert.equal(f.panel.value.progressOf(row), 5)
f.send(0, failed)
await flush()
assert.equal(f.panel.value.removalErrorLines(row)[0], 'remove failed')
assert.equal(f.panel.value.isRemoving(row), false)
assert.equal(f.intervals.size, 0)
assert.equal(f.requests.length, 1)
})
test('panel retry drops a previous run error and attaches fresh progress for the reused skill ID', async (t) => {
const row = { id: 'skill', name: 'Skill', status: 'failed', enabled: true }
const f = await panelFixture({
listConfigSkills: async () => ({ data: [{ ...row }] }),
reinstallConfigSkill: async () => { row.status = 'installing' },
})
t.after(f.close)
f.panel.value.setInstallEvent('a', 'skill', failed)
assert.equal(f.panel.value.progressLog(row), 'remove failed')
await f.panel.value.retrySkill(row)
assert.equal(f.panel.value.progressLog(row), '')
assert.equal(f.panel.value.progressOf(row), 0)
assert.equal(f.requests.length, 1)
f.send(0, running)
assert.equal(f.panel.value.progressOf(row), 37.4)
})
test('late list/image results cannot revive subscriptions after config replacement or unmount', async (t) => {
for (const unmount of [false, true]) {
const list = deferred<any>(), image = deferred<any>()
const f = await panelFixture({
listConfigSkills: (id: string) => id === 'a' ? list.promise : Promise.resolve({ data: [] }),
getSandboxConfigById: (id: string) => id === 'a' ? image.promise : Promise.resolve({ data: { id } }),
})
t.after(f.close)
if (unmount) f.close()
else { f.record.value = { id: 'b' }; await flush() }
list.resolve({ data: [f.row] })
image.resolve({ data: { id: 'a' } })
await flush()
assert.equal(f.requests.length, 0)
assert.equal(f.intervals.size, 0)
assert.ok(f.emitted.every(event => event.id !== 'a'))
}
})
test('late retry/stop/remove actions cannot attach the old skill to the new config', async (t) => {
for (const [action, method] of [['retrySkill', 'reinstallConfigSkill'], ['stopSkill', 'stopConfigSkill'], ['removeSkill', 'deleteConfigSkill']]) {
const pending = deferred<any>()
const row = { id: 'skill', name: 'Skill', status: 'failed', enabled: true }
const f = await panelFixture({ listConfigSkills: async () => ({ data: [row] }), [method!]: () => pending.promise })
t.after(f.close)
const runningAction = f.panel.value[action!](row)
f.record.value = { id: 'b' }
await flush()
pending.resolve({ data: row })
await runningAction
assert.equal(f.requests.length, 0)
assert.equal(f.panel.value.uninstallingId, '')
assert.equal(f.intervals.size, 0)
}
})

View File

@ -23,6 +23,8 @@ export {
export function useConfigSkillInstallProgress(options?: {
onDone?: (target: SkillInstallProgressTarget, event: ConfigSkillInstallEvent) => void
/** Detail panels retain terminal errors until an explicit retry or reset. */
retainProgress?: boolean
}) {
const progressByKey = ref<Record<string, ConfigSkillInstallEvent>>({})
const abortByKey = new Map<string, AbortController>()
@ -35,7 +37,7 @@ export function useConfigSkillInstallProgress(options?: {
return liveInstallPercent(eventOf(configId, skillId))
}
function forget(key: string) {
function forgetKey(key: string) {
if (!(key in progressByKey.value)) return
const next = { ...progressByKey.value }
delete next[key]
@ -53,15 +55,32 @@ export function useConfigSkillInstallProgress(options?: {
for (const key of [...abortByKey.keys()]) stop(key)
}
function reset() {
stopAll()
progressByKey.value = {}
}
function forget(configId: string, skillId: string) {
const key = progressKey(configId, skillId)
stop(key)
forgetKey(key)
}
function setEvent(configId: string, skillId: string, event: ConfigSkillInstallEvent) {
progressByKey.value = { ...progressByKey.value, [progressKey(configId, skillId)]: event }
}
function follow(configId: string, skillId: string) {
const key = progressKey(configId, skillId)
if (!configId || !skillId || abortByKey.has(key)) return
// abortByKey is the in-flight guard. A finished event for this key is
// either status lag or a new run of the same skill id (retry); skipping
// reconnect would leave the drawer showing the previous 100%.
forget(key)
if (!options?.retainProgress) forgetKey(key)
const controller = new AbortController()
abortByKey.set(key, controller)
const isCurrent = () => abortByKey.get(key) === controller
const stopCurrent = () => { if (isCurrent()) stop(key) }
const token = localStorage.getItem('weknora_token')
const tenantId = localStorage.getItem('weknora_selected_tenant_id')
@ -78,26 +97,25 @@ export function useConfigSkillInstallProgress(options?: {
signal: controller.signal,
openWhenHidden: true,
onmessage(ev) {
if (!ev.data) return
if (!isCurrent() || !ev.data) return
let parsed: ConfigSkillInstallEvent
try {
parsed = JSON.parse(ev.data) as ConfigSkillInstallEvent
} catch {
return
}
progressByKey.value = { ...progressByKey.value, [key]: parsed }
if (!parsed || typeof parsed !== 'object') return
setEvent(configId, skillId, parsed)
if (parsed.done) {
stop(key)
stopCurrent()
options?.onDone?.({ configId, skillId }, parsed)
}
},
onerror() {
stop(key)
stopCurrent()
throw new Error('skill install stream closed')
},
}).catch(() => {
stop(key)
})
}).catch(() => {}).finally(stopCurrent)
}
function sync(targets: SkillInstallProgressTarget[]) {
@ -113,10 +131,12 @@ export function useConfigSkillInstallProgress(options?: {
for (const key of [...abortByKey.keys()]) {
if (!wanted.has(key)) stop(key)
}
for (const key of Object.keys(progressByKey.value)) {
if (!wanted.has(key)) forget(key)
if (!options?.retainProgress) {
for (const key of Object.keys(progressByKey.value)) {
if (!wanted.has(key)) forgetKey(key)
}
}
}
return { progressByKey, eventOf, percentOf, follow, sync, stopAll }
return { progressByKey, eventOf, percentOf, follow, sync, stopAll, reset, forget, setEvent }
}