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

701 lines
31 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
},
},
}
vm.runInNewContext(source, { window, document, console, URL, Map, Set, WeakMap, Promise, setTimeout, clearTimeout }, { filename: 'client.js' })
return { loaded, exports: loaded.exports, styleCount: () => styleCount, css: () => cssText }
}
/** 模拟宿主 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: {
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,
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 only 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.right.pane.tab', 'sidebar.right.pane.tab.title'])
assert.equal(registrations.some((entry) => entry.options.name === 'sidebar.panellist'), false, '不再注册左侧整页面板入口')
assert.equal(registrations.some((entry) => entry.options.name === 'sidebar.panellist.actions'), false)
assert.equal(registrations.some((entry) => entry.options.name === 'main'), false, '不再占用 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')
const tab = registrations.find((entry) => entry.options.name === 'sidebar.right.pane.tab')
assert.ok(tab, '右侧栏注册朝堂页签')
assert.equal(tab.options.key, 'sansheng-liubu-tab')
})
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')
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')
})
/**
* 回归:右侧栏页签由宿主注入 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, [], '不允许出现挂着类名却没有样式的元素')
})