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

984 lines
44 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 }
let cssText = ''
const document = {
getElementById: () => null,
querySelector: () => null,
createElement: () => {
const tag = { dataset: {}, appendChild() {}, setAttribute() {} }
let text = ''
Object.defineProperty(tag, 'textContent', {
get: () => text,
set: (value) => { text = String(value); cssText = text },
})
return tag
},
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
},
},
}
const storage = new Map()
const localStorage = {
getItem: (key) => (storage.has(key) ? storage.get(key) : null),
setItem: (key, value) => { storage.set(key, String(value)) },
removeItem: (key) => { storage.delete(key) },
}
vm.runInNewContext(source, { window, document, console, URL, Map, Set, WeakMap, Promise, setTimeout, clearTimeout, localStorage }, { filename: 'client.js' })
return { loaded, exports: loaded.exports, styleCount: () => styleCount, css: () => cssText, storage }
}
/** 全局模型清单的样板值:宿主一代只给一份,任何会话读到的都是它。 */
const CATALOG_VALUE = {
default: { provider: 'deepseek', model: 'deepseek-chat' },
failures: [],
groups: [
{
id: 'deepseek',
name: 'DeepSeek',
models: [
{ id: 'deepseek-chat', name: 'DeepSeek Chat' },
{ id: 'deepseek-reasoner', name: 'DeepSeek Reasoner', reasoning: { defaultEffort: 'high', efforts: [{ id: 'high', name: '高' }] } },
],
},
],
}
/** 模拟宿主 ctx:只实现面板调用到的服务面。 */
function mockContext(prompts = []) { const registrations = []
const injected = []
const selections = []
const tabTypes = []
const openTabs = []
let selection = { sessionId: 'lead-1' }
const sessionIds = ['lead-1']
const sessionById = { 'lead-1': { id: 'lead-1', updatedAt: 1 } }
const sessionList = {
getSnapshot: () => ({ ids: sessionIds.slice(), byId: sessionById, projectionsBySession: {} }),
subscribe: () => () => {},
}
const addSession = (id, workspaceId) => {
sessionIds.push(id)
sessionById[id] = { id, workspaceId, updatedAt: Date.now() }
return id
}
const selectionStore = {
getSnapshot: () => selection,
subscribe: () => () => {},
set: (next) => { selection = next; selections.push(next) },
}
let startSessionImpl
const ctx = {
effect(callback) { const dispose = callback(); return typeof dispose === 'function' ? dispose : () => {} },
sessions: {
list: sessionList,
binding(sessionId) {
return { session: { prompt: async (parts, mode) => { prompts.push({ sessionId, parts, mode }); return { ok: true } } } }
},
subagentAddress: () => undefined,
refreshProjections: async () => {},
},
uiWorkspace: {
selection: selectionStore,
currentWorkspaceId: 'test-workspace',
startSession(workspaceId, options) { if (startSessionImpl) startSessionImpl(workspaceId, options) },
openSession(target) { selections.push(target) },
},
uiConversation: { binding: () => ({ target: () => ({ getSnapshot: () => undefined }) }) },
modelDirectories: {
catalog: {
load: async () => CATALOG_VALUE,
store: { getSnapshot: () => ({ value: CATALOG_VALUE, status: 'ready', error: null }) },
},
directoryFor: () => ({
load: async () => {},
select: async () => ({ ok: true }),
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 }) },
session: { selectModel: 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,
prompts,
addSession,
setStartSession(fn) { startSessionImpl = fn },
portal: { getSnapshot: () => ({}), subscribe: () => () => {} },
}
}
test('registers one web client bundle entry', () => {
const { loaded } = loadPlugin()
assert.equal(loaded.id, 'dsh-sansheng-liubu-panel')
})
test('exports the panel and the seat mention helpers', () => {
const { exports } = loadPlugin()
assert.equal(typeof exports.apply, 'function')
assert.equal(exports.PANEL_ID, 'sansheng-liubu')
assert.equal(typeof exports.SanshengPanel, 'function')
assert.equal(JSON.stringify(exports.inject), JSON.stringify(['slots', 'sessions', 'uiWorkspace', 'uiConversation', 'modelDirectories', 'remote', 'remote.agentPresets', 'sidebarRightTabs', 'sidebarRight']))
})
test('registers the left nav row, one rail entry, the native header action and right sidebar tabs', () => {
const { exports } = loadPlugin()
const { ctx, registrations, injected } = mockContext()
exports.apply(ctx)
assert.deepEqual(injected, ['conversation.session.header.actions', 'sidebar.panellist', 'main', 'sidebar.right.pane.tab', 'sidebar.right.pane.tab.title'])
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')
const nav = registrations.find((entry) => entry.options.name === 'sidebar.panellist')
assert.ok(nav, '左侧栏导航列也有入口')
assert.equal(nav.options.id, 'sansheng-liubu')
assert.equal(nav.options.label(), '上朝', '用户要求这行叫「上朝」')
assert.ok(nav.options.order < 0, '要排在其它插件行之前(置顶)')
assert.ok(Number.isFinite(nav.options.order), '导航列要给出排序,才能稳定落在固定位置')
const stub = registrations.find((entry) => entry.options.name === 'main')
assert.ok(stub, '那一列的点击会索取 main 槽,必须有落点')
assert.equal(stub.options.key, 'sansheng-liubu', 'main 用 key 与侧栏行对齐,不是再开一套面板')
const tab = registrations.find((entry) => entry.options.name === 'sidebar.right.pane.tab')
assert.ok(tab, '右侧栏注册朝堂页签')
assert.equal(tab.options.key, 'sansheng-liubu-tab')
})
test('左栏导航图标的「三」字样标按激活状态换描边', () => {
const { exports } = loadPlugin()
const { ctx, registrations } = mockContext()
exports.apply(ctx)
const nav = registrations.find((entry) => entry.options.name === 'sidebar.panellist')
// 注册项返回 h(SanshengNavGlyph, props),再调用一次才是真正的 svg 节点。
const glyphOf = (props) => {
const wrapper = nav.component(props)
return wrapper.type(wrapper.props)
}
const idle = glyphOf({ size: 18, active: false })
const active = glyphOf({ size: 18, active: true })
assert.equal(idle.type, 'svg')
assert.equal(idle.props.width, 18)
assert.equal(idle.props['data-sansheng-glyph'], 'idle')
assert.equal(active.props['data-sansheng-glyph'], 'active')
// 替身的 createElement 把可变参数放进 children,数组实参会成为单层嵌套,这里拉平。
const kids = (idle.children || []).flat()
assert.equal(kids.length, 4, '外框 + 三横')
const activeKids = (active.children || []).flat()
assert.ok(activeKids[0].props.strokeWidth > kids[0].props.strokeWidth, '激活态加粗')
})
test('导航列点击后把朝堂停靠到右侧栏,再退回原会话', () => {
const { exports } = loadPlugin()
const { dockToSidebarTab } = exports.__test
const calls = []
const okHost = {
openSanshengTab: () => ({ ok: true }),
setToggleNotice: (value) => calls.push(['notice', value]),
selectPanel: (id) => calls.push(['selectPanel', id]),
}
assert.equal(dockToSidebarTab(okHost), null)
assert.deepEqual(calls, [['notice', null], ['selectPanel', null]], '成功后清掉提示并退出 main 槽')
calls.length = 0
const failHost = {
openSanshengTab: () => ({ ok: false, error: '当前还没有打开任何会话' }),
setToggleNotice: (value) => calls.push(['notice', value]),
selectPanel: (id) => calls.push(['selectPanel', id]),
}
assert.equal(dockToSidebarTab(failHost), '当前还没有打开任何会话')
assert.deepEqual(calls, [['notice', '当前还没有打开任何会话']], '失败时只写提示,不能把人留在一个不存在的面板上')
})
test('summarizes the court into four sidebar stats', () => {
const { exports } = loadPlugin()
const { arrangeRoster, courtStats } = 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: [],
})
const buckets = {
pending: [{ id: 'p1' }, { id: 'p2' }],
in_progress: [{ id: 'r1' }],
completed: [{ id: 'c1' }, { id: 'c2' }, { id: 'c3' }],
}
const running = new Set(['lead-1', 'z-1', 'g-1'])
const stats = Array.from(courtStats(seats, buckets, (entry) => running.has(entry.id)))
assert.deepEqual(Array.from(stats, (stat) => stat.label), ['在朝成员', '正在运行', '在办任务', '已完成'])
assert.deepEqual(Array.from(stats, (stat) => stat.value), [3, 3, 3, 3], '在办任务包含执行中与待办任务')
assert.deepEqual(Array.from(stats, (stat) => stat.key), ['members', 'running', 'pending', 'done'])
assert.deepEqual(Array.from(courtStats(undefined, undefined, () => true), (stat) => stat.value), [0, 0, 0, 0])
})
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, 10)
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, '中书省')
assert.deepEqual(
['libu', 'hubu', 'lipu', 'bingbu', 'xingbu', 'gongbu'].map((role) => byRole[role].label),
['吏部', '户部', '礼部', '兵部', '刑部', '工部'],
)
assert.deepEqual(
['libu', 'hubu', 'lipu', 'bingbu', 'xingbu', 'gongbu'].map((role) => byRole[role].row),
[2, 2, 2, 2, 2, 2],
'六部直属尚书省,同在第 2 排',
)
})
test('exposes department sessions as native @ mention candidates', async () => {
const { exports } = loadPlugin()
const { arrangeRoster, seatMentionOptions, childRoleOf } = 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: 'active' },
],
tasks: [],
})
const options = seatMentionOptions(seats)
assert.deepEqual(Array.from(options, (item) => item.label), ['中书省', '工部'])
assert.deepEqual(Array.from(options, (item) => item.value), ['z-1', 'g-1'])
assert.match(options[1].description, /选择后进入该部门会话/)
assert.equal(childRoleOf(seats, 'g-1'), 'gongbu')
assert.equal(childRoleOf(seats, 'unknown'), undefined)
const sources = []
const { ctx } = mockContext()
ctx.get = (name) => name === 'inputTriggers'
? { registerSource(source) { sources.push(source); return () => {} } }
: undefined
exports.apply(ctx)
assert.equal(sources.length, 1)
assert.equal(sources[0].trigger, '@')
const { createSeatMentionSource } = exports.__test
let opened
const source = createSeatMentionSource({
sessions: {
list: { getSnapshot: () => ({ projectionsBySession: { 'lead-1': { values: { agentTeam: {
members: [
{ id: 'lead-1', name: 'lead', phase: 'active' },
{ id: 'z-1', name: 'zhongshu', phase: 'active' },
{ id: 'g-1', name: 'gongbu', phase: 'active' },
],
} } } } }) },
subagentAddress: () => ({ parentSessionId: 'lead-1', childSessionId: 'child-1' }),
},
uiWorkspace: { selection: { getSnapshot: () => ({ sessionId: 'child-1' }) } },
}, { openSession: (id) => { opened = id } })
const matched = Array.from(await source.candidates({ sessionId: 'child-1' }, { query: '工' }))
assert.deepEqual(Array.from(matched, (item) => item.label), ['工部'])
const outcome = source.onPick({ candidate: matched[0] })
assert.equal(outcome.text, '')
assert.deepEqual(Object.keys(outcome), ['text'])
await Promise.resolve()
assert.equal(opened, 'g-1')
})
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')
const subagentPlan = modelSwitchPlan(undefined, { provider: 'a', model: 'b' }, true)
assert.equal(subagentPlan.ok, true, '子会话改模型走模式插件的部门路由')
assert.equal(subagentPlan.via, 'command')
assert.equal(modelSwitchPlan({ provider: 'a', model: 'b' }, { 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')
})
/**
* 回归:右侧栏页签由宿主注入 props,不应依赖会话级 hook 才能渲染;
* 面板必须只靠 host 的服务层 store 就能出图,否则会整片空白。
*/
test('sidebar 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 classes = new Set()
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(' ').forEach((name) => classes.add(name))
if (cls.split(' ').includes('sl-root')) hasRoot = true
}
walk(node.children)
}
walk(tree)
assert.equal(hasRoot, true, '无会话级 hook 时仍渲染出面板根节点')
for (const name of ['sl-side-meta', 'sl-side-tabs', 'sl-map-head', 'sl-detail-title']) {
assert.ok(classes.has(name), `新版侧栏缺少 ${name}`)
}
assert.equal(classes.has('sl-left'), false, '侧栏形态不再包含独立聊天栏')
assert.equal(classes.has('sl-conv'), false)
})
test('renders a card-first court and a settings panel without duplicate decree input', () => {
const { exports } = loadPlugin()
const { ctx } = mockContext()
ctx.sessions.list.getSnapshot = () => ({
ids: ['lead-1'],
byId: { 'lead-1': { id: 'lead-1' } },
projectionsBySession: {
'lead-1': {
values: {
agentTeam: {
members: [{ id: 'lead-1', name: 'lead', phase: 'active' }],
tasks: [],
},
},
},
},
})
exports.apply(ctx)
const tree = exports.SanshengPanel({ host: exports.createHost(ctx) })
const nodes = []
const childrenOf = (node) => {
if (Array.isArray(node.children) && node.children.length > 0) return node.children
return node.props && node.props.children
}
const walk = (node) => {
if (Array.isArray(node)) { node.forEach(walk); return }
if (!node || typeof node !== 'object') return
nodes.push(node)
walk(childrenOf(node))
}
walk(tree)
const seatElements = nodes.filter((node) => typeof node.type === 'function' && node.type.name === 'SeatCard')
assert.equal(seatElements.length, 10, '朝堂图始终保留十席卡片')
seatElements.forEach((node) => walk(node.type(node.props)))
const withClass = (name) => nodes.filter((node) => node.type && String(node.props?.className || '').split(' ').includes(name))
const textOf = (node) => {
if (typeof node === 'string' || typeof node === 'number') return String(node)
if (Array.isArray(node)) return node.map(textOf).join('')
if (!node || typeof node !== 'object') return ''
return textOf(childrenOf(node))
}
assert.equal(withClass('sl-node').length, 10, '朝堂图始终保留十席卡片')
assert.equal(withClass('sl-node-check').length, 1, '只有当前部门显示选中勾')
assert.equal(withClass('sl-node-status').length, 10, '每张卡片都有独立状态行')
assert.equal(withClass('sl-ministry-group').length, 1, '六部收在同一个尚书省分组')
assert.equal(withClass('sl-sidebar').length, 1, '根节点是右侧栏形态')
assert.equal(withClass('sl-side-tabs').length, 1, '侧栏顶部有朝堂/任务切换')
assert.equal(nodes.filter((node) => node.props && node.props['data-side-tab']).length, 2)
assert.match(textOf(withClass('sl-side-tabs')[0]), /朝堂/)
assert.match(textOf(withClass('sl-side-tabs')[0]), /任务/)
assert.equal(withClass('sl-side-court').length, 1, '默认展示朝堂编制')
const courtTab = nodes.find((node) => node.props && node.props['data-side-tab'] === 'court')
assert.equal(courtTab.props['aria-selected'], true)
assert.equal(withClass('sl-left').length, 0, '不再保留重复的左侧聊天栏')
assert.equal(withClass('sl-conv').length, 0)
assert.equal(withClass('sl-left-nav').length, 0)
assert.equal(withClass('sl-task-jump').length, 0)
assert.equal(nodes.filter((node) => node.props && node.props['data-task-flow-jump'] === '1').length, 0)
assert.equal(withClass('sl-stat-pending')[0].type, 'button', '在办任务统计可直接切换到任务流转')
assert.equal(withClass('sl-stat-members')[0].type, 'button', '在朝成员统计可直接进入朝堂编制')
assert.equal(withClass('sl-stat-members')[0].props.title, '查看朝堂编制')
assert.equal(typeof withClass('sl-stat-members')[0].props.onClick, 'function')
const grid = withClass('sl-grid-6')[0]
assert.ok(grid, '六部使用独立网格')
const gridKids = Array.isArray(childrenOf(grid)) ? childrenOf(grid).flat(2) : []
assert.equal(gridKids.filter((node) => typeof node?.type === 'function' && node.type.name === 'SeatCard').length, 6)
assert.equal(withClass('sl-conversation-action').length, 1, '设置区有明确的子 Agent 对话入口')
assert.match(textOf(withClass('sl-conversation-action')[0]), /丞相主会话/)
assert.equal(withClass('sl-advanced').length, 1, '技术信息收在高级信息里')
assert.equal(withClass('sl-detail-chip')[0] && textOf(withClass('sl-detail-chip')[0]), '固定职责')
assert.equal(withClass('sl-setting-block').length, 1)
assert.equal(withClass('sl-model-foot').length, 1)
assert.equal(nodes.filter((node) => node.type === 'textarea').length, 0, '不再提供重复的下旨输入框')
assert.equal(nodes.filter((node) => node.type === 'input').length, 0, '设置区没有可编辑的预设输入')
assert.equal(nodes.filter((node) => node.type === 'datalist').length, 0)
const text = textOf(tree)
assert.match(text, /输入 @ 选择部门/, '侧栏提示原生 @ 入口')
assert.doesNotMatch(text, /打开主对话/)
assert.doesNotMatch(text, /下旨/)
assert.doesNotMatch(text, /预设 ID 可直接填写/)
assert.match(text, /空闲/)
assert.doesNotMatch(text, /\bidle\b/)
assert.doesNotMatch(text, /项在办/, '窄卡片不塞任务计数,避免状态行换行')
})
test('sidebar tab wraps its content in a visible error boundary', () => {
const { exports } = loadPlugin()
const { ctx, registrations } = mockContext()
exports.apply(ctx)
const tab = registrations.find((entry) => entry.options.name === 'sidebar.right.pane.tab')
const tree = tab.component({})
assert.ok(tree, '侧栏页签组件返回元素树')
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)
}
if (typeof tree.type === 'function') walk(tree.type(tree.props))
else walk(tree)
assert.equal(found, true, '内容被错误边界包住')
})
test('sendPrompt returns a structured error instead of throwing when the session is missing', async () => {
const { exports } = loadPlugin()
const { ctx } = mockContext()
ctx.sessions.binding = () => undefined
const host = exports.createHost(ctx)
const result = await host.sendPrompt('not-here', '测试')
assert.equal(result.ok, false)
assert.equal(result.errorCode, 'no-session')
assert.match(result.error, /对话通道|会话/)
})
test('opens an independent court session and delivers the formation prompt exactly once', async () => {
const { exports } = loadPlugin()
const { ctx, prompts, addSession, setStartSession } = mockContext()
setStartSession((workspaceId) => addSession('court-1', workspaceId))
const host = exports.createHost(ctx)
const result = await host.openCourtSession()
assert.equal(result.ok, true, JSON.stringify(result))
assert.equal(result.stage, 'delivered')
assert.equal(result.sessionId, 'court-1')
assert.equal(prompts.length, 1, '只投递一次组建指令')
assert.equal(prompts[0].sessionId, 'court-1')
const text = prompts[0].parts[0].text
assert.match(text, /组建朝班/)
assert.ok(text.indexOf('\n') > 0, '组建指令里应有真实换行')
assert.equal(text.indexOf('\\n'), -1, '不应出现字面反斜杠 n')
})
test('refuses a second court session request while the first one is pending', async () => {
const { exports } = loadPlugin()
const { ctx } = mockContext()
const host = exports.createHost(ctx)
const first = host.openCourtSession()
const second = await host.openCourtSession()
assert.equal(second.ok, false)
assert.equal(second.errorCode, 'busy')
const settled = await first
assert.equal(settled.ok, false)
assert.equal(settled.errorCode, 'create-timeout')
})
test('openConversation starts a usable conversation with the 上朝 preset and sends nothing', async () => {
const { exports } = loadPlugin()
const { ctx, prompts, addSession, setStartSession, selections } = mockContext()
const started = []
setStartSession((workspaceId, options) => { started.push({ workspaceId, options }); addSession('court-2', workspaceId) })
const host = exports.createHost(ctx)
const result = await host.openConversation()
assert.equal(result.ok, true, JSON.stringify(result))
assert.equal(result.stage, 'created')
assert.equal(result.sessionId, 'court-2')
assert.equal(started.length, 1)
assert.equal(started[0].options.agentPreset, 'sansheng-liubu', '新对话带上朝预设')
assert.equal(prompts.length, 0, '只开对话,不自动发组建指令')
assert.ok(selections.indexOf('court-2') >= 0, '把中央切到新会话')
})
test('focusConversation jumps to the existing session and reports a missing one', () => {
const { exports } = loadPlugin()
const { ctx, selections } = mockContext()
const host = exports.createHost(ctx)
const jumped = host.focusConversation()
assert.equal(jumped.ok, true)
assert.equal(jumped.sessionId, 'lead-1')
assert.ok(selections.indexOf('lead-1') >= 0)
const empty = mockContext()
empty.ctx.sessions.list = { getSnapshot: () => ({ ids: [], byId: {}, projectionsBySession: {} }) }
empty.ctx.uiWorkspace.selection = { getSnapshot: () => ({}), subscribe: () => () => {} }
const other = exports.createHost(empty.ctx)
const miss = other.focusConversation()
assert.equal(miss.ok, false)
assert.equal(miss.errorCode, 'no-session')
})
test('会话头开关拿不到会话时给出可见原因,而不是静默失效', () => {
const { exports } = loadPlugin()
const { ctx, registrations } = mockContext()
// 模拟「还没有打开任何会话」:会话列表与当前选中都为空。
ctx.sessions.list = { getSnapshot: () => ({ ids: [], byId: {}, projectionsBySession: {} }) }
ctx.uiWorkspace.selection = { getSnapshot: () => ({}), subscribe: () => () => {} }
exports.apply(ctx)
const host = exports.createHost(ctx)
const toggle = registrations.find((entry) => entry.options.name === 'conversation.session.header.actions')
assert.ok(toggle, '会话头入口已注册')
// 把函数组件就地展开成一棵扁平节点表。宿主由注册项自己注入,测试不另造一份。
const expand = (node) => {
if (Array.isArray(node)) return node.flatMap(expand)
if (!node || typeof node !== 'object') return []
if (typeof node.type === 'function') return expand(node.type(node.props))
return [node, ...expand(node.children), ...expand(node.props && node.props.children)]
}
const render = () => {
const wrapper = toggle.component({})
return { host: wrapper.props.host, nodes: expand(wrapper) }
}
const withClass = (nodes, name) => nodes.filter((node) => String((node.props && node.props.className) || '').split(' ').includes(name))
const before = render()
assert.notEqual(before.host, host, '注册项注入的是它自己那份 host')
assert.equal(withClass(before.nodes, 'sl-toggle-notice').length, 0, '还没点击时不显示提示')
const button = before.nodes.find((node) => node.type === 'button')
assert.equal(typeof button.props.onClick, 'function')
button.props.onClick()
const after = render()
const notices = withClass(after.nodes, 'sl-toggle-notice')
assert.equal(notices.length, 1, '失败原因要渲染出来,不能只回退不吭声')
assert.match(String(notices[0].props.children), /会话/)
assert.equal(notices[0].props.role, 'status')
assert.equal(notices[0].props.title, notices[0].props.children, '完整原因放在 title 里')
after.host.setToggleNotice(null)
assert.equal(withClass(render().nodes, 'sl-toggle-notice').length, 0, '提示可以被清掉')
})
test('面板用到的每个 sl-* 类名都有对应 CSS 规则', () => {
const { css } = loadPlugin()
const text = css()
assert.ok(text.length > 2000, '样式已注入宿主')
const defined = new Set([...text.matchAll(/\.([a-zA-Z0-9_-]+)/g)].map((match) => match[1]))
const used = new Set()
for (const match of source.matchAll(/className:\s*"([^"$]*)"/g)) {
for (const token of match[1].split(/\s+/)) {
if (token.startsWith('sl-') && !token.endsWith('-')) used.add(token)
}
}
assert.ok(used.size > 30, '至少要扫到面板的类名')
const missing = [...used].filter((name) => !defined.has(name)).sort()
assert.deepEqual(missing, [], '不允许出现挂着类名却没有样式的元素')
})
test('响应式跟随侧栏容器宽度,而不是浏览器视口', () => {
const { css } = loadPlugin()
const text = css()
assert.match(text, /\.sl-root\{[^}]*container-type:inline-size/, '根节点要建立尺寸容器,才能按侧栏宽度断点')
assert.equal(/@media\s*\(\s*max-width/.test(text), false, '不得再用视口断点:侧栏宽度与浏览器窗口宽度无关')
const queries = [...text.matchAll(/@container slpanel \(max-width:(\d+)px\)/g)].map((match) => Number(match[1]))
assert.ok(queries.length >= 10, `容器断点太少:${queries.length}`)
for (const px of [1180, 980, 620]) {
assert.ok(queries.includes(px), `缺少 ${px}px 容器断点`)
}
})
test('部门设置里的最近活动单独占一行,不再和状态挤在同一行', () => {
const { css } = loadPlugin()
const rule = css().match(/\.sl-detail-status small\{([^}]*)\}/)
assert.ok(rule, '.sl-detail-status small 要有独立规则')
assert.match(rule[1], /flex:1 1 100%/, '最近活动要独占一整行')
assert.equal(/white-space:nowrap/.test(rule[1]), false, '不能强制单行,否则窄侧栏会横向挤压')
})
test('会话头开关失败时不再回退到不存在的整页面板', () => {
const { exports } = loadPlugin()
const { ctx, registrations, selections } = mockContext()
ctx.sessions.list = { getSnapshot: () => ({ ids: [], byId: {}, projectionsBySession: {} }) }
ctx.uiWorkspace.selection = { getSnapshot: () => ({}), subscribe: () => () => {} }
exports.apply(ctx)
const toggle = registrations.find((entry) => entry.options.name === 'conversation.session.header.actions')
const expand = (node) => {
if (Array.isArray(node)) return node.flatMap(expand)
if (!node || typeof node !== 'object') return []
if (typeof node.type === 'function') return expand(node.type(node.props))
return [node, ...expand(node.children), ...expand(node.props && node.props.children)]
}
expand(toggle.component({})).find((node) => node.type === 'button').props.onClick()
assert.equal(selections.includes(exports.PANEL_ID), false, '失败时不得 selectPanel 到无 main 槽的面板')
})
/** 模型目录相关用例:宿主面按用例替换 modelDirectories。 */
function catalogHost(overrides = {}) {
const { exports } = loadPlugin()
const context = mockContext()
Object.assign(context.ctx, overrides)
exports.apply(context.ctx)
return { ...context, host: exports.createHost(context.ctx) }
}
test('宿主没有模型目录服务时,错误要说清是服务缺失', async () => {
const { host } = catalogHost({ modelDirectories: undefined })
const result = await host.loadCatalog('lead-1')
assert.equal(result.options.length, 0)
assert.match(result.error, /没有模型目录服务/)
assert.notEqual(result.error, '当前宿主未提供模型目录', '不能再用那句笼统的误导文案')
const saved = await host.selectModel('lead-1', { provider: 'deepseek', model: 'deepseek-chat' })
assert.equal(saved.ok, false)
assert.match(saved.error, /没有模型目录服务/)
})
test('清单来自全局目录,不依赖哪个会话是否在本页登记', async () => {
const calls = []
const { host } = catalogHost({
modelDirectories: {
catalog: {
load: async () => CATALOG_VALUE,
store: { getSnapshot: () => ({ value: CATALOG_VALUE, status: 'ready', error: null }) },
},
directoryFor(sessionId) {
calls.push(sessionId)
throw new Error('ui-model-selection: session "' + sessionId + '" resolved no scope')
},
},
})
const result = await host.loadCatalog('libu')
assert.equal(result.error, null, '未登记的会话也要能列出模型')
assert.equal(result.options.map((option) => option.rowId).join(','), 'deepseek/deepseek-chat,deepseek/deepseek-reasoner')
assert.equal(result.inherited, true, '读不到该部门自己的选择时标成跟随默认')
assert.deepEqual(result.current, { provider: 'deepseek', model: 'deepseek-chat' })
assert.equal(result.unresolved, true, '界面据此提示「未在本页打开」')
assert.deepEqual(calls, ['libu'])
})
test('部门会话没在本页登记时,保存直接走宿主 RPC', async () => {
const sent = []
const { host } = catalogHost({
modelDirectories: {
catalog: {
load: async () => CATALOG_VALUE,
store: { getSnapshot: () => ({ value: CATALOG_VALUE, status: 'ready', error: null }) },
},
directoryFor() { throw new Error('ui-model-selection: session "libu" resolved no binding') },
},
remote: {
agentPresets: { list: async () => ({ ok: true, value: { presets: [] } }), select: async () => ({ ok: true }) },
session: { selectModel: async (request) => { sent.push(request); return { ok: true } } },
},
})
const saved = await host.selectModel('libu', { provider: 'deepseek', model: 'deepseek-reasoner', reasoningEffort: 'high' })
assert.equal(JSON.stringify(saved), JSON.stringify({ ok: true }))
assert.equal(JSON.stringify(sent), JSON.stringify([{ sessionId: 'libu', provider: 'deepseek', model: 'deepseek-reasoner', reasoningEffort: 'high' }]), '要带 sessionId 和推理等级')
})
test('宿主拒绝保存时把原因原样带出', async () => {
const { host } = catalogHost({
modelDirectories: {
catalog: {
load: async () => CATALOG_VALUE,
store: { getSnapshot: () => ({ value: CATALOG_VALUE, status: 'ready', error: null }) },
},
directoryFor() { throw new Error('ui-model-selection: session "libu" resolved no binding') },
},
remote: {
agentPresets: { list: async () => ({ ok: true, value: { presets: [] } }), select: async () => ({ ok: true }) },
session: { selectModel: async () => ({ ok: false, error: { code: 'session/unknown', message: '没有这个会话' } }) },
},
})
const saved = await host.selectModel('libu', { provider: 'deepseek', model: 'deepseek-chat' })
assert.equal(saved.ok, false)
assert.match(saved.error, /session\/unknown:没有这个会话/)
})
test('清单读取失败时说明是读清单失败,并保留已知缓存', async () => {
const { host } = catalogHost({
modelDirectories: {
catalog: {
load: async () => { throw new Error('宿主断线') },
store: { getSnapshot: () => ({ value: null, status: 'error', error: '宿主断线' }) },
},
directoryFor: () => ({
load: async () => {},
select: async () => ({ ok: true }),
store: { getSnapshot: () => ({ current: { provider: 'p', model: 'm' }, groups: [], failures: [], status: 'ready', error: null }) },
}),
},
})
const result = await host.loadCatalog('lead-1')
assert.match(result.error, /读取模型清单失败:宿主断线/)
assert.deepEqual(result.current, { provider: 'p', model: 'm' }, '清单读不到时仍显示该会话已知的当前模型')
assert.equal(result.unresolved, false)
})
test('正常路径给出全局清单与该会话自己的当前选择', async () => {
const { host } = catalogHost()
const result = await host.loadCatalog('lead-1')
assert.equal(result.error, null)
assert.equal(result.unresolved, false)
assert.equal(result.inherited, false)
assert.equal(result.options.length, 2)
assert.deepEqual(result.current, { provider: 'p', model: 'm' })
})
test('部门是子会话时,改模型改由丞相会话下发 /dept-model', async () => {
const prompts = []
const { host } = catalogHost({
sessions: {
list: () => [],
binding: (sessionId) => ({
session: { prompt: async (parts, mode) => { prompts.push({ sessionId, parts, mode }); return { ok: true } } },
}),
subagentAddress: () => ({ parentSessionId: 'lead-1', childSessionId: 'gongbu-1' }),
refreshProjections: async () => {},
},
})
const result = await host.routeModel('gongbu', { provider: 'deepseek', model: 'deepseek-chat', reasoningEffort: 'high' })
assert.equal(result.ok, true)
assert.equal(prompts.length, 1)
assert.equal(prompts[0].sessionId, 'lead-1', '指令投给丞相会话')
assert.equal(prompts[0].parts[0].text, '/dept-model gongbu deepseek deepseek-chat high')
})
test('子会话的固定路由从面板记录里读出来当「当前模型」', async () => {
const { exports, storage } = loadPlugin()
storage.set('sansheng-liubu.route.gongbu', JSON.stringify({ provider: 'deepseek', model: 'deepseek-reasoner', reasoningEffort: 'high' }))
const context = mockContext()
context.ctx.sessions.subagentAddress = () => ({ parentSessionId: 'lead-1', childSessionId: 'gongbu-1' })
exports.apply(context.ctx)
const host = exports.createHost(context.ctx)
const result = await host.loadCatalog('gongbu-1', 'gongbu')
assert.equal(result.fixed, true, '有固定路由时不算继承')
assert.equal(result.current.model, 'deepseek-reasoner')
assert.equal(result.current.reasoningEffort, 'high')
})
test('还没召见的部门也能先选好模型,保存走 /dept-model', async () => {
const { exports } = loadPlugin()
const { ctx } = mockContext()
exports.apply(ctx)
const host = exports.createHost(ctx)
const catalog = await host.loadCatalog(undefined, 'libu')
assert.equal(catalog.options.length, 2, '没有会话也能拿到全局模型清单')
assert.equal(catalog.subagent, true, '未召见的部门同样按子会话处理')
assert.equal(catalog.error, null)
const routed = await host.routeModel('libu', { provider: 'deepseek', model: 'deepseek-chat' })
assert.equal(routed.ok, true)
assert.match(routed.text, /^\/dept-model libu deepseek deepseek-chat$/)
// 详情区的模型设置对缺席席位也要渲染出来(不再是 seat.present 才给)。
assert.match(source, /seat \? h\("div", \{ className: "sl-setting-block" \}, \[/, '模型设置绑定席位,而不是绑定「已召见」')
})