diff --git a/sansheng/client.js b/sansheng/client.js new file mode 100644 index 0000000..ae83f38 --- /dev/null +++ b/sansheng/client.js @@ -0,0 +1,271 @@ +window.__ModuleLoader__.load({ + id: 'dsh-sansheng-sansheng', + factory: (require) => { + var module = { exports: {} } + var exports = module.exports + Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' }) + + const React = require('react') + const h = React.createElement + + const TAB_ID = 'sansheng-roles' + const TAB_KIND = 'sansheng-roles' + const CSS_ID = 'dsh-sansheng-roles' + const POLL_MS = 4000 + const ACTIVE_KEY = 'dsh.sansheng.activeProject' + + const ROLE_MARK = { lead: '丞', shangshu: '尚', gongbu: '工' } + + const CSS = ` +.ss-root{display:flex;flex-direction:column;height:100%;min-height:0;background:var(--dsw-alias-bg-layer-1,#fff);color:var(--dsw-alias-label-primary,#1f2329);font-size:13px;line-height:20px} +.ss-bar{display:flex;align-items:center;gap:8px;padding:10px 12px;border-bottom:1px solid var(--dsw-alias-border-l1,rgba(127,127,127,.14));flex:none} +.ss-bar select{appearance:none;border:1px solid var(--dsw-alias-border-l2,rgba(127,127,127,.24));background:var(--dsw-alias-bg-layer-2,rgba(127,127,127,.06));color:inherit;font:inherit;font-size:12px;padding:2px 22px 2px 8px;border-radius:7px;min-height:26px;max-width:100%} +.ss-bar-note{margin-left:auto;font-size:11px;color:var(--dsw-alias-label-tertiary,#8a8f98);white-space:nowrap} +.ss-list{flex:1;min-height:0;overflow:auto;display:flex;flex-direction:column;gap:10px;padding:12px} +.ss-card{position:relative;display:flex;flex-direction:column;gap:6px;padding:11px 12px;border:1px solid var(--dsw-alias-border-l2,rgba(127,127,127,.2));border-radius:12px;background:var(--dsw-alias-bg-layer-2,rgba(127,127,127,.04));text-align:left;color:inherit;font:inherit;width:100%;min-width:0} +.ss-card[data-role="lead"]{--ss-role:#b8860b} +.ss-card[data-role="shangshu"]{--ss-role:#2f6fed} +.ss-card[data-role="gongbu"]{--ss-role:#12805c} +.ss-card[data-tone="warn"]{border-color:color-mix(in srgb,var(--dsw-alias-state-error-primary,#dc2626) 45%,transparent)} +.ss-card-head{display:flex;align-items:center;gap:8px;min-width:0} +.ss-mark{flex:none;width:22px;height:22px;border-radius:7px;display:inline-flex;align-items:center;justify-content:center;font-size:11px;font-weight:600;color:#fff;background:var(--ss-role,#666)} +.ss-card-head strong{font-size:13px;font-weight:600;letter-spacing:.02em} +.ss-dot{flex:none;margin-left:auto;width:7px;height:7px;border-radius:50%;background:var(--dsw-alias-label-tertiary,#9ca3af)} +.ss-card[data-tone="active"] .ss-dot{background:var(--dsw-alias-state-business-primary,#3b82f6)} +.ss-card[data-tone="ok"] .ss-dot{background:#1a9d6a} +.ss-card[data-tone="warn"] .ss-dot{background:var(--dsw-alias-state-error-primary,#dc2626)} +.ss-card[data-tone="attention"] .ss-dot{background:#c9871f} +.ss-duty{font-size:11px;color:var(--dsw-alias-label-tertiary,#8a8f98);white-space:nowrap;overflow:hidden;text-overflow:ellipsis} +.ss-main{font-size:12.5px;font-weight:500;white-space:nowrap;overflow:hidden;text-overflow:ellipsis} +.ss-sub{font-size:11px;line-height:17px;color:var(--dsw-alias-label-secondary,#5b616b);display:-webkit-box;-webkit-line-clamp:2;-webkit-box-orient:vertical;overflow:hidden;word-break:break-word} +.ss-foot{display:flex;align-items:center;gap:6px;font-size:10.5px;color:var(--dsw-alias-label-tertiary,#8a8f98);min-width:0} +.ss-foot span{white-space:nowrap;overflow:hidden;text-overflow:ellipsis} +.ss-chip{flex:none;border:1px solid var(--dsw-alias-border-l2,rgba(127,127,127,.24));border-radius:999px;padding:0 7px;font-size:10px;line-height:16px} +.ss-empty{display:flex;flex-direction:column;gap:8px;align-items:flex-start;padding:18px 4px;color:var(--dsw-alias-label-secondary,#5b616b);font-size:12px} +.ss-empty code{font-size:11px;background:var(--dsw-alias-bg-layer-3,rgba(127,127,127,.14));padding:1px 5px;border-radius:5px} +.ss-error{color:var(--dsw-alias-state-error-primary,#dc2626);font-size:11px;line-height:17px} +.ss-tab-title{display:inline-flex;align-items:center;gap:6px;min-width:0} +.ss-tab-mark{width:18px;height:18px;border-radius:6px;display:inline-flex;align-items:center;justify-content:center;font-size:9px;font-weight:600;color:#fff;background:linear-gradient(135deg,#b8860b,#2f6fed 60%,#12805c)} +.ss-tab-count{border-radius:999px;padding:0 6px;font-size:10px;line-height:15px;background:var(--dsw-alias-state-business-primary,#3b82f6);color:#fff} +.ss-open{appearance:none;border:0;background:0 0;color:var(--dsw-alias-label-tertiary,#8a8f98);font:inherit;font-size:12px;display:inline-flex;align-items:center;gap:5px;padding:3px 7px;border-radius:6px;cursor:pointer;min-height:26px} +.ss-open:hover,.ss-open:focus-visible{color:var(--dsw-alias-label-primary,#1f2329);background:var(--dsw-alias-bg-layer-2,rgba(127,127,127,.08))} +` + + function ensureCss() { + if (typeof document === 'undefined') return + try { + const selector = 'style[data-plugin-css=' + JSON.stringify(CSS_ID) + ']' + if (document.querySelector(selector)) return + const style = document.createElement('style') + style.setAttribute('data-plugin-css', CSS_ID) + style.textContent = CSS + document.head.appendChild(style) + } catch (error) { + /* 样式注入失败不影响功能 */ + } + } + + function serviceOf(ctx, name) { + try { + if (typeof ctx.get === 'function') { + const service = ctx.get(name, false) + if (service) return service + } + } catch (error) { /* 老宿主没有该服务 */ } + return undefined + } + + function betterSidebarOf(ctx) { + const service = serviceOf(ctx, 'betterSidebar') + return service && typeof service.openTab === 'function' ? service : undefined + } + + /** 打开右栏「三省六部」页签:优先 better-sidebar,其次宿主原生右栏。 */ + function openRolesTab(ctx, sessionId) { + if (!sessionId) return { ok: false, error: '先打开一个会话,右侧卡片是会话级的。' } + const better = betterSidebarOf(ctx) + if (better) { + try { + better.openTab({ type: TAB_ID }, { sessionId }) + return { ok: true } + } catch (error) { /* 退回原生右栏 */ } + } + const nav = serviceOf(ctx, 'sidebarRight') + if (nav) { + try { + if (typeof nav.openTabIn === 'function') { + nav.openTabIn(sessionId, TAB_KIND) + return { ok: true } + } + if (typeof nav.openTab === 'function') { + nav.openTab(TAB_KIND) + return { ok: true } + } + } catch (error) { /* 统一报错 */ } + } + return { ok: false, error: '宿主右栏不可用。' } + } + + function useSanshengState() { + const [state, setState] = React.useState({ loading: true, error: null, data: null }) + React.useEffect(() => { + let alive = true + let timer + const tick = async () => { + try { + const response = await fetch('/sansheng/state', { cache: 'no-cache' }) + if (!response.ok) throw new Error('HTTP ' + response.status) + const data = await response.json() + if (alive) setState({ loading: false, error: null, data }) + } catch (error) { + if (alive) setState(prev => ({ loading: false, error: String((error && error.message) || error), data: prev.data })) + } finally { + if (alive) timer = setTimeout(tick, POLL_MS) + } + } + tick() + return () => { + alive = false + if (timer) clearTimeout(timer) + } + }, []) + return state + } + + function RoleCard({ project, card }) { + const model = card.model ? String(card.model) : '默认模型' + return h('div', { + className: 'ss-card', + 'data-role': card.role, + 'data-tone': card.tone, + title: [card.duty, card.detail].filter(Boolean).join('\n'), + }, [ + h('div', { key: 'head', className: 'ss-card-head' }, [ + h('span', { key: 'mark', className: 'ss-mark', 'aria-hidden': 'true', children: ROLE_MARK[card.role] }), + h('strong', { key: 'label', children: card.label }), + h('span', { key: 'dot', className: 'ss-dot', 'aria-hidden': 'true' }), + ]), + h('div', { key: 'duty', className: 'ss-duty', children: `${card.name || '未就绪'} · ${model}` }), + h('div', { key: 'main', className: 'ss-main', children: card.line }), + card.detail ? h('div', { key: 'sub', className: 'ss-sub', children: card.detail }) : null, + h('div', { key: 'foot', className: 'ss-foot' }, [ + h('span', { key: 'duty', children: card.duty }), + h('span', { key: 'proj', className: 'ss-chip', children: project.name }), + ]), + ]) + } + + function EmptyHint({ error }) { + return h('div', { className: 'ss-empty' }, [ + error ? h('div', { key: 'error', className: 'ss-error', children: `读不到项目状态:${error}` }) : null, + h('div', { key: 'text', children: '还没有三省六部项目。在对话里让助手调用 sansheng_provision 创建项目(三 Bot + 项目群)。' }), + h('div', { key: 'tip', children: '已有的群用 sansheng_bind 绑定;创建后可在这里看到丞相、尚书、工部三张卡片。' }), + ]) + } + + function RolesColumn() { + const { loading, error, data } = useSanshengState() + const projects = (data && data.projects) || [] + const [activeId, setActiveId] = React.useState(() => { + try { return window.localStorage.getItem(ACTIVE_KEY) || '' } catch (e) { return '' } + }) + const project = projects.find(item => item.id === activeId) || projects[0] + React.useEffect(() => { + if (project && project.id !== activeId) { + setActiveId(project.id) + try { window.localStorage.setItem(ACTIVE_KEY, project.id) } catch (e) { /* 忽略 */ } + } + }, [project && project.id]) + const attention = projects.reduce((sum, item) => sum + item.roles.filter(card => card.tone === 'warn' || card.tone === 'attention').length, 0) + const onPick = event => { + const next = event.target.value + setActiveId(next) + try { window.localStorage.setItem(ACTIVE_KEY, next) } catch (e) { /* 忽略 */ } + } + return h('div', { className: 'ss-root', 'data-sansheng-roles': '1' }, [ + h('div', { key: 'bar', className: 'ss-bar' }, [ + projects.length > 1 + ? h('select', { key: 'select', value: project ? project.id : '', onChange: onPick, 'aria-label': '选择项目' }, + projects.map(item => h('option', { key: item.id, value: item.id, children: item.name }))) + : h('strong', { key: 'name', children: project ? project.name : (loading ? '载入中…' : '三省六部') }), + h('span', { key: 'note', className: 'ss-bar-note', children: attention > 0 ? `待处理 ${attention}` : '就绪' }), + ]), + h('div', { key: 'list', className: 'ss-list' }, + project + ? [ + ...project.roles.map(card => h(RoleCard, { key: card.role, project, card })), + error ? h('div', { key: 'err', className: 'ss-error', children: `状态刷新失败:${error}` }) : null, + ] + : [h(EmptyHint, { key: 'empty', error: error })]), + ]) + } + + function RolesTabTitle() { + const { data } = useSanshengState() + const projects = (data && data.projects) || [] + const attention = projects.reduce((sum, item) => sum + item.roles.filter(card => card.tone === 'warn').length, 0) + return h('div', { className: 'ss-tab-title' }, [ + h('span', { key: 'mark', className: 'ss-tab-mark', children: '三省' }), + h('span', { key: 'label', children: '角色' }), + attention > 0 ? h('span', { key: 'count', className: 'ss-tab-count', children: String(attention) }) : null, + ]) + } + + function HeaderButton(props) { + const ctx = props.__ctx + const sessionId = props && props.sessionId ? props.sessionId : undefined + const [notice, setNotice] = React.useState(null) + return h('button', { + className: 'ss-open', + type: 'button', + title: notice || '打开右侧三省六部角色卡片', + onClick: () => { + const result = openRolesTab(ctx, sessionId) + setNotice(result.ok ? null : result.error) + }, + }, [h('span', { key: 'mark', children: '三省' }), h('span', { key: 'text', children: notice ? '右栏不可用' : '角色' })]) + } + + function apply(ctx) { + ensureCss() + const wrap = component => props => h(component, { ...props, __ctx: ctx }) + + ctx.effect(() => { + try { + return ctx.sidebarRightTabs.register({ + id: TAB_ID, + kind: TAB_KIND, + priority: 'builtin', + title: () => '三省六部', + keepMounted: true, + }) + } catch (error) { + console.warn('[三省六部] 右栏页签注册失败:', error) + return () => {} + } + }, '三省六部:右栏角色页签') + + ctx.slots.inject('sidebar.right.pane.tab', () => ctx.slots.register({ + name: 'sidebar.right.pane.tab', + key: TAB_ID, + }, wrap(RolesColumn))) + + ctx.slots.inject('sidebar.right.pane.tab.title', () => ctx.slots.register({ + name: 'sidebar.right.pane.tab.title', + key: TAB_ID, + }, () => h(RolesTabTitle, null))) + + ctx.slots.inject('conversation.session.header.actions', () => ctx.slots.register({ + name: 'conversation.session.header.actions', + id: TAB_ID + ':open', + order: 60, + }, wrap(HeaderButton))) + } + + exports.apply = apply + exports.inject = ['slots', 'sidebarRightTabs', 'sidebarRight'] + exports.TAB_ID = TAB_ID + exports.TAB_KIND = TAB_KIND + return module.exports + }, +}) diff --git a/sansheng/index.js b/sansheng/index.js index bb4be9e..03bd9d9 100644 --- a/sansheng/index.js +++ b/sansheng/index.js @@ -3,6 +3,7 @@ import { installGates } from './src/gates.js' import { installObserver } from './src/observe.js' import { dsbotStatePath, sanshengStatePath } from './src/paths.js' import { newBootId } from './src/records.js' +import { installRoute } from './src/route.js' import { SanshengStore } from './src/store.js' import { installTools } from './src/tools.js' @@ -36,4 +37,5 @@ export async function apply(ctx, config = {}) { installGates({ ctx, store, dsbot }) installObserver({ ctx, store, dsbot, bootId }) installTools({ ctx, store, dsbot, bootId }) + installRoute({ ctx, store, dsbot }) } diff --git a/sansheng/package.json b/sansheng/package.json index c2104bc..e2669a8 100644 --- a/sansheng/package.json +++ b/sansheng/package.json @@ -7,12 +7,28 @@ "main": "./index.js", "exports": { ".": "./index.js", + "./client": "./client.js", "./package.json": "./package.json" }, + "files": [ + "index.js", + "client.js", + "cordis.patch.yml", + "src", + "README.md", + "test" + ], "dsh": { "manifestVersion": 1, "bundle": { "patch": "./cordis.patch.yml" + }, + "client": { + "platform": "web", + "inject": [ + "@deepseek-ai/dsh-client-ui-conversation", + "@deepseek-ai/dsh-client-ui-primitives" + ] } }, "scripts": { diff --git a/sansheng/src/api.js b/sansheng/src/api.js new file mode 100644 index 0000000..3e7758f --- /dev/null +++ b/sansheng/src/api.js @@ -0,0 +1,181 @@ +import { budgetOf } from './gate.js' +import { ROLE_IDS, ROLE_LABEL } from './roles.js' + +const DETAIL_MAX = 80 + +function clip(text, max = DETAIL_MAX) { + const value = String(text ?? '').replace(/\s+/g, ' ').trim() + if (value === '') return '' + return value.length <= max ? value : `${value.slice(0, max - 1)}…` +} + +function latest(reviews) { + return reviews.length > 0 ? reviews[0] : undefined +} + +function taskCounts(stage, botId) { + const tasks = (stage?.tasks ?? []).filter(task => task.botId === botId) + const done = tasks.filter(task => task.status === 'done').length + const active = tasks.filter(task => task.status === 'active' || task.status === 'doing').length + return { total: tasks.length, done, active, open: tasks.length - done } +} + +function leadCard({ project, goal, bot, goalReviews }) { + const review = latest(goalReviews) + const card = { + role: 'lead', + label: ROLE_LABEL.lead, + duty: '定目标 · 最终验收', + botId: project.bots?.lead ?? null, + name: bot?.name ?? null, + model: project.models?.lead ?? bot?.model ?? null, + exists: Boolean(bot), + line: '等待交付', + detail: '', + tone: 'idle', + } + if (review) { + card.line = review.verdict === 'pass' + ? `已验收 rev ${review.goalRevision ?? '?'}` + : `驳回 rev ${review.goalRevision ?? '?'}` + card.detail = clip(review.reason ?? review.evidence) + card.tone = review.verdict === 'pass' ? 'ok' : 'warn' + return card + } + if (goal && (goal.stages ?? []).length > 0 && (goal.stages ?? []).every(stage => stage.status === 'passed')) { + card.line = '等待验收' + card.tone = 'attention' + } else if (goal) { + card.line = '目标进行中' + } + card.detail = clip(goal?.objective ?? '') + return card +} + +function shangshuCard({ project, goal, bot, budget, unknown, dispatches, botId }) { + const card = { + role: 'shangshu', + label: ROLE_LABEL.shangshu, + duty: '调度阶段 · 核查证据', + botId: project.bots?.shangshu ?? null, + name: bot?.name ?? null, + model: project.models?.shangshu ?? bot?.model ?? null, + exists: Boolean(bot), + line: '未起草目标', + detail: '', + tone: 'idle', + } + if (!goal) { + card.detail = '用 group_goal draft / start 起草目标' + return card + } + const stages = goal.stages ?? [] + const passed = stages.filter(stage => stage.status === 'passed').length + const stage = stages[goal.current] + card.line = stage ? `阶段 ${passed}/${stages.length} · ${clip(stage.title, 24)}` : `阶段 ${passed}/${stages.length}` + const parts = [`返工 ${budget.used}/${budget.max}`] + if (unknown > 0) parts.push(`待核实 ${unknown}`) + const recent = latest(dispatches) + if (recent) parts.push(clip(recent.action, 12)) + card.detail = parts.join(' · ') + card.tone = goal.status === 'complete' ? 'ok' : unknown > 0 ? 'warn' : 'active' + return card +} + +function gongbuCard({ project, goal, bot, stageReviews }) { + const card = { + role: 'gongbu', + label: ROLE_LABEL.gongbu, + duty: '执行工单 · 提交证据', + botId: project.bots?.gongbu ?? null, + name: bot?.name ?? null, + model: project.models?.gongbu ?? bot?.model ?? null, + exists: Boolean(bot), + line: '无工单', + detail: '', + tone: 'idle', + } + const stage = goal?.stages?.[goal.current] + const counts = taskCounts(stage, project.bots?.gongbu) + const reject = latest(stageReviews.filter(review => review.verdict === 'reject')) + if (counts.total > 0) { + const open = (stage.tasks ?? []).find(task => task.botId === project.bots?.gongbu && task.status !== 'done') + card.line = reject + ? `返工中 · 工单 ${counts.done}/${counts.total}` + : counts.open > 0 ? `工单 ${counts.done}/${counts.total}` : `工单 ${counts.total} 条已完成` + card.detail = clip(reject?.reason ?? open?.task ?? (stage.tasks ?? []).find(task => task.botId === project.bots?.gongbu)?.task ?? '') + card.tone = reject ? 'warn' : counts.open > 0 ? 'active' : 'ok' + return card + } + if (reject) { + card.line = '返工中' + card.detail = clip(reject.reason) + card.tone = 'warn' + } + return card +} + +/** + * 右侧栏三卡片的数据源:纯函数,方便单测。 + * 只读 sansheng 自己的状态 + DS Bot 的只读视图,不写任何东西。 + */ +export function buildStatePayload({ store, dsbot, now = Date.now() }) { + const state = store.peek() + const projects = Object.values(state.projects ?? {}).map(project => { + const room = dsbot.roomOf(project.roomId) + const goal = room?.goal + const budget = budgetOf(goal, project) + const unknown = store.unknownDispatches(project.id).length + const dispatches = store.dispatchesFor(project.id, 3) + const goalReviews = store.reviewsFor({ projectId: project.id, kind: 'goal' }) + const stageReviews = store.reviewsFor({ projectId: project.id, kind: 'stage' }) + const bots = ROLE_IDS.map(role => dsbot.botOf(project.bots?.[role])) + const roles = [ + leadCard({ project, goal, bot: bots[0], goalReviews }), + shangshuCard({ project, goal, bot: bots[1], budget, unknown, dispatches, botId: project.bots?.shangshu }), + gongbuCard({ project, goal, bot: bots[2], stageReviews }), + ] + return { + id: project.id, + name: project.name, + roomId: project.roomId, + roomName: room?.name ?? null, + roomExists: Boolean(room), + autoRework: project.autoRework !== false, + roles, + goal: goal + ? { + status: goal.status, + revision: goal.revision, + title: clip(goal.title, 60), + objective: clip(goal.objective), + stages: (goal.stages ?? []).length, + passed: (goal.stages ?? []).filter(stage => stage.status === 'passed').length, + stageIndex: goal.current, + stageTitle: clip(goal.stages?.[goal.current]?.title, 60), + } + : null, + budget, + unknownDispatches: unknown, + reviews: goalReviews.concat(stageReviews) + .sort((a, b) => (b.at ?? 0) - (a.at ?? 0)) + .slice(0, 3) + .map(review => ({ + kind: review.kind, + verdict: review.verdict, + reviewerRole: review.reviewerRole, + goalRevision: review.goalRevision, + stageIndex: review.stageIndex, + at: review.at, + })), + recentDispatches: dispatches.map(item => ({ + action: item.action, + status: item.status, + at: item.at, + stageIndex: item.stageIndex, + })), + } + }) + projects.sort((a, b) => String(a.name).localeCompare(String(b.name), 'zh-Hans-CN')) + return { generatedAt: now, projects } +} diff --git a/sansheng/src/route.js b/sansheng/src/route.js new file mode 100644 index 0000000..4d0fbb5 --- /dev/null +++ b/sansheng/src/route.js @@ -0,0 +1,37 @@ +import { buildStatePayload } from './api.js' + +function send(res, status, payload) { + const body = JSON.stringify(payload) + res.statusCode = status + res.setHeader('content-type', 'application/json; charset=utf-8') + res.setHeader('cache-control', 'no-store') + res.setHeader('content-length', Buffer.byteLength(body)) + res.end(body) +} + +/** + * 右栏三卡片的数据接口。只读:读 sansheng 自己的状态与 DS Bot 的只读视图。 + * 与工具走同一份数据,页面不额外持有真相。 + */ +export function installRoute({ ctx, store, dsbot }) { + const web = typeof ctx.get === 'function' ? ctx.get('webServer', false) : undefined + if (!web || typeof web.register !== 'function') { + console.warn('sansheng: 没有 webServer 服务,右栏数据接口不可用(工具与门禁不受影响)。') + return + } + ctx.effect(() => web.register({ + kind: 'exact', + path: '/sansheng/state', + handler: async (req, res) => { + if (req.method !== 'GET' && req.method !== 'HEAD') { + send(res, 405, { error: 'method not allowed' }) + return + } + try { + send(res, 200, buildStatePayload({ store, dsbot })) + } catch (error) { + send(res, 500, { error: `读取三省六部状态失败:${error?.message ?? error}` }) + } + }, + }), 'sansheng: 右栏数据接口') +} diff --git a/sansheng/test/api.test.js b/sansheng/test/api.test.js new file mode 100644 index 0000000..aa57f1c --- /dev/null +++ b/sansheng/test/api.test.js @@ -0,0 +1,137 @@ +import assert from 'node:assert/strict' +import test from 'node:test' +import { buildStatePayload } from '../src/api.js' + +function fakeStore({ projects = {}, reviews = [], dispatches = [], unknown = 0 } = {}) { + return { + peek: () => ({ version: 2, projects, reviews, dispatches, reworks: [], events: [] }), + unknownDispatches: () => Array.from({ length: unknown }, (_, index) => ({ id: `dsp-${index}` })), + dispatchesFor: () => dispatches, + reviewsFor: match => reviews.filter(item => Object.entries(match).every(([key, value]) => item[key] === value)), + } +} + +function fakeDsbot({ bots = {}, rooms = {} } = {}) { + return { + botOf: id => bots[id], + roomOf: id => rooms[id], + } +} + +const project = { + id: 'prj-1', + name: '示例项目', + roomId: 'room-1', + bots: { lead: 'bot-lead', shangshu: 'bot-shang', gongbu: 'bot-gong' }, + models: {}, + maxReworks: 3, +} + +const bots = { + 'bot-lead': { id: 'bot-lead', name: '丞相', model: 'magpie/m1' }, + 'bot-shang': { id: 'bot-shang', name: '尚书', model: 'magpie/m2' }, + 'bot-gong': { id: 'bot-gong', name: '工部', model: 'magpie/m3' }, +} + +const goal = { + id: 'goal-1', + revision: 4, + status: 'active', + title: '示例目标', + objective: '把示例功能做出来并验证', + acceptance: '测试通过', + current: 0, + stages: [ + { + id: 's1', + title: '搭骨架', + status: 'active', + reworks: 1, + tasks: [ + { id: 't1', botId: 'bot-gong', task: '写脚手架', status: 'active' }, + { id: 't2', botId: 'bot-gong', task: '补测试', status: 'done' }, + ], + }, + { id: 's2', title: '接界面', status: 'pending', reworks: 0, tasks: [] }, + ], +} + +test('没有项目时返回空数组', () => { + const payload = buildStatePayload({ store: fakeStore(), dsbot: fakeDsbot(), now: 1 }) + assert.deepEqual(payload, { generatedAt: 1, projects: [] }) +}) + +test('三张卡片按角色顺序给出名称、模型与阶段信息', () => { + const store = fakeStore({ projects: { 'prj-1': project }, unknown: 1 }) + const dsbot = fakeDsbot({ bots, rooms: { 'room-1': { id: 'room-1', name: '示例项目 · 三省六部', goal } } }) + const [card] = buildStatePayload({ store, dsbot }).projects + assert.deepEqual(card.roles.map(item => item.role), ['lead', 'shangshu', 'gongbu']) + assert.equal(card.roles[0].name, '丞相') + assert.equal(card.roles[0].model, 'magpie/m1') + assert.equal(card.roles[0].line, '目标进行中') + assert.match(card.roles[1].line, /阶段 0\/2 · 搭骨架/) + assert.match(card.roles[1].detail, /返工 1\/3/) + assert.match(card.roles[1].detail, /待核实 1/) + assert.equal(card.roles[1].tone, 'warn') + assert.match(card.roles[2].line, /工单 1\/2/) + assert.equal(card.roles[2].tone, 'active') + assert.equal(card.budget.used, 1) + assert.equal(card.goal.revision, 4) + assert.equal(card.roomName, '示例项目 · 三省六部') +}) + +test('模型未配置时回退到 Bot 自己的模型', () => { + const store = fakeStore({ projects: { 'prj-1': project } }) + const dsbot = fakeDsbot({ bots, rooms: { 'room-1': { id: 'room-1', goal } } }) + const [card] = buildStatePayload({ store, dsbot }).projects + assert.equal(card.roles[2].model, 'magpie/m3') +}) + +test('丞相验收记录决定丞相卡片;阶段驳回显示在工部卡片', () => { + const reviews = [ + { projectId: 'prj-1', kind: 'goal', verdict: 'pass', goalRevision: 6, reviewerRole: 'lead', at: 20 }, + { projectId: 'prj-1', kind: 'stage', verdict: 'reject', stageIndex: 0, reason: '测试没跑', reviewerRole: 'shangshu', at: 10 }, + ] + const store = fakeStore({ projects: { 'prj-1': project }, reviews }) + const dsbot = fakeDsbot({ bots, rooms: { 'room-1': { id: 'room-1', goal } } }) + const [card] = buildStatePayload({ store, dsbot }).projects + assert.equal(card.roles[0].line, '已验收 rev 6') + assert.equal(card.roles[0].tone, 'ok') + assert.match(card.roles[2].detail, /测试没跑/) + assert.equal(card.reviews.length, 2) + assert.equal(card.reviews[0].kind, 'goal') +}) + +test('全部阶段通过但还没验收时丞相卡片提示等待验收', () => { + const passed = { + ...goal, + current: 2, + stages: [ + { id: 's1', title: '一', status: 'passed', tasks: [] }, + { id: 's2', title: '二', status: 'passed', tasks: [] }, + ], + } + const store = fakeStore({ projects: { 'prj-1': project } }) + const dsbot = fakeDsbot({ bots, rooms: { 'room-1': { id: 'room-1', goal: passed } } }) + const [card] = buildStatePayload({ store, dsbot }).projects + assert.equal(card.roles[0].line, '等待验收') + assert.equal(card.roles[0].tone, 'attention') + assert.equal(card.goal.passed, 2) +}) + +test('没有目标时三张卡片都给出可执行的下一步', () => { + const store = fakeStore({ projects: { 'prj-1': project } }) + const dsbot = fakeDsbot({ bots, rooms: { 'room-1': { id: 'room-1' } } }) + const [card] = buildStatePayload({ store, dsbot }).projects + assert.equal(card.goal, null) + assert.equal(card.roles[1].line, '未起草目标') + assert.match(card.roles[1].detail, /group_goal/) + assert.equal(card.roles[2].line, '无工单') +}) + +test('群被删掉时仍能返回项目,roomExists 为 false', () => { + const store = fakeStore({ projects: { 'prj-1': project } }) + const [card] = buildStatePayload({ store, dsbot: fakeDsbot({ bots }) }).projects + assert.equal(card.roomExists, false) + assert.equal(card.roomName, null) +}) diff --git a/sansheng/test/plugin.test.js b/sansheng/test/plugin.test.js index 40cc028..1edc9f8 100644 --- a/sansheng/test/plugin.test.js +++ b/sansheng/test/plugin.test.js @@ -54,3 +54,21 @@ test('apply 注册全部工具、门禁与派发观测,并能读损坏的 DS B await rm(dir, { recursive: true, force: true }) } }) + +test('宿主提供 webServer 时注册右栏数据接口', async () => { + const dir = await mkdtemp(join(tmpdir(), 'sansheng-plugin-')) + try { + const routes = [] + const ctx = fakeCtx() + ctx.effect = fn => fn() + ctx.get = (name, fallback) => (name === 'webServer' ? { register: options => { routes.push(options); return () => {} } } : fallback) + await apply(ctx, { + statePath: join(dir, 'sansheng.json'), + dsbotStatePath: join(dir, 'missing-bot-state.json'), + }) + assert.equal(routes.length, 1, '注册了 /sansheng/state') + assert.equal(routes[0].path, '/sansheng/state') + } finally { + await rm(dir, { recursive: true, force: true }) + } +}) diff --git a/sansheng/test/route.test.js b/sansheng/test/route.test.js new file mode 100644 index 0000000..2783982 --- /dev/null +++ b/sansheng/test/route.test.js @@ -0,0 +1,76 @@ +import assert from 'node:assert/strict' +import test from 'node:test' +import { installRoute } from '../src/route.js' + +function fakeCtx(web) { + return { + get: (name, fallback) => (name === 'webServer' ? web : fallback), + effect: fn => fn(), + } +} + +function fakeStore() { + return { + peek: () => ({ version: 2, projects: {}, reviews: [], dispatches: [], reworks: [], events: [] }), + unknownDispatches: () => [], + dispatchesFor: () => [], + reviewsFor: () => [], + } +} + +function fakeRes() { + const headers = {} + return { + statusCode: 0, + headers, + body: '', + setHeader(name, value) { headers[name.toLowerCase()] = value }, + end(body) { this.body = body ?? '' }, + } +} + +test('注册 GET /sansheng/state 并返回 JSON', async () => { + const routes = [] + const web = { register: options => { routes.push(options); return () => {} } } + installRoute({ ctx: fakeCtx(web), store: fakeStore(), dsbot: { botOf: () => undefined, roomOf: () => undefined } }) + assert.equal(routes.length, 1) + assert.equal(routes[0].kind, 'exact') + assert.equal(routes[0].path, '/sansheng/state') + + const res = fakeRes() + await routes[0].handler({ method: 'GET' }, res) + assert.equal(res.statusCode, 200) + assert.match(res.headers['content-type'], /application\/json/) + assert.equal(res.headers['cache-control'], 'no-store') + assert.deepEqual(JSON.parse(res.body).projects, []) +}) + +test('非 GET 请求返回 405', async () => { + const routes = [] + const web = { register: options => { routes.push(options); return () => {} } } + installRoute({ ctx: fakeCtx(web), store: fakeStore(), dsbot: { botOf: () => undefined, roomOf: () => undefined } }) + const res = fakeRes() + await routes[0].handler({ method: 'POST' }, res) + assert.equal(res.statusCode, 405) +}) + +test('状态读取抛错时返回 500,而不是击穿宿主', async () => { + const routes = [] + const web = { register: options => { routes.push(options); return () => {} } } + const broken = { + peek: () => { throw new Error('磁盘坏了') }, + unknownDispatches: () => [], + dispatchesFor: () => [], + reviewsFor: () => [], + } + installRoute({ ctx: fakeCtx(web), store: broken, dsbot: { botOf: () => undefined, roomOf: () => undefined } }) + const res = fakeRes() + await routes[0].handler({ method: 'GET' }, res) + assert.equal(res.statusCode, 500) + assert.match(JSON.parse(res.body).error, /磁盘坏了/) +}) + +test('宿主没有 webServer 时安静跳过,不抛错', () => { + const ctx = { get: (name, fallback) => fallback, effect: fn => fn() } + assert.doesNotThrow(() => installRoute({ ctx, store: fakeStore(), dsbot: {} })) +})