821 lines
31 KiB
JavaScript
821 lines
31 KiB
JavaScript
import assert from 'node:assert/strict'
|
||
import { readFile } from 'node:fs/promises'
|
||
import { test } from 'node:test'
|
||
|
||
/**
|
||
* 在 Node 里加载浏览器端插件:伪造 __ModuleLoader__、React 与最小 DOM。
|
||
* 覆盖:右栏注册、项目上下文推导、原生上下文菜单、状态轮询与错误保留、
|
||
* 配置/初始化折叠表单、角色卡会话打开和过期响应丢弃。
|
||
*/
|
||
|
||
function reactStub() {
|
||
const createElement = (type, props, ...children) => {
|
||
const list = children.length === 0 ? undefined : children.length === 1 ? children[0] : children
|
||
return { type, props: { ...(props ?? {}), ...(list === undefined ? {} : { children: list }) } }
|
||
}
|
||
const useState = initial => [typeof initial === 'function' ? initial() : initial, () => {}]
|
||
const useEffect = () => {}
|
||
return {
|
||
createElement,
|
||
useState,
|
||
useEffect,
|
||
useMemo: fn => fn(),
|
||
useCallback: fn => fn,
|
||
useRef: value => ({ current: value }),
|
||
useLayoutEffect: useEffect,
|
||
Fragment: 'Fragment',
|
||
}
|
||
}
|
||
|
||
function domStub() {
|
||
const styles = new Map()
|
||
const document = {
|
||
querySelector(selector) {
|
||
return styles.get(selector) ?? null
|
||
},
|
||
createElement() {
|
||
const node = { attrs: {}, textContent: '' }
|
||
node.setAttribute = (key, value) => { node.attrs[key] = value }
|
||
node.remove = () => { for (const [key, value] of styles) if (value === node) styles.delete(key) }
|
||
return node
|
||
},
|
||
head: {
|
||
appendChild(node) {
|
||
styles.set('style[data-plugin-css=' + JSON.stringify(node.attrs['data-plugin-css']) + ']', node)
|
||
},
|
||
},
|
||
}
|
||
return { document, styles }
|
||
}
|
||
|
||
async function loadClient({ fetch: customFetch, react: customReact } = {}) {
|
||
const source = await readFile(new URL('../client.js', import.meta.url), 'utf8')
|
||
const { document, styles } = domStub()
|
||
let captured
|
||
const reactImpl = customReact ?? reactStub()
|
||
const window = {
|
||
__ModuleLoader__: {
|
||
load(options) {
|
||
captured = options
|
||
return { exports: {} }
|
||
},
|
||
},
|
||
localStorage: {
|
||
store: new Map(),
|
||
getItem(key) { return this.store.has(key) ? this.store.get(key) : null },
|
||
setItem(key, value) { this.store.set(key, String(value)) },
|
||
},
|
||
events: [],
|
||
listeners: new Map(),
|
||
addEventListener(name, fn) {
|
||
if (!this.listeners.has(name)) this.listeners.set(name, [])
|
||
this.listeners.get(name).push(fn)
|
||
},
|
||
removeEventListener(name, fn) {
|
||
const list = this.listeners.get(name) ?? []
|
||
this.listeners.set(name, list.filter(item => item !== fn))
|
||
},
|
||
dispatchEvent(event) {
|
||
this.events.push(event.type)
|
||
for (const fn of this.listeners.get(event.type) ?? []) fn(event)
|
||
return true
|
||
},
|
||
}
|
||
const fetchImpl = typeof customFetch === 'function'
|
||
? customFetch
|
||
: () => Promise.reject(new Error('测试里不联网'))
|
||
const run = new Function('window', 'document', 'fetch', 'nextTick', source)
|
||
run(window, document, fetchImpl, () => {})
|
||
return { module: captured.factory((name) => (name === 'react' ? reactImpl : (() => { throw new Error(name) })())), captured, document, styles, window }
|
||
}
|
||
|
||
function fakeCtx(options = {}) {
|
||
const { better, contextMenus, uiWorkspace, workspaces, sessions, toast } = options
|
||
const tabs = []
|
||
const slots = []
|
||
const menuRegistrations = []
|
||
const toasts = []
|
||
const effectCleanups = []
|
||
const services = {
|
||
sidebarRightTabs: { register(registration) { tabs.push(registration); return () => {} } },
|
||
sidebarRight: { openTabIn(sessionId, kind) { services.sidebarRight.opened = [sessionId, kind] } },
|
||
}
|
||
if (better) services.betterSidebar = { openTab(registration, target) { services.betterSidebar.opened = [registration, target] } }
|
||
if (contextMenus) {
|
||
services.contextMenus = contextMenus === true
|
||
? { register(registration) { menuRegistrations.push(registration); return () => {} } }
|
||
: contextMenus
|
||
}
|
||
if (uiWorkspace) services.uiWorkspace = uiWorkspace
|
||
if (workspaces) services.workspaces = workspaces.list ? workspaces : { list: { getSnapshot: () => workspaces } }
|
||
if (sessions) services.sessions = sessions.list ? sessions : { list: { getSnapshot: () => sessions } }
|
||
const ctx = {
|
||
effect(fn) {
|
||
const cleanup = fn()
|
||
if (typeof cleanup === 'function') effectCleanups.push(cleanup)
|
||
return cleanup
|
||
},
|
||
sidebarRightTabs: services.sidebarRightTabs,
|
||
get(name, fallback) { return services[name] ?? fallback },
|
||
slots: {
|
||
inject(name, callback) {
|
||
const result = callback()
|
||
slots.push({ name, ...result })
|
||
return () => {}
|
||
},
|
||
register(spec, component) {
|
||
return { spec, component }
|
||
},
|
||
},
|
||
tabs,
|
||
effectCleanups,
|
||
slotsList: slots,
|
||
services,
|
||
menuRegistrations,
|
||
toasts,
|
||
}
|
||
if (contextMenus) ctx.contextMenus = services.contextMenus
|
||
if (typeof toast === 'function') ctx.toast = toast
|
||
return ctx
|
||
}
|
||
|
||
function flush() {
|
||
return new Promise(resolve => setTimeout(resolve, 0))
|
||
}
|
||
|
||
function textOf(node, depth = 0) {
|
||
if (node === null || node === undefined || node === false || node === true) return ''
|
||
if (typeof node === 'string' || typeof node === 'number') return String(node)
|
||
if (Array.isArray(node)) return node.map(item => textOf(item, depth)).join(' ')
|
||
if (typeof node === 'function') return node.name || ''
|
||
if (typeof node === 'object' && node.type) {
|
||
if (typeof node.type === 'function') {
|
||
if (depth > 8) return node.type.name || ''
|
||
try {
|
||
return textOf(node.type(node.props ?? {}), depth + 1)
|
||
} catch (error) {
|
||
return node.type.name || ''
|
||
}
|
||
}
|
||
return [String(node.type), textOf(node.props?.children, depth + 1)].join(' ')
|
||
}
|
||
return ''
|
||
}
|
||
|
||
function findAll(node, predicate, out = []) {
|
||
if (node === null || node === undefined || typeof node !== 'object') return out
|
||
if (Array.isArray(node)) {
|
||
for (const item of node) findAll(item, predicate, out)
|
||
return out
|
||
}
|
||
if (predicate(node)) out.push(node)
|
||
if (node.props && node.props.children !== undefined) findAll(node.props.children, predicate, out)
|
||
return out
|
||
}
|
||
|
||
function projectFixture(overrides = {}) {
|
||
return {
|
||
id: 'prj-1',
|
||
name: '示例项目',
|
||
phase: '执行中',
|
||
workspaceId: 'ws-1',
|
||
models: { lead: 'model-lead', shangshu: 'model-shang', gongbu: 'model-gong' },
|
||
roles: [
|
||
{ role: 'lead', label: '丞相', name: '丞相 Bot', model: 'model-lead', line: '目标进行中', detail: '目标说明', tone: 'active', sessionId: 'sess-lead', exists: true },
|
||
{ role: 'shangshu', label: '尚书', name: '尚书 Bot', model: 'model-shang', line: '阶段 0/2', detail: '返工 0/3', tone: 'idle', sessionId: 'sess-shang', exists: true },
|
||
{ role: 'gongbu', label: '工部', name: '工部 Bot', model: 'model-gong', line: '无工单', detail: '', tone: 'idle', sessionId: 'sess-gong', exists: true },
|
||
],
|
||
reviewsHistory: [],
|
||
...overrides,
|
||
}
|
||
}
|
||
|
||
test('客户端模块导出页签常量与依赖注入', async () => {
|
||
const { module, captured } = await loadClient()
|
||
assert.equal(captured.id, 'dsh-sansheng-sansheng')
|
||
assert.equal(typeof module.apply, 'function')
|
||
assert.deepEqual(module.inject, ['slots', 'sidebarRightTabs', 'sidebarRight'])
|
||
assert.equal(module.TAB_ID, 'sansheng-roles')
|
||
assert.equal(module.TAB_KIND, 'sansheng-roles')
|
||
assert.equal(typeof module.workspaceIdOf, 'function')
|
||
assert.equal(typeof module.__test.isStale, 'function')
|
||
})
|
||
|
||
test('apply 注册右栏页签与三个插槽,并只注入一次样式', async () => {
|
||
const { module, styles } = await loadClient()
|
||
const ctx = fakeCtx()
|
||
module.apply(ctx)
|
||
|
||
assert.equal(ctx.tabs.length, 1)
|
||
const tab = ctx.tabs[0]
|
||
assert.equal(tab.id, 'sansheng-roles')
|
||
assert.equal(tab.kind, 'sansheng-roles')
|
||
assert.equal(tab.keepMounted, true)
|
||
assert.equal(tab.priority, 'builtin')
|
||
assert.equal(tab.title(), '三省六部')
|
||
|
||
assert.deepEqual(ctx.slotsList.map(item => item.name), [
|
||
'sidebar.right.pane.tab',
|
||
'sidebar.right.pane.tab.title',
|
||
'conversation.session.header.actions',
|
||
'sidebar.footer.action',
|
||
])
|
||
const pane = ctx.slotsList[0].spec
|
||
assert.equal(pane.key, 'sansheng-roles')
|
||
const header = ctx.slotsList[2].spec
|
||
assert.equal(header.id, 'sansheng-roles:open')
|
||
assert.equal(header.order, 60)
|
||
const footer = ctx.slotsList[3].spec
|
||
assert.equal(footer.id, 'sansheng-roles:footer')
|
||
|
||
assert.equal(styles.size, 1, '样式只注入一次')
|
||
module.apply(fakeCtx())
|
||
assert.equal(styles.size, 1, '重复 apply 不重复注入样式')
|
||
})
|
||
|
||
test('右栏列在没有项目时渲染引导文案', async () => {
|
||
const { module } = await loadClient()
|
||
const ctx = fakeCtx()
|
||
module.apply(ctx)
|
||
const wrap = ctx.slotsList[0].component
|
||
const element = wrap({ sessionId: 'sess-1' })
|
||
const tree = element.type(element.props)
|
||
const text = textOf(tree)
|
||
assert.match(text, /正在载入当前项目状态|还没有三省六部项目/)
|
||
assert.match(text, /载入|sansheng_provision/)
|
||
})
|
||
|
||
test('页签标题渲染三省与角色字样', async () => {
|
||
const { module } = await loadClient()
|
||
const ctx = fakeCtx()
|
||
module.apply(ctx)
|
||
const title = ctx.slotsList[1].component
|
||
const text = textOf(title())
|
||
assert.match(text, /角色/)
|
||
})
|
||
|
||
test('头部按钮在当前会话打开右栏页签', async () => {
|
||
const { module } = await loadClient()
|
||
const ctx = fakeCtx()
|
||
module.apply(ctx)
|
||
const wrap = ctx.slotsList[2].component
|
||
const element = wrap({ sessionId: 'sess-42' })
|
||
const tree = element.type(element.props)
|
||
assert.match(textOf(tree), /角色/)
|
||
tree.props.onClick()
|
||
assert.deepEqual(ctx.services.sidebarRight.opened, ['sess-42', 'sansheng-roles'])
|
||
})
|
||
|
||
test('装了 better-sidebar 时优先走它的 openTab', async () => {
|
||
const { module } = await loadClient()
|
||
const ctx = fakeCtx({ better: true })
|
||
module.apply(ctx)
|
||
const wrap = ctx.slotsList[2].component
|
||
const element = wrap({ sessionId: 'sess-7' })
|
||
const tree = element.type(element.props)
|
||
tree.props.onClick()
|
||
assert.deepEqual(ctx.services.betterSidebar.opened, [{ type: 'sansheng-roles' }, { sessionId: 'sess-7' }])
|
||
})
|
||
|
||
test('没有当前会话时提示页签是会话级的', async () => {
|
||
const { module } = await loadClient()
|
||
const ctx = fakeCtx()
|
||
module.apply(ctx)
|
||
const wrap = ctx.slotsList[2].component
|
||
const element = wrap({})
|
||
const tree = element.type(element.props)
|
||
tree.props.onClick()
|
||
assert.equal(ctx.services.sidebarRight.opened, undefined)
|
||
})
|
||
|
||
test('workspaceIdOf 按 retainedBy.mainView 反查当前会话所属项目,不拿第一个项目冒充', async () => {
|
||
const { module } = await loadClient()
|
||
const ctx = fakeCtx({
|
||
workspaces: {
|
||
items: [
|
||
{ workspaceId: 'ws-first', sessionIds: ['sess-first'] },
|
||
{ workspaceId: 'ws-current', sessionIds: ['sess-current'] },
|
||
],
|
||
},
|
||
sessions: {
|
||
byId: {
|
||
'sess-first': { id: 'sess-first', retainedBy: { mainView: 0 } },
|
||
'sess-current': { id: 'sess-current', retainedBy: { mainView: 1 } },
|
||
},
|
||
},
|
||
})
|
||
assert.equal(module.workspaceIdOf(ctx), 'ws-current')
|
||
const noSelection = fakeCtx({
|
||
workspaces: { items: [{ workspaceId: 'ws-first', sessionIds: ['sess-first'] }] },
|
||
sessions: { byId: { 'sess-first': { id: 'sess-first' } } },
|
||
})
|
||
assert.equal(module.workspaceIdOf(noSelection), null, '没有明确选择时返回 null')
|
||
})
|
||
|
||
test('apply 注册 workspace 与 session 两个原生上下文菜单', async () => {
|
||
const { module } = await loadClient()
|
||
const ctx = fakeCtx({ contextMenus: true })
|
||
module.apply(ctx)
|
||
|
||
assert.equal(ctx.menuRegistrations.length, 2)
|
||
const workspaceMenu = ctx.menuRegistrations.find(item => item.target === 'workspace')
|
||
const sessionMenu = ctx.menuRegistrations.find(item => item.target === 'session')
|
||
assert.ok(workspaceMenu, '注册 workspace 菜单')
|
||
assert.ok(sessionMenu, '注册 session 菜单')
|
||
assert.equal(workspaceMenu.id, 'sansheng.workspace.open')
|
||
assert.equal(workspaceMenu.order, 260)
|
||
assert.deepEqual(workspaceMenu.observe(), [])
|
||
assert.equal(sessionMenu.id, 'sansheng.session.open')
|
||
assert.equal(sessionMenu.order, 260)
|
||
|
||
const items = sessionMenu.resolve({ sessionId: 'sess-9', displayTitle: '会话九' })
|
||
assert.equal(items.length, 1)
|
||
assert.equal(items[0].id, 'sansheng-open')
|
||
assert.equal(items[0].label, '打开三省六部')
|
||
items[0].run()
|
||
assert.deepEqual(ctx.services.sidebarRight.opened, ['sess-9', 'sansheng-roles'])
|
||
})
|
||
|
||
test('没有 contextMenus 服务时安静跳过,不报错、不虚报注册', async () => {
|
||
const { module } = await loadClient()
|
||
const ctx = fakeCtx()
|
||
assert.doesNotThrow(() => module.apply(ctx))
|
||
assert.equal(ctx.menuRegistrations.length, 0)
|
||
})
|
||
|
||
test('workspace 菜单按 /sansheng/state 的 current 显示已绑定或初始化文案', async () => {
|
||
let payload = { generatedAt: 1, current: { id: 'prj-1', name: '示例项目' }, projects: [] }
|
||
const calls = []
|
||
const fetch = async (url, options) => {
|
||
calls.push({ url, options })
|
||
return { ok: true, status: 200, json: async () => payload }
|
||
}
|
||
const { module } = await loadClient({ fetch })
|
||
const ctx = fakeCtx({ contextMenus: true })
|
||
module.apply(ctx)
|
||
const workspaceMenu = ctx.menuRegistrations.find(item => item.target === 'workspace')
|
||
|
||
const bound = await workspaceMenu.resolve({ workspaceId: 'ws-1', path: 'C:\\work\\a', displayTitle: 'A' })
|
||
assert.equal(bound[0].label, '三省六部')
|
||
assert.match(calls[0].url, /^\/sansheng\/state\?workspaceId=ws-1$/)
|
||
|
||
payload = { generatedAt: 2, current: null, projects: [] }
|
||
const unbound = await workspaceMenu.resolve({ workspaceId: 'ws-2', path: 'C:\\work\\b', displayTitle: 'B' })
|
||
assert.equal(unbound[0].label, '初始化三省六部')
|
||
})
|
||
|
||
test('workspace 菜单 run 打开项目第一个会话并展开右栏', async () => {
|
||
const opened = []
|
||
const fetch = async () => ({ ok: true, status: 200, json: async () => ({ generatedAt: 1, current: { id: 'prj-1' }, projects: [] }) })
|
||
const { module } = await loadClient({ fetch })
|
||
const ctx = fakeCtx({
|
||
contextMenus: true,
|
||
workspaces: { items: [{ workspaceId: 'ws-1', sessionIds: ['sess-w'] }] },
|
||
uiWorkspace: { openSession(sessionId) { opened.push(sessionId) } },
|
||
})
|
||
module.apply(ctx)
|
||
const workspaceMenu = ctx.menuRegistrations.find(item => item.target === 'workspace')
|
||
const items = await workspaceMenu.resolve({ workspaceId: 'ws-1', path: 'C:\\work', displayTitle: 'A' })
|
||
items[0].run()
|
||
await flush()
|
||
assert.deepEqual(opened, ['sess-w'])
|
||
assert.deepEqual(ctx.services.sidebarRight.opened, ['sess-w', 'sansheng-roles'])
|
||
})
|
||
|
||
test('空项目 openWorkbench 通过 startSession 新建会话后再展开右栏', async () => {
|
||
const opened = []
|
||
const workspace = { workspaceId: 'ws-empty', sessionIds: [] }
|
||
const { module } = await loadClient()
|
||
const ctx = fakeCtx({
|
||
workspaces: { items: [workspace] },
|
||
uiWorkspace: {
|
||
selection: { getSnapshot: () => ({ sessionId: 'sess-old-other-workspace' }) },
|
||
startSession(workspaceId) { workspace.sessionIds.push('sess-new') },
|
||
openSession(sessionId) { opened.push(sessionId) },
|
||
},
|
||
})
|
||
const result = await module.__test.openWorkbench(ctx, 'ws-empty')
|
||
assert.equal(result.ok, true)
|
||
assert.deepEqual(opened, ['sess-new'])
|
||
assert.deepEqual(ctx.services.sidebarRight.opened, ['sess-new', 'sansheng-roles'])
|
||
})
|
||
|
||
test('轮询请求带 workspaceId 与 sessionId,断连时保留上次数据并显示上次状态', async () => {
|
||
const ctx = fakeCtx({
|
||
workspaces: { items: [{ workspaceId: 'ws-9', sessionIds: ['sess-9'] }] },
|
||
sessions: { byId: { 'sess-9': { id: 'sess-9', retainedBy: { mainView: 1 } } } },
|
||
})
|
||
const calls = []
|
||
let failing = false
|
||
const payload = { generatedAt: 1, current: { id: 'prj-9', name: 'A', phase: '执行中' }, projects: [] }
|
||
const fetch = async url => {
|
||
calls.push(url)
|
||
if (failing) throw new Error('网络断了')
|
||
return { ok: true, status: 200, json: async () => payload }
|
||
}
|
||
const states = []
|
||
const poller = (await loadClient()).module.__test.createStatePoller({
|
||
ctx,
|
||
fetchImpl: fetch,
|
||
onChange: state => states.push(state),
|
||
intervalMs: 60000,
|
||
})
|
||
poller.start()
|
||
await flush()
|
||
assert.equal(calls.length, 1)
|
||
assert.equal(calls[0], '/sansheng/state?workspaceId=ws-9&sessionId=sess-9')
|
||
assert.equal(states.at(-1).data.current.name, 'A')
|
||
|
||
failing = true
|
||
poller.refresh()
|
||
await flush()
|
||
const last = states.at(-1)
|
||
assert.equal(last.data.current.name, 'A', '断连不丢上次数据')
|
||
assert.match(last.error, /网络断了/)
|
||
assert.equal(last.updatedAt > 0, true)
|
||
poller.stop()
|
||
})
|
||
|
||
test('旧缓存错误提示文案明确显示“连接中断 · 显示上次状态”', async () => {
|
||
const { module } = await loadClient()
|
||
const project = projectFixture()
|
||
const tree = module.__test.RolesView({
|
||
ctx: fakeCtx(),
|
||
data: { current: project, projects: [project] },
|
||
error: 'HTTP 500',
|
||
loading: false,
|
||
updatedAt: Date.now() - 5000,
|
||
context: { workspaceId: 'ws-1', sessionId: 'sess-1' },
|
||
activeId: '',
|
||
onPick: () => {},
|
||
onRefresh: () => {},
|
||
})
|
||
const text = textOf(tree)
|
||
assert.match(text, /连接中断 · 显示上次状态/)
|
||
assert.match(text, /HTTP 500/)
|
||
})
|
||
|
||
test('项目配置默认折叠(details 无 open 属性),且历史审查最多 5 条', async () => {
|
||
const { module } = await loadClient()
|
||
const project = projectFixture({
|
||
reviewsHistory: Array.from({ length: 7 }, (_, index) => ({
|
||
id: 'rev-' + index,
|
||
kind: index % 2 === 0 ? 'stage' : 'goal',
|
||
verdict: 'pass',
|
||
reviewerRole: 'shangshu',
|
||
at: 1000 + index,
|
||
})),
|
||
})
|
||
const tree = module.__test.RolesView({
|
||
ctx: fakeCtx(),
|
||
data: { current: project, projects: [project] },
|
||
error: null,
|
||
loading: false,
|
||
updatedAt: Date.now(),
|
||
context: { workspaceId: 'ws-1', sessionId: 'sess-1' },
|
||
activeId: '',
|
||
onPick: () => {},
|
||
onRefresh: () => {},
|
||
})
|
||
const configNode = findAll(tree, node => node.type === module.__test.ConfigPanel)[0]
|
||
assert.ok(configNode, '渲染项目配置')
|
||
const configTree = configNode.type(configNode.props)
|
||
const configDetails = findAll(configTree, node => node.type === 'details')
|
||
assert.equal(configDetails.length, 1)
|
||
assert.equal(configDetails[0].props.open, undefined, '配置表单默认收起')
|
||
assert.match(textOf(configTree), /项目配置/)
|
||
|
||
const historyNode = findAll(tree, node => node.type === module.__test.HistoryPanel)[0]
|
||
assert.ok(historyNode)
|
||
const historyTree = historyNode.type(historyNode.props)
|
||
const historyDetails = findAll(historyTree, node => node.type === 'details')
|
||
assert.equal(historyDetails[0].props.open, undefined, '历史审查默认收起')
|
||
const items = findAll(historyTree, node => node.props && node.props.className === 'ss-history-item')
|
||
assert.equal(items.length, 5, '最多列 5 条历史审查')
|
||
})
|
||
|
||
test('角色卡可点击打开真实会话;缺会话显示“会话缺失,点此修复”和原因', async () => {
|
||
const { module } = await loadClient()
|
||
const opened = []
|
||
const toasts = []
|
||
const ctx = fakeCtx({ uiWorkspace: { openSession(sessionId) { opened.push(sessionId) } }, toast: text => toasts.push(text) })
|
||
const project = projectFixture()
|
||
const tree = module.__test.RoleCard({ ctx, project, card: project.roles[0] })
|
||
tree.props.onClick()
|
||
assert.deepEqual(opened, ['sess-lead'])
|
||
|
||
const missing = module.__test.RoleCard({
|
||
ctx,
|
||
project,
|
||
card: { role: 'shangshu', label: '尚书', name: '尚书 Bot', model: 'm', line: '状态', detail: '', tone: 'warn', exists: true, sessionId: null, reason: '绑定会话已被删除' },
|
||
})
|
||
const text = textOf(missing)
|
||
assert.match(text, /会话缺失,点此修复/)
|
||
assert.match(text, /绑定会话已被删除/)
|
||
const repair = findAll(missing, node => node.props && node.props.className === 'ss-repair')[0]
|
||
repair.props.onClick({ stopPropagation() {} })
|
||
assert.equal(toasts.length, 1)
|
||
assert.match(toasts[0], /绑定会话已被删除/)
|
||
})
|
||
|
||
test('配置保存 POST body 只含 projectId 与三个模型;isStale 丢弃旧请求', async () => {
|
||
const calls = []
|
||
const fetch = async (url, options) => {
|
||
calls.push({ url, options })
|
||
return { ok: true, status: 200, json: async () => ({}) }
|
||
}
|
||
const { module } = await loadClient({ fetch })
|
||
const project = projectFixture()
|
||
const tree = module.__test.ConfigPanel({ ctx: fakeCtx(), project, onRefresh: () => {} })
|
||
const form = findAll(tree, node => node.type === 'form')[0]
|
||
await form.props.onSubmit({ preventDefault() {} })
|
||
assert.equal(calls[0].url, '/sansheng/config')
|
||
assert.equal(calls[0].options.method, 'POST')
|
||
const body = JSON.parse(calls[0].options.body)
|
||
assert.deepEqual(body, {
|
||
projectId: 'prj-1',
|
||
models: { lead: 'model-lead', shangshu: 'model-shang', gongbu: 'model-gong' },
|
||
})
|
||
|
||
assert.equal(module.__test.isStale(1, 2), true)
|
||
assert.equal(module.__test.isStale(2, 2), false)
|
||
assert.equal(module.__test.stateUrlOf({ workspaceId: 'ws-1', sessionId: 'sess-1' }), '/sansheng/state?workspaceId=ws-1&sessionId=sess-1')
|
||
})
|
||
|
||
test('初始化项目提交 POST /sansheng/provision 且 body 含 workspaceId/path/name/models', async () => {
|
||
const calls = []
|
||
const fetch = async (url, options) => {
|
||
calls.push({ url, options })
|
||
return { ok: true, status: 200, json: async () => ({ project: { id: 'prj-new' } }) }
|
||
}
|
||
const { module } = await loadClient({ fetch })
|
||
const tree = module.__test.InitPanel({
|
||
ctx: fakeCtx(),
|
||
context: { workspaceId: 'ws-new', path: 'C:\\work\\new', displayTitle: '新项目' },
|
||
onDone: () => {},
|
||
})
|
||
const form = findAll(tree, node => node.type === 'form')[0]
|
||
await form.props.onSubmit({ preventDefault() {} })
|
||
assert.equal(calls[0].url, '/sansheng/provision')
|
||
const body = JSON.parse(calls[0].options.body)
|
||
assert.deepEqual(body, { workspaceId: 'ws-new', path: 'C:\\work\\new', name: '新项目', models: {} })
|
||
const text = textOf(tree)
|
||
assert.match(text, /此项目尚未初始化/)
|
||
})
|
||
|
||
test('Bot 切换列表在右栏渲染并可打开对应会话', async () => {
|
||
const { module } = await loadClient()
|
||
const opened = []
|
||
const ctx = fakeCtx({ uiWorkspace: { openSession(sessionId) { opened.push(sessionId) } } })
|
||
const tree = module.__test.BotSwitcher({
|
||
ctx,
|
||
data: {
|
||
bots: [{ id: 'b1', name: '丞相', role: '丞相', sessionId: 'sess-b1', projectName: '项目A' }],
|
||
rooms: [{ id: 'r1', name: '项目A · 三省六部', sessionId: 'sess-r1', projectName: '项目A' }],
|
||
},
|
||
})
|
||
const text = textOf(tree)
|
||
assert.match(text, /Bot 切换/)
|
||
assert.match(text, /丞相/)
|
||
const buttons = findAll(tree, node => node.type === 'button')
|
||
assert.ok(buttons.length >= 2)
|
||
buttons[0].props.onClick()
|
||
assert.deepEqual(opened, ['sess-b1'])
|
||
})
|
||
|
||
test('角色卡模型下拉调用 /sansheng/config,只改当前角色模型', async () => {
|
||
const calls = []
|
||
const fetch = async (url, options) => {
|
||
calls.push({ url, options })
|
||
return { ok: true, status: 200, json: async () => ({ ok: true }) }
|
||
}
|
||
const { module } = await loadClient({ fetch })
|
||
const project = projectFixture()
|
||
const tree = module.__test.RoleCard({
|
||
ctx: fakeCtx(),
|
||
project,
|
||
card: project.roles[0],
|
||
models: [{ ref: 'provider/new-model', name: 'New Model' }],
|
||
})
|
||
const select = findAll(tree, node => node.type === 'select')[0]
|
||
assert.ok(select, '有可用模型时渲染下拉')
|
||
await select.props.onChange({ target: { value: 'provider/new-model' }, stopPropagation() {} })
|
||
assert.equal(calls[0].url, '/sansheng/config')
|
||
const body = JSON.parse(calls[0].options.body)
|
||
assert.deepEqual(body, { projectId: 'prj-1', models: { lead: 'provider/new-model' } })
|
||
})
|
||
|
||
test('切到 B 后请求失败,不把 A 的缓存配上 B 的上下文', async () => {
|
||
const workspaces = { items: [{ workspaceId: 'ws-A', sessionIds: ['sess-A'] }] }
|
||
const sessions = { byId: { 'sess-A': { id: 'sess-A', retainedBy: { mainView: 1 } } } }
|
||
const ctx = fakeCtx({ workspaces, sessions })
|
||
let failing = false
|
||
const fetch = async () => {
|
||
if (failing) throw new Error('网络断了')
|
||
return { ok: true, status: 200, json: async () => ({ generatedAt: 1, current: { id: 'prj-A', name: 'A' }, projects: [] }) }
|
||
}
|
||
const states = []
|
||
const poller = (await loadClient()).module.__test.createStatePoller({ ctx, fetchImpl: fetch, onChange: state => states.push(state), intervalMs: 60000 })
|
||
poller.start()
|
||
await flush()
|
||
assert.equal(states.at(-1).data.current.name, 'A')
|
||
|
||
sessions.byId['sess-A'].retainedBy.mainView = 0
|
||
sessions.byId['sess-B'] = { id: 'sess-B', retainedBy: { mainView: 1 } }
|
||
workspaces.items = [{ workspaceId: 'ws-B', sessionIds: ['sess-B'] }]
|
||
failing = true
|
||
poller.refresh()
|
||
await flush()
|
||
const last = states.at(-1)
|
||
assert.equal(last.context.workspaceId, 'ws-B')
|
||
assert.equal(last.data, null, '跨项目失败不显示旧项目数据')
|
||
assert.match(last.error, /网络断了/)
|
||
poller.stop()
|
||
})
|
||
|
||
test('Q12:Hook 状态合并保留 loading,切换项目唤醒不受节流丢弃', async () => {
|
||
const { module } = await loadClient()
|
||
const merged = module.__test.mergePollState(
|
||
{ loading: false, error: null, data: { old: true }, updatedAt: 1, context: { workspaceId: 'a' } },
|
||
{ loading: true, error: null, data: null, updatedAt: 0, context: { workspaceId: 'b' } },
|
||
)
|
||
assert.equal(merged.loading, true)
|
||
assert.equal(merged.data, null)
|
||
assert.equal(merged.context.workspaceId, 'b')
|
||
|
||
let signature = 'a'
|
||
let refreshes = 0
|
||
const gate = module.__test.createWakeGate({
|
||
refresh: () => { refreshes += 1 },
|
||
signatureOf: () => signature,
|
||
throttleMs: 20,
|
||
})
|
||
gate.wake()
|
||
assert.equal(refreshes, 1)
|
||
gate.wake()
|
||
gate.wake()
|
||
assert.equal(refreshes, 1, '节流窗口内不立即重复刷新')
|
||
await new Promise(resolve => setTimeout(resolve, 30))
|
||
assert.equal(refreshes, 2, '节流窗口结束补一次 trailing 刷新')
|
||
signature = 'b'
|
||
gate.wake()
|
||
assert.equal(refreshes, 3, '项目身份变化立即刷新')
|
||
gate.dispose()
|
||
})
|
||
|
||
test('Q12b:悬挂请求超时后进入错误状态,不永久卡住轮询', async () => {
|
||
const { module } = await loadClient()
|
||
const states = []
|
||
let calls = 0
|
||
const fetch = (url, options) => new Promise((resolve, reject) => {
|
||
calls += 1
|
||
const signal = options?.signal
|
||
if (signal) signal.addEventListener('abort', () => reject(new Error('请求超时')))
|
||
})
|
||
const ctx = fakeCtx({ workspaces: { items: [{ workspaceId: 'ws-timeout', sessionIds: [] }] } })
|
||
const poller = module.__test.createStatePoller({
|
||
ctx,
|
||
fetchImpl: fetch,
|
||
onChange: state => states.push(state),
|
||
intervalMs: 60000,
|
||
requestTimeoutMs: 20,
|
||
})
|
||
poller.start()
|
||
await new Promise(resolve => setTimeout(resolve, 60))
|
||
assert.equal(calls >= 1, true)
|
||
assert.match(states.at(-1).error, /超时/)
|
||
poller.stop()
|
||
})
|
||
|
||
function hookReact() {
|
||
let cells = []
|
||
let cursor = 0
|
||
let pending = []
|
||
let scheduled = null
|
||
let hookFn
|
||
let current
|
||
let setCalls = 0
|
||
let effectCalls = 0
|
||
const depsChanged = (a, b) => !a || !b || a.length !== b.length || a.some((value, index) => value !== b[index])
|
||
const render = () => {
|
||
cursor = 0
|
||
pending = []
|
||
current = hookFn()
|
||
for (const run of pending) run()
|
||
return current
|
||
}
|
||
const schedule = () => {
|
||
if (scheduled) return
|
||
scheduled = setTimeout(() => { scheduled = null; render() }, 0)
|
||
}
|
||
const React = {
|
||
__id: 'custom-hook-react',
|
||
createElement: () => null,
|
||
Fragment: 'Fragment',
|
||
useMemo: fn => fn(),
|
||
useCallback: fn => fn(),
|
||
useRef: value => ({ current: value }),
|
||
useState(initial) {
|
||
const index = cursor++
|
||
if (!(index in cells)) cells[index] = typeof initial === 'function' ? initial() : initial
|
||
return [cells[index], value => {
|
||
setCalls += 1
|
||
cells[index] = typeof value === 'function' ? value(cells[index]) : value
|
||
schedule()
|
||
}]
|
||
},
|
||
useEffect(fn, deps) {
|
||
effectCalls += 1
|
||
const index = cursor++
|
||
const previous = cells[index]
|
||
if (!previous || depsChanged(previous.deps, deps)) {
|
||
cells[index] = { deps, cleanup: undefined }
|
||
pending.push(() => { cells[index].cleanup = fn() })
|
||
}
|
||
},
|
||
useLayoutEffect: () => {},
|
||
}
|
||
return {
|
||
React,
|
||
mount(fn) { hookFn = fn; return render() },
|
||
get state() { return current },
|
||
get setCalls() { return setCalls },
|
||
get effectCalls() { return effectCalls },
|
||
stop() {
|
||
if (scheduled) clearTimeout(scheduled)
|
||
scheduled = null
|
||
for (const cell of cells) {
|
||
if (cell && typeof cell.cleanup === 'function') {
|
||
try { cell.cleanup() } catch { /* ignore */ }
|
||
}
|
||
}
|
||
},
|
||
}
|
||
}
|
||
|
||
test('Q12c:真实 useSanshengState Hook 切换项目保留 loading 并清空旧数据', async () => {
|
||
let selection = { sessionId: 'sess-a' }
|
||
const workspaceItems = [
|
||
{ workspaceId: 'wa', sessionIds: ['sess-a'] },
|
||
{ workspaceId: 'wb', sessionIds: ['sess-b'] },
|
||
]
|
||
const sessionRows = {
|
||
byId: {
|
||
'sess-a': { id: 'sess-a', retainedBy: { mainView: 1 } },
|
||
'sess-b': { id: 'sess-b', retainedBy: { mainView: 0 } },
|
||
},
|
||
}
|
||
const workspaceListeners = []
|
||
const workspaces = { list: { getSnapshot: () => ({ items: workspaceItems }), subscribe: fn => { workspaceListeners.push(fn); return () => {} } } }
|
||
const sessions = { list: { getSnapshot: () => sessionRows, subscribe: fn => { return () => {} } } }
|
||
let fetchCalls = 0
|
||
const fetch = async url => {
|
||
fetchCalls += 1
|
||
if (url.includes('workspaceId=wa')) {
|
||
return { ok: true, status: 200, json: async () => ({ current: { id: 'A', name: 'A' }, projects: [] }) }
|
||
}
|
||
await new Promise(resolve => setTimeout(resolve, 50))
|
||
throw new Error('B 网络断了')
|
||
}
|
||
const ctx = fakeCtx({
|
||
uiWorkspace: { selection: { getSnapshot: () => selection } },
|
||
workspaces,
|
||
sessions,
|
||
})
|
||
const hook = hookReact()
|
||
const { module } = await loadClient({ fetch, react: hook.React })
|
||
hook.mount(() => module.__test.useSanshengState(ctx, ''))
|
||
await new Promise(resolve => setTimeout(resolve, 20))
|
||
assert.ok(hook.effectCalls >= 1, 'effect calls=' + hook.effectCalls + ' fetch=' + fetchCalls)
|
||
assert.equal(hook.state.data && hook.state.data.current && hook.state.data.current.id, 'A', JSON.stringify(hook.state))
|
||
|
||
selection = { sessionId: 'sess-b' }
|
||
sessionRows.byId['sess-a'].retainedBy.mainView = 0
|
||
sessionRows.byId['sess-b'].retainedBy.mainView = 1
|
||
assert.equal(module.__test.workspaceContextOf(ctx).workspaceId, 'wb')
|
||
for (const listener of workspaceListeners) listener()
|
||
await new Promise(resolve => setTimeout(resolve, 15))
|
||
assert.equal(hook.state.context.workspaceId, 'wb')
|
||
assert.equal(hook.state.loading, true, '切换后先进入 loading')
|
||
assert.equal(hook.state.data, null, '旧项目数据立即清空')
|
||
|
||
await new Promise(resolve => setTimeout(resolve, 60))
|
||
assert.equal(hook.state.context.workspaceId, 'wb')
|
||
assert.match(hook.state.error, /B 网络断了/)
|
||
assert.equal(hook.state.data, null)
|
||
hook.stop()
|
||
})
|
||
|
||
test('R4-06:三省卸载时撤销共存标记、发 workbench-gone 并清理样式', async () => {
|
||
const ctx = fakeCtx()
|
||
const { module, styles, window } = await loadClient()
|
||
module.apply(ctx)
|
||
assert.equal(globalThis.__SANSENG_WORKBENCH__, true)
|
||
assert.equal(styles.size, 1, '应注入样式')
|
||
assert.deepEqual(window.events, ['sansheng:workbench-ready'])
|
||
for (const cleanup of [...ctx.effectCleanups].reverse()) cleanup()
|
||
assert.equal(globalThis.__SANSENG_WORKBENCH__, false)
|
||
assert.equal(styles.size, 0, '卸载后样式应清理')
|
||
assert.deepEqual(window.events, ['sansheng:workbench-ready', 'sansheng:workbench-gone'])
|
||
})
|