// 三省六部 Web 工作台 v2:按用户提供的静态设计稿落地的真实前端。 // 只使用 createElement(无 JSX);数据全部来自现有 host API,不伪造示例数据。 import { createElement as h, useCallback, useEffect, useMemo, useRef, useState } from 'react' import { SEAT_IDS, SEATS } from '../shared/roles.js' import { buildWorkbenchView, findModelOption, updateDraft, clearDraft, describeModel, } from './workbench.js' import { request } from './transport.js' const TODAY = () => { const d = new Date() d.setHours(0, 0, 0, 0) return d.getTime() } const TASK_LABELS = { draft: '待派发', dispatched: '已派发', running: '进行中', prepared: '待复核', done: '已完成', cancelled: '已取消', failed: '失败', waiting_user: '待用户批准', returned: '已退回', reconfirm: '待重新确认', } const TASK_TONES = { draft: 'idle', dispatched: 'review', running: 'run', prepared: 'review', done: 'done', cancelled: 'idle', failed: 'fail', waiting_user: 'review', returned: 'fail', reconfirm: 'fail', } const OPEN_STATUS = new Set(['dispatched', 'running', 'prepared']) const REQ_STATUS_LABELS = { discussing: '商讨中', ready: '待下派', published: '已下派', returned: '已退回', cancelled: '已取消', } const REQ_JUDGEMENT_LABELS = { can_do: '可立项', needs_discussion: '需商讨', not_now: '暂不可做', } const WORKFLOW_STAGE_LABELS = { zhongshu_draft: '中书拟案', menxia_review: '门下审核', awaiting_execution_approval: '待用户批准', shangshu_dispatch: '尚书调度', department_exec: '六部执行', menxia_acceptance: '门下验收', lead_delivery: '丞相交付', delivered: '已交付', reconfirm: '待重新确认', } function toneOfSeat(seat) { if (!seat) return 'idle' if (seat.runtimeState === 'running') return 'run' if (seat.runtimeState === 'idle' || seat.runtimeState === 'unknown') return 'idle' if (seat.status === 'failed' || seat.status === 'missing') return 'fail' if (seat.status === 'creating') return 'run' return 'idle' } function seatStateText(seat) { if (!seat) return '待命' if (seat.approvalState === 'waiting') return '等待审批' if (seat.runtimeLabel) return seat.runtimeLabel if (seat.status === 'bound') return '待命' if (seat.status === 'creating') return '开启中' if (seat.status === 'missing') return '会话缺失' if (seat.status === 'failed') return '创建失败' return '待命' } function taskTone(status) { return TASK_TONES[status] || 'idle' } function taskLabel(status) { return TASK_LABELS[status] || status || '未知' } function refreshList(value, previous, projectChanged = false) { if (Array.isArray(value)) return value return projectChanged ? [] : previous } const DELIVERY_LABELS = { pending: '待发送', sending: '发送中', unknown: '结果未知', accepted: '已接收', failed: '投递失败' } function deliveryLabel(state) { return DELIVERY_LABELS[state] || '' } function pad2(n) { return String(n).padStart(2, '0') } function clockText(ts) { const n = Number(ts) if (!Number.isFinite(n) || n <= 0) return '—' const d = new Date(n) return pad2(d.getHours()) + ':' + pad2(d.getMinutes()) } function dateText(ts) { const n = Number(ts) if (!Number.isFinite(n) || n <= 0) return '—' const d = new Date(n) return (d.getMonth() + 1) + '-' + pad2(d.getDate()) + ' ' + clockText(n) } function durationText(ms) { const n = Number(ms) if (!Number.isFinite(n) || n <= 0) return '—' const total = Math.round(n / 1000) const sec = total % 60 const min = Math.floor(total / 60) % 60 const hour = Math.floor(total / 3600) if (hour > 0) return hour + 'h ' + min + 'm' if (min > 0) return min + 'm ' + pad2(sec) + 's' return sec + 's' } function dateLabel() { try { return new Intl.DateTimeFormat('zh-CN', { weekday: 'long', year: 'numeric', month: 'long', day: 'numeric' }).format(new Date()) } catch { return '' } } function taskDurationMs(task) { if (!task) return 0 const start = Number(task.dispatchedAt || task.createdAt || 0) const end = task.resultAt ? Number(task.resultAt) : Date.now() if (!Number.isFinite(start) || !Number.isFinite(end) || start <= 0 || end <= start) return 0 return end - start } function shortText(text, max) { const value = String(text || '').replace(/\s+/g, ' ').trim() if (!value) return '' return value.length > max ? value.slice(0, max - 1) + '…' : value } function splitResultText(text) { const clean = String(text || '').replace(/\r/g, '').trim() if (!clean) return { summary: '', points: [], hasMore: false } const lines = clean.split('\n').map(line => line.trim()).filter(Boolean) const first = lines[0] || '' let summary = first.replace(/^#{1,6}\s*/, '') let rest = lines.slice(1) if (/[。!?!?]/.test(first)) { const sentences = first.split(/(?<=[。!?!?])/).map(item => item.trim()).filter(Boolean) if (sentences.length > 0) { summary = sentences[0] rest = [...sentences.slice(1), ...lines.slice(1)] } } if (summary.length > 120) summary = summary.slice(0, 119) + '…' const bullets = rest .filter(line => /^([-*•]\s+|\d+[.)、]\s+|[一二三四五六七八九十]+、)/.test(line)) .map(line => line.replace(/^([-*•]\s+|\d+[.)、]\s+|[一二三四五六七八九十]+、)/, '').trim()) .filter(Boolean) const source = bullets.length > 0 ? bullets : rest.flatMap(line => line.split(/(?<=[。!?!?])/).map(item => item.trim()).filter(Boolean)) const points = source.slice(0, 3).map(item => shortText(item, 90)) const covered = summary.length + points.join('').length return { summary, points, hasMore: clean.length > covered + 12 } } function renderRichText(text) { const lines = String(text || '').replace(/\r/g, '').split('\n') const blocks = [] let list = [] let code = null const flushList = () => { if (list.length === 0) return blocks.push(h('ul', { className: 'rs-list', key: 'list-' + blocks.length }, list.map((item, index) => h('li', { key: index }, item)))) list = [] } lines.forEach(line => { const value = line.trim() if (value.startsWith('```')) { flushList() if (code === null) code = [] else { blocks.push(h('pre', { className: 'rs-code', key: 'code-' + blocks.length }, h('code', null, code.join('\n')))); code = null } return } if (code !== null) { code.push(line); return } if (!value) { flushList(); return } if (/^#{1,6}\s+/.test(value)) { flushList() blocks.push(h('h4', { className: 'rs-heading', key: 'h-' + blocks.length }, value.replace(/^#{1,6}\s+/, ''))) return } if (/^([-*•]\s+|\d+[.)、]\s+|[一二三四五六七八九十]+、)/.test(value)) { list.push(value.replace(/^([-*•]\s+|\d+[.)、]\s+|[一二三四五六七八九十]+、)/, '')) return } flushList() if (/^(?:[A-Za-z]:[\\/]|\/|\.{0,2}\/|[\w.-]+[\\/])/.test(value) && !/\s{2,}/.test(value) && value.length <= 260) { blocks.push(h('code', { className: 'rs-path', key: 'p-' + blocks.length }, value)) } else { blocks.push(h('p', { className: 'rs-para', key: 'p-' + blocks.length }, value)) } }) flushList() if (code !== null) blocks.push(h('pre', { className: 'rs-code', key: 'code-' + blocks.length }, h('code', null, code.join('\n')))) return blocks } function SummaryBlock(props) { const text = String(props && props.text ? props.text : '').trim() const label = props && props.label ? props.label : '摘要' const empty = props && props.empty ? props.empty : '(暂无内容)' const max = props && props.max ? props.max : 120 return h('div', { className: 'card-summary' + (text ? '' : ' is-empty') }, label ? h('span', { className: 't-label' }, label) : null, h('p', { className: 'card-summary-text' }, text ? shortText(text, max) : empty), ) } function fileIcon(paths, size) { return h('svg', { viewBox: '0 0 24 24', width: size || 16, height: size || 16, fill: 'none', stroke: 'currentColor', strokeWidth: 1.8, strokeLinecap: 'round', strokeLinejoin: 'round', 'aria-hidden': 'true' }, paths.map((d, i) => h('path', { key: i, d }))) } const RefreshIcon = () => fileIcon(['M21 12a9 9 0 1 1-2.64-6.36', 'M21 3v6h-6']) const ChatIcon = () => fileIcon(['M21 15a2 2 0 0 1-2 2H7l-4 4V5a2 2 0 0 1 2-2h14a2 2 0 0 1 2 2z']) const PlusIcon = () => fileIcon(['M12 5v14', 'M5 12h14']) const SearchIcon = () => h('svg', { viewBox: '0 0 24 24', width: 15, height: 15, fill: 'none', stroke: 'currentColor', strokeWidth: 2, strokeLinecap: 'round', 'aria-hidden': 'true' }, h('circle', { cx: 11, cy: 11, r: 8 }), h('path', { d: 'm21 21-4.3-4.3' })) const ArrowIcon = () => fileIcon(['m9 18 6-6-6-6'], 15) const BookIcon = () => fileIcon(['M4 19.5A2.5 2.5 0 0 1 6.5 17H20', 'M6.5 2H20v20H6.5A2.5 2.5 0 0 1 4 19.5v-15A2.5 2.5 0 0 1 6.5 2z'], 15) const SlidersIcon = () => fileIcon(['M4 21v-7', 'M4 10V3', 'M12 21v-9', 'M12 8V3', 'M20 21v-5', 'M20 12V3', 'M2 14h4', 'M10 8h4', 'M18 16h4'], 15) function seatKind(id) { if (id === 'lead') return '总协调' if (id === 'zhongshu') return '方案' if (id === 'menxia') return '审核' if (id === 'shangshu') return '调度' return '工作' } function seatRecordOf(view, id) { const seats = view && view.project ? view.project.seats : null if (Array.isArray(seats)) return seats.find(seat => seat && seat.id === id) || null if (seats && typeof seats === 'object') return seats[id] || null return null } function fmtModel(rec, options) { const model = rec ? (rec.configuredModel ?? rec.model) : null const described = describeModel(model, options) return described.modelLabel } export function WorkbenchV2(props) { const { onClose, resolveWorkspace, navigateToSession, openRightTab, selectionCache, getLastSeatId, setLastSeatId, } = props || {} const [phase, setPhase] = useState('loading') const [error, setError] = useState(null) const [errorRetryable, setErrorRetryable] = useState(true) const [notice, setNotice] = useState(null) const [view, setView] = useState(null) const [models, setModels] = useState(null) const [selectedSeatId, setSelectedSeatId] = useState(() => { const saved = typeof getLastSeatId === 'function' ? getLastSeatId() : null return SEAT_IDS.includes(saved) ? saved : SEAT_IDS[0] }) const [tab, setTab] = useState('overview') const [queueSearch, setQueueSearch] = useState('') const [selectedTask, setSelectedTask] = useState(null) const [reviewPanelOpen, setReviewPanelOpen] = useState(false) const [durationPanelOpen, setDurationPanelOpen] = useState(false) const [tokenPanelOpen, setTokenPanelOpen] = useState(false) const [queuePanelOpen, setQueuePanelOpen] = useState(false) const [draft, setDraft] = useState({}) const [busy, setBusy] = useState(false) const [summaryBusy, setSummaryBusy] = useState(false) const [memory, setMemory] = useState(null) const [memoryDraft, setMemoryDraft] = useState({ goal: '', constraints: '', acceptance: '', decisions: '' }) const [tasks, setTasks] = useState([]) const [requirements, setRequirements] = useState([]) const [approvals, setApprovals] = useState([]) const [pendingApprovals, setPendingApprovals] = useState([]) const [approvalStatus, setApprovalStatus] = useState(null) const [reqView, setReqView] = useState('requirements') const [artifacts, setArtifacts] = useState([]) const [artifactDraft, setArtifactDraft] = useState({ title: '', path: '', summary: '' }) const [artifactFormOpen, setArtifactFormOpen] = useState(false) const [orgCols, setOrgCols] = useState(6) const alive = useRef(true) const orgRef = useRef(null) const loadedProjectId = useRef(null) const taskAnswerVersion = useRef(0) useEffect(() => { alive.current = true return () => { alive.current = false } }, []) const loadProject = useCallback(async () => { setPhase('loading'); setError(null); setErrorRetryable(true); setNotice(null) if (typeof resolveWorkspace !== 'function') { setPhase('no-workspace'); return } const workspace = resolveWorkspace() if (!workspace) { setPhase('no-workspace'); return } try { const projectView = await request('open', { workspaceId: workspace.workspaceId, name: workspace.name, path: workspace.path }) let modelCatalog = null try { modelCatalog = await request('models') } catch (modelError) { console.warn('[sansheng] 模型目录加载失败:', modelError && modelError.message ? modelError.message : modelError) } let memoryData = null try { memoryData = (await request('memory', { projectId: projectView.project.id })).memory } catch { /* 项目共识尚未建立 */ } const nextProjectId = projectView.project.id const answerVersion = taskAnswerVersion.current const [taskRes, artifactRes, requirementData, approvalData] = await Promise.allSettled([ request('tasks', { projectId: nextProjectId }), request('artifacts', { projectId: nextProjectId }), request('requirements', { projectId: nextProjectId }), request('approvals', { projectId: nextProjectId }), ]) if (!alive.current) return const projectChanged = loadedProjectId.current !== nextProjectId loadedProjectId.current = nextProjectId setView(projectView); setModels(modelCatalog); setMemory(memoryData) setMemoryDraft({ goal: memoryData?.goal ?? '', constraints: (memoryData?.constraints ?? []).join('\n'), acceptance: (memoryData?.acceptance ?? []).join('\n'), decisions: '' }) if (projectChanged) setSelectedTask(null) if (projectChanged || taskAnswerVersion.current === answerVersion) setTasks(previous => refreshList(taskRes.value?.tasks, previous, projectChanged)) setArtifacts(previous => refreshList(artifactRes.value?.artifacts, previous, projectChanged)) setRequirements(previous => refreshList(requirementData.value?.requirements, previous, projectChanged)) setApprovals(previous => refreshList(requirementData.value?.approvals, previous, projectChanged)) setPendingApprovals(previous => refreshList(approvalData.value?.approvals, previous, projectChanged)) setApprovalStatus(approvalData.status === 'fulfilled' ? approvalData.value?.status ?? null : { available: false, degraded: true }) setPhase('ready') } catch (loadError) { if (!alive.current) return setError(loadError && loadError.message ? loadError.message : '加载失败') setErrorRetryable(!(loadError && loadError.retryable === false)); setPhase('error') } }, [resolveWorkspace]) useEffect(() => { void loadProject() }, [loadProject]) const projectId = view && view.project ? view.project.id : null // 派工等操作在聊天里发生,工作台没有事件通道;轮询真实接口让队列/席位状态自动跟上。 // 页面隐藏时跳过;回到前台立即补一次。绝不把轮询结果写进草稿或配置。 useEffect(() => { if (!projectId) return undefined let disposed = false let running = false let timer = null const tick = async () => { if (disposed || running) return if (typeof document !== 'undefined' && document.visibilityState === 'hidden') return running = true try { const answerVersion = taskAnswerVersion.current const [projectRes, taskRes, artifactRes, requirementData, approvalData] = await Promise.allSettled([ request('project', { projectId }), request('tasks', { projectId }), request('artifacts', { projectId }), request('requirements', { projectId }), request('approvals', { projectId }), ]) if (disposed || !alive.current || loadedProjectId.current !== projectId) return if (projectRes.value) setView(projectRes.value) if (taskAnswerVersion.current === answerVersion) setTasks(previous => refreshList(taskRes.value?.tasks, previous)) setArtifacts(previous => refreshList(artifactRes.value?.artifacts, previous)) setRequirements(previous => refreshList(requirementData.value?.requirements, previous)) setApprovals(previous => refreshList(requirementData.value?.approvals, previous)) setPendingApprovals(previous => refreshList(approvalData.value?.approvals, previous)) setApprovalStatus(approvalData.status === 'fulfilled' ? approvalData.value?.status ?? null : { available: false, degraded: true }) } finally { running = false } } timer = setInterval(tick, 4000) const onVisibility = () => { if (document.visibilityState === 'visible') void tick() } document.addEventListener('visibilitychange', onVisibility) void tick() return () => { disposed = true if (timer !== null) clearInterval(timer) document.removeEventListener('visibilitychange', onVisibility) } }, [projectId]) useEffect(() => { if (!projectId || !selectionCache) return const saved = selectionCache.get(projectId) if (saved && SEAT_IDS.includes(saved)) setSelectedSeatId(saved) }, [projectId, selectionCache]) const wb = buildWorkbenchView(view, { selectedSeatId, models, draft }) const seatById = useMemo(() => { const map = {} for (const seat of wb.seats) map[seat.id] = seat return map }, [wb.seats]) useEffect(() => { const node = orgRef.current if (!node || typeof ResizeObserver === 'undefined') return undefined const sync = () => { const w = node.clientWidth || 0 setOrgCols(w <= 700 ? 2 : w <= 1180 ? 3 : 6) } sync() const observer = new ResizeObserver(sync) observer.observe(node) return () => observer.disconnect() }, [phase, tab]) function setSeat(id) { if (!id || id === selectedSeatId) return setSelectedSeatId(id) if (typeof setLastSeatId === 'function') setLastSeatId(id) if (projectId && selectionCache) selectionCache.set(projectId, id) } function setModelValue(value) { setDraft(prev => updateDraft(prev, selectedSeatId, { modelValue: value })) void rememberModel(value, selectedSeatId) } function setInstructions(value) { setDraft(prev => updateDraft(prev, selectedSeatId, { instructions: value })) } function modelFromValue(value) { const option = findModelOption(wb.selected.modelOptions, value) if (option) { return option.reasoningEffort ? { provider: option.provider, model: option.model, reasoningEffort: option.reasoningEffort } : { provider: option.provider, model: option.model } } const parts = String(value || '').split('::') if (parts.length >= 2 && parts[0] && parts[1]) { return parts[2] ? { provider: parts[0], model: parts[1], reasoningEffort: parts[2] } : { provider: parts[0], model: parts[1] } } return null } async function rememberModel(value, seatId) { if (!projectId || !value || !seatId) return const model = modelFromValue(value) if (!model) return try { const saved = await request('configure', { projectId, seatId, model }) if (!alive.current) return setView(prev => { if (!prev || !prev.project) return prev const seats = Array.isArray(prev.project.seats) ? prev.project.seats.map(seat => (seat && seat.id === seatId ? { ...seat, ...(saved && saved.seat ? saved.seat : { model }) } : seat)) : prev.project.seats return { ...prev, revision: (prev.revision ?? 0) + 1, project: { ...prev.project, seats } } }) setNotice('已记住「' + (SEATS[seatId]?.label ?? seatId) + '」的模型') } catch (error) { if (alive.current) setNotice(error && error.message ? error.message : '模型记忆失败') } } async function openSeat(seatId) { const seat = seatById[seatId] if (!projectId || !seat) return if (seat.status === 'missing') { setNotice('「' + seat.name + '」的会话已不存在,点「重建会话」可重新建立'); return } if (seat.status !== 'bound') { setNotice('「' + seat.name + '」还没开启,先点「开启『' + seat.name + '』」'); return } setBusy(true); setError(null) try { const result = await request('openSeat', { projectId, seatId }) if (!alive.current) return if (!result || !result.sessionId) throw new Error('宿主没有返回会话') navigateToSession(result.sessionId) setNotice('已切换到「' + seat.name + '」会话') } catch (openError) { if (alive.current) setError(openError && openError.message ? openError.message : '打开会话失败') if (openError && openError.code === 'sansheng/session-missing') { try { const next = await request('project', { projectId }); if (alive.current) setView(next) } catch { /* 保留当前视图 */ } } } finally { if (alive.current) setBusy(false) } } async function rebuildSeat(seatId) { const seat = seatById[seatId] if (!projectId || !seat) return const rec = seatRecordOf(view, seatId) setBusy(true); setError(null); setNotice('正在重建「' + seat.name + '」的会话…') try { const next = await request('rebuildSeat', { projectId, seatId, expectedSessionId: rec && rec.sessionId ? rec.sessionId : undefined }) if (!alive.current) return setView(next); setNotice('已重建「' + seat.name + '」的会话;旧会话历史仍保留') } catch (rebuildError) { if (alive.current) setError(rebuildError && rebuildError.message ? rebuildError.message : '重建会话失败') if (rebuildError && rebuildError.code === 'sansheng/session-conflict') { try { const next = await request('project', { projectId }); if (alive.current) setView(next) } catch { /* 保留当前视图 */ } } } finally { if (alive.current) setBusy(false) } } async function enableSeat(seatId) { if (!projectId) return const seat = seatById[seatId] setBusy(true); setError(null); setNotice('正在开启「' + (seat ? seat.name : seatId) + '」…') try { const next = await request('enableSeat', { projectId, seatId }) if (!alive.current) return setView(next); setNotice('已开启「' + (seat ? seat.name : seatId) + '」的独立会话') try { if (typeof openRightTab === 'function') openRightTab() } catch { /* 打开失败不影响开启 */ } } catch (enableError) { if (alive.current) setError(enableError && enableError.message ? enableError.message : '开启失败') } finally { if (alive.current) setBusy(false) } } async function saveConfig() { if (!projectId) return const seatId = wb.selected.id const value = wb.selected.modelValue if (!value) { setNotice('请先为当前角色选择模型'); return } const model = modelFromValue(value) setBusy(true); setError(null); setNotice('保存中…') try { await request('configure', { projectId, seatId, model, instructions: wb.selected.instructions }) const next = await request('project', { projectId }) if (!alive.current) return setView(next); setDraft(prev => clearDraft(prev, seatId)); setNotice('已保存') } catch (saveError) { if (alive.current) setError(saveError && saveError.message ? saveError.message : '保存失败') } finally { if (alive.current) setBusy(false) } } async function setGlobalDefaultForSeat() { if (!projectId) return const seatId = wb.selected.id const model = modelFromValue(wb.selected.modelValue) if (!model) { setNotice('请先为当前角色选择模型'); return } if (typeof window !== 'undefined' && typeof window.confirm === 'function' && !window.confirm('把「' + wb.selected.name + '」当前模型设为全局默认?其他未覆盖的项目会继承。')) return setBusy(true); setError(null) try { const result = await request('setGlobalDefault', { seatId, model }) const next = await request('project', { projectId }) if (!alive.current) return setView(next); setNotice('已设为全局默认;继承项目已同步 ' + ((result.applied || []).length) + ' 个') } catch (error) { if (alive.current) setError(error && error.message ? error.message : '设置全局默认失败') } finally { if (alive.current) setBusy(false) } } async function clearSeatOverride() { if (!projectId) return const seatId = wb.selected.id setBusy(true); setError(null) try { await request('configure', { projectId, seatId, model: null }) const next = await request('project', { projectId }) if (!alive.current) return setView(next); setDraft(prev => clearDraft(prev, seatId)); setNotice('已恢复继承全局默认') } catch (error) { if (alive.current) setError(error && error.message ? error.message : '恢复继承失败') } finally { if (alive.current) setBusy(false) } } async function retryModelSync() { if (!projectId) return setBusy(true); setError(null) try { const result = await request('retrySeatModel', { projectId, seatId: wb.selected.id }) const next = await request('project', { projectId }) if (!alive.current) return setView(next); setNotice('模型同步:' + (result.sync?.status ?? 'unknown')) } catch (error) { if (alive.current) setError(error && error.message ? error.message : '重试同步失败') } finally { if (alive.current) setBusy(false) } } async function saveMemory() { if (!projectId) return setBusy(true); setError(null); setNotice('保存项目共识…') try { const result = await request('memoryUpdate', { projectId, expectedRevision: memory?.revision ?? 0, goal: memoryDraft.goal, constraints: memoryDraft.constraints.split('\n').map(x => x.trim()).filter(Boolean), acceptance: memoryDraft.acceptance.split('\n').map(x => x.trim()).filter(Boolean), decisions: memoryDraft.decisions.split('\n').map(x => x.trim()).filter(Boolean).map(text => ({ type: 'user', status: 'active', text, sourceRefs: [] })), sources: [], }) if (!alive.current) return setMemory(result.memory) setMemoryDraft(prev => ({ ...prev, decisions: '' })) setNotice('项目共识已保存(v' + result.memory.revision + ')') } catch (memoryError) { if (alive.current) setError(memoryError && memoryError.message ? memoryError.message : '保存项目共识失败') } finally { if (alive.current) setBusy(false) } } async function reloadTasks() { if (!projectId) return const answerVersion = taskAnswerVersion.current try { const result = await request('tasks', { projectId }) if (alive.current && loadedProjectId.current === projectId && taskAnswerVersion.current === answerVersion) { setTasks(previous => refreshList(result?.tasks, previous)) } } catch (error) { if (alive.current && loadedProjectId.current === projectId) setNotice(error && error.message ? error.message : '任务列表刷新失败') } } async function summarizeByShangshu() { if (!projectId) return setSummaryBusy(true); setError(null) try { const result = await request('shangshuSummary', { projectId }) if (!alive.current) return if (!result || !result.sessionId) throw new Error('宿主没有返回尚书会话') setNotice('已请尚书汇总当前任务,正在打开尚书会话…') navigateToSession(result.sessionId) } catch (summaryError) { if (alive.current) setError(summaryError && summaryError.message ? summaryError.message : '尚书汇总请求失败') } finally { if (alive.current) setSummaryBusy(false) } } async function addArtifact() { if (!projectId) return const title = artifactDraft.title.trim() if (!title) { setNotice('成果名称不能为空'); return } setBusy(true); setError(null) try { const result = await request('artifactAdd', { projectId, title, path: artifactDraft.path, summary: artifactDraft.summary }) setArtifacts(list => [...list, result.artifact]); setArtifactDraft({ title: '', path: '', summary: '' }); setArtifactFormOpen(false); setNotice('成果已登记。') } catch (error) { if (alive.current) setError(error && error.message ? error.message : '登记成果失败') } finally { if (alive.current) setBusy(false) } } const todayStart = TODAY() const todayTasks = tasks.filter(task => Number(task.createdAt) >= todayStart) const todayDone = todayTasks.filter(task => task.status === 'done') const reviewTasks = tasks.filter(task => task.ownerSeatId === 'menxia' && OPEN_STATUS.has(task.status)) const anomalyTasks = tasks.filter(task => task.status === 'failed' || task.deliveryState === 'failed') const projectDurationMs = tasks.reduce((sum, task) => sum + taskDurationMs(task), 0) function latestTaskOf(seatId) { return tasks.filter(task => task.ownerSeatId === seatId).sort((a, b) => Number(b.updatedAt || b.createdAt || 0) - Number(a.updatedAt || a.createdAt || 0))[0] || null } function tasksOf(seatId) { return tasks.filter(task => task.ownerSeatId === seatId).sort((a, b) => Number(b.updatedAt || b.createdAt || 0) - Number(a.updatedAt || a.createdAt || 0)) } function selectedSeatRecord(id) { return seatRecordOf(view, id) } function modelLabelOf(id) { return fmtModel(selectedSeatRecord(id), wb.selected.modelOptions) } const statusBanner = error ? h('p', { className: 'ssv-banner is-error', role: 'alert' }, error) : (notice ? h('p', { className: 'ssv-banner is-notice', role: 'status' }, notice) : null) function renderTopbar(title, extra) { const shortcuts = tab === 'overview' ? [ h('button', { type: 'button', key: 'memory', className: 'icon-btn', title: '记忆', 'aria-label': '记忆', onClick: () => setTab('memory') }, h(BookIcon)), h('button', { type: 'button', key: 'settings', className: 'icon-btn', title: '设置', 'aria-label': '设置', onClick: () => setTab('settings') }, h(SlidersIcon)), ] : [] return h('header', { className: 'topbar' }, h('div', { className: 'topbar-title' }, h('h1', null, title), tab === 'overview' ? h('span', { className: 'date' }, dateLabel()) : null, h('div', { className: 'topbar-icons' }, shortcuts), ), h('span', { className: 'spacer' }), ...(extra || []), ) } function renderSeatNode(seat) { const tone = toneOfSeat(seat) const latest = latestTaskOf(seat.id) return h('div', { key: seat.id, className: 'node' + (seat.id === selectedSeatId ? ' selected' : ''), 'data-seat': seat.id }, h('button', { type: 'button', className: 'node-main', onClick: () => setSeat(seat.id), 'aria-pressed': seat.id === selectedSeatId ? 'true' : 'false' }, h('span', { className: 'node-top' }, h('span', { className: 'node-name' }, seat.name), h('span', { className: 'status ' + tone }, h('i'), seatStateText(seat))), h('span', { className: 'node-role' }, seat.duty), h('span', { className: 'node-task' }, h('span', { className: 't-label' }, '当前任务'), h('span', { className: 'task-text' }, latest ? latest.title : '—')), h('span', { className: 'node-model' }, '主任模型 ', h('span', { className: 'num' }, modelLabelOf(seat.id))), ), h('div', { className: 'node-foot' }, h('span', { className: 'elapsed' }, latest ? taskLabel(latest.status) : (seat.status === 'bound' ? '在线 · 待命' : '未运行 · 待命'))), ) } function reqTone(status) { if (status === 'ready' || status === 'published') return 'review' if (status === 'returned') return 'fail' if (status === 'cancelled') return 'idle' return 'run' } function copyRequirementText(text) { try { if (navigator.clipboard && typeof navigator.clipboard.writeText === 'function') { void navigator.clipboard.writeText(text).then(() => setNotice('已复制:' + text)).catch(() => {}) } } catch { /* 剪贴板不可用时保留可手动选择文本 */ } } function renderRequirementGate(selected) { const views = [ { id: 'requirements', label: '需求清单' }, { id: 'flow', label: '流转任务' }, { id: 'delivery', label: '交付结果' }, ] const workflowTasks = tasks.filter(task => task.kind === 'workflow' || task.kind === 'execution') const deliveryTasks = tasks.filter(task => task.kind === 'workflow' && (task.stage === 'delivered' || task.status === 'done')) let body if (reqView === 'flow') { body = workflowTasks.length ? h('div', { className: 'review-list req-list' }, workflowTasks.map(task => h('article', { className: 'review-card req-card', key: task.id }, h('div', { className: 'rc-head' }, h('div', { className: 'rc-title' }, task.title), h('span', { className: 'rc-status ' + taskTone(task.status) }, h('i'), taskLabel(task.status)), ), h('div', { className: 'req-meta' }, h('span', null, task.id), h('span', null, (SEATS[task.ownerSeatId] && SEATS[task.ownerSeatId].label) || task.ownerSeatId || '—'), h('span', null, WORKFLOW_STAGE_LABELS[task.stage] || task.stage || '—'), task.requirementId ? h('span', null, task.requirementId + ' v' + task.requirementRevision) : null, task.approvalId ? h('span', null, task.approvalId) : null, ), h(SummaryBlock, { text: task.goal || task.requirement || '', label: '任务说明', empty: '(无任务说明)', max: 110 }), h(SummaryBlock, { text: task.result || task.note || task.blockedReason || '', label: '当前结果 / 阻塞', empty: '(尚未回报)', max: 110 }), h('div', { className: 'rc-actions' }, h('span', { className: 'spacer' }), h('button', { type: 'button', className: 'r-open', onClick: () => setSelectedTask(task) }, '查看详情 →')), ))) : h('p', { className: 'empty-note' }, '还没有流转任务。丞相下派需求后会出现在这里。') } else if (reqView === 'delivery') { body = deliveryTasks.length ? h('div', { className: 'review-list req-list' }, deliveryTasks.map(task => { const children = tasks.filter(item => item.parentTaskId === task.id && item.kind === 'execution') return h('article', { className: 'review-card req-card', key: task.id }, h('div', { className: 'rc-head' }, h('div', { className: 'rc-title' }, task.title), h('span', { className: 'rc-status done' }, h('i'), '已交付')), h('div', { className: 'req-meta' }, h('span', null, task.requirementId || '—'), h('span', null, 'v' + (task.requirementRevision || '—')), h('span', null, task.id)), h(SummaryBlock, { text: task.deliveryNote || task.summary || '', label: '交付说明', empty: '(暂无交付说明)', max: 110 }), children.length ? h('div', { className: 'req-children' }, children.map(child => h('div', { className: 'req-child', key: child.id }, h('span', { className: 'req-child-owner' }, (SEATS[child.ownerSeatId] && SEATS[child.ownerSeatId].label) || child.ownerSeatId), h('span', { className: 'rc-status ' + taskTone(child.status) }, h('i'), taskLabel(child.status)), h('span', { className: 'req-child-result' }, child.result || child.note || '(暂无结果)'), h('span', { className: 'req-child-session' }, child.resultSessionId ? '结果会话 ' + child.resultSessionId : '尚无结果会话'), ))) : null, ) })) : h('p', { className: 'empty-note' }, '还没有已交付结果。') } else { body = requirements.length ? h('div', { className: 'review-list req-list' }, requirements.map(req => h('article', { className: 'review-card req-card', key: req.id }, h('div', { className: 'rc-head' }, h('div', { className: 'rc-title' }, req.id + ' · ' + req.title), h('span', { className: 'rc-status ' + reqTone(req.status) }, h('i'), REQ_STATUS_LABELS[req.status] || req.status), ), h('div', { className: 'req-meta' }, h('span', null, 'v' + req.revision), h('span', null, '丞相判断:' + (REQ_JUDGEMENT_LABELS[req.judgement] || req.judgement || '—')), h('span', null, '当前阻塞:' + (req.blockedReason || '—')), ), h(SummaryBlock, { text: req.summary || req.originalText || '', label: '摘要', empty: '(暂无摘要)', max: 110 }), h(SummaryBlock, { text: req.judgementReason || '', label: '判断理由', empty: '(暂无判断理由)', max: 110 }), h('details', { className: 'req-details' }, h('summary', null, '范围、验收与待补信息'), h('dl', { className: 'kv' }, h('dt', null, '用户原话'), h('dd', null, req.originalText || '—'), h('dt', null, '范围'), h('dd', null, req.scope || '—'), h('dt', null, '非目标'), h('dd', null, req.nonGoals || '—'), h('dt', null, '验收标准'), h('dd', null, req.acceptanceCriteria || '—'), h('dt', null, '风险'), h('dd', null, req.risks || '—'), h('dt', null, '依赖'), h('dd', null, req.dependencies || '—'), h('dt', null, '待补信息'), h('dd', null, req.missingInfo || '—'), ), ), h('div', { className: 'rc-actions' }, h('button', { type: 'button', className: 'btn', onClick: () => copyRequirementText(req.id) }, '复制条目编号'), h('span', { className: 'spacer' }), ), ))) : h('p', { className: 'empty-note' }, '还没有需求条目。可以先与丞相讨论。') } return h('section', { className: 'card req-gate', 'aria-label': '丞相需求门控' }, h('h3', null, '需求门控 ', h('span', { className: 'seat-tag' }, selected.name)), h('p', { className: 'foot-note ws-hint' }, '与丞相商讨后,需求会整理到这里。想推进哪条需求,直接在聊天中告诉丞相下派。中书拟案,门下通过后由尚书安排执行。'), h('div', { className: 'req-tabs', role: 'tablist' }, views.map(view => h('button', { key: view.id, type: 'button', role: 'tab', 'aria-selected': reqView === view.id, className: 'req-tab' + (reqView === view.id ? ' is-active' : ''), onClick: () => setReqView(view.id), }, view.label))), body, ) } async function answerApproval(entry, choice) { if (!projectId || !entry) return setBusy(true); setError(null) try { await request('approvalAnswer', { projectId, seatId: entry.seatId, id: entry.id, sessionId: entry.sessionId, choice }) const data = await request('approvals', { projectId }) if (!alive.current || loadedProjectId.current !== projectId) return setPendingApprovals(previous => refreshList(data?.approvals, previous)) setApprovalStatus(data?.status ?? null) setNotice(choice === 'allow' ? '已允许审批' : '已拒绝审批') } catch (error) { if (alive.current) setError(error && error.message ? error.message : '审批应答失败') } finally { if (alive.current) setBusy(false) } } async function answerDecision(taskId, decisionId, value) { if (!projectId || busy) return setBusy(true); setError(null) try { await request('taskDecisionAnswer', { projectId, taskId, decisionId, value }) if (!alive.current || loadedProjectId.current !== projectId) return taskAnswerVersion.current += 1 setTasks(previous => previous.map(task => task.id === taskId && Array.isArray(task.decisions) ? { ...task, decisions: task.decisions.map(decision => decision.id === decisionId ? { ...decision, status: 'answered', answer: value } : decision) } : task)) setNotice('已提交项目决定') } catch (error) { if (alive.current && loadedProjectId.current === projectId) setError(error?.message || '项目决定提交失败') } finally { if (alive.current) setBusy(false) } } function renderPendingActions() { const degraded = approvalStatus?.degraded const toolApprovals = degraded ? [] : pendingApprovals const decisions = tasks.flatMap(task => (task.decisions || []) .filter(decision => decision.status === 'pending') .map(decision => ({ task, decision }))) const count = toolApprovals.length + decisions.length if (!count && !degraded) return null return h('section', { className: 'card approval-card', 'aria-label': '待你处理' }, h('h3', null, '待你处理 ', count ? h('span', { className: 'seat-tag' }, String(count)) : null), degraded ? h('p', { className: 'foot-note' }, '工作台暂时无法获取工具审批,请在席位会话中使用原生审批卡。' + (approvalStatus.reason ? '(' + approvalStatus.reason + ')' : '')) : null, count ? h('div', { className: 'approval-list' }, toolApprovals.map(entry => h('article', { className: 'approval-item', key: 'tool:' + entry.sessionId + ':' + entry.id }, h('div', { className: 'approval-head' }, h('strong', null, SEATS[entry.seatId]?.label || entry.seatId), h('span', null, entry.tool || '工具审批')), h('p', null, entry.reason || entry.detail?.text || '等待审批'), h('div', { className: 'approval-actions' }, h('button', { type: 'button', className: 'btn primary', disabled: busy, onClick: () => answerApproval(entry, 'allow') }, '允许一次'), h('button', { type: 'button', className: 'btn', disabled: busy, onClick: () => answerApproval(entry, 'reject') }, '拒绝'), ), )), decisions.map(({ task, decision }) => h('article', { className: 'approval-item', key: 'decision:' + task.id + ':' + decision.id }, h('div', { className: 'approval-head' }, h('strong', null, task.title || task.id), h('span', null, '项目决定')), h('p', null, decision.question), h('div', { className: 'approval-actions', role: 'group', 'aria-label': decision.question }, decision.options.map(option => h('button', { type: 'button', className: 'btn', key: option.value, disabled: busy, onClick: () => answerDecision(task.id, decision.id, option.value) }, option.label), )), )), ) : null, ) } function renderOverview() { const stats = [ h('button', { type: 'button', className: 'stat stat-link', key: 'cost', onClick: () => setTokenPanelOpen(true) }, h('div', { className: 'label' }, '消耗金额'), h('div', { className: 'big' }, h('em', null, '—'), h('span', { className: 'unit' }, '元')), h('div', { className: 'foot' }, 'Token 统计待接入'), ), h('button', { type: 'button', className: 'stat stat-link', key: 'duration', onClick: () => setDurationPanelOpen(true) }, h('div', { className: 'label' }, '消耗时间'), h('div', { className: 'big' }, projectDurationMs > 0 ? durationText(projectDurationMs) : '—'), h('div', { className: 'foot' }, '按任务单程累计'), ), h('button', { type: 'button', className: 'stat stat-link', key: 'review', onClick: () => setReviewPanelOpen(true) }, h('div', { className: 'label' }, '待审核'), h('div', { className: 'big' }, h('em', null, String(reviewTasks.length)), ' ', h('span', { className: 'unit' }, '件')), h('div', { className: 'foot' }, '待门下复核'), ), h('button', { type: 'button', className: 'stat stat-link', key: 'anomaly', onClick: () => { setQueueSearch('失败'); setQueuePanelOpen(true) } }, h('div', { className: 'label' }, '异常 / 失败'), h('div', { className: 'big' }, h('em', null, String(anomalyTasks.length)), ' ', h('span', { className: 'unit' }, '条')), h('div', { className: 'foot' }, '失败或投递失败'), ), ] const selected = wb.selected const selectedLatest = latestTaskOf(selected.id) const selectedTasks = tasksOf(selected.id) const selectedToday = todayTasks.filter(task => task.ownerSeatId === selected.id) const selectedDone = selectedToday.filter(task => task.status === 'done') const excerpt = (selectedLatest && (selectedLatest.result || selectedLatest.note)) || selected.responsibility const actionLabel = selected.status === 'bound' ? '开始对话' : (selected.status === 'missing' ? '重建会话' : '开启「' + selected.name + '」') const action = selected.status === 'bound' ? () => openSeat(selected.id) : (selected.status === 'missing' ? () => rebuildSeat(selected.id) : () => enableSeat(selected.id)) const detail = h('section', { className: 'card', 'aria-label': '席位详情' }, h('div', { className: 'detail-head' }, h('h3', null, '席位详情'), h('button', { type: 'button', className: 'btn primary', disabled: busy || selected.status === 'creating', onClick: action }, h(ChatIcon), actionLabel)), h('div', { className: 'detail-name' }, selected.name), h('div', { className: 'detail-role' }, selected.duty + ' · ' + selected.statusLabel), h('dl', { className: 'kv' }, h('dt', null, '主任模型'), h('dd', null, selected.modelLabel), h('dt', null, '当前任务'), h('dd', null, selectedLatest ? selectedLatest.title : '—'), h('dt', null, '本日派工'), h('dd', null, selectedToday.length + ' 条 · 完成 ' + selectedDone.length), h('dt', null, '最近会话'), h('dd', null, selected.sessionId ? '已绑定 · ' + selected.sessionId.slice(0, 8) : '尚未建立'), ), h('div', { className: 'excerpt' }, h(SummaryBlock, { text: excerpt, label: '最近产出', empty: '(暂无产出)', max: 110 })), ) const workspace = selected.id === 'lead' ? renderRequirementGate(selected) : h('section', { className: 'card', 'aria-label': '席位工作区' }, h('h3', null, '席位工作区 ', h('span', { className: 'seat-tag' }, selected.name), ' ', h('span', { className: 'w-kind' }, seatKind(selected.id))), selected.id === 'shangshu' ? h('div', { className: 'ws-actions' }, h('button', { type: 'button', className: 'btn primary', disabled: summaryBusy || busy, onClick: summarizeByShangshu }, summaryBusy ? '汇总中…' : '尚书汇总当前任务')) : null, h('p', { className: 'foot-note ws-hint' }, '需求请先在聊天中与丞相商讨,再直接告诉丞相下派。中书拟案,门下通过后由尚书向六部派工。'), selectedTasks.length === 0 ? h('p', { className: 'empty-note' }, '该席位还没有任务记录。') : h('div', { className: 'review-list' }, selectedTasks.slice(0, 3).map(task => h('article', { className: 'review-card', key: task.id }, h('div', { className: 'rc-head' }, h('div', { className: 'rc-title' }, task.title), h('span', { className: 'rc-status ' + taskTone(task.status) }, h('i'), taskLabel(task.status))), h(SummaryBlock, { text: task.goal || task.requirement || '', label: '任务说明', empty: '(无任务说明)', max: 110 }), h(SummaryBlock, { text: task.result || taskLabel(task.status), label: '任务完成情况', empty: '(暂无结果)', max: 110 }), h('div', { className: 'rc-actions' }, h('span', { className: 'spacer' }), h('button', { type: 'button', className: 'r-open', onClick: () => setSelectedTask(task) }, '查看详情 →'), ), ))), ) const modelChoices = [] const seenModels = new Set() for (const option of selected.modelOptions) { const key = option.provider + '::' + option.model if (seenModels.has(key)) continue seenModels.add(key) modelChoices.push({ value: key, label: option.model, provider: option.provider, model: option.model }) } const valueParts = String(selected.modelValue || '').split('::') const currentProvider = valueParts[0] || '' const currentModel = valueParts[1] || '' const currentModelValue = currentProvider && currentModel ? currentProvider + '::' + currentModel : '' if (currentModelValue && !seenModels.has(currentModelValue)) { modelChoices.unshift({ value: currentModelValue, label: currentModel, provider: currentProvider, model: currentModel }) } const effortChoices = [] for (const option of selected.modelOptions) { if (option.provider !== currentProvider || option.model !== currentModel || !option.reasoningEffort) continue if (!effortChoices.includes(option.reasoningEffort)) effortChoices.push(option.reasoningEffort) } const currentEffort = valueParts[2] || '' if (currentEffort && !effortChoices.includes(currentEffort)) effortChoices.unshift(currentEffort) const configCard = h('details', { className: 'card dept-config-card', 'aria-label': '部门配置' }, h('summary', null, h('span', null, '部门配置'), h('span', { className: 'seat-tag' }, selected.name)), h('div', { className: 'dept-config-body' }, h('div', { className: 'cfg-grid' }, h('label', { className: 'cfg-row' }, '主任模型', h('select', { value: currentModelValue, onChange: event => setModelValue(event.target.value) }, h('option', { value: '' }, '请选择模型'), modelChoices.map(option => h('option', { key: option.value, value: option.value }, option.label)), )), h('label', { className: 'cfg-row' }, '推理等级', h('select', { value: currentEffort, disabled: effortChoices.length === 0, title: effortChoices.length === 0 ? '当前模型目录未提供可调推理等级' : undefined, onChange: event => setModelValue(event.target.value ? currentProvider + '::' + currentModel + '::' + event.target.value : currentModelValue), }, effortChoices.length === 0 ? h('option', { value: '' }, '默认(模型固定)') : [h('option', { key: 'default', value: '' }, '默认'), ...effortChoices.map(effort => h('option', { key: effort, value: effort }, effort))], )), h('label', { className: 'cfg-row', style: { gridColumn: '1 / -1' } }, '角色补充说明', h('textarea', { rows: 3, className: 'ssv-textarea', value: selected.instructions, placeholder: '仅对该席位追加的补充说明', onChange: event => setInstructions(event.target.value), })), ), h('div', { className: 'cfg-model-status' }, h('div', null, '配置来源:' + selected.modelSourceLabel), h('div', null, '当前会话模型:' + (selected.sessionModel ? (selected.sessionModel.provider + '/' + selected.sessionModel.model) : '未知')), h('div', null, '同步状态:' + (selected.modelStatus || '未同步') + (selected.modelSync && selected.modelSync.error ? '(' + selected.modelSync.error + ')' : '')), ), h('div', { className: 'cfg-skills' }, h('span', { className: 't-label' }, '技能绑定'), h('ul', { className: 'skill-list' }, h('li', null, h('span', { className: 'skill-name' }, '真实会话绑定'), h('span', { className: 'skill-state' + (selected.status === 'bound' ? ' bound' : '') }, h('i'), selected.status === 'bound' ? '已绑定' : '未绑定')), h('li', null, h('span', { className: 'skill-name' }, '工作台派工工具'), h('span', { className: 'skill-state' + (selected.status === 'bound' ? ' bound' : '') }, h('i'), selected.status === 'bound' ? '可用' : '待开启')), h('li', null, h('span', { className: 'skill-name' }, '职责'), h('span', { className: 'skill-state bound' }, h('i'), selected.duty)), )), h('div', { className: 'ws-actions' }, h('button', { type: 'button', className: 'btn primary', disabled: busy, onClick: saveConfig }, busy ? '保存中…' : '保存配置'), selected.status === 'bound' && selected.configuredModel ? h('button', { type: 'button', className: 'btn', disabled: busy, onClick: setGlobalDefaultForSeat }, '设为全局默认') : null, selected.modelSource === 'project' ? h('button', { type: 'button', className: 'btn', disabled: busy, onClick: clearSeatOverride }, '恢复继承全局默认') : null, selected.modelSyncStatus === 'failed' || selected.modelSyncStatus === 'unresolved' ? h('button', { type: 'button', className: 'btn', disabled: busy, onClick: retryModelSync }, '重试同步') : null, selected.status !== 'bound' ? h('button', { type: 'button', className: 'btn', disabled: busy, onClick: action }, actionLabel) : null, ), ), ) return h('div', { className: 'page' }, renderTopbar('总览', [ h('button', { type: 'button', className: 'btn primary btn-cx', onClick: () => { setSeat('lead'); if (seatById.lead.status === 'bound') void openSeat('lead'); else setTab('settings') } }, h('span', { className: 'cx-name' }, '丞相'), h('span', { className: 'cx-dot', 'aria-hidden': 'true' }), h('span', { className: 'cx-state' }, seatStateText(seatById.lead))), ]), h('section', { className: 'stats', 'aria-label': '关键指标' }, stats), renderPendingActions(), h('section', { 'aria-label': '席位谱系', style: { marginTop: '22px' } }, h('div', { className: 'panel-head' }, h('h2', null, '席位谱系')), h('div', { id: 'orgTree', ref: orgRef }, h('div', { className: 'org-rows', 'data-cols': String(orgCols) }, h('div', { className: 'org-row org-row-3' }, wb.groups.sansheng.map(id => h('div', { className: 'org-cell', key: id, 'data-slot': id }, renderSeatNode(seatById[id])))), h('div', { className: 'org-wires org-wires-2', 'aria-hidden': 'true' }, h('span', { className: 'wire-v', style: { left: '50%', top: 0, height: 11 } }), h('span', { className: 'wire-h', style: { left: '8.3333%', right: '8.3333%', top: 11 } }), ...[8.3333, 25, 41.6667, 58.3333, 75, 91.6667].map((left, i) => h('span', { key: i, className: 'wire-v w2-b' + (i + 1), style: { left: left + '%', top: 11, height: 11 } }))), h('div', { className: 'org-row org-row-6' }, wb.groups.liubu.map(id => h('div', { className: 'org-cell', key: id, 'data-slot': id }, renderSeatNode(seatById[id])))), )), ), h('div', { className: 'grid' }, h('div', { className: 'detail-col' }, detail, workspace), h('div', { className: 'rail' }, configCard)), h('p', { className: 'foot-note' }, '数据来自当前项目真实会话 · ' + (wb.project.boundCount + ' / ' + wb.project.seatCount + ' 席已启用')), ) } function renderQueuePanel() { if (!queuePanelOpen) return null const query = queueSearch.trim().toLowerCase() const filtered = tasks.filter(task => { if (!query) return true const seatName = SEATS[task.ownerSeatId]?.label || task.ownerSeatId || '' const haystack = [task.title, seatName, task.id, task.goal, task.requirement, task.result, taskLabel(task.status), deliveryLabel(task.deliveryState)].filter(Boolean).join(' ').toLowerCase() return haystack.includes(query) }) const openTask = task => { setQueuePanelOpen(false); setSelectedTask(task) } return h('div', { className: 'modal-backdrop', onClick: event => { if (event.target === event.currentTarget) setQueuePanelOpen(false) } }, h('div', { className: 'modal wide', role: 'dialog', 'aria-modal': 'true', 'aria-labelledby': 'ssv-queue-title' }, h('div', { className: 'modal-head' }, h('h3', { id: 'ssv-queue-title' }, '派工队列'), h('button', { type: 'button', className: 'modal-close', 'aria-label': '关闭', onClick: () => setQueuePanelOpen(false) }, '✕')), h('div', { className: 'modal-toolbar' }, h('label', { className: 'search' }, h(SearchIcon), h('input', { type: 'search', value: queueSearch, placeholder: '搜索派工记录…', 'aria-label': '搜索派工队列', onChange: event => setQueueSearch(event.target.value) })), h('button', { type: 'button', className: 'btn', disabled: summaryBusy || busy, onClick: summarizeByShangshu }, summaryBusy ? '汇总中…' : '尚书汇总'), h('button', { type: 'button', className: 'btn', disabled: busy, onClick: reloadTasks }, h(RefreshIcon), '刷新'), ), h('div', { className: 'queue-table-wrap' }, h('div', { className: 'table-scroll' }, h('table', null, h('thead', null, h('tr', null, ['任务', '承办席位', '状态', '结果', '耗时', '派发时间'].map(label => h('th', { key: label, scope: 'col' }, label)))), h('tbody', null, filtered.map(task => h('tr', { key: task.id, className: 'clickable', tabIndex: 0, onClick: () => openTask(task), onKeyDown: event => { if (event.key === 'Enter') openTask(task) } }, h('td', null, h('span', { className: 'task-name' }, task.title), h('br'), h('span', { className: 'task-id' }, task.id)), h('td', null, SEATS[task.ownerSeatId]?.label || task.ownerSeatId || '—'), h('td', null, h('span', { className: 'pill ' + taskTone(task.status) }, h('i'), taskLabel(task.status)), task.deliveryState && task.deliveryState !== 'none' ? h('span', { className: 'pill ' + (['failed', 'unknown'].includes(task.deliveryState) ? 'fail' : 'idle'), style: { marginLeft: '4px' } }, h('i'), deliveryLabel(task.deliveryState)) : null), h('td', { className: 'result-cell' }, task.result ? shortText(task.result, 42) : '—'), h('td', { className: 'dur' }, taskDurationMs(task) > 0 ? durationText(taskDurationMs(task)) : '—'), h('td', { className: 'time' }, task.dispatchedAt ? dateText(task.dispatchedAt) : '—'), ))), )), h('p', { className: 'foot-note' }, filtered.length === 0 ? '没有匹配的派工记录,换个关键词试试。' : '共 ' + filtered.length + ' 条派工记录。'), ), )) } function renderMemory() { const constraints = Array.isArray(memory?.constraints) ? memory.constraints : [] const acceptance = Array.isArray(memory?.acceptance) ? memory.acceptance : [] const decisions = Array.isArray(memory?.decisions) ? memory.decisions : [] const item = (title, meta, body, tone) => h('article', { className: 'review-card', key: title }, h('div', { className: 'rc-head' }, h('div', { className: 'rc-title' }, title), h('span', { className: 'rc-status ' + (tone || 'pass') }, h('i'), '现行')), h('div', { className: 'rc-meta-row' }, h('span', { className: 'rc-from' }, '项目共识'), h('span', { className: 'rc-meta' }, meta)), h('div', { className: 'rc-excerpt' }, body || '(暂无)'), ) return h('div', { className: 'page' }, renderTopbar('记忆', [ h('span', { className: 'date' }, (wb.project.name || '项目') + ' · 项目共识 v' + (memory?.revision ?? 0)), ]), h('div', { className: 'settings-stack' }, h('section', { className: 'card', 'aria-label': '项目共识' }, h('h3', null, '项目共识 ', h('span', { className: 'seat-tag' }, 'v' + (memory?.revision ?? 0))), h('div', { className: 'review-list' }, item('项目目标', 'goal', memory?.goal || '尚未填写项目目标', 'pass'), item('硬约束', (constraints.length || 0) + ' 条', constraints.join(';'), constraints.length ? 'pass' : 'idle'), item('验收标准', (acceptance.length || 0) + ' 条', acceptance.join(';'), acceptance.length ? 'pass' : 'idle'), ...decisions.slice(-5).map((decision, index) => item(decision.text || ('决定 ' + (index + 1)), decision.recordedAt ? dateText(decision.recordedAt) : '项目记录', decision.status === 'active' ? '现行决定' : '已归档', 'pass')), ), ), h('details', { className: 'card memory-editor', 'aria-label': '编辑项目共识' }, h('summary', null, h('span', null, '编辑项目共识'), h('span', { className: 'seat-tag' }, '可折叠')), h('div', { className: 'cfg-grid' }, h('label', { className: 'cfg-row', style: { gridColumn: '1 / -1' } }, '项目目标', h('textarea', { rows: 3, className: 'ssv-textarea', value: memoryDraft.goal, placeholder: '这个项目最终要达成什么', onChange: event => setMemoryDraft({ ...memoryDraft, goal: event.target.value }) })), h('label', { className: 'cfg-row', style: { gridColumn: '1 / -1' } }, '硬约束(每行一条)', h('textarea', { rows: 3, className: 'ssv-textarea', value: memoryDraft.constraints, placeholder: '例如:不能改动线上数据', onChange: event => setMemoryDraft({ ...memoryDraft, constraints: event.target.value }) })), h('label', { className: 'cfg-row', style: { gridColumn: '1 / -1' } }, '验收标准(每行一条)', h('textarea', { rows: 3, className: 'ssv-textarea', value: memoryDraft.acceptance, placeholder: '例如:交付前必须跑完回归测试', onChange: event => setMemoryDraft({ ...memoryDraft, acceptance: event.target.value }) })), h('label', { className: 'cfg-row', style: { gridColumn: '1 / -1' } }, '新增决定(每行一条)', h('textarea', { rows: 2, className: 'ssv-textarea', value: memoryDraft.decisions, placeholder: '例如:先保证稳定性,再考虑样式', onChange: event => setMemoryDraft({ ...memoryDraft, decisions: event.target.value }) })), ), h('div', { className: 'ws-actions' }, h('button', { type: 'button', className: 'btn primary', disabled: busy, onClick: saveMemory }, busy ? '保存中…' : '保存共识')), ), h('section', { className: 'card', 'aria-label': '成果' }, h('h3', null, '成果登记 ', h('span', { className: 'seat-tag' }, String(artifacts.length))), h('div', { className: 'ws-actions' }, h('button', { type: 'button', className: 'btn', onClick: () => setArtifactFormOpen(true) }, h(PlusIcon), '登记成果')), artifacts.length === 0 ? h('p', { className: 'empty-note' }, '还没有登记成果。') : h('ul', { className: 'skill-list' }, artifacts.slice(0, 8).map(artifact => h('li', { key: artifact.id }, h('span', { className: 'skill-name' }, artifact.title), h('span', { className: 'skill-state bound' }, h('i'), artifact.path || '已登记')))), ), ), ) } function renderSettings() { return h('div', { className: 'page' }, renderTopbar('设置'), h('div', { className: 'settings-stack' }, h('section', { className: 'card', 'aria-label': '项目绑定' }, h('h3', null, '项目绑定'), h('dl', { className: 'kv' }, h('dt', null, '当前项目'), h('dd', null, wb.project.name || '未命名项目'), h('dt', null, '类型'), h('dd', null, '主项目'), h('dt', null, '席位'), h('dd', null, wb.project.seatCount + ' 席'), h('dt', null, '工作区'), h('dd', null, wb.project.workspaceId || '—'), ), ), h('section', { className: 'card', 'aria-label': '席位开关' }, h('h3', null, '席位开关'), h('ul', { className: 'skill-list' }, SEAT_IDS.map(id => { const seat = seatById[id] const online = seat.status === 'bound' return h('li', { key: id }, h('span', { className: 'skill-name' }, seat.name + ' · ' + seat.duty), h('span', { className: 'skill-state' + (online ? ' bound' : '') }, h('i'), online ? '已上线' : (seat.status === 'missing' ? '会话缺失' : '未上线')), h('button', { type: 'button', className: 'skill-toggle', disabled: busy, onClick: () => { if (seat.status === 'missing') void rebuildSeat(id); else if (online) void openSeat(id); else void enableSeat(id) } }, seat.status === 'missing' ? '重建' : (online ? '打开' : '上线')), ) })), ), h('section', { className: 'card', 'aria-label': '角色职责' }, h('h3', null, '角色职责'), h('ul', { className: 'skill-list' }, SEAT_IDS.map(id => h('li', { key: id }, h('span', { className: 'skill-name' }, h('b', null, SEATS[id].label)), h('span', { className: 'skill-state bound' }, h('i'), SEATS[id].duty), h('span', { className: 'rc-meta' }, modelLabelOf(id)), ))), ), ), ) } function renderReviewPanel() { if (!reviewPanelOpen) return null return h('div', { className: 'modal-backdrop', onClick: event => { if (event.target === event.currentTarget) setReviewPanelOpen(false) } }, h('div', { className: 'modal wide', role: 'dialog', 'aria-modal': 'true', 'aria-labelledby': 'ssv-review-title' }, h('div', { className: 'modal-head' }, h('h3', { id: 'ssv-review-title' }, '待审核 · 门下复核'), h('button', { type: 'button', className: 'modal-close', 'aria-label': '关闭', onClick: () => setReviewPanelOpen(false) }, '✕')), h('p', { className: 'foot-note' }, '只读展示当前待门下复核的任务。'), reviewTasks.length === 0 ? h('p', { className: 'empty-note' }, '当前没有待审核任务。') : h('div', { className: 'review-list' }, reviewTasks.map(task => h('article', { className: 'review-card', key: task.id }, h('div', { className: 'rc-head' }, h('div', { className: 'rc-title' }, task.title), h('span', { className: 'rc-status ' + taskTone(task.status) }, h('i'), taskLabel(task.status))), h('div', { className: 'rc-meta-row' }, h('span', { className: 'rc-from' }, task.id || '—'), h('span', { className: 'rc-meta' }, task.dispatchedAt ? '派发 ' + dateText(task.dispatchedAt) : '尚未派发')), h(SummaryBlock, { text: task.result || task.goal || task.requirement || '', label: '审核材料', empty: '(暂无内容)', max: 110 }), h('div', { className: 'rc-actions' }, h('span', { className: 'spacer' }), h('button', { type: 'button', className: 'r-open', onClick: () => { setReviewPanelOpen(false); setSelectedTask(task) } }, '查看任务 →')), ))), ), ) } function renderDurationPanel() { if (!durationPanelOpen) return null const rows = tasks.map(task => ({ task, ms: taskDurationMs(task) })).filter(row => row.ms > 0).sort((a, b) => b.ms - a.ms) return h('div', { className: 'modal-backdrop', onClick: event => { if (event.target === event.currentTarget) setDurationPanelOpen(false) } }, h('div', { className: 'modal wide', role: 'dialog', 'aria-modal': 'true', 'aria-labelledby': 'ssv-duration-title' }, h('div', { className: 'modal-head' }, h('h3', { id: 'ssv-duration-title' }, '单任务耗时'), h('button', { type: 'button', className: 'modal-close', 'aria-label': '关闭', onClick: () => setDurationPanelOpen(false) }, '✕')), h('p', { className: 'foot-note' }, '按任务从派发到完成的时间累计;进行中任务算到当前时刻。'), rows.length === 0 ? h('p', { className: 'empty-note' }, '还没有可统计的任务耗时。') : h('div', { className: 'table-card' }, h('div', { className: 'table-scroll' }, h('table', null, h('thead', null, h('tr', null, ['任务', '承办', '状态', '耗时'].map(label => h('th', { key: label, scope: 'col' }, label)))), h('tbody', null, rows.map(row => h('tr', { key: row.task.id }, h('td', null, h('span', { className: 'task-name' }, row.task.title)), h('td', null, SEATS[row.task.ownerSeatId]?.label || row.task.ownerSeatId || '—'), h('td', null, h('span', { className: 'pill ' + taskTone(row.task.status) }, h('i'), taskLabel(row.task.status))), h('td', { className: 'dur' }, durationText(row.ms)), ))), ))), ), ) } function renderTokenPanel() { if (!tokenPanelOpen) return null return h('div', { className: 'modal-backdrop', onClick: event => { if (event.target === event.currentTarget) setTokenPanelOpen(false) } }, h('div', { className: 'modal wide', role: 'dialog', 'aria-modal': 'true', 'aria-labelledby': 'ssv-token-title' }, h('div', { className: 'modal-head' }, h('h3', { id: 'ssv-token-title' }, 'Token 用量'), h('button', { type: 'button', className: 'modal-close', 'aria-label': '关闭', onClick: () => setTokenPanelOpen(false) }, '✕')), h('section', { className: 'stats', style: { marginTop: '16px' }, 'aria-label': 'Token 统计' }, h('div', { className: 'stat' }, h('div', { className: 'label' }, 'Token 消耗'), h('div', { className: 'big' }, h('em', null, '—')), h('div', { className: 'foot' }, '待接入宿主 usage 数据')), h('div', { className: 'stat' }, h('div', { className: 'label' }, '上下文占用'), h('div', { className: 'big' }, h('em', null, '—')), h('div', { className: 'foot' }, '统计粒度待定:项目 / 会话 / 席位')), ), h('section', { className: 'card', style: { marginTop: '18px' }, 'aria-label': 'Token 接入说明' }, h('h3', null, '接入说明'), h('p', { className: 'foot-note', style: { marginTop: '8px' } }, '当前宿主尚未提供稳定的 usage 数据源,这里先占位,不展示估算值,避免假精确。接入真实用量后会展示 Token 消耗、上下文占用和消耗金额。'), ), )) } function renderArtifactModal() { if (!artifactFormOpen) return null return h('div', { className: 'modal-backdrop', onClick: event => { if (event.target === event.currentTarget) setArtifactFormOpen(false) } }, h('div', { className: 'modal', role: 'dialog', 'aria-modal': 'true', 'aria-labelledby': 'ssv-artifact-title' }, h('div', { className: 'modal-head' }, h('h3', { id: 'ssv-artifact-title' }, '登记成果'), h('button', { type: 'button', className: 'modal-close', 'aria-label': '关闭', onClick: () => setArtifactFormOpen(false) }, '✕')), h('div', { className: 'm-sec' }, h('span', { className: 't-label' }, '成果名称'), h('input', { type: 'text', value: artifactDraft.title, placeholder: '例如:竞品分析报告 v1', onChange: event => setArtifactDraft({ ...artifactDraft, title: event.target.value }) })), h('div', { className: 'm-sec' }, h('span', { className: 't-label' }, '文件路径'), h('input', { type: 'text', value: artifactDraft.path, placeholder: '例如:docs/竞品分析.md', onChange: event => setArtifactDraft({ ...artifactDraft, path: event.target.value }) })), h('div', { className: 'm-sec' }, h('span', { className: 't-label' }, '摘要'), h('textarea', { rows: 3, value: artifactDraft.summary, placeholder: '这份成果解决了什么、在哪里', onChange: event => setArtifactDraft({ ...artifactDraft, summary: event.target.value }) })), h('div', { className: 'modal-actions' }, h('button', { type: 'button', className: 'btn primary', disabled: busy, onClick: addArtifact }, busy ? '提交中…' : '登记'), h('button', { type: 'button', className: 'btn', onClick: () => setArtifactFormOpen(false) }, '取消')), ), ) } function renderTaskDetail() { if (!selectedTask) return null const task = tasks.find(item => item.id === selectedTask.id) || selectedTask const seat = SEATS[task.ownerSeatId] const requirement = requirements.find(item => item.id === task.requirementId && item.revision === task.requirementRevision) const originalRequirement = task.requirementSnapshot?.originalText || task.requirement || requirement?.originalText const taskDescription = task.goal || task.requirement const description = taskDescription === originalRequirement ? '' : taskDescription const consultations = task.consultations || [] return h('div', { className: 'modal-backdrop', onClick: event => { if (event.target === event.currentTarget) setSelectedTask(null) } }, h('div', { className: 'modal wide', role: 'dialog', 'aria-modal': 'true' }, h('div', { className: 'modal-head' }, h('h3', null, task.title), h('button', { type: 'button', className: 'modal-close', 'aria-label': '关闭', onClick: () => setSelectedTask(null) }, '✕')), h('div', { className: 'm-from' }, '派工编号:' + (task.id || '—') + ' · ' + (task.dispatchedAt ? '派发时间 ' + dateText(task.dispatchedAt) : '尚未派发')), originalRequirement ? h('div', { className: 'm-sec' }, h('span', { className: 't-label' }, '原始需求'), h('p', { className: 'task-original-text' }, originalRequirement), ) : null, description || !originalRequirement ? h('div', { className: 'm-sec' }, h('span', { className: 't-label' }, '任务说明'), h('div', { className: 'm-rich' }, description ? renderRichText(description) : h('p', { className: 'empty-note' }, '(无任务说明)')), ) : null, consultations.length ? h('section', { className: 'm-sec', 'aria-label': '会商记录' }, h('span', { className: 't-label' }, '会商记录'), h('div', { className: 'approval-list' }, consultations.map(entry => h('article', { className: 'approval-item', key: entry.id }, h('div', { className: 'req-meta' }, h('span', null, (SEATS[entry.fromSeatId]?.label || entry.fromSeatId) + ' → ' + entry.toSeatIds.map(id => SEATS[id]?.label || id).join('、')), h('span', null, dateText(entry.createdAt)), ), h('p', { className: 'task-original-text' }, entry.text), ))), ) : null, h('div', { className: 'm-sec' }, h('span', { className: 't-label' }, '承办与状态'), h('p', null, '承办席位:' + (seat ? seat.label : task.ownerSeatId) + ' · 模型:' + modelLabelOf(task.ownerSeatId) + ' · 状态:' + taskLabel(task.status) + (task.deliveryState && task.deliveryState !== 'none' ? ' · ' + deliveryLabel(task.deliveryState) : ''))), h('div', { className: 'm-sec' }, h('span', { className: 't-label' }, '任务完成情况'), h('div', { className: 'm-rich' }, task.result ? renderRichText(task.result) : h('p', { className: 'empty-note' }, '(暂无结果)'))), h('div', { className: 'modal-actions' }, h('button', { type: 'button', className: 'btn', onClick: () => setSelectedTask(null) }, '关闭')), ), ) } function renderPage() { if (phase === 'loading') return h('div', { className: 'page' }, h('p', { className: 'empty-note' }, '正在载入工作台…')) if (phase === 'no-workspace') return h('div', { className: 'page' }, h('p', { className: 'empty-note' }, '请先在宿主中选择或建立一个项目工作区,再打开三省六部工作台。')) if (phase === 'error' && !view) return h('div', { className: 'page' }, h('p', { className: 'ssv-banner is-error', role: 'alert' }, error || '工作台加载失败'), errorRetryable ? h('div', { className: 'ws-actions' }, h('button', { type: 'button', className: 'btn primary', onClick: loadProject }, '重试')) : null) if (tab === 'memory') return renderMemory() if (tab === 'settings') return renderSettings() return renderOverview() } return h('div', { className: 'ssv2 ssw-tab-body' }, h('div', { className: 'main' }, h('div', { className: 'panel-top' }, h('div', { className: 'brand' }, h('span', { className: 'seal' }, '三省六部'), h('span', { className: 'sub' }, 'DSH 工作台')), tab !== 'overview' ? h('div', { className: 'panel-actions' }, h('button', { type: 'button', className: 'btn', onClick: () => setTab('overview') }, '← 总览'), ) : null, ), statusBanner, renderPage(), h('div', { className: 'project-dock' }, h('button', { type: 'button', className: 'proj', 'aria-label': '当前项目', onClick: () => setTab('settings') }, h('span', { className: 'dot' }), h('span', null, h('span', { className: 'name' }, wb.project.name || wb.projectTitle || '当前项目'), h('br'), h('span', { className: 'meta' }, '主项目 · ' + wb.project.seatCount + ' 席')), h('span', { className: 'ssv-proj-caret' }, '⌄')), ), ), renderArtifactModal(), renderTaskDetail(), renderReviewPanel(), renderDurationPanel(), renderQueuePanel(), renderTokenPanel(), ) }