dsh-sansheng-liubu/panel/test/client.test.js

360 lines
16 KiB
JavaScript
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

import test from 'node:test'
import assert from 'node:assert/strict'
import { readFileSync } from 'node:fs'
import { fileURLToPath } from 'node:url'
import { dirname, join } from 'node:path'
import vm from 'node:vm'
const here = dirname(fileURLToPath(import.meta.url))
const source = readFileSync(join(here, '..', 'lib', 'client.js'), 'utf8')
/** 用最小 React 替身加载客户端 bundle:只实现面板实际用到的钩子。 */
function loadPlugin() {
let loaded
let styleCount = 0
const React = {
createElement: (type, props, ...children) => ({ type, props: props ?? {}, children }),
createContext: (value) => ({ Provider: 'provider', value }),
Component: class { constructor(props) { this.props = props; this.state = {} } },
useContext: () => undefined,
Fragment: 'fragment',
useState: (initial) => [typeof initial === 'function' ? initial() : initial, () => {}],
useRef: () => ({ current: null }),
useEffect: () => {},
useCallback: (fn) => fn,
useMemo: (fn) => fn(),
}
const ReactDOM = { createPortal: (node) => node }
const document = {
getElementById: () => null,
querySelector: () => null,
createElement: () => ({ dataset: {}, appendChild() {}, textContent: '', setAttribute() {} }),
head: { appendChild() { styleCount += 1 } },
addEventListener() {},
removeEventListener() {},
body: {},
}
const window = {
__ModuleLoader__: {
load(options) {
loaded = options
const module = { exports: options.factory((name) => {
if (name === 'react') return React
if (name === 'react-dom') return ReactDOM
if (name === 'react/jsx-runtime') return { jsx: () => null, jsxs: () => null, Fragment: 'fragment' }
throw new Error('unexpected require: ' + name)
}) }
loaded.exports = module.exports
},
},
}
vm.runInNewContext(source, { window, document, console, URL, Map, Set, WeakMap, Promise, setTimeout, clearTimeout }, { filename: 'client.js' })
return { loaded, exports: loaded.exports, styleCount: () => styleCount }
}
/** 模拟宿主 ctx:只实现面板调用到的服务面。 */
function mockContext(prompts = []) {
const registrations = []
const injected = []
const selections = []
const tabTypes = []
const openTabs = []
let selection = { sessionId: 'lead-1' }
const selectionStore = {
getSnapshot: () => selection,
subscribe: () => () => {},
set: (next) => { selection = next; selections.push(next) },
}
const ctx = {
effect(callback) { const dispose = callback(); return typeof dispose === 'function' ? dispose : () => {} },
sessions: {
list: { getSnapshot: () => ({ ids: ['lead-1'], byId: { 'lead-1': { id: 'lead-1' } }, projectionsBySession: {} }) },
binding(sessionId) {
return { session: { prompt: async (parts, mode) => { prompts.push({ sessionId, parts, mode }); return { ok: true } } } }
},
subagentAddress: () => undefined,
refreshProjections: async () => {},
},
uiWorkspace: {
selection: selectionStore,
openSession(target) { selections.push(target) },
},
uiConversation: { binding: () => ({ target: () => ({ getSnapshot: () => undefined }) }) },
modelDirectories: {
directoryFor: () => ({
load: async () => {},
select: async () => {},
store: { getSnapshot: () => ({ current: { provider: 'p', model: 'm' }, groups: [], failures: [], status: 'ready', error: null }) },
}),
},
remote: { agentPresets: { list: async () => ({ ok: true, value: { presets: [] } }), select: async () => ({ ok: true }) } },
layout: { selectPanel(id) { selections.push(id) } },
get() { return undefined },
sidebarRightTabs: { register(descriptor) { tabTypes.push(descriptor); return () => {} } },
sidebarRight: {
openTab(kind, options) { openTabs.push({ sessionId: undefined, kind, options }) },
openTabIn(sessionId, kind, options) { openTabs.push({ sessionId, kind, options }) },
},
slots: {
register(options, component) {
registrations.push({ options, component })
return () => {}
},
inject(slotName, callback) {
injected.push(slotName)
return callback()
},
},
}
return { ctx, registrations, injected, selections, tabTypes, openTabs, portal: { getSnapshot: () => ({}), subscribe: () => () => {} } }
}
test('registers one web client bundle entry', () => {
const { loaded } = loadPlugin()
assert.equal(loaded.id, 'dsh-sansheng-liubu-panel')
})
test('exports the sidebar entry and the main panel', () => {
const { exports } = loadPlugin()
assert.equal(typeof exports.apply, 'function')
assert.equal(exports.PANEL_ID, 'sansheng-liubu')
assert.equal(typeof exports.SanshengPanel, 'function')
assert.equal(typeof exports.SidebarIcon, 'function')
assert.equal(JSON.stringify(exports.inject), JSON.stringify(['slots', 'sessions', 'uiWorkspace', 'uiConversation', 'modelDirectories', 'remote', 'remote.agentPresets', 'sidebarRightTabs', 'sidebarRight']))
})
test('registers a sidebar icon and a matching main panel', () => {
const { exports } = loadPlugin()
const { ctx, registrations, injected } = mockContext()
exports.apply(ctx)
assert.deepEqual(injected, ['sidebar.panellist', 'sidebar.panellist.actions', 'conversation.session.header.actions', 'main', 'sidebar.right.pane.tab', 'sidebar.right.pane.tab.title'])
const sidebar = registrations.find((entry) => entry.options.name === 'sidebar.panellist')
const main = registrations.find((entry) => entry.options.name === 'main')
assert.ok(sidebar, '已注册左侧导航图标')
assert.ok(main, '已注册 main 面板')
assert.equal(sidebar.options.id, 'sansheng-liubu')
assert.equal(main.options.key, sidebar.options.id, '侧栏 id 必须等于 main 面板 key')
assert.equal(sidebar.options.label(), '三省六部')
assert.equal(typeof main.component, 'function', 'main 面板有内容组件')
assert.equal(typeof exports.createHost(ctx).sendPrompt, 'function')
const toggle = registrations.find((entry) => entry.options.name === 'conversation.session.header.actions')
assert.ok(toggle, '会话头有开关,主对话不必离开就能收起朝堂')
assert.equal(toggle.options.id, 'sansheng-liubu:toggle')
assert.equal(typeof exports.createHost(ctx).togglePanel, 'function')
})
test('lays the roster out as 丞相 / 三省 / 六部', () => {
const { exports } = loadPlugin()
const { arrangeRoster } = exports.__test
const seats = arrangeRoster({
members: [
{ id: 'lead-1', name: 'lead', phase: 'active' },
{ id: 'z-1', name: 'zhongshu', phase: 'active' },
{ id: 'g-1', name: 'gongbu', phase: 'provisioning' },
],
tasks: [],
})
assert.equal(seats.length, 7)
const byRole = Object.fromEntries(seats.map((seat) => [seat.role, seat]))
assert.equal(byRole.lead.row, 0)
assert.equal(byRole.zhongshu.row, 1)
assert.equal(byRole.shangshu.row, 1)
assert.equal(byRole.menxia.row, 1)
assert.equal(byRole.zhongshu.column, 0)
assert.equal(byRole.shangshu.column, 1)
assert.equal(byRole.menxia.column, 2)
assert.equal(byRole.gongbu.row, 2)
assert.equal(byRole.gongbu.present, true)
assert.equal(byRole.gongbu.id, 'g-1')
assert.equal(byRole.libu.present, false, '未设官的部门仍占位')
assert.equal(byRole.zhongshu.label, '中书省')
})
test('separates running state from task state', () => {
const { exports } = loadPlugin()
const { memberStatus, bucketsOf, tasksOfRole, statusSummary } = exports.__test
assert.equal(memberStatus({ phase: 'active' }, true, false), 'running')
assert.equal(memberStatus({ phase: 'active' }, false, false), 'idle')
assert.equal(memberStatus({ phase: 'provisioning' }, false, false), 'provisioning')
assert.equal(memberStatus({ phase: 'failed' }, false, false), 'failed')
assert.equal(memberStatus(undefined, false, false), 'absent')
const tasks = [
{ id: 't1', subject: '规模', status: 'in_progress', ownerName: 'zhongshu' },
{ id: 't2', subject: '核对', status: 'completed', ownerName: 'menxia' },
{ id: 't3', subject: '备料', status: 'pending', ownerName: 'shangshu' },
]
const buckets = bucketsOf(tasks)
assert.equal(buckets.pending.length, 1)
assert.equal(buckets.in_progress.length, 1)
assert.equal(buckets.completed.length, 1)
assert.equal(tasksOfRole(tasks, 'menxia').length, 1)
const summary = statusSummary({ role: 'zhongshu', member: { phase: 'active' } }, { tasks }, true, false)
assert.equal(summary.status, 'running')
assert.equal(summary.statusLabel, '运行中')
assert.equal(summary.runningCount, 1)
})
test('builds model options with reasoning efforts', () => {
const { exports } = loadPlugin()
const { modelOptions, findModelOption, modelSwitchPlan } = exports.__test
const options = modelOptions({
groups: [{ id: 'moonshotai-cn', models: [{ id: 'kimi-k3', name: 'Kimi K3', reasoning: { efforts: [{ id: 'high', name: '高' }], defaultEffort: 'high' } }] }],
})
assert.equal(options.length, 1)
assert.equal(options[0].rowId, 'moonshotai-cn/kimi-k3')
assert.equal(options[0].provider, 'moonshotai-cn')
assert.equal(options[0].model, 'kimi-k3')
assert.equal(options[0].defaultEffort, 'high')
assert.equal(findModelOption(options, { provider: 'moonshotai-cn', model: 'kimi-k3' }).model, 'kimi-k3')
const plan = modelSwitchPlan({ provider: 'x', model: 'y' }, { provider: 'moonshotai-cn', model: 'kimi-k3', reasoningEffort: 'high' }, false)
assert.equal(plan.ok, true)
assert.equal(plan.payload.provider, 'moonshotai-cn')
assert.equal(plan.payload.reasoningEffort, 'high')
assert.equal(modelSwitchPlan(undefined, { provider: 'a', model: 'b' }, true).ok, false, '子会话不能单独换模型')
})
test('formats a decree with the target department', () => {
const { exports } = loadPlugin()
const text = exports.__test.decreeText('gongbu', ' 补一版安装脚本 ', {
tasks: [{ id: 't9', subject: '打包', status: 'in_progress' }],
})
assert.match(text, /工部/)
assert.match(text, /补一版安装脚本/)
assert.match(text, /打包/)
assert.equal(exports.__test.decreeText('gongbu', ' ', {}), '')
})
test('reads the latest exchange from chat nodes', () => {
const { exports } = loadPlugin()
const exchange = exports.__test.lastExchange([
{ kind: 'user', anchorSeq: 1, data: { content: [{ type: 'text', text: '拟一份方案' }] } },
{ kind: 'assistant', anchorSeq: 2, data: { blocks: [{ kind: 'text', text: '已有方案草稿' }] } },
])
assert.equal(exchange.lastUser, '拟一份方案')
assert.equal(exchange.lastAssistant, '已有方案草稿')
})
test('delivers a decree into the selected department session', async () => {
const { exports } = loadPlugin()
const prompts = []
const { ctx } = mockContext(prompts)
exports.apply(ctx)
const host = exports.createHost(ctx)
const result = await host.sendPrompt('gongbu-1', '补一版安装脚本')
assert.equal(result.ok, true)
assert.equal(prompts.length, 1)
assert.equal(prompts[0].sessionId, 'gongbu-1')
assert.equal(prompts[0].mode, 'queue')
assert.equal(prompts[0].parts[0].text, '补一版安装脚本')
})
test('registers its page through better-sidebar when that plugin is installed', () => {
const { exports } = loadPlugin()
const { ctx, tabTypes, openTabs } = mockContext()
const registered = []
ctx.betterSidebar = {
registerTab(descriptor) { registered.push(descriptor); return () => {} },
openTab(seed, scope) { openTabs.push({ seed, scope }) },
}
exports.apply(ctx)
// 让位给 better-sidebar:不再重复注册宿主原生 tab 类型。
assert.equal(tabTypes.length, 0)
assert.equal(registered.length, 1)
const descriptor = registered[0]
assert.equal(descriptor.id, exports.SANSENG_TAB_ID)
assert.equal(descriptor.single, true)
assert.equal(typeof descriptor.component, 'function')
const host = exports.createHost(ctx)
const result = host.openSanshengTab('lead-1')
assert.equal(result.ok, true)
assert.equal(openTabs.length, 1)
assert.equal(openTabs[0].seed.type, exports.SANSENG_TAB_ID)
assert.equal(openTabs[0].scope.sessionId, 'lead-1')
const tree = descriptor.component({ scope: { sessionId: 'lead-1' }, host })
const panelEl = tree.children[0]
const rendered = panelEl.type(panelEl.props)
assert.equal(rendered.props['data-sansheng-compact'], '1', '朝堂页以紧凑形态渲染到侧边栏')
})
test('falls back to the newest session when nothing is selected', () => {
const { exports } = loadPlugin()
const { ctx } = mockContext()
// 空选中记录:模拟用户还没点开任何会话就打开朝堂页。
ctx.uiWorkspace.selection.getSnapshot = () => ({})
ctx.sessions.list.getSnapshot = () => ({
ids: ['old-1', 'new-1', 'blank-1'],
byId: {
'old-1': { id: 'old-1', updatedAt: '2026-11-01T00:00:00.000Z' },
'new-1': { id: 'new-1', updatedAt: '2026-11-07T00:00:00.000Z' },
'blank-1': { id: 'blank-1', blank: true, updatedAt: '2026-11-09T00:00:00.000Z' },
},
projectionsBySession: {},
})
exports.apply(ctx)
const host = exports.createHost(ctx)
assert.equal(host.getSelectedSession(), 'new-1')
})
test('opens an addressed child conversation with its parent', () => {
const { exports } = loadPlugin()
const { ctx, selections } = mockContext()
ctx.sessions.list.getSnapshot = () => ({
ids: ['lead-1', 'child-1'],
byId: { 'child-1': { id: 'child-1', subagent: { address: { parentSessionId: 'lead-1', childSessionId: 'child-1' } } } },
projectionsBySession: {},
})
exports.apply(ctx)
const host = exports.createHost(ctx)
host.openSession('child-1')
const target = selections.find((entry) => entry && typeof entry === 'object' && entry.childSessionId === 'child-1')
assert.ok(target, '子会话按 parent/child 地址打开')
assert.equal(target.parentSessionId, 'lead-1')
assert.equal(target.mode, 'continuable')
})
/**
* 回归:main 是 root 级槽,宿主注入的 useSessions / useSessionStatus /
* usePanelInfo 在 root 作用域下不可靠。面板必须只靠 host 的服务层 store
* 就能渲染,否则组件抛错会被 SlotErrorBoundary 隔离成整片空白。
*/
test('main panel renders without slot-provided session hooks', () => {
const { exports } = loadPlugin()
const { ctx } = mockContext()
exports.apply(ctx)
const tree = exports.SanshengPanel({ host: exports.createHost(ctx) })
let hasRoot = false
const walk = (node) => {
if (Array.isArray(node)) { node.forEach(walk); return }
if (!node || typeof node !== 'object') return
const cls = node.props && node.props.className
if (typeof cls === 'string' && cls.split(' ').includes('sl-root')) hasRoot = true
walk(node.children)
}
walk(tree)
assert.equal(hasRoot, true, '无会话级 hook 时仍渲染出面板根节点')
})
test('main panel wraps its content in a visible error boundary', () => {
const { exports } = loadPlugin()
const { ctx, registrations } = mockContext()
exports.apply(ctx)
const main = registrations.find((entry) => entry.options.name === 'main')
const tree = main.component({})
assert.ok(tree, 'main 组件返回元素树')
assert.equal(tree.props['data-sansheng-main'], '1', '始终可见的页头外壳')
let found = false
const walk = (node) => {
if (Array.isArray(node)) { node.forEach(walk); return }
if (!node || typeof node !== 'object') return
if (typeof node.type === 'function' && /PanelBoundary/.test(node.type.name || '')) found = true
const kids = Array.isArray(node.children) ? node.children : node.props && node.props.children
if (Array.isArray(kids)) kids.forEach(walk)
else if (kids) walk(kids)
}
walk(tree)
assert.equal(found, true, '内容被错误边界包住')
})