Release seat preset UI and dismiss obsolete question cards
This commit is contained in:
parent
c53e3d416c
commit
83caa1ae8a
1160
sansheng/client.js
1160
sansheng/client.js
File diff suppressed because it is too large
Load Diff
|
|
@ -1,10 +1,20 @@
|
|||
// 丞相会话内的非阻塞卡片行:按工具名 sansheng_card 注册到 tool.call.toolview。
|
||||
// 卡片状态来自项目 store(cardGet/cardAnswer),不占用聊天输入框,也不新造 session 事件。
|
||||
// 丞相/三省六部会话内的非阻塞卡片行:
|
||||
// 1. tool.call.toolview (sansheng_card):兼容原生未折叠工具视图;
|
||||
// 2. conversation.chat.turnTail:透出被 dsh-better-chat 折叠或被 run_code (:ptc:) 包裹的卡片,
|
||||
// 并结合实时 approvals 判断审批卡是否已失效/取消,避免点击死卡。
|
||||
import { createElement as h, useEffect, useState } from 'react'
|
||||
import { request } from './transport.js'
|
||||
import {
|
||||
collectTurnToolCalls,
|
||||
isApprovalCardExpired,
|
||||
matchTurnCards,
|
||||
} from './pending-model.js'
|
||||
|
||||
const COLORS = {
|
||||
line: 'var(--dsw-alias-border-l1, rgba(127,127,127,.28))',
|
||||
warnLine: 'rgba(196, 86, 60, .42)',
|
||||
warnBg: 'rgba(196, 86, 60, .08)',
|
||||
warnInk: 'var(--dsw-alias-state-error-primary, #b3261e)',
|
||||
bg: 'var(--dsw-alias-bg-base, transparent)',
|
||||
ink: 'var(--dsw-alias-label-primary, inherit)',
|
||||
muted: 'var(--dsw-alias-label-tertiary, #888)',
|
||||
|
|
@ -12,19 +22,216 @@ const COLORS = {
|
|||
accent: 'var(--dsw-alias-label-primary, currentColor)',
|
||||
}
|
||||
|
||||
const POLL_MS = 2000
|
||||
const workspaceProjectCache = new Map()
|
||||
const inflightWorkspaceLookups = new Map()
|
||||
const projectSubscriptions = new Map()
|
||||
|
||||
function errorText(error) {
|
||||
return error?.message ? error.message : String(error)
|
||||
}
|
||||
|
||||
function isStaleAnswerError(error) {
|
||||
if (error?.code === 'sansheng/approval-stale') return true
|
||||
const msg = errorText(error)
|
||||
return /已结束|已取消|不存在|失效|stale|expired/i.test(msg)
|
||||
}
|
||||
|
||||
function workspaceKey(ws) {
|
||||
if (!ws || (!ws.workspaceId && !ws.path)) return ''
|
||||
return (ws.workspaceId || '') + '|' + (ws.path || '')
|
||||
}
|
||||
|
||||
async function resolveExistingProjectId(ws) {
|
||||
const key = workspaceKey(ws)
|
||||
if (!key) return null
|
||||
const cached = workspaceProjectCache.get(key)
|
||||
if (cached && cached.expiresAt > Date.now()) return cached.projectId
|
||||
if (inflightWorkspaceLookups.has(key)) return inflightWorkspaceLookups.get(key)
|
||||
|
||||
const pending = (async () => {
|
||||
try {
|
||||
const listRes = await request('list')
|
||||
const items = Array.isArray(listRes?.projects) ? listRes.projects : []
|
||||
let matchedId = null
|
||||
if (items.length > 0) {
|
||||
const settled = await Promise.allSettled(
|
||||
items.map(item => request('project', { projectId: item.id })),
|
||||
)
|
||||
for (const res of settled) {
|
||||
if (res.status !== 'fulfilled') continue
|
||||
const project = res.value?.project ?? res.value
|
||||
if (!project?.id) continue
|
||||
const sameId = Boolean(ws.workspaceId && project.workspaceId === ws.workspaceId)
|
||||
const samePath = Boolean(ws.path && project.path === ws.path)
|
||||
if (sameId || samePath) {
|
||||
matchedId = project.id
|
||||
break
|
||||
}
|
||||
}
|
||||
}
|
||||
workspaceProjectCache.set(key, {
|
||||
projectId: matchedId,
|
||||
expiresAt: Date.now() + (matchedId ? 60000 : 4000),
|
||||
})
|
||||
return matchedId
|
||||
} catch {
|
||||
workspaceProjectCache.set(key, { projectId: null, expiresAt: Date.now() + 3000 })
|
||||
return null
|
||||
} finally {
|
||||
inflightWorkspaceLookups.delete(key)
|
||||
}
|
||||
})()
|
||||
|
||||
inflightWorkspaceLookups.set(key, pending)
|
||||
return pending
|
||||
}
|
||||
|
||||
async function fetchProjectCardState(projectId) {
|
||||
const entry = projectSubscriptions.get(projectId)
|
||||
if (!entry) return
|
||||
const [cardsRes, apprRes] = await Promise.allSettled([
|
||||
request('cards', { projectId }),
|
||||
request('approvals', { projectId }),
|
||||
])
|
||||
if (!projectSubscriptions.has(projectId)) return
|
||||
const prev = entry.data
|
||||
const next = {
|
||||
loaded: true,
|
||||
cards: cardsRes.status === 'fulfilled' && Array.isArray(cardsRes.value?.cards)
|
||||
? cardsRes.value.cards
|
||||
: prev.cards,
|
||||
approvals: apprRes.status === 'fulfilled' && Array.isArray(apprRes.value?.approvals)
|
||||
? apprRes.value.approvals
|
||||
: prev.approvals,
|
||||
approvalStatus: apprRes.status === 'fulfilled' && apprRes.value?.status
|
||||
? apprRes.value.status
|
||||
: prev.approvalStatus,
|
||||
}
|
||||
entry.data = next
|
||||
for (const listener of entry.listeners) listener(next)
|
||||
}
|
||||
|
||||
function refreshProjectCards(projectId) {
|
||||
if (!projectId) return undefined
|
||||
return fetchProjectCardState(projectId)
|
||||
}
|
||||
|
||||
function subscribeProjectCards(projectId, listener) {
|
||||
if (!projectId) return undefined
|
||||
let entry = projectSubscriptions.get(projectId)
|
||||
if (!entry) {
|
||||
entry = {
|
||||
listeners: new Set(),
|
||||
timer: null,
|
||||
data: { loaded: false, cards: [], approvals: [], approvalStatus: null },
|
||||
}
|
||||
projectSubscriptions.set(projectId, entry)
|
||||
void fetchProjectCardState(projectId)
|
||||
entry.timer = setInterval(() => { void fetchProjectCardState(projectId) }, POLL_MS)
|
||||
}
|
||||
entry.listeners.add(listener)
|
||||
if (entry.data.loaded) listener(entry.data)
|
||||
return () => {
|
||||
const cur = projectSubscriptions.get(projectId)
|
||||
if (!cur) return
|
||||
cur.listeners.delete(listener)
|
||||
if (cur.listeners.size === 0) {
|
||||
if (cur.timer) clearInterval(cur.timer)
|
||||
projectSubscriptions.delete(projectId)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function CardBox({ card, expired, busy, error, onAnswer, badgeNote }) {
|
||||
const answered = card.status === 'answered'
|
||||
const dismissed = card.status === 'dismissed'
|
||||
const options = Array.isArray(card.options) ? card.options : []
|
||||
const badgeText = card.kind === 'approval'
|
||||
? (expired ? '审批 · 已失效' : '审批')
|
||||
: (dismissed ? '问答 · 已删除' : '需要你回答')
|
||||
|
||||
return h('div', {
|
||||
style: {
|
||||
border: '1px solid ' + (expired ? COLORS.warnLine : COLORS.line),
|
||||
borderRadius: 10,
|
||||
background: expired ? COLORS.warnBg : COLORS.bg,
|
||||
padding: '12px 14px',
|
||||
margin: '4px 0',
|
||||
display: 'flex',
|
||||
flexDirection: 'column',
|
||||
gap: 8,
|
||||
maxWidth: 720,
|
||||
},
|
||||
'data-sansheng-card': card.id,
|
||||
'data-sansheng-card-status': expired ? 'expired' : card.status,
|
||||
},
|
||||
h('div', { style: { display: 'flex', alignItems: 'center', gap: 8, flexWrap: 'wrap' } },
|
||||
h('span', {
|
||||
style: {
|
||||
fontSize: 11,
|
||||
lineHeight: '18px',
|
||||
padding: '0 7px',
|
||||
borderRadius: 999,
|
||||
background: expired ? COLORS.warnBg : COLORS.soft,
|
||||
color: expired ? COLORS.warnInk : COLORS.muted,
|
||||
border: expired ? '1px solid ' + COLORS.warnLine : 'none',
|
||||
},
|
||||
}, badgeText),
|
||||
h('strong', { style: { fontSize: 14, color: COLORS.ink } }, card.title),
|
||||
badgeNote ? h('span', { style: { fontSize: 11, color: COLORS.muted, marginLeft: 'auto' } }, badgeNote) : null,
|
||||
),
|
||||
h('div', { style: { fontSize: 13, lineHeight: 1.7, color: COLORS.ink, whiteSpace: 'pre-wrap' } }, card.body),
|
||||
card.kind === 'approval' && (card.seatLabel || card.tool || card.reason)
|
||||
? h('div', { style: { fontSize: 12, lineHeight: 1.7, color: COLORS.muted, whiteSpace: 'pre-wrap' } },
|
||||
[card.seatLabel ? '申请:' + card.seatLabel : '', card.tool ? '操作:' + card.tool : '', card.reason ? '原因:' + card.reason : ''].filter(Boolean).join('\n'))
|
||||
: null,
|
||||
answered
|
||||
? h('div', { style: { fontSize: 13, color: COLORS.ink, fontWeight: 600 } }, '已选择:' + (card.answerLabel || card.answer || ''))
|
||||
: dismissed ? null : expired
|
||||
? h('div', {
|
||||
style: {
|
||||
fontSize: 12,
|
||||
lineHeight: 1.6,
|
||||
color: COLORS.warnInk,
|
||||
padding: '6px 8px',
|
||||
borderRadius: 6,
|
||||
background: 'rgba(196, 86, 60, .06)',
|
||||
},
|
||||
}, '关联的原审批请求已失效或已被取消(例如工具调用超时中断)。请查看席位是否已重发新卡,或在右侧「三省六部 -> 待你处理」查看最新审批。')
|
||||
: h('div', { style: { display: 'flex', flexWrap: 'wrap', gap: 8 } },
|
||||
options.map(option => h('button', {
|
||||
key: option.value,
|
||||
type: 'button',
|
||||
disabled: Boolean(busy),
|
||||
onClick: () => { onAnswer(option.value) },
|
||||
title: option.description || '',
|
||||
style: {
|
||||
border: '1px solid ' + COLORS.line,
|
||||
borderRadius: 8,
|
||||
background: busy === option.value ? COLORS.soft : 'transparent',
|
||||
color: COLORS.ink,
|
||||
padding: '6px 12px',
|
||||
cursor: busy ? 'default' : 'pointer',
|
||||
fontSize: 13,
|
||||
},
|
||||
}, busy === option.value ? '处理中…' : option.label))),
|
||||
error ? h('div', { style: { fontSize: 12, color: COLORS.warnInk } }, error) : null,
|
||||
answered || dismissed || expired ? null : h('div', { style: { fontSize: 12, color: COLORS.muted } }, '可以在聊天里继续,也可以去右侧「三省六部 -> 待你处理」统一处理。'))
|
||||
}
|
||||
|
||||
export function SanshengCardRow(props) {
|
||||
const callId = props?.callId || props?.block?.callId || ''
|
||||
const [card, setCard] = useState(null)
|
||||
const [projectState, setProjectState] = useState(null)
|
||||
const [staleExpired, setStaleExpired] = useState(false)
|
||||
const [error, setError] = useState('')
|
||||
const [busy, setBusy] = useState('')
|
||||
|
||||
useEffect(() => {
|
||||
if (!callId) return undefined
|
||||
let alive = true
|
||||
setStaleExpired(false)
|
||||
const load = async () => {
|
||||
try {
|
||||
const value = await request('cardGet', { cardId: callId })
|
||||
|
|
@ -40,6 +247,16 @@ export function SanshengCardRow(props) {
|
|||
return () => { alive = false; clearInterval(timer) }
|
||||
}, [callId])
|
||||
|
||||
const cardProjectId = card?.projectId || ''
|
||||
const needsApprovalWatch = Boolean(cardProjectId && card?.kind === 'approval' && card?.status === 'pending')
|
||||
useEffect(() => {
|
||||
if (!needsApprovalWatch) {
|
||||
setProjectState(null)
|
||||
return undefined
|
||||
}
|
||||
return subscribeProjectCards(cardProjectId, setProjectState)
|
||||
}, [needsApprovalWatch, cardProjectId])
|
||||
|
||||
const answer = async choice => {
|
||||
if (!callId || busy || card?.status === 'answered') return
|
||||
setBusy(choice)
|
||||
|
|
@ -47,8 +264,15 @@ export function SanshengCardRow(props) {
|
|||
try {
|
||||
const value = await request('cardAnswer', { cardId: callId, choice })
|
||||
setCard(value.card)
|
||||
if (cardProjectId) void refreshProjectCards(cardProjectId)
|
||||
} catch (answerError) {
|
||||
setError(errorText(answerError))
|
||||
if (isStaleAnswerError(answerError)) {
|
||||
setStaleExpired(true)
|
||||
setError('这条审批已经失效或被取消,无法再通过旧卡继续操作。')
|
||||
if (cardProjectId) void refreshProjectCards(cardProjectId)
|
||||
} else {
|
||||
setError(errorText(answerError))
|
||||
}
|
||||
} finally {
|
||||
setBusy('')
|
||||
}
|
||||
|
|
@ -59,62 +283,107 @@ export function SanshengCardRow(props) {
|
|||
return h('div', { style: { border: '1px solid ' + COLORS.line, borderRadius: 8, padding: '10px 12px', margin: '4px 0', color: COLORS.muted, fontSize: 13 } },
|
||||
error || '卡片加载中…')
|
||||
}
|
||||
const answered = card.status === 'answered'
|
||||
const options = Array.isArray(card.options) ? card.options : []
|
||||
return h('div', {
|
||||
style: {
|
||||
border: '1px solid ' + COLORS.line,
|
||||
borderRadius: 10,
|
||||
background: COLORS.bg,
|
||||
padding: '12px 14px',
|
||||
margin: '4px 0',
|
||||
display: 'flex',
|
||||
flexDirection: 'column',
|
||||
gap: 8,
|
||||
maxWidth: 720,
|
||||
},
|
||||
'data-sansheng-card': card.id,
|
||||
'data-sansheng-card-status': card.status,
|
||||
},
|
||||
h('div', { style: { display: 'flex', alignItems: 'center', gap: 8 } },
|
||||
h('span', {
|
||||
style: {
|
||||
fontSize: 11,
|
||||
lineHeight: '18px',
|
||||
padding: '0 7px',
|
||||
borderRadius: 999,
|
||||
background: COLORS.soft,
|
||||
color: COLORS.muted,
|
||||
},
|
||||
}, card.kind === 'approval' ? '审批' : '需要你回答'),
|
||||
h('strong', { style: { fontSize: 14, color: COLORS.ink } }, card.title),
|
||||
),
|
||||
h('div', { style: { fontSize: 13, lineHeight: 1.7, color: COLORS.ink, whiteSpace: 'pre-wrap' } }, card.body),
|
||||
card.kind === 'approval' && (card.seatLabel || card.tool || card.reason)
|
||||
? h('div', { style: { fontSize: 12, lineHeight: 1.7, color: COLORS.muted, whiteSpace: 'pre-wrap' } },
|
||||
[card.seatLabel ? '申请:' + card.seatLabel : '', card.tool ? '操作:' + card.tool : '', card.reason ? '原因:' + card.reason : ''].filter(Boolean).join('\n'))
|
||||
: null,
|
||||
answered
|
||||
? h('div', { style: { fontSize: 13, color: COLORS.ink, fontWeight: 600 } }, '已选择:' + (card.answerLabel || card.answer || ''))
|
||||
: h('div', { style: { display: 'flex', flexWrap: 'wrap', gap: 8 } },
|
||||
options.map(option => h('button', {
|
||||
key: option.value,
|
||||
type: 'button',
|
||||
disabled: Boolean(busy),
|
||||
onClick: () => { void answer(option.value) },
|
||||
title: option.description || '',
|
||||
style: {
|
||||
border: '1px solid ' + COLORS.line,
|
||||
borderRadius: 8,
|
||||
background: busy === option.value ? COLORS.soft : 'transparent',
|
||||
color: COLORS.ink,
|
||||
padding: '6px 12px',
|
||||
cursor: busy ? 'default' : 'pointer',
|
||||
fontSize: 13,
|
||||
},
|
||||
}, busy === option.value ? '处理中…' : option.label))),
|
||||
error ? h('div', { style: { fontSize: 12, color: 'var(--dsw-alias-state-error-primary, #b3261e)' } }, error) : null,
|
||||
answered ? null : h('div', { style: { fontSize: 12, color: COLORS.muted } }, '可以在聊天里继续,之后再回来点这张卡。'))
|
||||
const expired = staleExpired || (projectState
|
||||
? isApprovalCardExpired(card, projectState.approvals, projectState.approvalStatus)
|
||||
: false)
|
||||
|
||||
return h(CardBox, {
|
||||
card,
|
||||
expired,
|
||||
busy,
|
||||
error,
|
||||
onAnswer: choice => { void answer(choice) },
|
||||
})
|
||||
}
|
||||
|
||||
function TurnTailCardItem({ card, projectId, expired }) {
|
||||
const [localCard, setLocalCard] = useState(card)
|
||||
const [staleExpired, setStaleExpired] = useState(false)
|
||||
const [busy, setBusy] = useState('')
|
||||
const [error, setError] = useState('')
|
||||
|
||||
useEffect(() => {
|
||||
setLocalCard(card)
|
||||
}, [card])
|
||||
|
||||
const answer = async choice => {
|
||||
if (!localCard?.id || busy || localCard.status === 'answered') return
|
||||
setBusy(choice)
|
||||
setError('')
|
||||
try {
|
||||
const value = await request('cardAnswer', { cardId: localCard.id, choice })
|
||||
if (value?.card) setLocalCard(value.card)
|
||||
void refreshProjectCards(projectId)
|
||||
} catch (answerError) {
|
||||
if (isStaleAnswerError(answerError)) {
|
||||
setStaleExpired(true)
|
||||
setError('这条审批已经失效或被取消,无法再通过旧卡继续操作。')
|
||||
void refreshProjectCards(projectId)
|
||||
} else {
|
||||
setError(errorText(answerError))
|
||||
}
|
||||
} finally {
|
||||
setBusy('')
|
||||
}
|
||||
}
|
||||
|
||||
return h(CardBox, {
|
||||
card: localCard,
|
||||
expired: Boolean(expired || staleExpired),
|
||||
busy,
|
||||
error,
|
||||
badgeNote: String(localCard?.id || '').includes(':ptc:') ? 'PTC 内嵌卡片' : null,
|
||||
onAnswer: choice => { void answer(choice) },
|
||||
})
|
||||
}
|
||||
|
||||
export function createTurnTailCards({ getWorkspace } = {}) {
|
||||
return function TurnTailCards(props) {
|
||||
const { callIds, hasCardOrPtcCall } = collectTurnToolCalls(props?.turn)
|
||||
const callIdsKey = callIds.join('|')
|
||||
const ws = typeof getWorkspace === 'function' ? getWorkspace() : null
|
||||
const wsKey = workspaceKey(ws)
|
||||
const [projectId, setProjectId] = useState(null)
|
||||
const [projectState, setProjectState] = useState(null)
|
||||
|
||||
useEffect(() => {
|
||||
if (!hasCardOrPtcCall || !callIdsKey || !wsKey) {
|
||||
setProjectId(null)
|
||||
return undefined
|
||||
}
|
||||
let alive = true
|
||||
void resolveExistingProjectId(ws).then(pid => {
|
||||
if (alive) setProjectId(pid)
|
||||
})
|
||||
return () => { alive = false }
|
||||
}, [hasCardOrPtcCall, callIdsKey, wsKey])
|
||||
|
||||
useEffect(() => {
|
||||
if (!projectId) {
|
||||
setProjectState(null)
|
||||
return undefined
|
||||
}
|
||||
return subscribeProjectCards(projectId, setProjectState)
|
||||
}, [projectId])
|
||||
|
||||
if (!hasCardOrPtcCall || callIds.length === 0 || !projectState) return null
|
||||
const matched = matchTurnCards(projectState.cards, callIds)
|
||||
const inBetterChat = Boolean(props && Object.prototype.hasOwnProperty.call(props, 'readerProducedPaths'))
|
||||
const visibleCards = inBetterChat
|
||||
? matched
|
||||
: matched.filter(c => String(c?.id || '').includes(':ptc:'))
|
||||
if (visibleCards.length === 0) return null
|
||||
|
||||
return h('div', {
|
||||
style: { display: 'flex', flexDirection: 'column', gap: 6, marginTop: 6 },
|
||||
'data-sansheng-turn-cards': String(visibleCards.length),
|
||||
}, visibleCards.map(card => h(TurnTailCardItem, {
|
||||
key: card.id,
|
||||
card,
|
||||
projectId,
|
||||
expired: isApprovalCardExpired(card, projectState.approvals, projectState.approvalStatus),
|
||||
})))
|
||||
}
|
||||
}
|
||||
|
||||
export default SanshengCardRow
|
||||
|
|
@ -7,7 +7,7 @@ import { WorkbenchV2 } from './workbench-v2.js'
|
|||
import { MasterWorkbench } from './master-workbench.js'
|
||||
import { workspaceForSession, workspaceItemsFromSnapshot, sessionSummaryFromSnapshot } from './workspace.js'
|
||||
import { CSS as WORKBENCH_CSS } from './styles.js'
|
||||
import { SanshengCardRow } from './cards.js'
|
||||
import { SanshengCardRow, createTurnTailCards } from './cards.js'
|
||||
|
||||
export const inject = ['sessions', 'workspaces', 'uiWorkspace', 'uiConversation', 'slots', 'theme', 'layout', 'sidebarRightTabs', 'sidebarRight']
|
||||
|
||||
|
|
@ -582,8 +582,25 @@ export function apply(ctx) {
|
|||
}
|
||||
}
|
||||
|
||||
function registerTurnTailCards() {
|
||||
if (!ctx.slots || !isFn(ctx.slots.inject) || !isFn(ctx.slots.register)) return
|
||||
try {
|
||||
const TurnTailCards = createTurnTailCards({
|
||||
getWorkspace: () => workspaceForSessionId(currentSessionId()),
|
||||
})
|
||||
ctx.slots.inject('conversation.chat.turnTail', () => ctx.slots.register({
|
||||
name: 'conversation.chat.turnTail',
|
||||
id: 'dsh-sansheng:turn-tail-cards',
|
||||
order: 20,
|
||||
}, TurnTailCards))
|
||||
} catch (error) {
|
||||
console.warn('[sansheng] 注册回合尾部卡片失败:', error && error.message ? error.message : error)
|
||||
}
|
||||
}
|
||||
|
||||
registerNavEntry()
|
||||
registerCardToolview()
|
||||
registerTurnTailCards()
|
||||
|
||||
// 原生右栏先等一个短窗口:若并行子插件已接管,rightTabOpener 会在 apply 时挂上,这里就跳过。
|
||||
const nativeRightTabTimer = setTimeout(() => {
|
||||
|
|
|
|||
|
|
@ -1,7 +1,8 @@
|
|||
// 主工作台总台(跨项目任务看板):仅使用 createElement,样式全部来自 styles.js (.ssmwb),数据全走 /api/sansheng。
|
||||
import { createElement as h, useCallback, useEffect, useMemo, useRef, useState } from 'react'
|
||||
import { SEAT_GROUPS, SEATS } from '../shared/roles.js'
|
||||
import { collectModelOptions } from './workbench.js'
|
||||
import { collectModelOptions, PRESET_OPTIONS, presetShortLabel, recommendedPresetForSeat } from './workbench.js'
|
||||
import { mergePendingItems } from './pending-model.js'
|
||||
import { request } from './transport.js'
|
||||
import {
|
||||
buildMasterItems,
|
||||
|
|
@ -89,9 +90,11 @@ export function MasterWorkbench(props) {
|
|||
const [projects, setProjects] = useState([])
|
||||
const [bundles, setBundles] = useState([])
|
||||
const [approvals, setApprovals] = useState([])
|
||||
const [questionCards, setQuestionCards] = useState([])
|
||||
const [degradedInfo, setDegradedInfo] = useState(null)
|
||||
const [modelsCatalog, setModelsCatalog] = useState(null)
|
||||
const [globalDefaults, setGlobalDefaults] = useState(null)
|
||||
const [globalPresetDraft, setGlobalPresetDraft] = useState({})
|
||||
|
||||
const [projectFilter, setProjectFilter] = useState('all')
|
||||
const [projMenuOpen, setProjMenuOpen] = useState(false)
|
||||
|
|
@ -153,14 +156,15 @@ export function MasterWorkbench(props) {
|
|||
])
|
||||
|
||||
const detailSettled = await Promise.all(projList.map(async (summary) => {
|
||||
const [projR, tasksR, reqsR, apprR, artR] = await Promise.allSettled([
|
||||
const [projR, tasksR, reqsR, apprR, artR, cardR] = await Promise.allSettled([
|
||||
request('project', { projectId: summary.id }),
|
||||
request('tasks', { projectId: summary.id }),
|
||||
request('requirements', { projectId: summary.id }),
|
||||
request('approvals', { projectId: summary.id }),
|
||||
request('artifacts', { projectId: summary.id }),
|
||||
request('cards', { projectId: summary.id }),
|
||||
])
|
||||
return { summary, projR, tasksR, reqsR, apprR, artR }
|
||||
return { summary, projR, tasksR, reqsR, apprR, artR, cardR }
|
||||
}))
|
||||
|
||||
if (!alive.current) return
|
||||
|
|
@ -194,21 +198,30 @@ export function MasterWorkbench(props) {
|
|||
|
||||
if (answerVersion.current === startVer) {
|
||||
const nextApprovals = []
|
||||
const nextQuestionCards = []
|
||||
let degraded = null
|
||||
detailSettled.forEach(({ summary, apprR }, idx) => {
|
||||
detailSettled.forEach(({ summary, apprR, cardR }, idx) => {
|
||||
const colorVar = PROJECT_DOT_VARS[idx % PROJECT_DOT_VARS.length]
|
||||
if (apprR.status === 'fulfilled') {
|
||||
const st = apprR.value?.status
|
||||
if (st?.degraded) degraded = st.reason || 'approval-center-degraded'
|
||||
const list = Array.isArray(apprR.value?.approvals) ? apprR.value.approvals : []
|
||||
for (const entry of list) {
|
||||
nextApprovals.push({ ...entry, projectId: entry.projectId || summary.id, projectName: summary.name, colorVar })
|
||||
}
|
||||
} else {
|
||||
degraded = apprR.reason?.message || '审批队列暂不可达'
|
||||
const st = apprR.status === 'fulfilled'
|
||||
? apprR.value?.status
|
||||
: { degraded: true, reason: apprR.reason?.message || '审批队列暂不可达' }
|
||||
if (st?.degraded) degraded = st.reason || 'approval-center-degraded'
|
||||
const apprList = apprR.status === 'fulfilled' && Array.isArray(apprR.value?.approvals)
|
||||
? apprR.value.approvals
|
||||
: []
|
||||
const cardList = cardR.status === 'fulfilled' && Array.isArray(cardR.value?.cards)
|
||||
? cardR.value.cards
|
||||
: []
|
||||
const merged = mergePendingItems({ approvals: apprList, approvalStatus: st, cards: cardList, tasks: [] })
|
||||
for (const entry of merged.approvals) {
|
||||
nextApprovals.push({ ...entry, projectId: entry.projectId || summary.id, projectName: summary.name, colorVar })
|
||||
}
|
||||
for (const q of merged.questions) {
|
||||
nextQuestionCards.push({ ...q, projectId: q.projectId || summary.id, projectName: summary.name, colorVar })
|
||||
}
|
||||
})
|
||||
setApprovals(nextApprovals)
|
||||
setQuestionCards(nextQuestionCards)
|
||||
setDegradedInfo(degraded)
|
||||
}
|
||||
setLoading(false)
|
||||
|
|
@ -298,6 +311,10 @@ export function MasterWorkbench(props) {
|
|||
if (projectFilter !== 'all' && a.projectId !== projectFilter) continue
|
||||
out.push({ kind: 'approval', data: a })
|
||||
}
|
||||
for (const q of questionCards) {
|
||||
if (projectFilter !== 'all' && q.projectId !== projectFilter) continue
|
||||
out.push({ kind: 'question', data: q })
|
||||
}
|
||||
for (const item of allItems) {
|
||||
if (projectFilter !== 'all' && item.projectId !== projectFilter) continue
|
||||
for (const d of item.decisions || []) {
|
||||
|
|
@ -305,7 +322,7 @@ export function MasterWorkbench(props) {
|
|||
}
|
||||
}
|
||||
return out
|
||||
}, [approvals, allItems, projectFilter])
|
||||
}, [approvals, questionCards, allItems, projectFilter])
|
||||
|
||||
const hasPendingBlock = pendingExpanded && (pendingEntries.length > 0 || Boolean(degradedInfo))
|
||||
const layoutMode = computeMasterLayoutMode(frameWidth, hasPendingBlock)
|
||||
|
|
@ -318,6 +335,7 @@ export function MasterWorkbench(props) {
|
|||
const meta = projectMetaById.get(pid)
|
||||
const activeCnt = allItems.filter(it => it.projectId === pid && it.col !== 'done').length
|
||||
const pendCnt = approvals.filter(a => a.projectId === pid).length
|
||||
+ questionCards.filter(q => q.projectId === pid).length
|
||||
+ allItems.filter(it => it.projectId === pid).reduce((acc, it) => acc + (it.decisions || []).filter(d => d.status === 'pending').length, 0)
|
||||
return {
|
||||
id: pid,
|
||||
|
|
@ -327,9 +345,11 @@ export function MasterWorkbench(props) {
|
|||
activeCnt,
|
||||
pendCnt,
|
||||
}
|
||||
}), [bundles, projectMetaById, allItems, approvals])
|
||||
}), [bundles, projectMetaById, allItems, approvals, questionCards])
|
||||
|
||||
const totalPendingAll = approvals.length + allItems.reduce((acc, it) => acc + (it.decisions || []).filter(d => d.status === 'pending').length, 0)
|
||||
const totalPendingAll = approvals.length
|
||||
+ questionCards.length
|
||||
+ allItems.reduce((acc, it) => acc + (it.decisions || []).filter(d => d.status === 'pending').length, 0)
|
||||
const totalActiveAll = allItems.filter(it => it.col !== 'done').length
|
||||
const doneItems = useMemo(() => visibleItems.filter(it => it.col === 'done'), [visibleItems])
|
||||
|
||||
|
|
@ -390,6 +410,44 @@ export function MasterWorkbench(props) {
|
|||
}
|
||||
}
|
||||
|
||||
async function dismissQuestion(card) {
|
||||
if (!card?.projectId || busy || !globalThis.confirm('删除这张问答卡片?它会从「待你处理」移除。')) return
|
||||
setBusy(true)
|
||||
try {
|
||||
answerVersion.current += 1
|
||||
await request('cardDismiss', { projectId: card.projectId, cardId: card.id })
|
||||
if (!alive.current) return
|
||||
setQuestionCards(prev => prev.filter(item => item.projectId !== card.projectId || item.id !== card.id))
|
||||
showToast('已删除问答卡片', 'success')
|
||||
await loadAll({ silent: true })
|
||||
} catch (error) {
|
||||
if (alive.current) showToast(error?.message || '删除问答卡片失败', 'error')
|
||||
} finally {
|
||||
if (alive.current) setBusy(false)
|
||||
}
|
||||
}
|
||||
|
||||
async function handleCardAnswer(card, choice) {
|
||||
if (!card?.id || busy) return
|
||||
setBusy(true)
|
||||
try {
|
||||
answerVersion.current += 1
|
||||
await request('cardAnswer', { cardId: card.id, choice })
|
||||
setQuestionCards(prev => prev.filter(q => q.id !== card.id))
|
||||
if (card.kind === 'approval' && card.approvalId) {
|
||||
setApprovals(prev => prev.filter(a => a.id !== card.approvalId))
|
||||
}
|
||||
showToast('已提交卡片选择', 'success')
|
||||
await loadAll({ silent: true })
|
||||
} catch (error) {
|
||||
const stale = error?.code === 'sansheng/approval-stale' || /失效|已结束|已取消|stale|expired/i.test(error?.message || '')
|
||||
showToast(stale ? '该审批卡已失效或被取消,已刷新最新队列' : (error?.message || '卡片提交失败'), 'error')
|
||||
await loadAll({ silent: true })
|
||||
} finally {
|
||||
if (alive.current) setBusy(false)
|
||||
}
|
||||
}
|
||||
|
||||
async function handleDecision(item, decision, option) {
|
||||
if (!item || !decision || !option || busy) return
|
||||
setBusy(true)
|
||||
|
|
@ -507,6 +565,7 @@ export function MasterWorkbench(props) {
|
|||
pendingEntries.map(entry => {
|
||||
if (entry.kind === 'approval') {
|
||||
const a = entry.data
|
||||
const cardOpts = Array.isArray(a.card?.options) && a.card.options.length > 0 ? a.card.options : null
|
||||
return h('article', { className: 'frameless-item', key: 'apr:' + a.sessionId + ':' + a.id },
|
||||
h('div', { className: 'frameless-item-head' },
|
||||
h('span', { style: { display: 'inline-flex', alignItems: 'center', gap: 6, minWidth: 0 } },
|
||||
|
|
@ -514,19 +573,60 @@ export function MasterWorkbench(props) {
|
|||
h('span', { className: 'font-mono-num truncate', style: { fontSize: 12, fontWeight: 500 } }, a.projectName || a.projectId),
|
||||
),
|
||||
h('span', { style: { display: 'inline-flex', alignItems: 'center', gap: 6, marginLeft: 'auto' } },
|
||||
h('span', { className: 'frameless-chip is-err' }, h('span', { className: 'ss-dot is-error' }), '工具审批'),
|
||||
h('span', { className: 'frameless-chip is-err' }, h('span', { className: 'ss-dot is-error' }), cardOpts ? '审批卡片' : '工具审批'),
|
||||
h('span', { className: 'font-seal', style: { fontWeight: 700, fontSize: 13 } }, SEATS[a.seatId]?.label || a.seatId),
|
||||
),
|
||||
),
|
||||
a.card?.title ? h('div', { style: { fontSize: 12, fontWeight: 600, color: 'var(--ss-fg)' } }, a.card.title) : null,
|
||||
h('div', { className: 'frameless-code' },
|
||||
a.tool ? h('span', { className: 'font-mono-num', style: { color: 'var(--ss-muted)', marginRight: 6 } }, '[' + a.tool + ']') : null,
|
||||
a.reason || a.detail?.text || '等待工具授权',
|
||||
a.card?.body || a.reason || a.detail?.text || '等待工具授权',
|
||||
),
|
||||
h('div', { className: 'frameless-actions' },
|
||||
h('button', { type: 'button', className: 'frameless-link', disabled: busy, onClick: () => void handleOpenSeat(a.projectId, a.seatId) }, '查看会话 ↗'),
|
||||
cardOpts
|
||||
? h('div', { className: 'frameless-btn-group' },
|
||||
cardOpts.map((opt, idx) => h('button', {
|
||||
key: opt.value,
|
||||
type: 'button',
|
||||
className: opt.value === 'allow' || idx === 0 ? 'frameless-primary-btn' : 'frameless-btn',
|
||||
disabled: busy,
|
||||
onClick: () => void handleCardAnswer(a.card, opt.value),
|
||||
}, opt.label)))
|
||||
: h('div', { className: 'frameless-btn-group' },
|
||||
h('button', { type: 'button', className: 'frameless-btn', disabled: busy, onClick: () => void handleApproval(a, 'reject') }, '拒绝'),
|
||||
h('button', { type: 'button', className: 'frameless-primary-btn', disabled: busy, onClick: () => void handleApproval(a, 'allow') }, '允许一次'),
|
||||
),
|
||||
),
|
||||
)
|
||||
}
|
||||
if (entry.kind === 'question') {
|
||||
const q = entry.data
|
||||
return h('article', { className: 'frameless-item', key: 'qcard:' + (q.projectId || '') + ':' + q.id },
|
||||
h('div', { className: 'frameless-item-head' },
|
||||
h('span', { style: { display: 'inline-flex', alignItems: 'center', gap: 6, minWidth: 0 } },
|
||||
h('span', { style: { width: 8, height: 8, borderRadius: '50%', background: 'var(' + (q.colorVar || '--ss-primary') + ')', flexShrink: 0 } }),
|
||||
h('span', { className: 'font-mono-num truncate', style: { fontSize: 12, fontWeight: 500 } }, q.projectName || q.projectId),
|
||||
),
|
||||
h('span', { style: { display: 'inline-flex', alignItems: 'center', gap: 6, marginLeft: 'auto' } },
|
||||
h('span', { className: 'frameless-chip is-pri' }, h('span', { className: 'ss-dot is-primary' }), '问答卡片'),
|
||||
h('span', { className: 'font-seal', style: { fontWeight: 700, fontSize: 13 } }, q.seatLabel || SEATS[q.seatId]?.label || '丞相'),
|
||||
h('button', { type: 'button', className: 'frameless-link', disabled: busy, onClick: () => void dismissQuestion(q) }, '删除'),
|
||||
),
|
||||
),
|
||||
h('div', { style: { fontSize: 12, fontWeight: 600, color: 'var(--ss-fg)' } }, q.title),
|
||||
q.body ? h('div', { className: 'frameless-code' }, q.body) : null,
|
||||
h('div', { className: 'frameless-actions' },
|
||||
q.seatId ? h('button', { type: 'button', className: 'frameless-link', disabled: busy, onClick: () => void handleOpenSeat(q.projectId, q.seatId) }, '查看会话 ↗') : h('span'),
|
||||
h('div', { className: 'frameless-btn-group' },
|
||||
h('button', { type: 'button', className: 'frameless-btn', disabled: busy, onClick: () => void handleApproval(a, 'reject') }, '拒绝'),
|
||||
h('button', { type: 'button', className: 'frameless-primary-btn', disabled: busy, onClick: () => void handleApproval(a, 'allow') }, '允许一次'),
|
||||
(q.options || []).map(opt => h('button', {
|
||||
key: opt.value,
|
||||
type: 'button',
|
||||
className: 'frameless-btn',
|
||||
disabled: busy,
|
||||
title: opt.description || '',
|
||||
onClick: () => void handleCardAnswer(q, opt.value),
|
||||
}, opt.label)),
|
||||
),
|
||||
),
|
||||
)
|
||||
|
|
@ -909,11 +1009,35 @@ export function MasterWorkbench(props) {
|
|||
{ title: '六部', ids: SEAT_GROUPS.liubu },
|
||||
]
|
||||
const gSeats = globalDefaults?.seats || {}
|
||||
return h('aside', { className: 'mwb-split-drawer', 'aria-label': '全局默认模型配置' },
|
||||
const gPresets = globalDefaults?.seatPresets || globalDefaults?.presets || {}
|
||||
const globalPresetSupported = Boolean(globalDefaults?.capabilities?.seatPreset || globalDefaults?.seatPresets || globalDefaults?.presets)
|
||||
const handleGlobalPresetChange = async (sid, nextPreset) => {
|
||||
if (!globalPresetSupported) {
|
||||
setGlobalPresetDraft(prev => ({ ...prev, [sid]: nextPreset }))
|
||||
showToast('已记录「' + (SEATS[sid]?.label || sid) + '」执行模式偏好预览;写入生效需待后续后端改造完成', 'primary')
|
||||
return
|
||||
}
|
||||
setBusy(true)
|
||||
try {
|
||||
const res = await request('setGlobalDefault', {
|
||||
seatId: sid,
|
||||
model: gSeats[sid] ?? null,
|
||||
agentPreset: nextPreset || null,
|
||||
})
|
||||
if (res?.globalDefaults) setGlobalDefaults(res.globalDefaults)
|
||||
showToast('已更新「' + (SEATS[sid]?.label || sid) + '」全局默认执行模式', 'success')
|
||||
await loadAll({ silent: true })
|
||||
} catch (error) {
|
||||
showToast(error?.message || '全局默认执行模式保存失败', 'error')
|
||||
} finally {
|
||||
if (alive.current) setBusy(false)
|
||||
}
|
||||
}
|
||||
return h('aside', { className: 'mwb-split-drawer', 'aria-label': '全局默认模型与模式配置' },
|
||||
h('div', { className: 'mwb-drawer-head' },
|
||||
h('div', { style: { display: 'flex', alignItems: 'center', justifyContent: 'space-between', gap: 8 } },
|
||||
h('div', null,
|
||||
h('h2', { style: { margin: 0, fontSize: 14, fontWeight: 600 } }, '全局默认模型(R-001)'),
|
||||
h('h2', { style: { margin: 0, fontSize: 14, fontWeight: 600 } }, '全局默认模型与模式(R-001)'),
|
||||
h('p', { className: 'font-mono-num truncate', style: { margin: '2px 0 0', fontSize: 12, color: 'var(--ss-muted)' } }, globalDefaults?.path || '~/.dsh/sansheng-liubu/setting.json'),
|
||||
),
|
||||
h('button', { type: 'button', className: 'wb-modal-close', 'aria-label': '关闭抽屉', onClick: () => setDrawer(null) }, '✕'),
|
||||
|
|
@ -921,6 +1045,21 @@ export function MasterWorkbench(props) {
|
|||
),
|
||||
h('div', { className: 'mwb-drawer-body' },
|
||||
h('p', { style: { margin: 0, color: 'var(--ss-muted)', lineHeight: 1.55 } }, '点击任一席位展开调整;未设项目覆盖的席位自动从此处读取全局默认。'),
|
||||
h('div', { className: 'mwb-card-ticker', style: { display: 'flex', flexDirection: 'column', gap: 6 } },
|
||||
h('span', null, '建议模式分工:中枢 / 三省走「标准模式」防 2 分钟审批超时;六部走「OPS PTC」批量读写。' + (globalPresetSupported ? '' : '(当前展示前端推荐,持久化待后端启用)')),
|
||||
h('button', {
|
||||
type: 'button',
|
||||
className: 'frameless-btn',
|
||||
style: { alignSelf: 'flex-start' },
|
||||
disabled: busy,
|
||||
onClick: () => {
|
||||
const next = {}
|
||||
for (const g of groups) for (const id of g.ids) next[id] = recommendedPresetForSeat(id)
|
||||
setGlobalPresetDraft(next)
|
||||
showToast('已在全局配置中按角色填入推荐模式分工(中枢/三省=标准,六部=PTC)' + (globalPresetSupported ? '' : ';待后端启用写入后生效'), 'primary')
|
||||
},
|
||||
}, '按角色填入推荐模式'),
|
||||
),
|
||||
groups.map(group => h('div', { key: group.title, style: { display: 'flex', flexDirection: 'column', gap: 6 } },
|
||||
h('div', { style: { padding: '0 4px', fontWeight: 500, color: 'var(--ss-muted)' } }, group.title),
|
||||
h('div', { className: 'mwb-gcfg-group' }, group.ids.map(sid => {
|
||||
|
|
@ -934,6 +1073,11 @@ export function MasterWorkbench(props) {
|
|||
: modelChoices
|
||||
const isOpen = expandedGlobalSeatId === sid
|
||||
const previewText = current ? shortModelName(current) : '未设置(回退部署默认)'
|
||||
const recPreset = recommendedPresetForSeat(sid)
|
||||
const currentPreset = Object.prototype.hasOwnProperty.call(globalPresetDraft, sid)
|
||||
? globalPresetDraft[sid]
|
||||
: (gPresets[sid] || '')
|
||||
const modeShort = currentPreset ? presetShortLabel(currentPreset) : ('荐·' + presetShortLabel(recPreset))
|
||||
return h('div', { key: sid, className: 'mwb-gcfg-item' + (isOpen ? ' is-open' : '') },
|
||||
h('button', {
|
||||
type: 'button',
|
||||
|
|
@ -945,7 +1089,8 @@ export function MasterWorkbench(props) {
|
|||
h('span', { className: 'font-seal', style: { fontWeight: 700, fontSize: 14, flexShrink: 0 } }, meta.label),
|
||||
h('span', { className: 'truncate', style: { color: 'var(--ss-muted)' } }, meta.duty),
|
||||
),
|
||||
h('span', { style: { display: 'flex', alignItems: 'center', gap: 8, flexShrink: 0 } },
|
||||
h('span', { style: { display: 'flex', alignItems: 'center', gap: 6, flexShrink: 0 } },
|
||||
h('span', { className: 'ss-pill', style: { color: currentPreset ? 'var(--ss-primary)' : 'var(--ss-muted)' } }, modeShort),
|
||||
h('span', { className: 'ss-pill font-mono-num', style: { color: current ? 'var(--ss-fg)' : 'var(--ss-muted)' } }, previewText),
|
||||
ChevronDownSvg({ style: { color: isOpen ? 'var(--ss-primary)' : 'var(--ss-muted)', transform: isOpen ? 'rotate(180deg)' : 'none', transition: 'transform 150ms ease' } }),
|
||||
),
|
||||
|
|
@ -982,6 +1127,18 @@ export function MasterWorkbench(props) {
|
|||
),
|
||||
),
|
||||
),
|
||||
h('label', { style: { display: 'flex', flexDirection: 'column', gap: 4 } },
|
||||
h('span', { style: { color: 'var(--ss-muted)' } }, '执行模式(推荐:' + (recPreset === 'standard' ? '标准模式' : 'OPS PTC') + ')'),
|
||||
h('select', {
|
||||
className: 'wb-select',
|
||||
disabled: busy,
|
||||
value: currentPreset,
|
||||
onChange: (e) => void handleGlobalPresetChange(sid, e.target.value),
|
||||
},
|
||||
h('option', { value: '' }, '按角色推荐(推荐:' + (recPreset === 'standard' ? '标准模式' : 'OPS PTC') + ')'),
|
||||
PRESET_OPTIONS.map(opt => h('option', { key: opt.value, value: opt.value }, opt.label)),
|
||||
),
|
||||
),
|
||||
h('div', { style: { display: 'flex', alignItems: 'center', justifyContent: 'space-between', gap: 8 } },
|
||||
h('button', {
|
||||
type: 'button',
|
||||
|
|
|
|||
|
|
@ -0,0 +1,98 @@
|
|||
// 纯客户端逻辑:合并原生审批 / 非阻塞卡片 / 任务决定 / 流程阻塞,以及从回合提取工具调用 ID。
|
||||
// 不依赖 React 或 DOM,可直接由 node:test 导入验证。
|
||||
|
||||
export function collectTurnToolCalls(turn) {
|
||||
const callIds = []
|
||||
const seen = new Set()
|
||||
let hasCardOrPtcCall = false
|
||||
|
||||
const record = (callId, name) => {
|
||||
if (typeof callId !== 'string' || !callId) return
|
||||
if (!seen.has(callId)) {
|
||||
seen.add(callId)
|
||||
callIds.push(callId)
|
||||
}
|
||||
if (name === 'sansheng_card' || name === 'run_code') hasCardOrPtcCall = true
|
||||
}
|
||||
|
||||
const visitBlock = block => {
|
||||
if (!block || typeof block !== 'object') return
|
||||
const callId = block.callId
|
||||
const name = 'kind' in block ? block.call?.name : block.name
|
||||
record(callId, name)
|
||||
if (Array.isArray(block.subCalls)) {
|
||||
for (const child of block.subCalls) visitBlock(child)
|
||||
}
|
||||
}
|
||||
|
||||
const steps = Array.isArray(turn?.steps) ? turn.steps : []
|
||||
for (const step of steps) {
|
||||
const assistant = step?.data?.get?.('assistant-step') ?? step?.assistantStep
|
||||
const blocks = Array.isArray(assistant?.blocks) ? assistant.blocks : []
|
||||
for (const block of blocks) {
|
||||
if (block?.kind === 'tool-call') record(block.callId, block.name)
|
||||
}
|
||||
const nodes = Array.isArray(step?.nodes) ? step.nodes : []
|
||||
for (const node of nodes) {
|
||||
if (node?.kind === 'tool-call' && node.data?.root) visitBlock(node.data.root)
|
||||
}
|
||||
}
|
||||
|
||||
return { callIds, hasCardOrPtcCall }
|
||||
}
|
||||
|
||||
export function matchTurnCards(cards, callIds) {
|
||||
if (!Array.isArray(cards) || !Array.isArray(callIds) || callIds.length === 0) return []
|
||||
return cards.filter(card => {
|
||||
const id = typeof card?.id === 'string' ? card.id : ''
|
||||
if (!id) return false
|
||||
return callIds.some(cid => id === cid || id.startsWith(cid + ':'))
|
||||
})
|
||||
}
|
||||
|
||||
export function isApprovalCardExpired(card, approvals, approvalStatus) {
|
||||
if (!card || card.kind !== 'approval' || card.status !== 'pending') return false
|
||||
if (!approvalStatus || approvalStatus.degraded) return false
|
||||
const list = Array.isArray(approvals) ? approvals : []
|
||||
return !list.some(entry => entry && entry.id === card.approvalId)
|
||||
}
|
||||
|
||||
export function mergePendingItems({ approvals = [], approvalStatus = null, cards = [], tasks = [] } = {}) {
|
||||
const degraded = Boolean(approvalStatus?.degraded)
|
||||
const liveApprovals = degraded ? [] : (Array.isArray(approvals) ? approvals : [])
|
||||
const cardList = Array.isArray(cards) ? cards : []
|
||||
const taskList = Array.isArray(tasks) ? tasks : []
|
||||
|
||||
const pendingApprovalCardsByApprovalId = new Map()
|
||||
const pendingQuestions = []
|
||||
for (const card of cardList) {
|
||||
if (!card || card.status !== 'pending') continue
|
||||
if (card.kind === 'approval' && card.approvalId) {
|
||||
// 同一个 approvalId 可能先后挂过多次卡,保留最新一张的说明。
|
||||
pendingApprovalCardsByApprovalId.set(card.approvalId, card)
|
||||
} else if (card.kind === 'question') {
|
||||
pendingQuestions.push(card)
|
||||
}
|
||||
}
|
||||
|
||||
const enrichedApprovals = liveApprovals.map(entry => {
|
||||
const card = pendingApprovalCardsByApprovalId.get(entry.id) ?? null
|
||||
return { ...entry, card }
|
||||
})
|
||||
|
||||
const decisions = taskList.flatMap(task => (Array.isArray(task?.decisions) ? task.decisions : [])
|
||||
.filter(d => d && d.status === 'pending')
|
||||
.map(decision => ({ task, decision })))
|
||||
|
||||
const blockedTasks = taskList.filter(task =>
|
||||
task && task.workflowBlockage && !['done', 'failed', 'cancelled', 'reconfirm'].includes(task.status))
|
||||
|
||||
return {
|
||||
degraded,
|
||||
approvals: enrichedApprovals,
|
||||
questions: pendingQuestions,
|
||||
decisions,
|
||||
blockedTasks,
|
||||
pendingCount: enrichedApprovals.length + pendingQuestions.length + decisions.length,
|
||||
}
|
||||
}
|
||||
|
|
@ -138,10 +138,10 @@ html[data-theme="dark"] .ssmwb,
|
|||
.frameless-code{background:color-mix(in srgb,var(--ss-fg) 3.5%,var(--ss-card));border:0;border-radius:8px;padding:7px 10px;font-size:12px;line-height:1.55;color:var(--ss-fg);overflow-wrap:anywhere}
|
||||
.frameless-actions{display:flex;flex-wrap:wrap;align-items:center;justify-content:space-between;gap:8px}
|
||||
.frameless-btn-group{display:flex;flex-wrap:wrap;align-items:center;gap:6px;margin-left:auto}
|
||||
.frameless-btn{background:color-mix(in srgb,var(--ss-fg) 4.5%,var(--ss-card));color:var(--ss-fg);border:0;border-radius:8px;padding:5px 11px;font-size:12px;font-weight:500;transition:background-color 140ms ease,color 140ms ease}
|
||||
.frameless-btn:hover{background:color-mix(in srgb,var(--ss-primary) 11%,var(--ss-card));color:var(--ss-primary)}
|
||||
.frameless-primary-btn{background:var(--ss-primary);color:var(--ss-primary-fg);border:0;border-radius:8px;padding:5px 12px;font-size:12px;font-weight:500;transition:opacity 140ms ease}
|
||||
.frameless-primary-btn:hover{opacity:.9}
|
||||
.ssv2 .frameless-btn,.ssmwb .frameless-btn,.frameless-btn{background:color-mix(in srgb,var(--ss-fg) 4.5%,var(--ss-card));color:var(--ss-fg);border:1px solid var(--ss-border);border-radius:8px;padding:5px 11px;font-size:12px;font-weight:500;transition:background-color 140ms ease,border-color 140ms ease,color 140ms ease}
|
||||
.ssv2 .frameless-btn:hover,.ssmwb .frameless-btn:hover,.frameless-btn:hover{background:color-mix(in srgb,var(--ss-primary) 11%,var(--ss-card));border-color:color-mix(in srgb,var(--ss-primary) 34%,var(--ss-border));color:var(--ss-primary)}
|
||||
.ssv2 .frameless-primary-btn,.ssmwb .frameless-primary-btn,.frameless-primary-btn{background:var(--ss-primary);color:var(--ss-primary-fg);border:0;border-radius:8px;padding:5px 12px;font-size:12px;font-weight:500;transition:opacity 140ms ease}
|
||||
.ssv2 .frameless-primary-btn:hover,.ssmwb .frameless-primary-btn:hover,.frameless-primary-btn:hover{opacity:.9}
|
||||
.frameless-link{font-size:12px;color:var(--ss-link);flex-shrink:0}
|
||||
.frameless-link:hover{text-decoration:underline}
|
||||
|
||||
|
|
@ -223,10 +223,11 @@ html[data-theme="dark"] .ssmwb,
|
|||
.ssv2 .seat-card.is-dimmed{opacity:.35}
|
||||
.ssv2 .seat-head{display:flex;align-items:center;justify-content:space-between;gap:6px}
|
||||
.ssv2 .seat-title-wrap{display:inline-flex;align-items:center;gap:6px;min-width:0}
|
||||
.ssv2 .seat-name{font-family:var(--ss-font-seal);font-weight:700;font-size:15px;line-height:1.25}
|
||||
.ssv2 .seat-name{font-family:var(--ss-font-seal);font-weight:700;font-size:15px;line-height:1.25;white-space:nowrap;flex-shrink:0}
|
||||
.ssv2 .seat-card.is-sansheng .seat-name{font-size:16px}
|
||||
.ssv2 .seat-card.is-selected .seat-name{color:var(--ss-primary)}
|
||||
.ssv2 .seat-live-tag{padding:2px 6px;border-radius:4px;font-size:12px;line-height:1;background:var(--ss-primary);color:var(--ss-primary-fg)}
|
||||
.ssv2 .seat-live-tag{padding:2px 6px;border-radius:4px;font-size:12px;line-height:1;background:var(--ss-primary);color:var(--ss-primary-fg);white-space:nowrap;flex-shrink:0}
|
||||
.ssv2 .seat-mode-tag{padding:1px 5px;border-radius:4px;font-size:11px;line-height:1.15;border:1px solid var(--ss-border);background:var(--ss-subtle);color:var(--ss-muted);white-space:nowrap;flex-shrink:0}
|
||||
.ssv2 .seat-status-text{display:inline-flex;align-items:center;gap:4px;font-size:12px;white-space:nowrap;color:var(--ss-muted)}
|
||||
.ssv2 .seat-status-text.is-error{color:var(--ss-error);font-weight:500}
|
||||
.ssv2 .seat-status-text.is-success{color:var(--ss-success);font-weight:500}
|
||||
|
|
|
|||
|
|
@ -5,11 +5,17 @@ import {
|
|||
buildWorkbenchView,
|
||||
clearDraft,
|
||||
describeModel,
|
||||
describeSeatPreset,
|
||||
draftOf,
|
||||
findModelOption,
|
||||
PRESET_OPTIONS,
|
||||
presetLabel,
|
||||
presetShortLabel,
|
||||
recommendedPresetForSeat,
|
||||
UNCHOSEN_MODEL_LABEL,
|
||||
updateDraft,
|
||||
} from './workbench.js'
|
||||
import { mergePendingItems } from './pending-model.js'
|
||||
import { groupModelChoices, modelPartsOf, modelObjectFromParts, shortModelName } from './master-model.js'
|
||||
import { request } from './transport.js'
|
||||
|
||||
|
|
@ -175,6 +181,7 @@ export function WorkbenchV2(props) {
|
|||
const [tasks, setTasks] = useState([])
|
||||
const [requirements, setRequirements] = useState([])
|
||||
const [pendingApprovals, setPendingApprovals] = useState([])
|
||||
const [pendingCards, setPendingCards] = useState([])
|
||||
const [approvalStatus, setApprovalStatus] = useState(null)
|
||||
|
||||
const [artifacts, setArtifacts] = useState([])
|
||||
|
|
@ -208,11 +215,12 @@ export function WorkbenchV2(props) {
|
|||
try { memoryData = (await request('memory', { projectId: projectView.project.id })).memory } catch { /* 共识可选 */ }
|
||||
const nextProjectId = projectView.project.id
|
||||
const answerVersion = taskAnswerVersion.current
|
||||
const [taskRes, artifactRes, requirementRes, approvalRes] = await Promise.allSettled([
|
||||
const [taskRes, artifactRes, requirementRes, approvalRes, cardRes] = await Promise.allSettled([
|
||||
request('tasks', { projectId: nextProjectId }),
|
||||
request('artifacts', { projectId: nextProjectId }),
|
||||
request('requirements', { projectId: nextProjectId }),
|
||||
request('approvals', { projectId: nextProjectId }),
|
||||
request('cards', { projectId: nextProjectId }),
|
||||
])
|
||||
if (!alive.current) return
|
||||
const projectChanged = loadedProjectId.current !== nextProjectId
|
||||
|
|
@ -236,6 +244,7 @@ export function WorkbenchV2(props) {
|
|||
setArtifacts(prev => refreshList(artifactRes.value?.artifacts, prev, projectChanged))
|
||||
setRequirements(prev => refreshList(requirementRes.value?.requirements, prev, projectChanged))
|
||||
setPendingApprovals(prev => refreshList(approvalRes.value?.approvals, prev, projectChanged))
|
||||
setPendingCards(prev => refreshList(cardRes.value?.cards, prev, projectChanged))
|
||||
setApprovalStatus(approvalRes.status === 'fulfilled' ? approvalRes.value?.status ?? null : { available: false, degraded: true })
|
||||
setPhase('ready')
|
||||
} catch (loadError) {
|
||||
|
|
@ -260,12 +269,13 @@ export function WorkbenchV2(props) {
|
|||
running = true
|
||||
try {
|
||||
const answerVer = taskAnswerVersion.current
|
||||
const [projectRes, taskRes, artifactRes, requirementRes, approvalRes] = await Promise.allSettled([
|
||||
const [projectRes, taskRes, artifactRes, requirementRes, approvalRes, cardRes] = await Promise.allSettled([
|
||||
request('project', { projectId }),
|
||||
request('tasks', { projectId }),
|
||||
request('artifacts', { projectId }),
|
||||
request('requirements', { projectId }),
|
||||
request('approvals', { projectId }),
|
||||
request('cards', { projectId }),
|
||||
])
|
||||
if (disposed || !alive.current || loadedProjectId.current !== projectId) return
|
||||
if (projectRes.value) setView(projectRes.value)
|
||||
|
|
@ -273,6 +283,7 @@ export function WorkbenchV2(props) {
|
|||
setArtifacts(prev => refreshList(artifactRes.value?.artifacts, prev))
|
||||
setRequirements(prev => refreshList(requirementRes.value?.requirements, prev))
|
||||
setPendingApprovals(prev => refreshList(approvalRes.value?.approvals, prev))
|
||||
setPendingCards(prev => refreshList(cardRes.value?.cards, prev))
|
||||
setApprovalStatus(approvalRes.status === 'fulfilled' ? approvalRes.value?.status ?? null : { available: false, degraded: true })
|
||||
} finally {
|
||||
running = false
|
||||
|
|
@ -347,7 +358,16 @@ export function WorkbenchV2(props) {
|
|||
const instructions = Object.prototype.hasOwnProperty.call(dEntry, 'instructions')
|
||||
? dEntry.instructions
|
||||
: (typeof seatRec.instructions === 'string' ? seatRec.instructions : '')
|
||||
return { modelKey, effort, modelValue, instructions }
|
||||
const presetInfo = describeSeatPreset(seatId, seatRec, dEntry, view?.project)
|
||||
return {
|
||||
modelKey,
|
||||
effort,
|
||||
modelValue,
|
||||
instructions,
|
||||
agentPreset: presetInfo.presetValue,
|
||||
hasDraftPreset: Object.prototype.hasOwnProperty.call(dEntry, 'agentPreset'),
|
||||
presetInfo,
|
||||
}
|
||||
}
|
||||
|
||||
function updateSeatDraftModel(seatId, nextKey, nextEffort) {
|
||||
|
|
@ -357,19 +377,29 @@ export function WorkbenchV2(props) {
|
|||
|
||||
async function saveSeatConfigFor(seatId) {
|
||||
if (!projectId) return
|
||||
const { modelKey, effort, instructions } = seatDraftState(seatId)
|
||||
const { modelKey, effort, instructions, agentPreset, hasDraftPreset, presetInfo } = seatDraftState(seatId)
|
||||
const model = modelObjectFromParts(modelKey, effort)
|
||||
if (!model) { setNotice('请先为当前角色选择模型'); return }
|
||||
if (!model) {
|
||||
setNotice('请先为当前角色选择模型' + (!presetInfo.presetSupported && hasDraftPreset ? '(执行模式持久化待后端启用)' : ''))
|
||||
return
|
||||
}
|
||||
setBusy(true)
|
||||
setError(null)
|
||||
setNotice('保存中…')
|
||||
try {
|
||||
await request('configure', { projectId, seatId, model, instructions })
|
||||
const payload = { projectId, seatId, model, instructions }
|
||||
if (presetInfo.presetSupported) payload.agentPreset = agentPreset || null
|
||||
await request('configure', payload)
|
||||
const next = await request('project', { projectId })
|
||||
if (!alive.current) return
|
||||
setView(next)
|
||||
setDraft(prev => clearDraft(prev, seatId))
|
||||
setNotice('已保存「' + (SEATS[seatId]?.label || seatId) + '」配置')
|
||||
const label = SEATS[seatId]?.label || seatId
|
||||
if (!presetInfo.presetSupported && hasDraftPreset) {
|
||||
setNotice('已保存「' + label + '」模型与说明;执行模式切换暂需后续后端启用后生效')
|
||||
} else {
|
||||
setNotice('已保存「' + label + '」配置')
|
||||
}
|
||||
} catch (err) {
|
||||
if (alive.current) setError(err?.message || '保存失败')
|
||||
} finally {
|
||||
|
|
@ -377,6 +407,50 @@ export function WorkbenchV2(props) {
|
|||
}
|
||||
}
|
||||
|
||||
async function applyRecommendedPresets() {
|
||||
if (!projectId) return
|
||||
if (!wb.project.presetSupported) {
|
||||
setDraft(prev => {
|
||||
let next = prev
|
||||
for (const id of SEAT_IDS) {
|
||||
next = updateDraft(next, id, { agentPreset: recommendedPresetForSeat(id) })
|
||||
}
|
||||
return next
|
||||
})
|
||||
setNotice('已在前端草稿按分工预填推荐模式(中枢与三省:标准模式;六部:OPS PTC)。当前后端尚未开启模式写入,待后端改造完成后可保存生效。')
|
||||
return
|
||||
}
|
||||
setBusy(true)
|
||||
setError(null)
|
||||
setNotice('正在按角色分工应用推荐执行模式…')
|
||||
try {
|
||||
let skipped = 0
|
||||
for (const id of SEAT_IDS) {
|
||||
const rec = seatRecMap[id] || {}
|
||||
const model = rec.configuredModel ?? rec.model ?? null
|
||||
if (!model) { skipped += 1; continue }
|
||||
await request('configure', {
|
||||
projectId,
|
||||
seatId: id,
|
||||
model,
|
||||
instructions: typeof rec.instructions === 'string' ? rec.instructions : '',
|
||||
agentPreset: recommendedPresetForSeat(id),
|
||||
})
|
||||
}
|
||||
const next = await request('project', { projectId })
|
||||
if (!alive.current) return
|
||||
setView(next)
|
||||
setDraft({})
|
||||
setNotice(skipped > 0
|
||||
? '已为已配模型的席位应用推荐执行模式(另有 ' + skipped + ' 个未选模型席位待配置)'
|
||||
: '已为全部十席应用推荐执行模式(中枢/三省=标准模式,六部=OPS PTC)')
|
||||
} catch (err) {
|
||||
if (alive.current) setError(err?.message || '应用推荐模式失败')
|
||||
} finally {
|
||||
if (alive.current) setBusy(false)
|
||||
}
|
||||
}
|
||||
|
||||
async function setGlobalDefaultFor(seatId) {
|
||||
if (!projectId) return
|
||||
const { modelKey, effort } = seatDraftState(seatId)
|
||||
|
|
@ -475,7 +549,7 @@ export function WorkbenchV2(props) {
|
|||
}
|
||||
}
|
||||
|
||||
async function rebuildSeat(seatId) {
|
||||
async function rebuildSeat(seatId, force = false) {
|
||||
const seat = seatById[seatId]
|
||||
if (!projectId || !seat) return
|
||||
const rec = seatRecMap[seatId]
|
||||
|
|
@ -487,6 +561,7 @@ export function WorkbenchV2(props) {
|
|||
projectId,
|
||||
seatId,
|
||||
expectedSessionId: rec?.sessionId || undefined,
|
||||
force,
|
||||
})
|
||||
if (!alive.current) return
|
||||
setView(next)
|
||||
|
|
@ -510,10 +585,18 @@ export function WorkbenchV2(props) {
|
|||
sessionId: entry.sessionId,
|
||||
choice,
|
||||
})
|
||||
const data = await request('approvals', { projectId })
|
||||
const [data, cardRes] = await Promise.allSettled([
|
||||
request('approvals', { projectId }),
|
||||
request('cards', { projectId }),
|
||||
])
|
||||
if (!alive.current || loadedProjectId.current !== projectId) return
|
||||
setPendingApprovals(prev => refreshList(data?.approvals, prev))
|
||||
setApprovalStatus(data?.status ?? null)
|
||||
if (data.status === 'fulfilled') {
|
||||
setPendingApprovals(prev => refreshList(data.value?.approvals, prev))
|
||||
setApprovalStatus(data.value?.status ?? null)
|
||||
}
|
||||
if (cardRes.status === 'fulfilled') {
|
||||
setPendingCards(prev => refreshList(cardRes.value?.cards, prev))
|
||||
}
|
||||
setNotice(choice === 'allow' ? '已允许审批' : '已拒绝审批')
|
||||
} catch (err) {
|
||||
if (alive.current) setError(err?.message || '审批应答失败')
|
||||
|
|
@ -522,6 +605,66 @@ export function WorkbenchV2(props) {
|
|||
}
|
||||
}
|
||||
|
||||
async function dismissQuestion(card) {
|
||||
if (!projectId || busy || !globalThis.confirm('删除这张问答卡片?它会从「待你处理」移除。')) return
|
||||
setBusy(true)
|
||||
setError(null)
|
||||
try {
|
||||
const { card: dismissed } = await request('cardDismiss', { projectId, cardId: card.id })
|
||||
if (!alive.current || loadedProjectId.current !== projectId) return
|
||||
setPendingCards(prev => prev.map(item => item.id === dismissed.id ? dismissed : item))
|
||||
setNotice('已删除问答卡片')
|
||||
} catch (error) {
|
||||
if (alive.current) setError(error?.message || '删除问答卡片失败')
|
||||
} finally {
|
||||
if (alive.current) setBusy(false)
|
||||
}
|
||||
}
|
||||
|
||||
async function answerCard(card, choice) {
|
||||
if (!projectId || !card?.id || busy) return
|
||||
setBusy(true)
|
||||
setError(null)
|
||||
try {
|
||||
await request('cardAnswer', { cardId: card.id, choice })
|
||||
const [cardRes, apprRes] = await Promise.allSettled([
|
||||
request('cards', { projectId }),
|
||||
request('approvals', { projectId }),
|
||||
])
|
||||
if (!alive.current || loadedProjectId.current !== projectId) return
|
||||
if (cardRes.status === 'fulfilled') setPendingCards(prev => refreshList(cardRes.value?.cards, prev))
|
||||
if (apprRes.status === 'fulfilled') {
|
||||
setPendingApprovals(prev => refreshList(apprRes.value?.approvals, prev))
|
||||
setApprovalStatus(apprRes.value?.status ?? null)
|
||||
}
|
||||
setNotice('已提交卡片选择')
|
||||
} catch (err) {
|
||||
const stale = err?.code === 'sansheng/approval-stale' || /失效|已结束|已取消|stale|expired/i.test(err?.message || '')
|
||||
if (alive.current) {
|
||||
if (stale) {
|
||||
setNotice('该审批卡已失效或被取消,正在刷新最新队列')
|
||||
try {
|
||||
const [cardRes, apprRes] = await Promise.allSettled([
|
||||
request('cards', { projectId }),
|
||||
request('approvals', { projectId }),
|
||||
])
|
||||
if (alive.current && loadedProjectId.current === projectId) {
|
||||
if (cardRes.status === 'fulfilled') setPendingCards(prev => refreshList(cardRes.value?.cards, prev))
|
||||
if (apprRes.status === 'fulfilled') {
|
||||
setPendingApprovals(prev => refreshList(apprRes.value?.approvals, prev))
|
||||
setApprovalStatus(apprRes.value?.status ?? null)
|
||||
}
|
||||
}
|
||||
} catch { /* 忽略刷新错误 */ }
|
||||
} else {
|
||||
setError(err?.message || '卡片提交失败')
|
||||
}
|
||||
}
|
||||
} finally {
|
||||
if (alive.current) setBusy(false)
|
||||
}
|
||||
}
|
||||
|
||||
async function answerDecision(taskId, decisionId, value) {
|
||||
if (!projectId || busy) return
|
||||
setBusy(true)
|
||||
|
|
@ -646,12 +789,18 @@ export function WorkbenchV2(props) {
|
|||
}
|
||||
|
||||
// ---- 派生计数 ----
|
||||
const degraded = Boolean(approvalStatus?.degraded)
|
||||
const toolApprovals = degraded ? [] : pendingApprovals
|
||||
const decisions = useMemo(() => tasks.flatMap(task => (task.decisions || [])
|
||||
.filter(d => d.status === 'pending')
|
||||
.map(decision => ({ task, decision }))), [tasks])
|
||||
const pendingCount = toolApprovals.length + decisions.length
|
||||
const pendingSummary = useMemo(() => mergePendingItems({
|
||||
approvals: pendingApprovals,
|
||||
approvalStatus,
|
||||
cards: pendingCards,
|
||||
tasks,
|
||||
}), [pendingApprovals, approvalStatus, pendingCards, tasks])
|
||||
const degraded = pendingSummary.degraded
|
||||
const toolApprovals = pendingSummary.approvals
|
||||
const questionCards = pendingSummary.questions
|
||||
const decisions = pendingSummary.decisions
|
||||
const blockedTasks = pendingSummary.blockedTasks
|
||||
const pendingCount = pendingSummary.pendingCount
|
||||
const openTasksCount = tasks.filter(t => ['running', 'prepared', 'dispatched', 'failed', 'waiting_user', 'reconfirm'].includes(t.status)).length
|
||||
const reviewCount = tasks.filter(t => t.ownerSeatId === 'menxia' && ['running', 'prepared', 'dispatched'].includes(t.status)).length
|
||||
const anomalyCount = tasks.filter(t => t.workflowBlockage || t.status === 'failed' || t.deliveryState === 'unknown').length
|
||||
|
|
@ -667,15 +816,16 @@ export function WorkbenchV2(props) {
|
|||
}
|
||||
|
||||
function renderPendingZone() {
|
||||
if (pendingCount === 0 && !degraded) return null
|
||||
if (pendingCount === 0 && blockedTasks.length === 0 && !degraded) return null
|
||||
return h('section', { className: 'frameless-zone', 'aria-label': '待你处理' },
|
||||
h('div', { className: 'frameless-zone-head' },
|
||||
h('div', { className: 'frameless-zone-title-wrap' },
|
||||
h('span', { className: 'ss-dot is-primary is-pulse' }),
|
||||
h('h2', { className: 'frameless-zone-title' }, '待你处理'),
|
||||
pendingCount > 0 ? h('span', { className: 'frameless-zone-count' }, String(pendingCount)) : null,
|
||||
blockedTasks.length > 0 ? h('span', { className: 'ss-pill is-error' }, blockedTasks.length + ' 阻塞') : null,
|
||||
),
|
||||
h('span', { className: 'frameless-zone-sub' }, '原生审批与决定同步'),
|
||||
h('span', { className: 'frameless-zone-sub' }, '审批 / 问答卡 / 决定 / 阻塞同步'),
|
||||
),
|
||||
degraded ? h('div', { className: 'frameless-code', style: { color: 'var(--ss-error)' } },
|
||||
'工作台暂时无法获取工具审批队列,请在席位原生会话中使用审批卡。' + (approvalStatus?.reason ? '(' + approvalStatus.reason + ')' : '')) : null,
|
||||
|
|
@ -683,16 +833,50 @@ export function WorkbenchV2(props) {
|
|||
toolApprovals.map(a => h('article', { className: 'frameless-item', key: 'apr:' + a.sessionId + ':' + a.id },
|
||||
h('div', { className: 'frameless-item-head' },
|
||||
h('div', { className: 'frameless-item-meta' },
|
||||
h('span', { className: 'frameless-chip is-err' }, h('span', { className: 'ss-dot is-error' }), '工具审批'),
|
||||
h('span', { className: 'frameless-chip is-err' }, h('span', { className: 'ss-dot is-error' }), a.card ? '审批卡片' : '工具审批'),
|
||||
h('span', { className: 'font-seal', style: { fontWeight: 700, fontSize: 13 } }, SEATS[a.seatId]?.label || a.seatId),
|
||||
a.tool ? h('span', { className: 'font-mono-num', style: { fontSize: 12, color: 'var(--ss-muted)' } }, a.tool) : null,
|
||||
),
|
||||
h('button', { type: 'button', className: 'frameless-link', disabled: busy, onClick: () => void openSeat(a.seatId) }, '查看会话 →'),
|
||||
),
|
||||
h('div', { className: 'frameless-code' }, a.reason || a.detail?.text || '等待工具授权'),
|
||||
h('div', { className: 'frameless-btn-group' },
|
||||
h('button', { type: 'button', className: 'frameless-btn', disabled: busy, onClick: () => void answerApproval(a, 'reject') }, '拒绝'),
|
||||
h('button', { type: 'button', className: 'frameless-primary-btn', disabled: busy, onClick: () => void answerApproval(a, 'allow') }, '允许一次'),
|
||||
a.card?.title ? h('p', { style: { margin: 0, fontSize: 12, fontWeight: 600 } }, a.card.title) : null,
|
||||
h('div', { className: 'frameless-code' }, a.card?.body || a.reason || a.detail?.text || '等待工具授权'),
|
||||
a.card && Array.isArray(a.card.options) && a.card.options.length > 0
|
||||
? h('div', { className: 'frameless-btn-group' },
|
||||
a.card.options.map((opt, idx) => h('button', {
|
||||
key: opt.value,
|
||||
type: 'button',
|
||||
className: opt.value === 'allow' || idx === 0 ? 'frameless-primary-btn' : 'frameless-btn',
|
||||
disabled: busy,
|
||||
onClick: () => void answerCard(a.card, opt.value),
|
||||
}, opt.label)))
|
||||
: h('div', { className: 'frameless-btn-group' },
|
||||
h('button', { type: 'button', className: 'frameless-btn', disabled: busy, onClick: () => void answerApproval(a, 'reject') }, '拒绝'),
|
||||
h('button', { type: 'button', className: 'frameless-primary-btn', disabled: busy, onClick: () => void answerApproval(a, 'allow') }, '允许一次'),
|
||||
),
|
||||
)),
|
||||
questionCards.map(card => h('article', { className: 'frameless-item', key: 'qcard:' + card.id },
|
||||
h('div', { className: 'frameless-item-head' },
|
||||
h('div', { className: 'frameless-item-meta' },
|
||||
h('span', { className: 'frameless-chip is-pri' }, h('span', { className: 'ss-dot is-primary' }), '问答卡片'),
|
||||
h('span', { className: 'font-seal', style: { fontWeight: 700, fontSize: 13 } }, card.seatLabel || SEATS[card.seatId]?.label || '丞相'),
|
||||
),
|
||||
h('div', { className: 'frameless-btn-group' },
|
||||
card.seatId ? h('button', { type: 'button', className: 'frameless-link', disabled: busy, onClick: () => void openSeat(card.seatId) }, '查看会话 →') : null,
|
||||
h('button', { type: 'button', className: 'frameless-link', disabled: busy, onClick: () => void dismissQuestion(card) }, '删除'),
|
||||
),
|
||||
),
|
||||
h('p', { style: { margin: 0, fontSize: 12, fontWeight: 600 } }, card.title),
|
||||
card.body ? h('div', { className: 'frameless-code' }, card.body) : null,
|
||||
h('div', { style: { display: 'flex', flexWrap: 'wrap', gap: 6 }, role: 'group', 'aria-label': card.title },
|
||||
(card.options || []).map(opt => h('button', {
|
||||
key: opt.value,
|
||||
type: 'button',
|
||||
className: 'frameless-btn',
|
||||
disabled: busy,
|
||||
title: opt.description || '',
|
||||
onClick: () => void answerCard(card, opt.value),
|
||||
}, opt.label)),
|
||||
),
|
||||
)),
|
||||
decisions.map(({ task, decision }) => h('article', { className: 'frameless-item', key: 'dec:' + task.id + ':' + decision.id },
|
||||
|
|
@ -714,13 +898,31 @@ export function WorkbenchV2(props) {
|
|||
}, opt.label)),
|
||||
),
|
||||
)),
|
||||
blockedTasks.map(task => {
|
||||
const seatLabel = SEATS[task.ownerSeatId]?.label || task.ownerSeatId || '席位'
|
||||
return h('article', { className: 'frameless-item', key: 'blk:' + task.id },
|
||||
h('div', { className: 'frameless-item-head' },
|
||||
h('div', { className: 'frameless-item-meta' },
|
||||
h('span', { className: 'frameless-chip is-err' }, h('span', { className: 'ss-dot is-error' }), '流程阻塞'),
|
||||
h('span', { className: 'font-seal', style: { fontWeight: 700, fontSize: 13 } }, seatLabel),
|
||||
h('span', { className: 'truncate', style: { fontSize: 12, fontWeight: 500 } }, task.title),
|
||||
),
|
||||
h('button', { type: 'button', className: 'frameless-link font-mono-num', onClick: () => setSelectedTask(task) }, '详情 →'),
|
||||
),
|
||||
h('div', { className: 'frameless-code', style: { color: 'var(--ss-error)' } },
|
||||
(task.workflowBlockage?.label ? task.workflowBlockage.label + ' · ' : '') + (task.workflowBlockage?.reason || '流程等待恢复')),
|
||||
task.ownerSeatId ? h('div', { className: 'frameless-btn-group' },
|
||||
h('button', { type: 'button', className: 'frameless-btn', disabled: busy, onClick: () => void openSeat(task.ownerSeatId) }, '打开' + seatLabel + '会话'),
|
||||
) : null,
|
||||
)
|
||||
}),
|
||||
),
|
||||
)
|
||||
}
|
||||
|
||||
function renderModelControlsForSeat(seatId, onSaveCallback) {
|
||||
const rec = seatRecMap[seatId] || {}
|
||||
const { modelKey, effort, instructions } = seatDraftState(seatId)
|
||||
const { modelKey, effort, instructions, agentPreset, presetInfo } = seatDraftState(seatId)
|
||||
const choiceObj = groupedChoices.find(c => c.value === modelKey) || null
|
||||
const extraChoices = modelKey && !choiceObj
|
||||
? [{ value: modelKey, label: (rec.model?.model || modelKey) + '(目录未列出)', efforts: effort ? [effort] : [] }, ...groupedChoices]
|
||||
|
|
@ -729,6 +931,7 @@ export function WorkbenchV2(props) {
|
|||
const configured = rec.configuredModel ?? rec.model ?? null
|
||||
const sourceLabel = wb.seats.find(s => s.id === seatId)?.modelSourceLabel || '未选择'
|
||||
const syncStatus = rec.modelSync?.status || null
|
||||
const activePresetDesc = PRESET_OPTIONS.find(p => p.value === (agentPreset || presetInfo.recommendedPreset))?.description || ''
|
||||
|
||||
return h('div', { style: { display: 'flex', flexDirection: 'column', gap: 10 } },
|
||||
h('div', { className: 'kv-grid-2' },
|
||||
|
|
@ -761,6 +964,21 @@ export function WorkbenchV2(props) {
|
|||
),
|
||||
),
|
||||
),
|
||||
h('label', { style: { display: 'flex', flexDirection: 'column', gap: 4, fontSize: 12 } },
|
||||
h('div', { style: { display: 'flex', justifyContent: 'space-between', alignItems: 'center', gap: 8 } },
|
||||
h('span', { style: { color: 'var(--ss-muted)' } }, '执行模式(防 2 分钟审批超时)'),
|
||||
h('span', { className: 'ss-pill' }, '推荐 ' + presetInfo.recommendedPresetShortLabel),
|
||||
),
|
||||
h('select', {
|
||||
className: 'wb-select',
|
||||
value: agentPreset,
|
||||
onChange: (e) => setDraft(prev => updateDraft(prev, seatId, { agentPreset: e.target.value })),
|
||||
},
|
||||
h('option', { value: '' }, '按角色推荐(推荐:' + presetInfo.recommendedPresetLabel + ')'),
|
||||
PRESET_OPTIONS.map(opt => h('option', { key: opt.value, value: opt.value }, opt.label)),
|
||||
),
|
||||
activePresetDesc ? h('span', { style: { fontSize: 11, color: 'var(--ss-muted)', lineHeight: 1.45 } }, activePresetDesc) : null,
|
||||
),
|
||||
h('div', { className: 'kv-box', style: { display: 'flex', flexDirection: 'column', gap: 4, fontSize: 12 } },
|
||||
h('div', { style: { display: 'flex', justifyContent: 'space-between', gap: 8 } },
|
||||
h('span', { style: { color: 'var(--ss-muted)' } }, '配置来源'),
|
||||
|
|
@ -770,6 +988,13 @@ export function WorkbenchV2(props) {
|
|||
h('span', { style: { color: 'var(--ss-muted)' } }, '当前会话模型'),
|
||||
h('span', { className: 'font-mono-num' }, rec.sessionModel ? (rec.sessionModel.provider + '/' + rec.sessionModel.model) : (configured ? shortModelName(configured) : '未绑定会话')),
|
||||
),
|
||||
h('div', { style: { display: 'flex', justifyContent: 'space-between', gap: 8 } },
|
||||
h('span', { style: { color: 'var(--ss-muted)' } }, '执行模式状态'),
|
||||
h('span', { style: { color: presetInfo.presetSupported ? 'var(--ss-fg)' : 'var(--ss-muted)' } },
|
||||
presetInfo.presetSupported
|
||||
? (presetInfo.sessionPresetLabel ? ('会话已绑定:' + presetInfo.sessionPresetLabel) : ('配置:' + presetInfo.presetShortLabel))
|
||||
: ('待后端启用按席写入(界面先预览:' + presetInfo.presetShortLabel + ')')),
|
||||
),
|
||||
h('div', { style: { display: 'flex', justifyContent: 'space-between', gap: 8 } },
|
||||
h('span', { style: { color: 'var(--ss-muted)' } }, '同步状态'),
|
||||
h('span', { style: { color: syncStatus === 'failed' ? 'var(--ss-error)' : syncStatus === 'synced' ? 'var(--ss-success)' : 'var(--ss-muted)' } },
|
||||
|
|
@ -816,6 +1041,7 @@ export function WorkbenchV2(props) {
|
|||
const dimmed = !filterMatch(seat)
|
||||
const latest = latestTaskOf(seatId)
|
||||
const modelShort = shortModelName(seatRecMap[seatId]?.configuredModel ?? seatRecMap[seatId]?.model ?? null)
|
||||
const presetShort = seatDraftState(seatId).presetInfo.presetShortLabel
|
||||
return h('button', {
|
||||
key: seatId,
|
||||
type: 'button',
|
||||
|
|
@ -839,7 +1065,10 @@ export function WorkbenchV2(props) {
|
|||
h('div', { className: 'seat-footer' },
|
||||
h('span', { className: 'seat-task-title', style: { color: latest ? 'var(--ss-fg)' : 'var(--ss-muted)' } },
|
||||
latest ? latest.title : (seat.status === 'bound' ? '空闲待命' : '点击按需开启')),
|
||||
h('span', { className: 'seat-model-tag hide-narrow' }, modelShort === '未选模型' ? '—' : modelShort),
|
||||
h('span', { style: { display: 'inline-flex', alignItems: 'center', gap: 4, flexShrink: 0 } },
|
||||
h('span', { className: 'seat-mode-tag', title: '执行模式:' + presetShort }, presetShort),
|
||||
h('span', { className: 'seat-model-tag hide-narrow' }, modelShort === '未选模型' ? '—' : modelShort),
|
||||
),
|
||||
),
|
||||
)
|
||||
}
|
||||
|
|
@ -869,7 +1098,7 @@ export function WorkbenchV2(props) {
|
|||
' ',
|
||||
h('span', { style: { color: 'var(--ss-muted)' } }, '待复核'),
|
||||
),
|
||||
h('button', { type: 'button', onClick: () => { setTab('flow'); setFlowSubTab('queue'); setQueueSearch('失败') } },
|
||||
h('button', { type: 'button', onClick: () => { setTab('flow'); setFlowSubTab('queue'); setQueueSearch('异常') } },
|
||||
h('strong', { className: 'font-mono-num', style: { color: anomalyCount > 0 ? 'var(--ss-error)' : 'inherit' } }, String(anomalyCount)),
|
||||
' ',
|
||||
h('span', { style: { color: 'var(--ss-muted)' } }, '异常'),
|
||||
|
|
@ -910,6 +1139,8 @@ export function WorkbenchV2(props) {
|
|||
h('span', { className: 'ss-dot is-' + leadTone + (leadTone === 'success' ? ' is-pulse' : '') }),
|
||||
seatStatusText(lead),
|
||||
),
|
||||
h('span', { className: 'seat-mode-tag', title: '执行模式:' + seatDraftState('lead').presetInfo.presetShortLabel },
|
||||
seatDraftState('lead').presetInfo.presetShortLabel),
|
||||
h('span', { className: 'hide-narrow', style: { fontSize: 12, color: 'var(--ss-muted)' } }, '总协调 · 需求入口'),
|
||||
),
|
||||
h('p', { className: 'truncate', style: { margin: '2px 0 0', fontSize: 12, color: 'var(--ss-muted)' } },
|
||||
|
|
@ -972,6 +1203,10 @@ export function WorkbenchV2(props) {
|
|||
h('span', null, '原会话在宿主中已不存在,重建后保留旧任务历史。'),
|
||||
h('button', { type: 'button', className: 'wb-btn-outline', disabled: busy, onClick: () => void rebuildSeat(sel.id) }, '重建会话'),
|
||||
) : null,
|
||||
sel.status === 'bound' && sel.presetMismatch ? h('div', { key: 'preset', className: 'wb-alert' },
|
||||
h('span', null, '当前会话的执行模式与配置不同,重建后保留旧会话历史。'),
|
||||
h('button', { type: 'button', className: 'wb-btn-outline', disabled: busy, onClick: () => void rebuildSeat(sel.id, true) }, '重建并切换模式'),
|
||||
) : null,
|
||||
sel.modelSyncStatus === 'failed' ? h('div', { key: 'fail', className: 'wb-alert' },
|
||||
h('span', null, '模型同步失败:' + (sel.modelSync?.error || '未知原因')),
|
||||
h('button', { type: 'button', className: 'wb-btn-outline', disabled: busy, onClick: () => void retrySyncFor(sel.id) }, '重试同步'),
|
||||
|
|
@ -1051,7 +1286,13 @@ export function WorkbenchV2(props) {
|
|||
if (!q) return true
|
||||
const sName = SEATS[t.ownerSeatId]?.label || ''
|
||||
const tmLabel = TASK_META[t.status]?.label || ''
|
||||
return [t.id, t.title, sName, tmLabel, t.goal, t.result].filter(Boolean).join(' ').toLowerCase().includes(q)
|
||||
const isAnomaly = Boolean(t.workflowBlockage || t.status === 'failed' || t.deliveryState === 'unknown')
|
||||
return [
|
||||
t.id, t.title, sName, tmLabel, t.goal, t.result,
|
||||
t.workflowBlockage?.label, t.workflowBlockage?.reason,
|
||||
t.workflowBlockage ? '阻塞' : '',
|
||||
isAnomaly ? '异常' : '',
|
||||
].filter(Boolean).join(' ').toLowerCase().includes(q)
|
||||
})
|
||||
const subTabs = [
|
||||
{ id: 'tasks', label: '流转任务', count: wfTasks.length },
|
||||
|
|
@ -1131,7 +1372,10 @@ export function WorkbenchV2(props) {
|
|||
return h('tr', { key: t.id, className: 'is-click', onClick: () => setSelectedTask(t) },
|
||||
h('td', null, h('div', { style: { fontWeight: 500 } }, t.title), h('div', { className: 'font-mono-num', style: { color: 'var(--ss-muted)' } }, t.id)),
|
||||
h('td', { className: 'font-seal', style: { fontWeight: 700, whiteSpace: 'nowrap' } }, SEATS[t.ownerSeatId]?.label || '—'),
|
||||
h('td', null, h('span', { className: 'ss-pill is-' + tm.tone }, tm.label)),
|
||||
h('td', null,
|
||||
h('span', { className: 'ss-pill is-' + tm.tone }, tm.label),
|
||||
t.workflowBlockage ? h('span', { className: 'ss-pill is-error', style: { marginLeft: 4 }, title: t.workflowBlockage.reason || '' }, '阻塞') : null,
|
||||
),
|
||||
h('td', { className: 'col-dur font-mono-num', style: { color: 'var(--ss-muted)', whiteSpace: 'nowrap' } }, durationText(taskDurationMs(t))),
|
||||
h('td', { className: 'col-time font-mono-num', style: { color: 'var(--ss-muted)', whiteSpace: 'nowrap' } }, dateText(t.dispatchedAt)),
|
||||
)
|
||||
|
|
@ -1327,11 +1571,23 @@ export function WorkbenchV2(props) {
|
|||
),
|
||||
h('span', { className: 'ss-pill is-success' }, '项目隔离已生效'),
|
||||
),
|
||||
h('div', { className: 'kv-box', style: { display: 'flex', flexWrap: 'wrap', alignItems: 'center', justifyContent: 'space-between', gap: 8 } },
|
||||
h('div', { style: { flex: '1 1 220px', fontSize: 12, lineHeight: 1.5, color: 'var(--ss-muted)' } },
|
||||
h('strong', { style: { color: 'var(--ss-fg)' } }, '执行模式分工建议:'),
|
||||
'中枢(丞相)与三省(中书 / 门下 / 尚书)使用「标准模式」,避免 2 分钟审批超时与卡片嵌套;六部使用「OPS PTC」批量读写。',
|
||||
!wb.project.presetSupported ? '(后端写入启用前,先展示推荐与前端草稿)' : ''),
|
||||
h('button', {
|
||||
type: 'button',
|
||||
className: 'wb-btn-outline',
|
||||
disabled: busy,
|
||||
onClick: () => void applyRecommendedPresets(),
|
||||
}, '一键按推荐填入分工'),
|
||||
),
|
||||
),
|
||||
h('section', { key: 'seatlist', className: 'wb-card', style: { padding: 0, overflow: 'hidden', gap: 0 } },
|
||||
h('div', { style: { padding: '10px 14px', borderBottom: '1px solid var(--ss-border)', display: 'flex', flexWrap: 'wrap', justifyContent: 'space-between', alignItems: 'center', gap: 8 } },
|
||||
h('h3', { style: { margin: 0, fontSize: 12, fontWeight: 600 } }, '十席开关与模型配置'),
|
||||
h('span', { style: { color: 'var(--ss-muted)' } }, '点击任一席位展开配置模型与说明'),
|
||||
h('h3', { style: { margin: 0, fontSize: 12, fontWeight: 600 } }, '十席开关、模型与执行模式'),
|
||||
h('span', { style: { color: 'var(--ss-muted)' } }, '点击任一席位展开配置模型、模式与说明'),
|
||||
),
|
||||
h('div', null, SEAT_IDS.map(id => {
|
||||
const seat = seatById[id]
|
||||
|
|
@ -1343,6 +1599,7 @@ export function WorkbenchV2(props) {
|
|||
const configured = rec.configuredModel ?? rec.model ?? null
|
||||
const modelShort = shortModelName(configured)
|
||||
const srcShort = rec.modelSource === 'project' ? '项目覆盖' : rec.modelSource === 'global' ? '全局默认' : '未设默认'
|
||||
const { presetInfo } = seatDraftState(id)
|
||||
return h('div', { key: id, className: 'cfg-row' + (expanded ? ' is-open' : '') },
|
||||
h('div', { className: 'cfg-row-head' },
|
||||
h('button', {
|
||||
|
|
@ -1357,9 +1614,10 @@ export function WorkbenchV2(props) {
|
|||
h('span', { className: 'font-seal', style: { fontWeight: 700, fontSize: 14, flexShrink: 0, color: expanded ? 'var(--ss-primary)' : 'var(--ss-fg)' } }, seat.name),
|
||||
h('span', { className: 'truncate', style: { color: 'var(--ss-muted)' } }, seat.duty),
|
||||
),
|
||||
h('div', { style: { display: 'flex', alignItems: 'center', gap: 6, minWidth: 0 } },
|
||||
h('div', { style: { display: 'flex', alignItems: 'center', gap: 6, minWidth: 0, flexWrap: 'wrap' } },
|
||||
h('span', { className: 'font-mono-num truncate' }, modelShort),
|
||||
h('span', { className: 'ss-pill' + (rec.modelSource === 'project' ? ' is-primary' : '') }, srcShort),
|
||||
h('span', { className: 'ss-pill' + (presetInfo.presetValue ? ' is-primary' : '') }, presetInfo.presetShortLabel),
|
||||
seat.modelSyncStatus === 'failed' ? h('span', { style: { color: 'var(--ss-error)', fontWeight: 500, flexShrink: 0 } }, '同步失败') : null,
|
||||
),
|
||||
),
|
||||
|
|
|
|||
|
|
@ -7,6 +7,96 @@ import { SEATS, SEAT_IDS, SEAT_GROUPS } from '../shared/roles.js'
|
|||
// 未选择模型时的固定文案,两端 UI 必须一致。
|
||||
export const UNCHOSEN_MODEL_LABEL = '请选择模型'
|
||||
|
||||
export const PRESET_OPTIONS = Object.freeze([
|
||||
{
|
||||
value: 'standard',
|
||||
label: '标准模式(直调工具)',
|
||||
shortLabel: '标准',
|
||||
description: '直接调用工具,不进代码沙盒,无 2 分钟审批超时,适合对话、挂卡、审阅与流转',
|
||||
},
|
||||
{
|
||||
value: 'ops-ptc',
|
||||
label: 'OPS PTC(代码批量)',
|
||||
shortLabel: 'PTC',
|
||||
description: '通过 run_code 沙盒批量并发调用工具,适合高频读写文件与工程检查',
|
||||
},
|
||||
])
|
||||
|
||||
const PRESET_LABELS = new Map(PRESET_OPTIONS.map(item => [item.value, item.label]))
|
||||
const PRESET_SHORT_LABELS = new Map(PRESET_OPTIONS.map(item => [item.value, item.shortLabel]))
|
||||
const STANDARD_RECOMMENDED_SEATS = new Set(['lead', ...SEAT_GROUPS.sansheng])
|
||||
|
||||
export function recommendedPresetForSeat(seatId) {
|
||||
return STANDARD_RECOMMENDED_SEATS.has(seatId) ? 'standard' : 'ops-ptc'
|
||||
}
|
||||
|
||||
export function presetLabel(preset) {
|
||||
if (!preset) return '跟随推荐'
|
||||
return PRESET_LABELS.get(preset) ?? String(preset)
|
||||
}
|
||||
|
||||
export function presetShortLabel(preset) {
|
||||
if (!preset) return '默认'
|
||||
return PRESET_SHORT_LABELS.get(preset) ?? String(preset)
|
||||
}
|
||||
|
||||
export const PRESET_SOURCE_LABELS = Object.freeze({
|
||||
project: '项目覆盖',
|
||||
global: '继承全局默认',
|
||||
'role-default': '按角色推荐',
|
||||
deployment: '跟随宿主默认',
|
||||
none: '跟随宿主默认',
|
||||
})
|
||||
|
||||
export function presetSourceLabel(source) {
|
||||
return PRESET_SOURCE_LABELS[source] ?? '跟随宿主默认'
|
||||
}
|
||||
|
||||
export function normalizePresetValue(value) {
|
||||
return value === 'standard' || value === 'ops-ptc' ? value : ''
|
||||
}
|
||||
|
||||
export function describeSeatPreset(seatId, rec, draftEntry, project) {
|
||||
const recommendedPreset = recommendedPresetForSeat(seatId)
|
||||
const safeRec = rec && typeof rec === 'object' ? rec : {}
|
||||
const presetSupported = Boolean(
|
||||
project?.capabilities?.seatPreset
|
||||
|| safeRec.configuredPreset !== undefined
|
||||
|| safeRec.agentPreset !== undefined
|
||||
|| safeRec.sessionPreset !== undefined
|
||||
|| safeRec.presetSource !== undefined
|
||||
)
|
||||
const backendPreset = normalizePresetValue(
|
||||
safeRec.configuredPreset ?? safeRec.agentPreset ?? '',
|
||||
)
|
||||
const hasDraft = Boolean(draftEntry && hasOwn(draftEntry, 'agentPreset'))
|
||||
const presetValue = hasDraft
|
||||
? normalizePresetValue(draftEntry.agentPreset)
|
||||
: backendPreset
|
||||
const sessionPreset = normalizePresetValue(safeRec.sessionPreset ?? '')
|
||||
const presetSource = safeRec.presetSource ?? (backendPreset ? 'project' : 'none')
|
||||
const effectivePreset = presetValue || (presetSupported ? recommendedPreset : sessionPreset || recommendedPreset)
|
||||
return {
|
||||
recommendedPreset,
|
||||
recommendedPresetLabel: presetLabel(recommendedPreset),
|
||||
recommendedPresetShortLabel: presetShortLabel(recommendedPreset),
|
||||
presetSupported,
|
||||
presetValue,
|
||||
configuredPreset: backendPreset || null,
|
||||
effectivePreset,
|
||||
presetLabel: presetValue ? presetLabel(presetValue) : `按角色推荐(${presetShortLabel(recommendedPreset)})`,
|
||||
presetShortLabel: presetValue ? presetShortLabel(presetValue) : `荐·${presetShortLabel(recommendedPreset)}`,
|
||||
presetSource,
|
||||
presetSourceLabel: presetSourceLabel(presetSource),
|
||||
sessionPreset: sessionPreset || null,
|
||||
sessionPresetLabel: sessionPreset ? presetLabel(sessionPreset) : '',
|
||||
presetSync: safeRec.presetSync ?? null,
|
||||
presetSyncStatus: safeRec.presetSync?.status ?? null,
|
||||
presetMismatch: Boolean(sessionPreset && presetValue && sessionPreset !== presetValue),
|
||||
presetOptions: PRESET_OPTIONS,
|
||||
}
|
||||
}
|
||||
|
||||
export const MODEL_SOURCE_LABELS = Object.freeze({
|
||||
project: '项目覆盖',
|
||||
global: '继承全局默认',
|
||||
|
|
@ -171,6 +261,7 @@ export function buildWorkbenchView(view, ui) {
|
|||
const seatStatus = typeof rec.status === 'string' ? rec.status : DEFAULT_SEAT_STATUS
|
||||
const configured = rec.configuredModel ?? rec.model ?? null
|
||||
const model = describeModel(configured, modelOptions)
|
||||
const preset = describeSeatPreset(id, rec, null, project)
|
||||
const runtime = rec.runtimeState && typeof rec.runtimeState === 'object' ? rec.runtimeState : null
|
||||
return {
|
||||
id,
|
||||
|
|
@ -185,6 +276,19 @@ export function buildWorkbenchView(view, ui) {
|
|||
modelSource: rec.modelSource ?? (rec.model ? 'project' : 'none'),
|
||||
modelSourceLabel: modelSourceLabel(rec.modelSource ?? (rec.model ? 'project' : 'none')),
|
||||
modelSyncStatus: rec.modelSync?.status ?? null,
|
||||
recommendedPreset: preset.recommendedPreset,
|
||||
recommendedPresetLabel: preset.recommendedPresetLabel,
|
||||
recommendedPresetShortLabel: preset.recommendedPresetShortLabel,
|
||||
presetSupported: preset.presetSupported,
|
||||
presetValue: preset.presetValue,
|
||||
configuredPreset: preset.configuredPreset,
|
||||
presetLabel: preset.presetLabel,
|
||||
presetShortLabel: preset.presetShortLabel,
|
||||
presetSource: preset.presetSource,
|
||||
presetSourceLabel: preset.presetSourceLabel,
|
||||
sessionPreset: preset.sessionPreset,
|
||||
presetSyncStatus: preset.presetSyncStatus,
|
||||
presetMismatch: preset.presetMismatch,
|
||||
runtimeState: runtime ? runtime.state : null,
|
||||
runtimeLabel: runtime ? runtime.label : null,
|
||||
approvalState: runtime ? runtime.approvalState ?? null : null,
|
||||
|
|
@ -195,6 +299,7 @@ export function buildWorkbenchView(view, ui) {
|
|||
const seatDef = SEATS[selectedSeatId]
|
||||
const seatRec = seatMap[selectedSeatId] ?? {}
|
||||
const draftEntry = draftOf(draft, selectedSeatId)
|
||||
const selectedPreset = describeSeatPreset(selectedSeatId, seatRec, draftEntry, project)
|
||||
let described
|
||||
if (hasOwn(draftEntry, 'modelValue')) {
|
||||
const raw = draftEntry.modelValue
|
||||
|
|
@ -238,6 +343,7 @@ export function buildWorkbenchView(view, ui) {
|
|||
seatCount: seats.length,
|
||||
boundCount,
|
||||
sessionCount,
|
||||
presetSupported: seats.some(seat => seat.presetSupported),
|
||||
},
|
||||
seats,
|
||||
groups: cloneGroups(),
|
||||
|
|
@ -257,6 +363,22 @@ export function buildWorkbenchView(view, ui) {
|
|||
sessionModel: seatRec.sessionModel ?? null,
|
||||
modelSync: seatRec.modelSync ?? null,
|
||||
modelStatus: seatRec.modelSync?.status ?? null,
|
||||
recommendedPreset: selectedPreset.recommendedPreset,
|
||||
recommendedPresetLabel: selectedPreset.recommendedPresetLabel,
|
||||
recommendedPresetShortLabel: selectedPreset.recommendedPresetShortLabel,
|
||||
presetSupported: selectedPreset.presetSupported,
|
||||
presetValue: selectedPreset.presetValue,
|
||||
configuredPreset: selectedPreset.configuredPreset,
|
||||
presetLabel: selectedPreset.presetLabel,
|
||||
presetShortLabel: selectedPreset.presetShortLabel,
|
||||
presetSource: selectedPreset.presetSource,
|
||||
presetSourceLabel: selectedPreset.presetSourceLabel,
|
||||
sessionPreset: selectedPreset.sessionPreset,
|
||||
sessionPresetLabel: selectedPreset.sessionPresetLabel,
|
||||
presetSync: selectedPreset.presetSync,
|
||||
presetStatus: selectedPreset.presetSyncStatus,
|
||||
presetMismatch: selectedPreset.presetMismatch,
|
||||
presetOptions: selectedPreset.presetOptions,
|
||||
instructions,
|
||||
modelOptions,
|
||||
dirty: Object.keys(draftEntry).length > 0,
|
||||
|
|
|
|||
|
|
@ -26,6 +26,7 @@ const ROUTES = {
|
|||
leadReports: (s, p) => s.leadReports(p.projectId),
|
||||
cardGet: (s, p) => s.cardGet(p.cardId),
|
||||
cardAnswer: (s, p) => s.cardAnswer(p.cardId, p.choice),
|
||||
cardDismiss: (s, p) => s.cardDismiss(p.projectId, p.cardId),
|
||||
cards: (s, p) => s.cards(p.projectId),
|
||||
setAvatar: (s, p) => s.setAvatar(p.projectId, p.seatId, p),
|
||||
clearAvatar: (s, p) => s.clearAvatar(p.projectId, p.seatId),
|
||||
|
|
|
|||
|
|
@ -28,6 +28,7 @@ export class SanshengService {
|
|||
this.leadReporter = leadReporter
|
||||
this.seatDelivery = seatDelivery
|
||||
this._seedStatus = { status: 'unknown', candidates: [] }
|
||||
this._cardActions = new Map()
|
||||
}
|
||||
|
||||
_flushLeadReports(projectId) {
|
||||
|
|
|
|||
|
|
@ -107,12 +107,42 @@ export const cardApprovalServiceMethods = {
|
|||
return { ok: true, card: structuredClone(card) }
|
||||
},
|
||||
|
||||
async _runCardAction(id, action) {
|
||||
const previous = this._cardActions.get(id) ?? Promise.resolve()
|
||||
const current = previous.then(action, action)
|
||||
this._cardActions.set(id, current)
|
||||
try { return await current }
|
||||
finally { if (this._cardActions.get(id) === current) this._cardActions.delete(id) }
|
||||
},
|
||||
|
||||
async cardDismiss(projectId, cardId) {
|
||||
await this._requireProject(projectId)
|
||||
const id = this._requireId(cleanText(cardId), 'cardId')
|
||||
return this._runCardAction(id, () => this.store.mutate(state => {
|
||||
const project = state.projects[projectId]
|
||||
const card = (project.cards ?? []).find(item => item.id === id)
|
||||
if (!card) throw new ServiceError('sansheng/card-not-found', '该项目没有这张卡片')
|
||||
if (card.kind !== 'question') throw new ServiceError('sansheng/card-invalid', '只有问答卡片可从待处理队列删除')
|
||||
if (card.status === 'dismissed') return { card: structuredClone(card) }
|
||||
if (card.status !== 'pending') throw new ServiceError('sansheng/card-invalid', '卡片已经处理,请刷新队列')
|
||||
card.status = 'dismissed'
|
||||
card.dismissedAt = Date.now()
|
||||
project.updatedAt = card.dismissedAt
|
||||
project.revision = (project.revision ?? 0) + 1
|
||||
return { card: structuredClone(card) }
|
||||
}))
|
||||
},
|
||||
|
||||
// 答题是普通用户消息(会唤醒丞相);审题结论只走 approval-center,不另造第二套决定。
|
||||
async cardAnswer(cardId, choice, actor = {}) {
|
||||
await this.store.ensureLoaded()
|
||||
const id = cleanText(cardId)
|
||||
const value = cleanText(choice)
|
||||
if (!id || !value) throw new ServiceError('sansheng/card-invalid', '缺少 cardId 或选择')
|
||||
return this._runCardAction(id, () => this._answerCard(id, value, actor))
|
||||
},
|
||||
|
||||
async _answerCard(id, value, actor) {
|
||||
await this.store.ensureLoaded()
|
||||
let project = null
|
||||
let card = null
|
||||
for (const candidate of this.store.list()) {
|
||||
|
|
@ -121,6 +151,7 @@ export const cardApprovalServiceMethods = {
|
|||
}
|
||||
if (!project || !card) throw new ServiceError('sansheng/card-not-found', `卡片 ${id} 不存在`)
|
||||
if (card.status === 'answered') return { ok: true, duplicate: true, card: structuredClone(card) }
|
||||
if (card.status === 'dismissed') throw new ServiceError('sansheng/card-dismissed', '这张问答卡片已删除')
|
||||
const option = card.options.find(item => item.value === value)
|
||||
if (!option) throw new ServiceError('sansheng/card-invalid', '卡片没有这个选项')
|
||||
const lead = project.seats?.lead
|
||||
|
|
|
|||
|
|
@ -118,6 +118,25 @@ test('问题卡:两张卡可以逆序回答,回答各自回到对应卡片',
|
|||
assert.deepEqual(followups.map(call => call.message.source.cardId), ['card-q2', 'card-q1'])
|
||||
})
|
||||
|
||||
test('删除旧问答卡保留记录,不能再回答或影响原生审批', async () => {
|
||||
const env = await setupCards()
|
||||
const question = await env.cardTool.execute({
|
||||
kind: 'question', title: '旧问题', body: '不再需要决定。',
|
||||
options: [{ label: 'A', value: 'a' }, { label: 'B', value: 'b' }],
|
||||
}, env.leadExec('obsolete-question'))
|
||||
const payload = { projectId: env.projectId, cardId: question.card.id }
|
||||
assert.equal((await env.api('cardDismiss', payload)).value.card.status, 'dismissed')
|
||||
assert.equal((await env.api('cardDismiss', payload)).value.card.status, 'dismissed')
|
||||
assert.equal((await env.api('cards', { projectId: env.projectId })).value.cards[0].status, 'dismissed')
|
||||
assert.equal((await env.api('cardAnswer', { cardId: question.card.id, choice: 'a' })).error.code, 'sansheng/card-dismissed')
|
||||
assert.equal(env.fake.calls.followup.length, 0)
|
||||
const { pending, entry } = await openApproval(env)
|
||||
const approval = await env.cardTool.execute({ kind: 'approval', title: '审批', body: '等待处理', approvalId: entry.id }, env.leadExec('live-approval'))
|
||||
assert.equal((await env.api('cardDismiss', { projectId: env.projectId, cardId: approval.card.id })).error.code, 'sansheng/card-invalid')
|
||||
await env.api('cardAnswer', { cardId: approval.card.id, choice: 'reject' })
|
||||
assert.equal(await pending, 'rejected')
|
||||
})
|
||||
|
||||
test('卡片只允许丞相挂出和回答,拒绝跨项目审批', async () => {
|
||||
const env = await setupCards()
|
||||
const wrongSeat = await env.cardTool.execute({
|
||||
|
|
|
|||
|
|
@ -0,0 +1,186 @@
|
|||
import test from 'node:test'
|
||||
import assert from 'node:assert/strict'
|
||||
import { readFileSync } from 'node:fs'
|
||||
import { fileURLToPath } from 'node:url'
|
||||
import { dirname, join } from 'node:path'
|
||||
import {
|
||||
collectTurnToolCalls,
|
||||
matchTurnCards,
|
||||
isApprovalCardExpired,
|
||||
mergePendingItems,
|
||||
} from '../src/client/pending-model.js'
|
||||
import {
|
||||
buildWorkbenchView,
|
||||
PRESET_OPTIONS,
|
||||
recommendedPresetForSeat,
|
||||
updateDraft,
|
||||
} from '../src/client/workbench.js'
|
||||
|
||||
const HERE = dirname(fileURLToPath(import.meta.url))
|
||||
const ROOT = dirname(HERE)
|
||||
|
||||
test('collectTurnToolCalls 提取直调与 PTC 嵌套调用并区分普通回合', () => {
|
||||
const ptcTurn = {
|
||||
steps: [
|
||||
{
|
||||
data: new Map([
|
||||
['assistant-step', {
|
||||
blocks: [{ kind: 'tool-call', callId: 'call-direct', name: 'sansheng_card' }],
|
||||
}],
|
||||
]),
|
||||
nodes: [
|
||||
{
|
||||
kind: 'tool-call',
|
||||
data: {
|
||||
root: {
|
||||
kind: 'tool-call',
|
||||
callId: 'call-ptc',
|
||||
call: { name: 'run_code' },
|
||||
subCalls: [
|
||||
{ callId: 'call-ptc:ptc:1', name: 'sansheng_card' },
|
||||
],
|
||||
},
|
||||
},
|
||||
},
|
||||
],
|
||||
},
|
||||
],
|
||||
}
|
||||
const got = collectTurnToolCalls(ptcTurn)
|
||||
assert.equal(got.hasCardOrPtcCall, true)
|
||||
assert.deepEqual(got.callIds, ['call-direct', 'call-ptc', 'call-ptc:ptc:1'])
|
||||
|
||||
const normalTurn = {
|
||||
steps: [
|
||||
{
|
||||
assistantStep: {
|
||||
blocks: [{ kind: 'tool-call', callId: 'call-read', name: 'read_file' }],
|
||||
},
|
||||
},
|
||||
],
|
||||
}
|
||||
const plain = collectTurnToolCalls(normalTurn)
|
||||
assert.equal(plain.hasCardOrPtcCall, false)
|
||||
assert.deepEqual(plain.callIds, ['call-read'])
|
||||
})
|
||||
|
||||
test('matchTurnCards 精确匹配直调 ID 与 :ptc: 前缀卡片,不误匹配相似前缀', () => {
|
||||
const cards = [
|
||||
{ id: 'c1', status: 'pending' },
|
||||
{ id: 'c2:ptc:1', status: 'pending' },
|
||||
{ id: 'c20', status: 'pending' },
|
||||
]
|
||||
const matched = matchTurnCards(cards, ['c1', 'c2'])
|
||||
assert.deepEqual(matched.map(c => c.id), ['c1', 'c2:ptc:1'])
|
||||
})
|
||||
|
||||
test('isApprovalCardExpired 仅在健康审批队列中缺少对应 approvalId 时判为已失效', () => {
|
||||
const card = { id: 'card-1', kind: 'approval', status: 'pending', approvalId: 'apr-1' }
|
||||
assert.equal(isApprovalCardExpired(card, [], null), false)
|
||||
assert.equal(isApprovalCardExpired(card, [], { degraded: true }), false)
|
||||
assert.equal(isApprovalCardExpired(card, [{ id: 'apr-1' }], { degraded: false }), false)
|
||||
assert.equal(isApprovalCardExpired(card, [], { degraded: false }), true)
|
||||
assert.equal(isApprovalCardExpired({ ...card, status: 'answered' }, [], { degraded: false }), false)
|
||||
assert.equal(isApprovalCardExpired({ id: 'q1', kind: 'question', status: 'pending' }, [], { degraded: false }), false)
|
||||
})
|
||||
|
||||
test('mergePendingItems 合并工具审批、审批附带卡片、问答卡、决定与流程阻塞', () => {
|
||||
const out = mergePendingItems({
|
||||
approvals: [{ id: 'apr-1', seatId: 'menxia', tool: 'pwsh' }],
|
||||
approvalStatus: { available: true, degraded: false },
|
||||
cards: [
|
||||
{ id: 'c-old', kind: 'approval', status: 'pending', approvalId: 'apr-1', title: '旧卡' },
|
||||
{ id: 'c-new', kind: 'approval', status: 'pending', approvalId: 'apr-1', title: '新卡' },
|
||||
{ id: 'c-q', kind: 'question', status: 'pending', title: '选方案 A 还是 B?' },
|
||||
{ id: 'c-done', kind: 'question', status: 'answered', title: '已答问题' },
|
||||
],
|
||||
tasks: [
|
||||
{
|
||||
id: 't1',
|
||||
status: 'dispatched',
|
||||
workflowBlockage: { label: '从交门下审核', reason: '宿主审批已取消' },
|
||||
decisions: [{ id: 'd1', status: 'pending', question: '是否提交?' }],
|
||||
},
|
||||
{
|
||||
id: 't2',
|
||||
status: 'done',
|
||||
workflowBlockage: { label: '历史记录', reason: '已完结' },
|
||||
},
|
||||
],
|
||||
})
|
||||
|
||||
assert.equal(out.degraded, false)
|
||||
assert.equal(out.approvals.length, 1)
|
||||
assert.equal(out.approvals[0].card?.title, '新卡')
|
||||
assert.deepEqual(out.questions.map(q => q.id), ['c-q'])
|
||||
assert.equal(out.decisions.length, 1)
|
||||
assert.deepEqual(out.blockedTasks.map(t => t.id), ['t1'])
|
||||
assert.equal(out.pendingCount, 3)
|
||||
|
||||
const degradedOut = mergePendingItems({
|
||||
approvals: [{ id: 'apr-1', seatId: 'menxia' }],
|
||||
approvalStatus: { degraded: true },
|
||||
cards: [{ id: 'c-q', kind: 'question', status: 'pending', title: 'Q' }],
|
||||
tasks: [],
|
||||
})
|
||||
assert.equal(degradedOut.degraded, true)
|
||||
assert.equal(degradedOut.approvals.length, 0)
|
||||
assert.equal(degradedOut.questions.length, 1)
|
||||
assert.equal(degradedOut.pendingCount, 1)
|
||||
})
|
||||
|
||||
test('workbench 推荐分工与执行模式草稿视图:中枢/三省为 standard,六部为 ops-ptc', () => {
|
||||
for (const id of ['lead', 'zhongshu', 'menxia', 'shangshu']) {
|
||||
assert.equal(recommendedPresetForSeat(id), 'standard')
|
||||
}
|
||||
for (const id of ['libu', 'hubu', 'lipu', 'bingbu', 'xingbu', 'gongbu']) {
|
||||
assert.equal(recommendedPresetForSeat(id), 'ops-ptc')
|
||||
}
|
||||
assert.deepEqual(PRESET_OPTIONS.map(p => p.value), ['standard', 'ops-ptc'])
|
||||
|
||||
const legacyView = buildWorkbenchView({
|
||||
project: {
|
||||
id: 'p1',
|
||||
name: '测试项目',
|
||||
status: 'ready',
|
||||
seats: {
|
||||
menxia: { id: 'menxia', status: 'bound', model: { provider: 'auto', model: 'gpt-5' } },
|
||||
},
|
||||
},
|
||||
}, { selectedSeatId: 'menxia', draft: updateDraft({}, 'menxia', { agentPreset: 'standard' }) })
|
||||
|
||||
assert.equal(legacyView.project.presetSupported, false)
|
||||
assert.equal(legacyView.selected.recommendedPreset, 'standard')
|
||||
assert.equal(legacyView.selected.presetValue, 'standard')
|
||||
assert.equal(legacyView.selected.dirty, true)
|
||||
|
||||
const enabledView = buildWorkbenchView({
|
||||
project: {
|
||||
id: 'p2',
|
||||
name: '已启用模式后端项目',
|
||||
status: 'ready',
|
||||
capabilities: { seatPreset: true },
|
||||
seats: {
|
||||
gongbu: { id: 'gongbu', status: 'bound', configuredPreset: 'ops-ptc', sessionPreset: 'ops-ptc' },
|
||||
},
|
||||
},
|
||||
}, { selectedSeatId: 'gongbu' })
|
||||
|
||||
assert.equal(enabledView.project.presetSupported, true)
|
||||
assert.equal(enabledView.selected.presetValue, 'ops-ptc')
|
||||
assert.equal(enabledView.selected.sessionPreset, 'ops-ptc')
|
||||
assert.equal(enabledView.selected.presetMismatch, false)
|
||||
})
|
||||
|
||||
test('前端源码契约:index.js 同时注册 turnTail,workbench 组件无 inherit 选项值', () => {
|
||||
const indexSrc = readFileSync(join(ROOT, 'src/client/index.js'), 'utf8')
|
||||
const v2Src = readFileSync(join(ROOT, 'src/client/workbench-v2.js'), 'utf8')
|
||||
const mwbSrc = readFileSync(join(ROOT, 'src/client/master-workbench.js'), 'utf8')
|
||||
|
||||
assert.match(indexSrc, /conversation\.chat\.turnTail/)
|
||||
assert.match(indexSrc, /dsh-sansheng:turn-tail-cards/)
|
||||
assert.match(v2Src, /mergePendingItems/)
|
||||
assert.match(mwbSrc, /mergePendingItems/)
|
||||
assert.doesNotMatch(v2Src, /value:\s*['"]inherit['"]/)
|
||||
assert.doesNotMatch(mwbSrc, /value:\s*['"]inherit['"]/)
|
||||
})
|
||||
Loading…
Reference in New Issue