1174 lines
51 KiB
JavaScript
1174 lines
51 KiB
JavaScript
window.__ModuleLoader__.load({
|
||
id: 'dsh-sansheng-sansheng',
|
||
factory: (require) => {
|
||
var module = { exports: {} }
|
||
var exports = module.exports
|
||
Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' })
|
||
|
||
const React = require('react')
|
||
const h = React.createElement
|
||
|
||
const TAB_ID = 'sansheng-roles'
|
||
const TAB_KIND = 'sansheng-roles'
|
||
const CSS_ID = 'dsh-sansheng-roles'
|
||
const POLL_MS = 4000
|
||
const ACTIVE_KEY = 'dsh.sansheng.activeProject'
|
||
const ROLE_ORDER = ['lead', 'shangshu', 'gongbu']
|
||
const ROLE_MARK = { lead: '丞', shangshu: '尚', gongbu: '工' }
|
||
const ROLE_LABEL = { lead: '丞相', shangshu: '尚书', gongbu: '工部' }
|
||
const MODEL_FIELDS = [
|
||
{ role: 'lead', label: '丞相模型' },
|
||
{ role: 'shangshu', label: '尚书模型' },
|
||
{ role: 'gongbu', label: '工部模型' },
|
||
]
|
||
|
||
const CSS = `
|
||
.ss-root{display:flex;flex-direction:column;height:100%;min-height:0;background:var(--dsw-alias-bg-layer-1,#fff);color:var(--dsw-alias-label-primary,#1f2329);font-size:13px;line-height:20px}
|
||
.ss-bar{display:flex;align-items:center;gap:8px;padding:8px 12px;border-bottom:1px solid var(--dsw-alias-border-l1,rgba(127,127,127,.14));flex:none;min-width:0}
|
||
.ss-bar strong{font-size:13px;font-weight:600;white-space:nowrap;overflow:hidden;text-overflow:ellipsis;min-width:0}
|
||
.ss-bar select{appearance:none;border:1px solid var(--dsw-alias-border-l2,rgba(127,127,127,.24));background:var(--dsw-alias-bg-layer-2,rgba(127,127,127,.06));color:inherit;font:inherit;font-size:12px;padding:2px 22px 2px 8px;border-radius:7px;min-height:26px;max-width:100%}
|
||
.ss-bar-note{margin-left:auto;font-size:11px;color:var(--dsw-alias-label-tertiary,#8a8f98);white-space:nowrap;flex:none}
|
||
.ss-phase{flex:none;border:1px solid var(--dsw-alias-border-l2,rgba(127,127,127,.24));border-radius:999px;padding:0 7px;font-size:10.5px;line-height:17px;color:var(--dsw-alias-label-secondary,#5b616b);background:var(--dsw-alias-bg-layer-2,rgba(127,127,127,.05))}
|
||
.ss-phase[data-tone="ok"]{color:#1a9d6a;border-color:color-mix(in srgb,#1a9d6a 40%,transparent)}
|
||
.ss-phase[data-tone="active"]{color:var(--dsw-alias-state-business-primary,#3b82f6);border-color:color-mix(in srgb,var(--dsw-alias-state-business-primary,#3b82f6) 40%,transparent)}
|
||
.ss-phase[data-tone="attention"]{color:#b7791f;border-color:color-mix(in srgb,#b7791f 40%,transparent)}
|
||
.ss-phase[data-tone="warn"]{color:var(--dsw-alias-state-error-primary,#dc2626);border-color:color-mix(in srgb,var(--dsw-alias-state-error-primary,#dc2626) 40%,transparent)}
|
||
.ss-strip{flex:none;padding:4px 12px;font-size:11px;line-height:17px;color:var(--dsw-alias-state-error-primary,#dc2626);background:color-mix(in srgb,var(--dsw-alias-state-error-primary,#dc2626) 7%,transparent);border-bottom:1px solid color-mix(in srgb,var(--dsw-alias-state-error-primary,#dc2626) 18%,transparent);word-break:break-word}
|
||
.ss-list{flex:1;min-height:0;overflow:auto;display:flex;flex-direction:column;gap:10px;padding:12px}
|
||
.ss-card{position:relative;display:flex;flex-direction:column;gap:6px;padding:11px 12px;border:1px solid var(--dsw-alias-border-l2,rgba(127,127,127,.2));border-radius:12px;background:var(--dsw-alias-bg-layer-2,rgba(127,127,127,.04));text-align:left;color:inherit;font:inherit;width:100%;min-width:0}
|
||
.ss-card[data-clickable="1"]{cursor:pointer}
|
||
.ss-card[data-clickable="1"]:hover,.ss-card[data-clickable="1"]:focus-visible{border-color:color-mix(in srgb,var(--dsw-alias-state-business-primary,#3b82f6) 55%,transparent);background:var(--dsw-alias-bg-layer-3,rgba(127,127,127,.08))}
|
||
.ss-card[data-role="lead"]{--ss-role:#b8860b}
|
||
.ss-card[data-role="shangshu"]{--ss-role:#2f6fed}
|
||
.ss-card[data-role="gongbu"]{--ss-role:#12805c}
|
||
.ss-card[data-tone="warn"]{border-color:color-mix(in srgb,var(--dsw-alias-state-error-primary,#dc2626) 45%,transparent)}
|
||
.ss-card-head{display:flex;align-items:center;gap:8px;min-width:0}
|
||
.ss-mark{flex:none;width:22px;height:22px;border-radius:7px;display:inline-flex;align-items:center;justify-content:center;font-size:11px;font-weight:600;color:#fff;background:var(--ss-role,#666)}
|
||
.ss-card-head strong{font-size:13px;font-weight:600;letter-spacing:.02em}
|
||
.ss-dot{flex:none;margin-left:auto;width:7px;height:7px;border-radius:50%;background:var(--dsw-alias-label-tertiary,#9ca3af)}
|
||
.ss-card[data-tone="active"] .ss-dot{background:var(--dsw-alias-state-business-primary,#3b82f6)}
|
||
.ss-card[data-tone="ok"] .ss-dot{background:#1a9d6a}
|
||
.ss-card[data-tone="warn"] .ss-dot{background:var(--dsw-alias-state-error-primary,#dc2626)}
|
||
.ss-card[data-tone="attention"] .ss-dot{background:#c9871f}
|
||
.ss-duty{font-size:11px;color:var(--dsw-alias-label-tertiary,#8a8f98);white-space:nowrap;overflow:hidden;text-overflow:ellipsis}
|
||
.ss-model-select{appearance:none;border:0;background:transparent;color:var(--dsw-alias-label-secondary,#5b616b);font:inherit;font-size:11px;max-width:55%;padding:0 14px 0 0;margin:0;cursor:pointer;text-overflow:ellipsis}
|
||
.ss-model-select:hover,.ss-model-select:focus-visible{color:var(--dsw-alias-label-primary,#1f2329)}
|
||
.ss-model-text{color:var(--dsw-alias-label-tertiary,#8a8f98)}
|
||
.ss-main{font-size:12.5px;font-weight:500;white-space:nowrap;overflow:hidden;text-overflow:ellipsis}
|
||
.ss-sub{font-size:11px;line-height:17px;color:var(--dsw-alias-label-secondary,#5b616b);display:-webkit-box;-webkit-line-clamp:2;-webkit-box-orient:vertical;overflow:hidden;word-break:break-word}
|
||
.ss-foot{display:flex;align-items:center;gap:6px;font-size:10.5px;color:var(--dsw-alias-label-tertiary,#8a8f98);min-width:0}
|
||
.ss-foot span{white-space:nowrap;overflow:hidden;text-overflow:ellipsis}
|
||
.ss-chip{flex:none;border:1px solid var(--dsw-alias-border-l2,rgba(127,127,127,.24));border-radius:999px;padding:0 7px;font-size:10px;line-height:16px}
|
||
.ss-missing{display:flex;flex-direction:column;gap:3px;padding-top:2px}
|
||
.ss-repair{appearance:none;border:0;background:transparent;color:var(--dsw-alias-state-error-primary,#dc2626);font:inherit;font-size:11px;line-height:17px;text-align:left;padding:0;cursor:pointer;text-decoration:underline;text-underline-offset:2px}
|
||
.ss-reason{font-size:10.5px;line-height:15px;color:var(--dsw-alias-label-tertiary,#8a8f98);word-break:break-word}
|
||
.ss-details{border:1px solid var(--dsw-alias-border-l2,rgba(127,127,127,.2));border-radius:10px;background:var(--dsw-alias-bg-layer-2,rgba(127,127,127,.03));padding:0 10px}
|
||
.ss-details[open]{padding-bottom:10px}
|
||
.ss-summary{cursor:pointer;font-size:11.5px;line-height:30px;color:var(--dsw-alias-label-secondary,#5b616b);list-style-position:inside;white-space:nowrap;overflow:hidden;text-overflow:ellipsis}
|
||
.ss-form{display:flex;flex-direction:column;gap:8px;padding-top:2px}
|
||
.ss-field{display:flex;flex-direction:column;gap:3px;font-size:11px;color:var(--dsw-alias-label-secondary,#5b616b)}
|
||
.ss-field input{appearance:none;border:1px solid var(--dsw-alias-border-l2,rgba(127,127,127,.26));background:var(--dsw-alias-bg-layer-1,#fff);color:inherit;font:inherit;font-size:12px;line-height:18px;padding:4px 7px;border-radius:6px;min-width:0}
|
||
.ss-field input:focus-visible{outline:2px solid color-mix(in srgb,var(--dsw-alias-state-business-primary,#3b82f6) 45%,transparent);outline-offset:0}
|
||
.ss-actions{display:flex;align-items:center;gap:8px;flex-wrap:wrap}
|
||
.ss-btn{appearance:none;border:1px solid var(--dsw-alias-border-l2,rgba(127,127,127,.26));background:var(--dsw-alias-bg-layer-2,rgba(127,127,127,.06));color:inherit;font:inherit;font-size:11.5px;line-height:18px;padding:3px 10px;border-radius:7px;cursor:pointer;min-height:26px}
|
||
.ss-btn:hover,.ss-btn:focus-visible{background:var(--dsw-alias-bg-layer-3,rgba(127,127,127,.12))}
|
||
.ss-btn[disabled]{opacity:.55;cursor:default}
|
||
.ss-btn-primary{border-color:color-mix(in srgb,var(--dsw-alias-state-business-primary,#3b82f6) 55%,transparent);background:var(--dsw-alias-state-business-primary,#3b82f6);color:#fff}
|
||
.ss-btn-primary:hover,.ss-btn-primary:focus-visible{background:color-mix(in srgb,var(--dsw-alias-state-business-primary,#3b82f6) 86%,#000)}
|
||
.ss-form-note{font-size:10.5px;line-height:15px;color:var(--dsw-alias-label-tertiary,#8a8f98)}
|
||
.ss-ok{color:#1a9d6a;font-size:11px;line-height:17px}
|
||
.ss-history{display:flex;flex-direction:column;gap:5px;padding-top:2px}
|
||
.ss-history-item{display:flex;align-items:baseline;gap:6px;font-size:11px;line-height:16px;color:var(--dsw-alias-label-secondary,#5b616b);min-width:0}
|
||
.ss-history-item b{font-weight:600}
|
||
.ss-bot-list{display:flex;flex-direction:column;gap:2px;padding-top:2px}
|
||
.ss-bot-rooms{border-top:1px solid var(--dsw-alias-border-l1,rgba(127,127,127,.14));margin-top:6px;padding-top:6px}
|
||
.ss-bot-row{display:flex;align-items:center;gap:6px;width:100%;min-width:0;border:0;background:none;color:inherit;font:inherit;font-size:12px;line-height:22px;padding:3px 6px;border-radius:6px;cursor:pointer;text-align:left}
|
||
.ss-bot-row:hover,.ss-bot-row:focus-visible{background:var(--dsw-alias-bg-layer-2,rgba(127,127,127,.08))}
|
||
.ss-bot-name{min-width:0;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;font-weight:500}
|
||
.ss-bot-role,.ss-bot-project{font-size:10.5px;color:var(--dsw-alias-label-tertiary,#8a8f98);white-space:nowrap;overflow:hidden;text-overflow:ellipsis}
|
||
.ss-bot-project{margin-left:auto;max-width:45%}
|
||
.ss-history-meta{margin-left:auto;color:var(--dsw-alias-label-tertiary,#8a8f98);white-space:nowrap;font-size:10px}
|
||
.ss-empty{display:flex;flex-direction:column;gap:8px;align-items:flex-start;padding:18px 4px;color:var(--dsw-alias-label-secondary,#5b616b);font-size:12px}
|
||
.ss-empty .ss-details{width:100%;box-sizing:border-box}
|
||
.ss-empty code{font-size:11px;background:var(--dsw-alias-bg-layer-3,rgba(127,127,127,.14));padding:1px 5px;border-radius:5px}
|
||
.ss-error{color:var(--dsw-alias-state-error-primary,#dc2626);font-size:11px;line-height:17px;word-break:break-word}
|
||
.ss-tab-title{display:inline-flex;align-items:center;gap:6px;min-width:0}
|
||
.ss-tab-mark{width:18px;height:18px;border-radius:6px;display:inline-flex;align-items:center;justify-content:center;font-size:9px;font-weight:600;color:#fff;background:linear-gradient(135deg,#b8860b,#2f6fed 60%,#12805c)}
|
||
.ss-tab-count{border-radius:999px;padding:0 6px;font-size:10px;line-height:15px;background:var(--dsw-alias-state-business-primary,#3b82f6);color:#fff}
|
||
.ss-open{appearance:none;border:0;background:0 0;color:var(--dsw-alias-label-tertiary,#8a8f98);font:inherit;font-size:12px;display:inline-flex;align-items:center;gap:5px;padding:3px 7px;border-radius:6px;cursor:pointer;min-height:26px}
|
||
.ss-open:hover,.ss-open:focus-visible{color:var(--dsw-alias-label-primary,#1f2329);background:var(--dsw-alias-bg-layer-2,rgba(127,127,127,.08))}
|
||
.ss-footer-entry{box-sizing:border-box;display:block;width:36px;min-width:36px}
|
||
.ss-footer-entry.is-wide{width:auto;max-width:100%}
|
||
.ss-footer-entry .ss-open{width:100%;justify-content:flex-start;min-height:36px;padding:0 8px;border-radius:8px;font-size:14px}
|
||
.ss-footer-entry:not(.is-wide) .ss-open{justify-content:center;padding:0;gap:0}
|
||
`
|
||
|
||
function ensureCss() {
|
||
if (typeof document === 'undefined') return
|
||
try {
|
||
const selector = 'style[data-plugin-css=' + JSON.stringify(CSS_ID) + ']'
|
||
if (document.querySelector(selector)) return
|
||
const style = document.createElement('style')
|
||
style.setAttribute('data-plugin-css', CSS_ID)
|
||
style.textContent = CSS
|
||
document.head.appendChild(style)
|
||
} catch (error) {
|
||
/* 样式注入失败不影响功能 */
|
||
}
|
||
}
|
||
|
||
function messageOf(error) {
|
||
if (error === null || error === undefined) return '未知错误'
|
||
if (error.message) return String(error.message)
|
||
return String(error)
|
||
}
|
||
|
||
function serviceOf(ctx, name) {
|
||
try {
|
||
if (ctx && typeof ctx.get === 'function') {
|
||
const service = ctx.get(name, false)
|
||
if (service) return service
|
||
}
|
||
} catch (error) { /* 老宿主没有该服务 */ }
|
||
try {
|
||
return ctx ? ctx[name] : undefined
|
||
} catch (error) {
|
||
return undefined
|
||
}
|
||
}
|
||
|
||
function contextMenuServiceOf(ctx) {
|
||
return serviceOf(ctx, 'contextMenus')
|
||
}
|
||
|
||
function notifyUser(ctx, text) {
|
||
const message = String(text || '')
|
||
if (!message) return false
|
||
try {
|
||
if (ctx && typeof ctx.toast === 'function') {
|
||
ctx.toast(message)
|
||
return true
|
||
}
|
||
if (ctx && typeof ctx.notify === 'function') {
|
||
ctx.notify(message)
|
||
return true
|
||
}
|
||
const toast = ctx && ctx.toast
|
||
if (toast) {
|
||
for (const name of ['show', 'notify', 'info', 'message', 'push', 'add']) {
|
||
if (typeof toast[name] === 'function') {
|
||
toast[name](message)
|
||
return true
|
||
}
|
||
}
|
||
}
|
||
} catch (error) { /* 继续尝试状态栏 */ }
|
||
try {
|
||
const status = serviceOf(ctx, 'statusBar')
|
||
if (status) {
|
||
for (const name of ['notice', 'show', 'set']) {
|
||
if (typeof status[name] === 'function') {
|
||
status[name](message)
|
||
return true
|
||
}
|
||
}
|
||
}
|
||
} catch (error) { /* console 兜底 */ }
|
||
try { console.warn('[三省六部] ' + message) } catch (error) { /* 忽略 */ }
|
||
return false
|
||
}
|
||
|
||
function listSnapshotOf(ctx, name) {
|
||
try {
|
||
const service = serviceOf(ctx, name)
|
||
const list = service && service.list
|
||
return list && typeof list.getSnapshot === 'function' ? list.getSnapshot() : undefined
|
||
} catch (error) {
|
||
return undefined
|
||
}
|
||
}
|
||
|
||
/** 当前主会话:宿主事实为 retainedBy.mainView > 0。 */
|
||
function currentSessionIdOf(ctx) {
|
||
const snapshot = listSnapshotOf(ctx, 'sessions') || {}
|
||
const byId = snapshot.byId && typeof snapshot.byId === 'object' ? snapshot.byId : {}
|
||
for (const [key, value] of Object.entries(byId)) {
|
||
const retained = value && value.retainedBy && value.retainedBy.mainView
|
||
if (typeof retained === 'number' && retained > 0) return value.id || key
|
||
}
|
||
const items = Array.isArray(snapshot.items) ? snapshot.items : []
|
||
const hit = items.find(value => {
|
||
const retained = value && value.retainedBy && value.retainedBy.mainView
|
||
return typeof retained === 'number' && retained > 0
|
||
})
|
||
return hit ? (hit.id || hit.sessionId) : null
|
||
}
|
||
|
||
function workspaceItemsOf(ctx) {
|
||
const snapshot = listSnapshotOf(ctx, 'workspaces') || {}
|
||
return Array.isArray(snapshot.items) ? snapshot.items : []
|
||
}
|
||
|
||
function workspaceItemOf(ctx, workspaceId) {
|
||
return workspaceItemsOf(ctx).find(item => item && (item.workspaceId === workspaceId || item.id === workspaceId))
|
||
}
|
||
|
||
function sessionIdsOfWorkspace(ctx, workspaceId) {
|
||
const item = workspaceItemOf(ctx, workspaceId)
|
||
return item && Array.isArray(item.sessionIds) ? item.sessionIds.slice() : []
|
||
}
|
||
|
||
function basename(path) {
|
||
const parts = String(path || '').split(/[\\/]+/).filter(Boolean)
|
||
return parts.length > 0 ? parts[parts.length - 1] : ''
|
||
}
|
||
|
||
/** 当前项目上下文。没有明确的主会话时返回空 workspaceId,不拿第一个项目冒充。 */
|
||
function workspaceContextOf(ctx) {
|
||
const sessionId = currentSessionIdOf(ctx)
|
||
if (!sessionId) return { workspaceId: null, sessionId: null, path: '', displayTitle: '' }
|
||
const item = workspaceItemsOf(ctx).find(candidate => Array.isArray(candidate && candidate.sessionIds) && candidate.sessionIds.includes(sessionId))
|
||
return {
|
||
workspaceId: item ? (item.workspaceId || item.id || null) : null,
|
||
sessionId,
|
||
path: item ? (item.path || '') : '',
|
||
displayTitle: item ? (item.displayTitle || item.title || '') : '',
|
||
}
|
||
}
|
||
|
||
function workspaceIdOf(ctx) {
|
||
const context = workspaceContextOf(ctx)
|
||
return context.workspaceId || null
|
||
}
|
||
|
||
function selectedSessionIdOf(ctx, workspaceId) {
|
||
const ui = serviceOf(ctx, 'uiWorkspace')
|
||
if (!ui) return null
|
||
const candidates = [ui.selection, ui.state]
|
||
let selected = null
|
||
for (const source of candidates) {
|
||
try {
|
||
if (source && typeof source.getSnapshot === 'function') {
|
||
const snapshot = source.getSnapshot()
|
||
const id = snapshot && (snapshot.sessionId || snapshot.id)
|
||
if (id) { selected = id; break }
|
||
}
|
||
} catch (error) { /* 忽略 */ }
|
||
}
|
||
if (!selected) return null
|
||
if (!workspaceId) return selected
|
||
const item = workspaceItemOf(ctx, workspaceId)
|
||
return item && Array.isArray(item.sessionIds) && item.sessionIds.includes(selected) ? selected : null
|
||
}
|
||
|
||
function stateUrlOf(context) {
|
||
const params = []
|
||
if (context && context.workspaceId) params.push('workspaceId=' + encodeURIComponent(context.workspaceId))
|
||
if (context && context.sessionId) params.push('sessionId=' + encodeURIComponent(context.sessionId))
|
||
return '/sansheng/state' + (params.length > 0 ? '?' + params.join('&') : '')
|
||
}
|
||
|
||
async function fetchState(ctx, context, signal) {
|
||
const response = await fetch(stateUrlOf(context), { cache: 'no-cache', signal })
|
||
if (!response || response.ok === false) throw new Error('HTTP ' + (response && response.status ? response.status : '???'))
|
||
return await response.json()
|
||
}
|
||
|
||
async function postJson(url, body) {
|
||
const response = await fetch(url, {
|
||
method: 'POST',
|
||
headers: { 'content-type': 'application/json' },
|
||
body: JSON.stringify(body),
|
||
})
|
||
let payload = null
|
||
try { payload = await response.json() } catch (error) { /* 非 JSON 错误体 */ }
|
||
if (!response || response.ok === false) {
|
||
throw new Error((payload && payload.error) || ('HTTP ' + (response && response.status ? response.status : '???')))
|
||
}
|
||
return payload
|
||
}
|
||
|
||
function isStale(requestId, latestRequestId) {
|
||
return requestId !== latestRequestId
|
||
}
|
||
|
||
function contextSignature(context) {
|
||
if (!context) return ''
|
||
return String(context.workspaceId || '') + '|' + String(context.sessionId || '')
|
||
}
|
||
|
||
const bindingCache = new Map()
|
||
|
||
function projectsOf(data) {
|
||
if (!data) return []
|
||
if (Array.isArray(data.projects)) return data.projects
|
||
if (data.projects && typeof data.projects === 'object') return Object.values(data.projects)
|
||
return []
|
||
}
|
||
|
||
function rememberState(data, context) {
|
||
for (const project of projectsOf(data)) {
|
||
const key = project && (project.workspaceId || project.hostWorkspaceId)
|
||
if (key) bindingCache.set(String(key), true)
|
||
}
|
||
if (context && context.workspaceId) {
|
||
bindingCache.set(String(context.workspaceId), Boolean(data && data.current))
|
||
}
|
||
}
|
||
|
||
function createStatePoller(options) {
|
||
const opts = options || {}
|
||
const ctx = opts.ctx
|
||
const fetchImpl = opts.fetchImpl || (typeof fetch === 'function' ? fetch : null)
|
||
const intervalMs = Number.isFinite(opts.intervalMs) ? opts.intervalMs : POLL_MS
|
||
const onChange = typeof opts.onChange === 'function' ? opts.onChange : () => {}
|
||
let latestRequestId = 0
|
||
let stopped = false
|
||
let timer = null
|
||
let lastData = null
|
||
let lastUpdatedAt = 0
|
||
let lastSignature = null
|
||
const schedule = delay => {
|
||
if (stopped) return
|
||
if (timer) clearTimeout(timer)
|
||
timer = setTimeout(tick, delay)
|
||
}
|
||
const tick = async () => {
|
||
if (stopped) return
|
||
const requestId = ++latestRequestId
|
||
// 项目切换以宿主当前 workspace 为准;不拿上次下拉选择去覆盖它,
|
||
// 否则从项目树切到 B 后仍会请求 A 的工作区,右栏永远停在旧项目。
|
||
const context = workspaceContextOf(ctx)
|
||
const signature = contextSignature(context)
|
||
let retryImmediately = false
|
||
try {
|
||
if (!fetchImpl) throw new Error('宿主没有 fetch')
|
||
const response = await fetchImpl(stateUrlOf(context), { cache: 'no-cache' })
|
||
if (!response || response.ok === false) throw new Error('HTTP ' + (response && response.status ? response.status : '???'))
|
||
const data = await response.json()
|
||
if (stopped || isStale(requestId, latestRequestId)) return
|
||
if (contextSignature(workspaceContextOf(ctx)) !== signature) {
|
||
retryImmediately = true
|
||
return
|
||
}
|
||
lastData = data
|
||
lastUpdatedAt = Date.now()
|
||
lastSignature = signature
|
||
rememberState(data, context)
|
||
onChange({ loading: false, error: null, data, updatedAt: lastUpdatedAt, context })
|
||
} catch (error) {
|
||
if (stopped || isStale(requestId, latestRequestId)) return
|
||
// 只有同一项目断连才展示上次数据;切到 B 后失败不能把 A 的卡片
|
||
// 配上 B 的上下文(Q12)。
|
||
const sameProject = signature === lastSignature
|
||
onChange({
|
||
loading: false,
|
||
error: messageOf(error),
|
||
data: sameProject ? lastData : null,
|
||
updatedAt: sameProject ? lastUpdatedAt : 0,
|
||
context,
|
||
})
|
||
} finally {
|
||
if (!stopped && !isStale(requestId, latestRequestId)) schedule(retryImmediately ? 0 : intervalMs)
|
||
}
|
||
}
|
||
return {
|
||
start() {
|
||
if (!stopped) tick()
|
||
return this
|
||
},
|
||
stop() {
|
||
stopped = true
|
||
latestRequestId += 1
|
||
if (timer) { clearTimeout(timer); timer = null }
|
||
return this
|
||
},
|
||
refresh() {
|
||
if (stopped) return this
|
||
if (timer) { clearTimeout(timer); timer = null }
|
||
tick()
|
||
return this
|
||
},
|
||
}
|
||
}
|
||
|
||
function useSanshengState(ctx, activeProjectId) {
|
||
const [state, setState] = React.useState({ loading: true, error: null, data: null, updatedAt: 0, context: null })
|
||
const [reloadToken, setReloadToken] = React.useState(0)
|
||
React.useEffect(() => {
|
||
let alive = true
|
||
const poller = createStatePoller({
|
||
ctx,
|
||
activeProjectId,
|
||
intervalMs: POLL_MS,
|
||
onChange(next) {
|
||
if (!alive) return
|
||
setState(prev => ({
|
||
loading: false,
|
||
error: next.error,
|
||
data: next.data === undefined ? prev.data : next.data,
|
||
updatedAt: next.updatedAt === undefined ? prev.updatedAt : next.updatedAt,
|
||
context: next.context || prev.context,
|
||
}))
|
||
},
|
||
})
|
||
poller.start()
|
||
const detach = []
|
||
let lastWake = 0
|
||
const wake = () => {
|
||
const now = Date.now()
|
||
if (now - lastWake < 1000) return
|
||
lastWake = now
|
||
poller.refresh()
|
||
}
|
||
for (const name of ['sessions', 'workspaces']) {
|
||
try {
|
||
const service = serviceOf(ctx, name)
|
||
const list = service && service.list
|
||
if (list && typeof list.subscribe === 'function') {
|
||
detach.push(list.subscribe(wake))
|
||
}
|
||
} catch (error) { /* 老宿主没有可订阅的列表 */ }
|
||
}
|
||
return () => {
|
||
alive = false
|
||
for (const off of detach) {
|
||
try { off() } catch (error) { /* 忽略 */ }
|
||
}
|
||
poller.stop()
|
||
}
|
||
}, [ctx, activeProjectId, reloadToken])
|
||
return {
|
||
...state,
|
||
refresh: () => setReloadToken(value => value + 1),
|
||
}
|
||
}
|
||
|
||
function useNow() {
|
||
const [now, setNow] = React.useState(Date.now())
|
||
React.useEffect(() => {
|
||
const timer = setInterval(() => setNow(Date.now()), 1000)
|
||
return () => clearInterval(timer)
|
||
}, [])
|
||
return now
|
||
}
|
||
|
||
function formatAge(updatedAt, now) {
|
||
if (!updatedAt) return '尚未更新'
|
||
const seconds = Math.max(0, Math.floor((now - updatedAt) / 1000))
|
||
return '更新于 ' + seconds + ' 秒前'
|
||
}
|
||
|
||
function phaseOf(project) {
|
||
if (!project) return ''
|
||
if (project.phase) return String(project.phase)
|
||
const status = project.goal && project.goal.status
|
||
if (status === 'complete') return '已完成'
|
||
if (status === 'paused') return '暂停'
|
||
if (status === 'failed') return '失败'
|
||
if (status === 'active') return '执行中'
|
||
return project.goal ? '执行中' : '待执行'
|
||
}
|
||
|
||
function phaseToneOf(phase) {
|
||
if (phase === '已完成') return 'ok'
|
||
if (phase === '失败' || phase === '待核实') return 'warn'
|
||
if (phase === '待审查' || phase === '待配置') return 'attention'
|
||
if (phase === '执行中' || phase === '返工中') return 'active'
|
||
return 'idle'
|
||
}
|
||
|
||
function rolesOf(project) {
|
||
return project && Array.isArray(project.roles) ? project.roles : []
|
||
}
|
||
|
||
function attentionOf(project) {
|
||
if (!project) return 0
|
||
const listed = Array.isArray(project.attention) ? project.attention.length : 0
|
||
const warned = rolesOf(project).filter(card => card && (card.tone === 'warn' || card.tone === 'attention')).length
|
||
return Math.max(listed, warned)
|
||
}
|
||
|
||
function formatTime(value) {
|
||
if (!value) return ''
|
||
try {
|
||
return new Date(value).toLocaleString('zh-CN', { hour12: false })
|
||
} catch (error) {
|
||
return String(value)
|
||
}
|
||
}
|
||
|
||
function openRolesTab(ctx, sessionId) {
|
||
if (!sessionId) return { ok: false, error: '先打开一个会话,右侧卡片是会话级的。' }
|
||
const better = serviceOf(ctx, 'betterSidebar')
|
||
if (better && typeof better.openTab === 'function') {
|
||
try {
|
||
better.openTab({ type: TAB_ID }, { sessionId })
|
||
return { ok: true }
|
||
} catch (error) { /* 退回原生右栏 */ }
|
||
}
|
||
const nav = serviceOf(ctx, 'sidebarRight')
|
||
if (nav) {
|
||
try {
|
||
if (typeof nav.openTabIn === 'function') {
|
||
nav.openTabIn(sessionId, TAB_KIND)
|
||
return { ok: true }
|
||
}
|
||
if (typeof nav.openTab === 'function') {
|
||
nav.openTab(TAB_KIND)
|
||
return { ok: true }
|
||
}
|
||
} catch (error) { /* 统一报错 */ }
|
||
}
|
||
return { ok: false, error: '宿主右栏不可用。' }
|
||
}
|
||
|
||
function openHostSession(ctx, sessionId) {
|
||
const ui = serviceOf(ctx, 'uiWorkspace')
|
||
if (ui && typeof ui.openSession === 'function') {
|
||
try {
|
||
const result = ui.openSession(sessionId)
|
||
if (result && typeof result.then === 'function') {
|
||
result.catch(error => notifyUser(ctx, '打开会话失败:' + messageOf(error)))
|
||
}
|
||
return true
|
||
} catch (error) { /* 退回 selection */ }
|
||
}
|
||
if (ui && ui.selection && typeof ui.selection.set === 'function') {
|
||
try {
|
||
ui.selection.set({ sessionId })
|
||
return true
|
||
} catch (error) { /* 无可用导航 */ }
|
||
}
|
||
return false
|
||
}
|
||
|
||
function openRoleSession(ctx, card) {
|
||
const sessionId = card && card.sessionId
|
||
if (!sessionId) {
|
||
const reason = (card && (card.reason || card.next)) || '绑定存在但会话不存在,未自动替换绑定。'
|
||
notifyUser(ctx, (card && card.label ? card.label : '角色') + '会话缺失:' + reason)
|
||
return { ok: false, error: reason }
|
||
}
|
||
if (openHostSession(ctx, sessionId)) return { ok: true }
|
||
const message = '宿主没有打开会话的能力。'
|
||
notifyUser(ctx, message)
|
||
return { ok: false, error: message }
|
||
}
|
||
|
||
async function waitForWorkspaceSession(ctx, workspaceId, beforeIds, timeoutMs) {
|
||
const before = new Set(beforeIds || [])
|
||
const started = Date.now()
|
||
while (Date.now() - started < timeoutMs) {
|
||
const selected = selectedSessionIdOf(ctx, workspaceId)
|
||
if (selected) return selected
|
||
const ids = sessionIdsOfWorkspace(ctx, workspaceId)
|
||
const fresh = ids.find(id => !before.has(id))
|
||
if (fresh) return fresh
|
||
await new Promise(resolve => setTimeout(resolve, 80))
|
||
}
|
||
return null
|
||
}
|
||
|
||
async function openWorkbench(ctx, workspaceId) {
|
||
try {
|
||
if (!workspaceId) throw new Error('缺少项目标识')
|
||
let sessionId = sessionIdsOfWorkspace(ctx, workspaceId)[0]
|
||
if (sessionId) {
|
||
if (!openHostSession(ctx, sessionId)) throw new Error('宿主没有打开会话的能力')
|
||
} else {
|
||
const ui = serviceOf(ctx, 'uiWorkspace')
|
||
if (!ui || typeof ui.startSession !== 'function') throw new Error('项目还没有会话,且宿主不支持新建会话')
|
||
const before = sessionIdsOfWorkspace(ctx, workspaceId)
|
||
try {
|
||
await ui.startSession(workspaceId)
|
||
} catch (error) {
|
||
throw new Error('新建会话失败:' + messageOf(error))
|
||
}
|
||
sessionId = await waitForWorkspaceSession(ctx, workspaceId, before, 2000)
|
||
if (!sessionId) throw new Error('已请求新建会话,但未能确定会话 id')
|
||
openHostSession(ctx, sessionId)
|
||
}
|
||
const targetSessionId = sessionId || selectedSessionIdOf(ctx) || sessionIdsOfWorkspace(ctx, workspaceId)[0]
|
||
if (!targetSessionId) throw new Error('未能确定要打开的项目会话')
|
||
const opened = openRolesTab(ctx, targetSessionId)
|
||
if (!opened.ok) throw new Error(opened.error)
|
||
return { ok: true, sessionId: targetSessionId }
|
||
} catch (error) {
|
||
const message = '打开三省六部失败:' + messageOf(error)
|
||
notifyUser(ctx, message)
|
||
return { ok: false, error: message }
|
||
}
|
||
}
|
||
|
||
async function workspaceMenuItems(ctx, target, signal) {
|
||
const workspaceId = target && target.workspaceId
|
||
const key = workspaceId ? String(workspaceId) : ''
|
||
let bound = key ? bindingCache.get(key) : undefined
|
||
try {
|
||
const data = await fetchState(ctx, { workspaceId, sessionId: null }, signal)
|
||
if (key) {
|
||
bound = Boolean(data && data.current)
|
||
bindingCache.set(key, bound)
|
||
}
|
||
rememberState(data, { workspaceId })
|
||
} catch (error) {
|
||
/* 菜单必须可用;读不到时用缓存,未知按已绑定显示,打开后再给可读错误 */
|
||
}
|
||
return [{
|
||
id: 'sansheng-open',
|
||
label: bound === false ? '初始化三省六部' : '三省六部',
|
||
run: () => { void openWorkbench(ctx, workspaceId) },
|
||
}]
|
||
}
|
||
|
||
function registerContextMenus(ctx) {
|
||
const mount = () => {
|
||
const service = contextMenuServiceOf(ctx)
|
||
if (!service || typeof service.register !== 'function') return () => {}
|
||
const disposers = []
|
||
const disposeAll = () => {
|
||
while (disposers.length > 0) {
|
||
try { disposers.pop()() } catch (error) { /* 忽略 */ }
|
||
}
|
||
}
|
||
try {
|
||
disposers.push(service.register({
|
||
id: 'sansheng.workspace.open',
|
||
target: 'workspace',
|
||
order: 260,
|
||
observe: () => [],
|
||
resolve: (target, signal) => workspaceMenuItems(ctx, target, signal),
|
||
}))
|
||
disposers.push(service.register({
|
||
id: 'sansheng.session.open',
|
||
target: 'session',
|
||
order: 260,
|
||
resolve: ({ sessionId }) => [{
|
||
id: 'sansheng-open',
|
||
label: '打开三省六部',
|
||
run: () => {
|
||
const result = openRolesTab(ctx, sessionId)
|
||
if (!result.ok) notifyUser(ctx, result.error)
|
||
},
|
||
}],
|
||
}))
|
||
} catch (error) {
|
||
console.warn('[三省六部] 上下文菜单注册失败:', error)
|
||
disposeAll()
|
||
return () => {}
|
||
}
|
||
return disposeAll
|
||
}
|
||
if (typeof ctx.effect === 'function') {
|
||
try {
|
||
ctx.effect(mount, '三省六部:项目与会话上下文菜单')
|
||
} catch (error) {
|
||
console.warn('[三省六部] 上下文菜单生命周期挂载失败:', error)
|
||
}
|
||
} else {
|
||
mount()
|
||
}
|
||
}
|
||
|
||
function RoleCard({ ctx, project, card, models, onRefresh }) {
|
||
const model = card.model ? String(card.model) : '默认模型'
|
||
const exists = card.exists === true ? '存在' : card.exists === false ? '不存在' : ''
|
||
const phase = card.phase || phaseOf(project)
|
||
const clickable = Boolean(card.sessionId)
|
||
const modelOptions = Array.isArray(models) ? models : []
|
||
const [savingModel, setSavingModel] = React.useState(false)
|
||
const [modelError, setModelError] = React.useState(null)
|
||
const changeModel = async value => {
|
||
if (!value || savingModel) return
|
||
setSavingModel(true)
|
||
setModelError(null)
|
||
try {
|
||
await postJson('/sansheng/config', { projectId: project.id, models: { [card.role]: value } })
|
||
if (typeof onRefresh === 'function') onRefresh()
|
||
} catch (error) {
|
||
setModelError(messageOf(error))
|
||
} finally {
|
||
setSavingModel(false)
|
||
}
|
||
}
|
||
const activate = () => { openRoleSession(ctx, card) }
|
||
const props = {
|
||
className: 'ss-card',
|
||
'data-role': card.role,
|
||
'data-tone': card.tone || 'idle',
|
||
'data-clickable': clickable ? '1' : '0',
|
||
title: [card.duty, card.detail, card.reason].filter(Boolean).join('\n'),
|
||
}
|
||
if (clickable) {
|
||
props.role = 'button'
|
||
props.tabIndex = 0
|
||
props.onClick = activate
|
||
props.onKeyDown = event => {
|
||
if (event && (event.key === 'Enter' || event.key === ' ')) {
|
||
if (event.preventDefault) event.preventDefault()
|
||
activate()
|
||
}
|
||
}
|
||
}
|
||
const modelControl = modelOptions.length > 0
|
||
? h('select', {
|
||
key: 'model',
|
||
className: 'ss-model-select',
|
||
value: card.model || '',
|
||
disabled: savingModel,
|
||
'aria-label': (card.label || card.role) + '模型',
|
||
onClick: event => { if (event && event.stopPropagation) event.stopPropagation() },
|
||
onKeyDown: event => { if (event && event.stopPropagation) event.stopPropagation() },
|
||
onChange: event => {
|
||
if (event && event.stopPropagation) event.stopPropagation()
|
||
void changeModel(event.target.value)
|
||
},
|
||
}, [
|
||
!card.model ? h('option', { key: 'default', value: '', children: '默认模型' }) : null,
|
||
card.model && !modelOptions.some(item => item.ref === card.model)
|
||
? h('option', { key: 'current', value: card.model, children: card.model })
|
||
: null,
|
||
...modelOptions.map(item => h('option', { key: item.ref, value: item.ref, children: item.name || item.ref })),
|
||
].filter(Boolean))
|
||
: h('span', { key: 'model', className: 'ss-model-text', children: model })
|
||
return h('div', props, [
|
||
h('div', { key: 'head', className: 'ss-card-head' }, [
|
||
h('span', { key: 'mark', className: 'ss-mark', 'aria-hidden': 'true', children: ROLE_MARK[card.role] || '省' }),
|
||
h('strong', { key: 'label', children: card.label || ROLE_LABEL[card.role] || card.role }),
|
||
h('span', { key: 'dot', className: 'ss-dot', 'aria-hidden': 'true' }),
|
||
]),
|
||
h('div', { key: 'duty', className: 'ss-duty' }, [
|
||
h('span', { key: 'name', children: card.name || '未就绪' }),
|
||
h('span', { key: 'sep', children: ' · ' }),
|
||
modelControl,
|
||
]),
|
||
modelError ? h('div', { key: 'model-error', className: 'ss-error', children: '模型切换失败:' + modelError }) : null,
|
||
h('div', { key: 'main', className: 'ss-main', children: card.line || card.next || '暂无状态' }),
|
||
card.detail ? h('div', { key: 'sub', className: 'ss-sub', children: card.detail }) : null,
|
||
h('div', { key: 'foot', className: 'ss-foot' }, [
|
||
card.duty ? h('span', { key: 'duty', children: card.duty }) : null,
|
||
phase ? h('span', { key: 'phase', className: 'ss-chip', children: phase }) : null,
|
||
exists ? h('span', { key: 'exists', className: 'ss-chip', children: exists }) : null,
|
||
].filter(Boolean)),
|
||
!card.sessionId ? h('div', { key: 'missing', className: 'ss-missing' }, [
|
||
h('button', {
|
||
key: 'repair',
|
||
type: 'button',
|
||
className: 'ss-repair',
|
||
onClick: event => {
|
||
if (event && event.stopPropagation) event.stopPropagation()
|
||
notifyUser(ctx, (card.label || '角色') + '会话缺失:' + ((card.reason || card.next) || '绑定存在但会话不存在,未自动替换绑定。'))
|
||
},
|
||
}, '会话缺失,点此修复'),
|
||
h('span', { key: 'reason', className: 'ss-reason', children: card.reason || card.next || '绑定存在但会话不存在,未自动替换绑定。' }),
|
||
]) : null,
|
||
].filter(Boolean))
|
||
}
|
||
|
||
function normalizeModels(draft) {
|
||
const models = {}
|
||
for (const role of ROLE_ORDER) {
|
||
const value = draft && draft[role] !== undefined ? String(draft[role]).trim() : ''
|
||
if (value) models[role] = value
|
||
}
|
||
return models
|
||
}
|
||
|
||
function ModelFields({ draft, onChange }) {
|
||
return ROLE_ORDER.map(role => {
|
||
const spec = MODEL_FIELDS.find(item => item.role === role)
|
||
return h('label', { key: role, className: 'ss-field' }, [
|
||
spec.label,
|
||
h('input', {
|
||
type: 'text',
|
||
value: draft[role] || '',
|
||
placeholder: '留空使用默认模型',
|
||
onChange: event => onChange(role, event.target.value),
|
||
}),
|
||
])
|
||
})
|
||
}
|
||
|
||
function ConfigPanel({ ctx, project, onRefresh }) {
|
||
const initial = () => ({
|
||
lead: (project.models && project.models.lead) || '',
|
||
shangshu: (project.models && project.models.shangshu) || '',
|
||
gongbu: (project.models && project.models.gongbu) || '',
|
||
})
|
||
const [draft, setDraft] = React.useState(initial)
|
||
const [status, setStatus] = React.useState(null)
|
||
const [saving, setSaving] = React.useState(false)
|
||
const projectRef = React.useRef(project.id)
|
||
projectRef.current = project.id
|
||
React.useEffect(() => {
|
||
setDraft(initial())
|
||
setStatus(null)
|
||
}, [project.id])
|
||
const update = (role, value) => setDraft(prev => ({ ...prev, [role]: value }))
|
||
const onSubmit = async event => {
|
||
if (event && event.preventDefault) event.preventDefault()
|
||
if (saving) return
|
||
const targetId = project.id
|
||
setSaving(true)
|
||
setStatus(null)
|
||
try {
|
||
await postJson('/sansheng/config', { projectId: targetId, models: normalizeModels(draft) })
|
||
if (projectRef.current !== targetId) return
|
||
setStatus({ kind: 'ok', text: '已保存' })
|
||
if (typeof onRefresh === 'function') onRefresh()
|
||
} catch (error) {
|
||
if (projectRef.current !== targetId) return
|
||
setStatus({ kind: 'error', text: '保存失败:' + messageOf(error) })
|
||
} finally {
|
||
if (projectRef.current === targetId) setSaving(false)
|
||
}
|
||
}
|
||
return h('details', { className: 'ss-details' }, [
|
||
h('summary', { key: 'summary', className: 'ss-summary', children: '项目配置' }),
|
||
h('form', { key: 'form', className: 'ss-form', onSubmit }, [
|
||
...ModelFields({ draft, onChange: update }),
|
||
h('div', { key: 'actions', className: 'ss-actions' }, [
|
||
h('button', {
|
||
key: 'save',
|
||
type: 'submit',
|
||
className: 'ss-btn ss-btn-primary',
|
||
disabled: saving,
|
||
}, saving ? '保存中…' : '保存模型配置'),
|
||
status && status.kind === 'ok' ? h('span', { key: 'ok', className: 'ss-ok', children: status.text }) : null,
|
||
status && status.kind === 'error' ? h('span', { key: 'err', className: 'ss-error', role: 'alert', children: status.text }) : null,
|
||
].filter(Boolean)),
|
||
h('div', { key: 'note', className: 'ss-form-note', children: '模型配置只影响本项目;执行中的修改默认从下一次执行生效。' }),
|
||
]),
|
||
])
|
||
}
|
||
|
||
function InitPanel({ ctx, context, onDone }) {
|
||
const workspaceId = context && context.workspaceId
|
||
const initialName = () => (context && (context.displayTitle || basename(context.path))) || ''
|
||
const [name, setName] = React.useState(initialName)
|
||
const [path, setPath] = React.useState((context && context.path) || '')
|
||
const [draft, setDraft] = React.useState({ lead: '', shangshu: '', gongbu: '' })
|
||
const [status, setStatus] = React.useState(null)
|
||
const [saving, setSaving] = React.useState(false)
|
||
const workspaceRef = React.useRef(workspaceId)
|
||
workspaceRef.current = workspaceId
|
||
React.useEffect(() => {
|
||
setName(initialName())
|
||
setPath((context && context.path) || '')
|
||
setDraft({ lead: '', shangshu: '', gongbu: '' })
|
||
setStatus(null)
|
||
}, [workspaceId])
|
||
const update = (role, value) => setDraft(prev => ({ ...prev, [role]: value }))
|
||
const onSubmit = async event => {
|
||
if (event && event.preventDefault) event.preventDefault()
|
||
if (saving) return
|
||
if (!name.trim() || !path.trim()) {
|
||
setStatus({ kind: 'error', text: '请填写项目名和工作目录。' })
|
||
return
|
||
}
|
||
setSaving(true)
|
||
setStatus(null)
|
||
const targetWorkspace = workspaceId
|
||
try {
|
||
await postJson('/sansheng/provision', {
|
||
workspaceId,
|
||
path: path.trim(),
|
||
name: name.trim(),
|
||
models: normalizeModels(draft),
|
||
})
|
||
if (workspaceRef.current !== targetWorkspace) return
|
||
setStatus({ kind: 'ok', text: '初始化成功,正在刷新…' })
|
||
if (typeof onDone === 'function') onDone()
|
||
} catch (error) {
|
||
if (workspaceRef.current !== targetWorkspace) return
|
||
setStatus({ kind: 'error', text: '初始化失败:' + messageOf(error) })
|
||
} finally {
|
||
if (workspaceRef.current === targetWorkspace) setSaving(false)
|
||
}
|
||
}
|
||
return h('div', { className: 'ss-empty' }, [
|
||
h('strong', { key: 'title', children: '此项目尚未初始化' }),
|
||
h('span', { key: 'desc', children: '为此项目创建丞相、尚书、工部三个角色与项目群。' }),
|
||
h('details', { key: 'details', className: 'ss-details' }, [
|
||
h('summary', { key: 'summary', className: 'ss-summary', children: '初始化三省六部' }),
|
||
h('form', { key: 'form', className: 'ss-form', onSubmit }, [
|
||
h('label', { key: 'name', className: 'ss-field' }, [
|
||
'项目名',
|
||
h('input', { type: 'text', value: name, onChange: event => setName(event.target.value) }),
|
||
]),
|
||
h('label', { key: 'path', className: 'ss-field' }, [
|
||
'工作目录',
|
||
h('input', { type: 'text', value: path, onChange: event => setPath(event.target.value) }),
|
||
]),
|
||
...ModelFields({ draft, onChange: update }),
|
||
h('div', { key: 'actions', className: 'ss-actions' }, [
|
||
h('button', { key: 'submit', type: 'submit', className: 'ss-btn ss-btn-primary', disabled: saving }, saving ? '创建中…' : '创建项目'),
|
||
status && status.kind === 'ok' ? h('span', { key: 'ok', className: 'ss-ok', children: status.text }) : null,
|
||
status && status.kind === 'error' ? h('span', { key: 'err', className: 'ss-error', role: 'alert', children: status.text }) : null,
|
||
].filter(Boolean)),
|
||
]),
|
||
]),
|
||
])
|
||
}
|
||
|
||
function HistoryPanel({ project }) {
|
||
const all = Array.isArray(project.reviewsHistory)
|
||
? project.reviewsHistory
|
||
: Array.isArray(project.reviews) ? project.reviews : []
|
||
const reviews = all.slice(0, 5)
|
||
return h('details', { className: 'ss-details' }, [
|
||
h('summary', { key: 'summary', className: 'ss-summary', children: '历史审查' }),
|
||
reviews.length === 0
|
||
? h('div', { key: 'empty', className: 'ss-form-note', children: '暂无历史审查' })
|
||
: h('div', { key: 'list', className: 'ss-history' }, reviews.map((review, index) => h('div', {
|
||
key: (review && (review.id || review.eventKey)) || index,
|
||
className: 'ss-history-item',
|
||
}, [
|
||
h('b', { key: 'verdict', children: review && review.verdict === 'pass' ? '通过' : '驳回' }),
|
||
h('span', { key: 'kind', children: (review && review.kind === 'goal' ? '目标' : '阶段') + (review && review.reviewerRole ? ' · ' + review.reviewerRole : '') }),
|
||
review && review.reason ? h('span', { key: 'reason', className: 'ss-reason', children: review.reason }) : null,
|
||
h('span', { key: 'time', className: 'ss-history-meta', children: formatTime(review && review.at) }),
|
||
].filter(Boolean)))),
|
||
])
|
||
}
|
||
|
||
function BotSwitcher({ ctx, data }) {
|
||
const bots = Array.isArray(data && data.bots) ? data.bots : []
|
||
const rooms = Array.isArray(data && data.rooms) ? data.rooms : []
|
||
if (bots.length === 0 && rooms.length === 0) return null
|
||
const open = sessionId => {
|
||
if (!sessionId) return
|
||
const result = openHostSession(ctx, sessionId)
|
||
if (result !== true) notifyUser(ctx, result || '打开 Bot 会话失败。')
|
||
}
|
||
const row = (item, kind) => h('button', {
|
||
key: kind + ':' + item.id,
|
||
type: 'button',
|
||
className: 'ss-bot-row',
|
||
title: item.projectName ? `${item.name} · ${item.projectName}` : item.name,
|
||
onClick: () => open(item.sessionId),
|
||
}, [
|
||
h('span', { key: 'name', className: 'ss-bot-name', children: item.name }),
|
||
item.role && item.role !== item.name ? h('span', { key: 'role', className: 'ss-bot-role', children: item.role }) : null,
|
||
item.isMain ? h('span', { key: 'main', className: 'ss-chip', children: 'Main' }) : null,
|
||
item.projectName ? h('span', { key: 'project', className: 'ss-bot-project', children: item.projectName }) : null,
|
||
].filter(Boolean))
|
||
return h('details', { className: 'ss-details' }, [
|
||
h('summary', { key: 'summary', className: 'ss-summary', children: `Bot 切换 · ${bots.length}` }),
|
||
bots.length > 0 ? h('div', { key: 'bots', className: 'ss-bot-list' }, bots.map(bot => row(bot, 'bot'))) : null,
|
||
rooms.length > 0 ? h('div', { key: 'rooms', className: 'ss-bot-list ss-bot-rooms' }, rooms.map(room => row(room, 'room'))) : null,
|
||
])
|
||
}
|
||
|
||
function EmptyHint({ error }) {
|
||
return h('div', { className: 'ss-empty' }, [
|
||
error ? h('div', { key: 'error', className: 'ss-error', children: `读不到项目状态:${error}` }) : null,
|
||
h('div', { key: 'text', children: '还没有三省六部项目。在对话里让助手调用 sansheng_provision 创建项目(三 Bot + 项目群)。' }),
|
||
h('div', { key: 'tip', children: '已有的群用 sansheng_bind 绑定;创建后可在这里看到丞相、尚书、工部三张卡片。' }),
|
||
])
|
||
}
|
||
|
||
function RolesView(props) {
|
||
const { ctx, data, error, loading, updatedAt, activeId, onPick, onRefresh } = props
|
||
const now = useNow()
|
||
const projects = projectsOf(data)
|
||
const current = data && data.current ? data.current : null
|
||
const context = props.context || workspaceContextOf(ctx)
|
||
let project = current
|
||
if (!project && !context.workspaceId) project = activeId ? projects.find(item => item && item.id === activeId) : null
|
||
if (!project && !context.workspaceId) project = projects[0] || null
|
||
const uninitialized = !project && Boolean(context && context.workspaceId) && (Boolean(data) || (!loading && !error))
|
||
const phase = project ? phaseOf(project) : uninitialized ? '未初始化' : ''
|
||
const barName = project
|
||
? project.name
|
||
: uninitialized
|
||
? ((context.displayTitle || basename(context.path)) || '当前项目')
|
||
: loading ? '载入中…' : '三省六部'
|
||
const attention = attentionOf(project)
|
||
const disconnected = Boolean(error)
|
||
const bar = h('div', { key: 'bar', className: 'ss-bar' }, [
|
||
project && projects.length > 0 && typeof onPick === 'function'
|
||
? h('select', { key: 'select', value: project.id, onChange: onPick, 'aria-label': '切换项目' },
|
||
projects.map(item => h('option', { key: item.id, value: item.id, children: item.name })))
|
||
: h('strong', { key: 'name', children: barName }),
|
||
phase ? h('span', { key: 'phase', className: 'ss-phase', 'data-tone': phaseToneOf(phase), children: phase }) : null,
|
||
attention > 0 ? h('span', { key: 'attention', className: 'ss-chip', children: '待处理 ' + attention }) : null,
|
||
h('span', { key: 'note', className: 'ss-bar-note', children: formatAge(updatedAt, now) }),
|
||
].filter(Boolean))
|
||
const strip = disconnected
|
||
? h('div', { key: 'strip', className: 'ss-strip', role: 'status' }, [
|
||
h('span', { key: 'text', children: data ? '连接中断 · 显示上次状态' : '连接中断 · 暂无状态' }),
|
||
h('span', { key: 'detail', children: '(' + error + ')' }),
|
||
])
|
||
: null
|
||
let body
|
||
if (uninitialized) {
|
||
body = h(InitPanel, { key: 'init', ctx, context, onDone: onRefresh })
|
||
} else if (project) {
|
||
const roles = rolesOf(project)
|
||
body = [
|
||
...roles.map(card => h(RoleCard, { key: card.role || card.label, ctx, project, card, models: data && data.models, onRefresh })),
|
||
h(BotSwitcher, { key: 'bots', ctx, data }),
|
||
h(HistoryPanel, { key: 'history', project }),
|
||
h(ConfigPanel, { key: 'config', ctx, project, onRefresh }),
|
||
]
|
||
} else {
|
||
body = [h(EmptyHint, { key: 'empty', error })]
|
||
}
|
||
return h('div', { className: 'ss-root', 'data-sansheng-roles': '1' }, [
|
||
bar,
|
||
strip,
|
||
h('div', { key: 'list', className: 'ss-list' }, body),
|
||
].filter(Boolean))
|
||
}
|
||
|
||
function RolesColumn(props) {
|
||
const ctx = props.__ctx
|
||
const [activeId, setActiveId] = React.useState(() => {
|
||
try { return window.localStorage.getItem(ACTIVE_KEY) || '' } catch (error) { return '' }
|
||
})
|
||
const state = useSanshengState(ctx, activeId)
|
||
const onPick = event => {
|
||
const next = event.target.value
|
||
setActiveId(next)
|
||
try { window.localStorage.setItem(ACTIVE_KEY, next) } catch (error) { /* 忽略 */ }
|
||
// 选择项目 = 切到该项目的宿主 workspace,再打开它的工作台会话;
|
||
// 不是只换右栏文案,避免左栏项目树和右栏状态脱节。
|
||
const picked = projectsOf(state.data).find(project => project && project.id === next)
|
||
if (picked && picked.workspaceId) {
|
||
void openWorkbench(ctx, picked.workspaceId)
|
||
}
|
||
}
|
||
return h(RolesView, {
|
||
...state,
|
||
ctx,
|
||
activeId,
|
||
onPick,
|
||
onRefresh: state.refresh,
|
||
})
|
||
}
|
||
|
||
function RolesTabTitle(props) {
|
||
const ctx = props && props.__ctx
|
||
const { data } = useSanshengState(ctx)
|
||
const projects = (data && data.projects) || []
|
||
const attention = projects.reduce((sum, item) => sum + rolesOf(item).filter(card => card && card.tone === 'warn').length, 0)
|
||
return h('div', { className: 'ss-tab-title' }, [
|
||
h('span', { key: 'mark', className: 'ss-tab-mark', children: '三省' }),
|
||
h('span', { key: 'label', children: '角色' }),
|
||
attention > 0 ? h('span', { key: 'count', className: 'ss-tab-count', children: String(attention) }) : null,
|
||
])
|
||
}
|
||
|
||
function HeaderButton(props) {
|
||
const ctx = props.__ctx
|
||
const sessionId = props && props.sessionId ? props.sessionId : undefined
|
||
const [notice, setNotice] = React.useState(null)
|
||
return h('button', {
|
||
className: 'ss-open',
|
||
type: 'button',
|
||
title: notice || '打开右侧三省六部角色卡片',
|
||
onClick: () => {
|
||
const result = openRolesTab(ctx, sessionId)
|
||
setNotice(result.ok ? null : result.error)
|
||
},
|
||
}, [h('span', { key: 'mark', children: '三省' }), h('span', { key: 'text', children: notice ? '右栏不可用' : '角色' })])
|
||
}
|
||
|
||
function FooterButton(props) {
|
||
const ctx = props.__ctx
|
||
const [notice, setNotice] = React.useState(null)
|
||
const wide = props && props.wide ? ' is-wide' : ''
|
||
const activate = () => {
|
||
const sessionId = currentSessionIdOf(ctx) || selectedSessionIdOf(ctx)
|
||
const result = openRolesTab(ctx, sessionId)
|
||
setNotice(result.ok ? null : result.error)
|
||
if (!result.ok) notifyUser(ctx, result.error)
|
||
}
|
||
return h('div', { className: 'ss-footer-entry' + wide }, [
|
||
h('button', {
|
||
key: 'button',
|
||
className: 'ss-open',
|
||
type: 'button',
|
||
title: notice || '打开右侧三省六部角色卡片',
|
||
onClick: activate,
|
||
}, [h('span', { key: 'mark', children: '三省' }), (wide ? h('span', { key: 'text', children: notice ? '右栏不可用' : '三省六部' }) : null)]),
|
||
])
|
||
}
|
||
|
||
function apply(ctx) {
|
||
ensureCss()
|
||
const wrap = component => props => h(component, { ...props, __ctx: ctx })
|
||
|
||
ctx.effect(() => {
|
||
try {
|
||
return ctx.sidebarRightTabs.register({
|
||
id: TAB_ID,
|
||
kind: TAB_KIND,
|
||
priority: 'builtin',
|
||
title: () => '三省六部',
|
||
keepMounted: true,
|
||
})
|
||
} catch (error) {
|
||
console.warn('[三省六部] 右栏页签注册失败:', error)
|
||
return () => {}
|
||
}
|
||
}, '三省六部:右栏角色页签')
|
||
|
||
ctx.slots.inject('sidebar.right.pane.tab', () => ctx.slots.register({
|
||
name: 'sidebar.right.pane.tab',
|
||
key: TAB_ID,
|
||
}, wrap(RolesColumn)))
|
||
|
||
ctx.slots.inject('sidebar.right.pane.tab.title', () => ctx.slots.register({
|
||
name: 'sidebar.right.pane.tab.title',
|
||
key: TAB_ID,
|
||
}, () => h(RolesTabTitle, { __ctx: ctx })))
|
||
|
||
ctx.slots.inject('conversation.session.header.actions', () => ctx.slots.register({
|
||
name: 'conversation.session.header.actions',
|
||
id: TAB_ID + ':open',
|
||
order: 60,
|
||
}, wrap(HeaderButton)))
|
||
|
||
// 原生侧栏底部入口:即使 DS Bot 页面不渲染会话头按钮,也能从这里打开。
|
||
ctx.slots.inject('sidebar.footer.action', () => ctx.slots.register({
|
||
name: 'sidebar.footer.action',
|
||
id: TAB_ID + ':footer',
|
||
order: 55,
|
||
}, wrap(FooterButton)))
|
||
|
||
registerContextMenus(ctx)
|
||
}
|
||
|
||
exports.apply = apply
|
||
exports.inject = ['slots', 'sidebarRightTabs', 'sidebarRight']
|
||
exports.TAB_ID = TAB_ID
|
||
exports.TAB_KIND = TAB_KIND
|
||
exports.workspaceIdOf = workspaceIdOf
|
||
exports.__test = {
|
||
isStale,
|
||
stateUrlOf,
|
||
workspaceContextOf,
|
||
workspaceIdOf,
|
||
createStatePoller,
|
||
normalizeModels,
|
||
openWorkbench,
|
||
openRolesTab,
|
||
openRoleSession,
|
||
workspaceMenuItems,
|
||
RolesView,
|
||
RolesColumn,
|
||
RoleCard,
|
||
BotSwitcher,
|
||
ConfigPanel,
|
||
HistoryPanel,
|
||
InitPanel,
|
||
formatAge,
|
||
phaseOf,
|
||
}
|
||
return module.exports
|
||
},
|
||
})
|