644 lines
28 KiB
JavaScript
644 lines
28 KiB
JavaScript
// 三省六部 Web 插件入口:左侧追加「三省六部」入口,点开右侧工作台。
|
||
// 所有对宿主可选服务的调用都用 ctx.get(...) 特性探测,探测不到就降级,不伪造接口。
|
||
|
||
import { createElement as h, Fragment, useCallback, useEffect, useMemo, useRef, useState } from 'react'
|
||
import { createPortal } from 'react-dom'
|
||
import { SEAT_IDS, SEATS } from '../shared/roles.js'
|
||
import {
|
||
buildWorkbenchView,
|
||
findModelOption,
|
||
updateDraft,
|
||
clearDraft,
|
||
UNCHOSEN_MODEL_LABEL,
|
||
} from './workbench.js'
|
||
import { request } from './transport.js'
|
||
import { CSS as WORKBENCH_CSS } from './styles.js'
|
||
import { install as installNativePanel } from '../native/index.js'
|
||
|
||
export const inject = ['sessions', 'uiWorkspace', 'uiConversation', 'slots', 'theme', 'layout']
|
||
|
||
const PLUGIN_ID = 'dsh-sansheng'
|
||
const TAB_KIND = 'sansheng-workbench'
|
||
const TAB_TYPE_ID = 'dsh-sansheng:workbench'
|
||
|
||
function installStyles(doc, tag, text) {
|
||
if (!doc || !doc.head) return null
|
||
const style = doc.createElement('style')
|
||
// 带上插件 id,避免被 ClientModuleSystem 当作别人的模块样式回收。
|
||
style.dataset.plugin = PLUGIN_ID
|
||
style.dataset.sansheng = tag
|
||
style.textContent = text
|
||
doc.head.appendChild(style)
|
||
return style
|
||
}
|
||
|
||
// ---------- 小图标(createElement,无 JSX) ----------
|
||
function svgWrap(children, props) {
|
||
return h('svg', {
|
||
viewBox: '0 0 24 24', width: 16, height: 16, fill: 'none', stroke: 'currentColor',
|
||
strokeWidth: 1.6, strokeLinecap: 'round', strokeLinejoin: 'round', 'aria-hidden': 'true',
|
||
...(props || {}),
|
||
}, children)
|
||
}
|
||
const TreeIcon = (props) => svgWrap([
|
||
h('rect', { key: 'a', x: 9, y: 2, width: 6, height: 5, rx: 1 }),
|
||
h('path', { key: 'b', d: 'M12 7v5M5 16v-4h14v4' }),
|
||
h('rect', { key: 'c', x: 2, y: 16, width: 6, height: 5, rx: 1 }),
|
||
h('rect', { key: 'd', x: 16, y: 16, width: 6, height: 5, rx: 1 }),
|
||
], props)
|
||
const CloseIcon = (props) => svgWrap([h('path', { key: 'p', d: 'm6 6 12 12M6 18 18 6' })], props)
|
||
const FolderIcon = (props) => svgWrap([h('path', { key: 'p', d: 'M3 7V5a2 2 0 0 1 2-2h5l2 3h7a2 2 0 0 1 2 2v11H3Z' })], props)
|
||
const GearIcon = (props) => svgWrap([
|
||
h('path', { key: 'a', d: 'M4 6h16M4 12h16M4 18h16' }),
|
||
h('circle', { key: 'b', cx: 9, cy: 6, r: 2 }),
|
||
h('circle', { key: 'c', cx: 16, cy: 12, r: 2 }),
|
||
h('circle', { key: 'd', cx: 8, cy: 18, r: 2 }),
|
||
], props)
|
||
const ChevronIcon = (props) => h('svg', {
|
||
viewBox: '0 0 24 24', width: 14, height: 14, fill: 'none', stroke: 'currentColor',
|
||
strokeWidth: 1.6, strokeLinecap: 'round', strokeLinejoin: 'round',
|
||
className: 'ssw-chevron', 'aria-hidden': 'true',
|
||
}, h('path', { d: 'm6 9 6 6 6-6' }))
|
||
|
||
function isFn(value) { return typeof value === 'function' }
|
||
function safeCall(obj, name) {
|
||
try {
|
||
if (!obj || !isFn(obj[name])) return undefined
|
||
return obj[name]()
|
||
} catch { return undefined }
|
||
}
|
||
function snapshotOf(obj) {
|
||
if (!obj) return undefined
|
||
if (isFn(obj.getSnapshot)) {
|
||
try { return obj.getSnapshot() } catch { return undefined }
|
||
}
|
||
return obj
|
||
}
|
||
|
||
export function apply(ctx) {
|
||
if (typeof document !== 'undefined') installStyles(document, 'workbench', WORKBENCH_CSS)
|
||
|
||
const get = (name) => { try { return ctx.get(name) } catch { return undefined } }
|
||
|
||
// ---------- 当前项目 / 工作区(特性探测,拿不到就提示用户先选项目) ----------
|
||
function workspaceItems() {
|
||
const fromWorkspaces = snapshotOf(get('workspaces')?.list)?.items
|
||
if (Array.isArray(fromWorkspaces)) return fromWorkspaces
|
||
const fromUi = snapshotOf(get('uiWorkspace')?.workspaces)?.items
|
||
if (Array.isArray(fromUi)) return fromUi
|
||
return []
|
||
}
|
||
|
||
function normalizeWorkspace(item) {
|
||
if (!item || typeof item !== 'object') return null
|
||
const workspaceId = item.workspaceId ?? item.id ?? null
|
||
if (typeof workspaceId !== 'string' || !workspaceId) return null
|
||
return {
|
||
workspaceId,
|
||
name: typeof item.name === 'string' ? item.name : (typeof item.title === 'string' ? item.title : undefined),
|
||
path: typeof item.path === 'string' ? item.path : undefined,
|
||
}
|
||
}
|
||
|
||
function currentSessionId() {
|
||
const snap = snapshotOf(get('sessions')?.list) ?? snapshotOf(get('sessions'))
|
||
if (!snap || typeof snap !== 'object') return null
|
||
for (const key of ['activeId', 'currentId', 'selectedId']) {
|
||
if (typeof snap[key] === 'string' && snap[key]) return snap[key]
|
||
}
|
||
if (snap.byId && typeof snap.byId === 'object') {
|
||
const main = Object.values(snap.byId).find(session => (session?.retainedBy?.mainView ?? 0) > 0)
|
||
if (main && typeof main.id === 'string') return main.id
|
||
}
|
||
return null
|
||
}
|
||
|
||
function currentWorkspaceId() {
|
||
const candidates = []
|
||
for (const holder of [get('workspaces'), get('uiWorkspace')]) {
|
||
if (!holder) continue
|
||
for (const key of ['currentWorkspaceId', 'currentId', 'activeId']) {
|
||
if (isFn(holder[key])) candidates.push(safeCall(holder, key))
|
||
else if (typeof holder[key] === 'string') candidates.push(holder[key])
|
||
}
|
||
for (const key of ['current', 'active', 'selected', 'currentWorkspace']) {
|
||
const value = holder[key]
|
||
const snap = snapshotOf(value)
|
||
if (snap && typeof snap === 'object') candidates.push(snap.workspaceId ?? snap.id)
|
||
else if (typeof value === 'string') candidates.push(value)
|
||
}
|
||
}
|
||
const sessionId = currentSessionId()
|
||
if (sessionId) {
|
||
const owner = workspaceItems().find(item => Array.isArray(item.sessionIds) && item.sessionIds.includes(sessionId))
|
||
if (owner) candidates.push(owner.workspaceId ?? owner.id)
|
||
}
|
||
return candidates.find(id => typeof id === 'string' && id) ?? null
|
||
}
|
||
|
||
function currentWorkspace() {
|
||
const items = workspaceItems().map(normalizeWorkspace).filter(Boolean)
|
||
const id = currentWorkspaceId()
|
||
if (id) {
|
||
const hit = items.find(item => item.workspaceId === id)
|
||
return hit || { workspaceId: id, name: undefined, path: undefined }
|
||
}
|
||
if (items.length === 1) return items[0]
|
||
return null
|
||
}
|
||
|
||
function seatRecordOf(view, id) {
|
||
const seats = view && view.project ? view.project.seats : null
|
||
if (Array.isArray(seats)) return seats.find(seat => seat && seat.id === id) || null
|
||
if (seats && typeof seats === 'object') return seats[id] || null
|
||
return null
|
||
}
|
||
|
||
// ---------- 会话导航(特性探测;拿不到只发意图并 console.warn) ----------
|
||
function navigateToSession(sessionId) {
|
||
if (!sessionId) return false
|
||
const attempts = []
|
||
const ui = get('uiWorkspace')
|
||
if (ui) {
|
||
if (isFn(ui.openSession)) attempts.push(() => ui.openSession(sessionId))
|
||
if (isFn(ui.open)) attempts.push(() => ui.open(sessionId))
|
||
}
|
||
const sessions = get('sessions')
|
||
if (sessions) {
|
||
if (isFn(sessions.open)) attempts.push(() => sessions.open(sessionId))
|
||
if (isFn(sessions.openSession)) attempts.push(() => sessions.openSession(sessionId))
|
||
if (isFn(sessions.select)) attempts.push(() => sessions.select(sessionId))
|
||
}
|
||
for (const name of ['navigation', 'navigator', 'router']) {
|
||
const svc = get(name)
|
||
if (!svc) continue
|
||
if (isFn(svc.openSession)) attempts.push(() => svc.openSession(sessionId))
|
||
if (isFn(svc.navigate)) attempts.push(() => svc.navigate({ sessionId }))
|
||
if (isFn(svc.open)) attempts.push(() => svc.open(sessionId))
|
||
}
|
||
for (const run of attempts) {
|
||
try {
|
||
const result = run()
|
||
if (result && isFn(result.then)) result.catch(() => {})
|
||
return true
|
||
} catch { /* 换下一个候选 */ }
|
||
}
|
||
console.warn('[sansheng] 未找到可用的会话导航接口,仅发出 navigate 意图:', sessionId)
|
||
try {
|
||
if (typeof window !== 'undefined') {
|
||
window.dispatchEvent(new CustomEvent('sansheng:navigate', { detail: { sessionId } }))
|
||
}
|
||
} catch { /* 忽略 */ }
|
||
return false
|
||
}
|
||
|
||
// ---------- 右侧标签页(真实契约:register 类型 + 正文/标题 slot;不可用时回退浮动面板) ----------
|
||
function ensureRightTab() {
|
||
const tabs = get('sidebarRightTabs')
|
||
if (!tabs || !isFn(tabs.get)) return false
|
||
try { return !!(tabs.get(TAB_KIND) || tabs.get(TAB_TYPE_ID)) } catch { return false }
|
||
}
|
||
// 桌面版右栏常是收起状态:只 openTab 不展开,用户会以为“点了没反应”。
|
||
function revealRightTab() {
|
||
const right = get('sidebarRight')
|
||
if (!right) return
|
||
try {
|
||
const rows = isFn(right.openTabs?.getSnapshot) ? right.openTabs.getSnapshot() : []
|
||
const row = Array.isArray(rows) ? rows.find(item => item && item.kind === TAB_KIND) : null
|
||
if (row && isFn(right.focus)) right.focus(row.tabId)
|
||
if (isFn(right.isExpanded) && !right.isExpanded() && isFn(right.toggleExpanded)) right.toggleExpanded()
|
||
} catch (error) {
|
||
console.warn('[sansheng] 展开右侧栏失败:', error && error.message ? error.message : error)
|
||
}
|
||
}
|
||
function tryOpenRightTab() {
|
||
const right = get('sidebarRight')
|
||
if (!right || !isFn(right.openTab)) return false
|
||
if (!ensureRightTab()) return false
|
||
try { right.openTab(TAB_KIND) } catch (error) {
|
||
console.warn('[sansheng] 打开右侧标签失败,改用浮动面板:', error && error.message ? error.message : error)
|
||
return false
|
||
}
|
||
revealRightTab()
|
||
// 确认页签确实出现;宿主拒绝(例如当前没有会话面板)时返回 false,让调用方回退,避免“点了没反应”。
|
||
try {
|
||
const rows = isFn(right.openTabs?.getSnapshot) ? right.openTabs.getSnapshot() : null
|
||
if (Array.isArray(rows) && rows.length > 0 && !rows.some(item => item && item.kind === TAB_KIND)) return false
|
||
} catch { /* 读不到就按已打开处理 */ }
|
||
return true
|
||
}
|
||
function SanshengTabBody() {
|
||
return h('div', { className: 'ssw-tab-body' }, h(SanshengWorkbench, {}))
|
||
}
|
||
function SanshengTabTitle() {
|
||
return h('span', { className: 'ssw-tab-title' }, '三省六部')
|
||
}
|
||
// 宿主按 definition.id 选 slot(TabSlot: entryKey=definition.id),因此 slot key 必须等于类型 id。
|
||
function registerRightTabType() {
|
||
try {
|
||
if (!isFn(ctx.inject)) return
|
||
ctx.inject(['sidebarRightTabs'], (injected) => {
|
||
const tabs = injected.get('sidebarRightTabs')
|
||
if (!tabs || !isFn(tabs.register)) return
|
||
let disposeType = null, disposeBody = null, disposeTitle = null
|
||
try {
|
||
disposeType = tabs.register({ id: TAB_TYPE_ID, kind: TAB_KIND, keepMounted: true, priority: 'extension', title: () => '三省六部' })
|
||
disposeBody = ctx.slots.inject('sidebar.right.pane.tab', () => ctx.slots.register({
|
||
name: 'sidebar.right.pane.tab', key: TAB_TYPE_ID, inject: (sessionId) => ({ sessionId }),
|
||
}, SanshengTabBody))
|
||
disposeTitle = ctx.slots.inject('sidebar.right.pane.tab.title', () => ctx.slots.register({
|
||
name: 'sidebar.right.pane.tab.title', key: TAB_TYPE_ID, inject: (sessionId) => ({ sessionId }),
|
||
}, SanshengTabTitle))
|
||
} catch (error) {
|
||
console.warn('[sansheng] 注册右侧标签失败:', error && error.message ? error.message : error)
|
||
try { disposeBody && disposeBody() } catch { /* 忽略 */ }
|
||
try { disposeTitle && disposeTitle() } catch { /* 忽略 */ }
|
||
try { disposeType && disposeType() } catch { /* 忽略 */ }
|
||
return
|
||
}
|
||
return () => {
|
||
try { disposeBody && disposeBody() } catch { /* 忽略 */ }
|
||
try { disposeTitle && disposeTitle() } catch { /* 忽略 */ }
|
||
try { disposeType && disposeType() } catch { /* 忽略 */ }
|
||
}
|
||
})
|
||
} catch (error) {
|
||
console.warn('[sansheng] 注册右侧标签失败:', error && error.message ? error.message : error)
|
||
}
|
||
}
|
||
|
||
// ---------- 工作台组件 ----------
|
||
function SanshengWorkbench(props) {
|
||
const onClose = props && props.onClose ? props.onClose : null
|
||
const [phase, setPhase] = useState('loading')
|
||
const [error, setError] = useState(null)
|
||
const [errorRetryable, setErrorRetryable] = useState(true)
|
||
const [notice, setNotice] = useState(null)
|
||
const [view, setView] = useState(null)
|
||
const [models, setModels] = useState(null)
|
||
const [selectedSeatId, setSelectedSeatId] = useState(SEAT_IDS[0])
|
||
const [draft, setDraft] = useState({})
|
||
const [busy, setBusy] = useState(false)
|
||
const [configOpen, setConfigOpen] = useState(false)
|
||
const [reportOpen, setReportOpen] = useState(false)
|
||
const alive = useRef(true)
|
||
|
||
useEffect(() => () => { alive.current = false }, [])
|
||
|
||
const loadProject = useCallback(async () => {
|
||
setPhase('loading'); setError(null); setErrorRetryable(true); setNotice(null)
|
||
const workspace = currentWorkspace()
|
||
if (!workspace) { setPhase('no-workspace'); return }
|
||
try {
|
||
const projectView = await request('open', {
|
||
workspaceId: workspace.workspaceId,
|
||
name: workspace.name,
|
||
path: workspace.path,
|
||
})
|
||
let modelCatalog = null
|
||
try { modelCatalog = await request('models') } catch (modelError) {
|
||
console.warn('[sansheng] 模型目录加载失败:', modelError && modelError.message ? modelError.message : modelError)
|
||
}
|
||
if (!alive.current) return
|
||
setView(projectView)
|
||
setModels(modelCatalog)
|
||
setPhase('ready')
|
||
} catch (loadError) {
|
||
if (!alive.current) return
|
||
setError(loadError && loadError.message ? loadError.message : '加载失败')
|
||
setErrorRetryable(!(loadError && loadError.retryable === false))
|
||
setPhase('error')
|
||
}
|
||
}, [])
|
||
|
||
useEffect(() => { void loadProject() }, [loadProject])
|
||
|
||
const wb = buildWorkbenchView(view, { selectedSeatId, models, draft })
|
||
const seatById = useMemo(() => {
|
||
const map = {}
|
||
for (const seat of wb.seats) map[seat.id] = seat
|
||
return map
|
||
}, [wb.seats])
|
||
|
||
function pickSeat(id) {
|
||
if (!id) return
|
||
if (id !== selectedSeatId) {
|
||
setSelectedSeatId(id)
|
||
setConfigOpen(false)
|
||
}
|
||
const seat = seatById[id]
|
||
if (wb.ready && seat && seat.status === 'bound') {
|
||
const rec = seatRecordOf(view, id)
|
||
if (rec && rec.sessionId) {
|
||
navigateToSession(rec.sessionId)
|
||
setNotice('已切换到' + seat.name + '会话')
|
||
return
|
||
}
|
||
}
|
||
if (wb.ready && seat && seat.status !== 'bound') setNotice('该席尚未绑定会话,先启用或重试启用')
|
||
}
|
||
|
||
function setModelValue(value) {
|
||
setDraft(prev => updateDraft(prev, selectedSeatId, { modelValue: value }))
|
||
}
|
||
function setInstructions(value) {
|
||
setDraft(prev => updateDraft(prev, selectedSeatId, { instructions: value }))
|
||
}
|
||
|
||
async function enableSeats() {
|
||
const projectId = view && view.project ? view.project.id : null
|
||
if (!projectId) return
|
||
setBusy(true); setError(null); setNotice('正在启用十席…')
|
||
try {
|
||
const next = await request('enable', { projectId })
|
||
if (!alive.current) return
|
||
setView(next)
|
||
setNotice('十席已启用(建立独立会话,不自动运行模型)')
|
||
} catch (enableError) {
|
||
if (alive.current) setError(enableError && enableError.message ? enableError.message : '启用失败')
|
||
} finally {
|
||
if (alive.current) setBusy(false)
|
||
}
|
||
}
|
||
|
||
async function saveConfig() {
|
||
const projectId = view && view.project ? view.project.id : null
|
||
if (!projectId) return
|
||
const seatId = wb.selected.id
|
||
const value = wb.selected.modelValue
|
||
if (!value) { setNotice('请先为当前角色选择模型'); return }
|
||
const option = findModelOption(wb.selected.modelOptions, value)
|
||
const model = option
|
||
? (option.reasoningEffort
|
||
? { provider: option.provider, model: option.model, reasoningEffort: option.reasoningEffort }
|
||
: { provider: option.provider, model: option.model })
|
||
: null
|
||
setBusy(true); setError(null); setNotice('保存中…')
|
||
try {
|
||
await request('configure', { projectId, seatId, model, instructions: wb.selected.instructions })
|
||
const next = await request('project', { projectId })
|
||
if (!alive.current) return
|
||
setView(next)
|
||
setDraft(prev => clearDraft(prev, seatId))
|
||
setNotice('已保存')
|
||
} catch (saveError) {
|
||
if (alive.current) setError(saveError && saveError.message ? saveError.message : '保存失败')
|
||
} finally {
|
||
if (alive.current) setBusy(false)
|
||
}
|
||
}
|
||
|
||
const seatCard = (seat) => h('button', {
|
||
key: seat.id, type: 'button', className: 'ssw-seat',
|
||
'aria-pressed': seat.selected ? 'true' : 'false',
|
||
title: seat.name + ' · ' + seat.duty + '(' + seat.statusLabel + ')',
|
||
onClick: () => pickSeat(seat.id),
|
||
},
|
||
h('span', { className: 'ssw-role-top' },
|
||
h('span', { className: 'ssw-role-name' }, seat.name),
|
||
h('span', { className: 'ssw-dot', 'data-status': seat.status, 'aria-hidden': 'true' }),
|
||
),
|
||
h('span', { className: 'ssw-role-duty' }, seat.duty),
|
||
)
|
||
|
||
const pickList = (ids) => ids.map(id => seatById[id]).filter(Boolean)
|
||
const tree = h('section', { className: 'ssw-tree', 'aria-label': '切换角色' },
|
||
h('div', { className: 'ssw-lead' }, pickList(wb.groups.lead).map(seatCard)),
|
||
h('div', { className: 'ssw-sansheng' },
|
||
h('span', { className: 'ssw-group-label' }, '三省'),
|
||
h('div', { className: 'ssw-trio' }, pickList(wb.groups.sansheng).map(seatCard)),
|
||
),
|
||
h('div', { className: 'ssw-ministries' },
|
||
h('span', { className: 'ssw-group-label' }, '六部 · 尚书统筹'),
|
||
h('div', { className: 'ssw-six' }, pickList(wb.groups.liubu).map(seatCard)),
|
||
),
|
||
)
|
||
|
||
const head = h('header', { className: 'ssw-head' },
|
||
h(TreeIcon),
|
||
h('strong', { className: 'ssw-head-title' }, '工作台'),
|
||
onClose
|
||
? h('button', { type: 'button', className: 'ssw-icon-btn', onClick: onClose, 'aria-label': '收起工作台' }, h(CloseIcon))
|
||
: null,
|
||
)
|
||
|
||
const projectInfo = h('div', { className: 'ssw-project' },
|
||
h('div', { className: 'ssw-project-line' },
|
||
h('span', { className: 'ssw-eyebrow' }, h(FolderIcon), '当前项目'),
|
||
h('span', { className: 'ssw-count' }, wb.project.seatCount + ' 个角色 · ' + wb.project.sessionCount + ' 个会话'),
|
||
),
|
||
h('div', { className: 'ssw-project-title' }, wb.projectTitle || '未命名项目'),
|
||
)
|
||
|
||
const enableBlock = !wb.ready
|
||
? h('div', { className: 'ssw-enable' },
|
||
h('p', { className: 'ssw-enable-note' }, '这个项目还没有启用十席。启用会建立十个独立会话,但不会自动运行模型。'),
|
||
h('button', {
|
||
type: 'button', className: 'ssw-primary', disabled: busy, onClick: enableSeats,
|
||
}, busy ? '正在启用…' : '启用此项目的十席'),
|
||
)
|
||
: null
|
||
|
||
const currentCard = h('section', { className: 'ssw-current' },
|
||
h('div', { className: 'ssw-current-top' },
|
||
h('strong', { className: 'ssw-current-name' }, wb.selected.name),
|
||
h('span', { className: 'ssw-current-label' }, '角色职责 · ' + wb.selected.statusLabel),
|
||
),
|
||
h('p', { className: 'ssw-current-text' }, wb.selected.responsibility),
|
||
)
|
||
|
||
const optionEls = wb.selected.modelOptions.map(option => h('option', { key: option.value, value: option.value }, option.label))
|
||
if (wb.selected.modelValue && !wb.selected.modelOptions.some(option => option.value === wb.selected.modelValue)) {
|
||
optionEls.push(h('option', { key: '__current__', value: wb.selected.modelValue }, wb.selected.modelLabel))
|
||
}
|
||
const config = h('section', { className: 'ssw-config' },
|
||
h('button', {
|
||
type: 'button', className: 'ssw-config-toggle', 'aria-expanded': configOpen ? 'true' : 'false',
|
||
onClick: () => setConfigOpen(value => !value),
|
||
},
|
||
h(GearIcon),
|
||
h('span', null, '配置' + wb.selected.name + (wb.selected.dirty ? ' · 未保存' : '')),
|
||
h(ChevronIcon),
|
||
),
|
||
configOpen
|
||
? h('div', { className: 'ssw-config-body' },
|
||
h('label', { className: 'ssw-label' }, '会话模型'),
|
||
h('select', {
|
||
className: 'ssw-field', value: wb.selected.modelValue, disabled: busy,
|
||
onChange: event => setModelValue(event.target.value),
|
||
},
|
||
h('option', { value: '', disabled: true }, UNCHOSEN_MODEL_LABEL),
|
||
...optionEls,
|
||
),
|
||
h('label', { className: 'ssw-label' }, '角色补充说明'),
|
||
h('textarea', {
|
||
className: 'ssw-field ssw-textarea', rows: 4, value: wb.selected.instructions, disabled: busy,
|
||
placeholder: '补充该角色在当前项目中的工作要求',
|
||
onChange: event => setInstructions(event.target.value),
|
||
}),
|
||
h('p', { className: 'ssw-scope-note' }, '每个角色是独立会话;模型与说明只影响当前项目当前角色,不改变宿主默认模型。'),
|
||
h('div', { className: 'ssw-save-row' },
|
||
h('button', { type: 'button', className: 'ssw-primary', disabled: busy, onClick: saveConfig }, busy ? '保存中…' : '保存配置'),
|
||
wb.selected.dirty ? h('span', { className: 'ssw-save-status' }, '有未保存修改') : null,
|
||
),
|
||
)
|
||
: null,
|
||
)
|
||
|
||
const report = h('section', { className: 'ssw-report' },
|
||
h('button', {
|
||
type: 'button', className: 'ssw-report-toggle', 'aria-expanded': reportOpen ? 'true' : 'false',
|
||
onClick: () => setReportOpen(value => !value),
|
||
}, reportOpen ? '收起职责汇报' : '全部汇报职责'),
|
||
reportOpen
|
||
? h('div', { className: 'ssw-report-list' },
|
||
SEAT_IDS.map(id => {
|
||
const rec = seatRecordOf(view, id)
|
||
const m = rec && rec.model
|
||
const modelLabel = m && m.model ? (m.model + (m.reasoningEffort ? ' · ' + m.reasoningEffort : '')) : '未选择模型'
|
||
return h('div', { key: id, className: 'ssw-report-item', 'data-seat': id },
|
||
h('div', { className: 'ssw-report-head' },
|
||
h('strong', null, SEATS[id].label),
|
||
h('span', null, SEATS[id].duty),
|
||
),
|
||
h('p', { className: 'ssw-report-model' }, '模型:' + modelLabel),
|
||
h('p', { className: 'ssw-report-text' }, SEATS[id].responsibility),
|
||
)
|
||
}),
|
||
)
|
||
: null,
|
||
)
|
||
|
||
const statusEl = error
|
||
? h('p', { className: 'ssw-error', role: 'alert' }, error)
|
||
: (notice ? h('p', { className: 'ssw-notice', role: 'status' }, notice) : null)
|
||
|
||
let body
|
||
if (phase === 'loading') body = h('div', { className: 'ssw-loading' }, '正在加载工作台…')
|
||
else if (phase === 'no-workspace') body = h('div', { className: 'ssw-empty' },
|
||
h('p', null, '请先选择项目'),
|
||
h('p', { className: 'ssw-hint' }, '在左侧工作区里选中一个项目后再打开三省六部。'),
|
||
h('button', { type: 'button', className: 'ssw-primary', onClick: loadProject }, '重新检查'),
|
||
)
|
||
else if (phase === 'error' && !view) body = h('div', { className: 'ssw-empty' },
|
||
h('p', { className: 'ssw-error' }, error || '加载失败'),
|
||
errorRetryable
|
||
? h('button', { type: 'button', className: 'ssw-primary', onClick: loadProject }, '重试')
|
||
: null,
|
||
)
|
||
else body = h(Fragment, null, projectInfo, enableBlock, tree, report, currentCard, config, statusEl)
|
||
|
||
return h('div', { className: 'ssw-root ssw-scope' }, head, body)
|
||
}
|
||
|
||
// ---------- 左侧导航入口 ----------
|
||
// 宿主正式扩展点是 sidebar.panellist:一行导航 + 一个同名 keyed main 页(插件/任务看板/记忆系统同机制)。
|
||
// 位置钉在记忆系统(order 30)与技能管理(31)之后、宿主「更多」之前。
|
||
const NAV_PANEL_ID = 'sansheng-workbench'
|
||
const NAV_ORDER = 32
|
||
|
||
function openRightWorkbench() {
|
||
return tryOpenRightTab()
|
||
}
|
||
|
||
function closeRightWorkbench() {
|
||
const layout = get('layout')
|
||
if (layout && isFn(layout.selectPanel)) {
|
||
try { layout.selectPanel(null); return } catch { /* 换下一个候选 */ }
|
||
}
|
||
const right = get('sidebarRight')
|
||
if (right && isFn(right.closeTab)) {
|
||
try { right.closeTab(TAB_KIND); return } catch { /* 忽略 */ }
|
||
}
|
||
}
|
||
|
||
// 导航行内容(宿主只把这里当图标渲染,标签由宿主按 label() 画)。
|
||
// 点击只开右侧工作台,并阻止冒泡,避免宿主把主区切成面板页——中央原生聊天因此保持原样。
|
||
function SanshengNavButton(props) {
|
||
const size = props && typeof props.size === 'number' ? props.size : 16
|
||
const [floating, setFloating] = useState(false)
|
||
const onClick = (event) => {
|
||
if (event && isFn(event.stopPropagation)) event.stopPropagation()
|
||
if (event && isFn(event.preventDefault)) event.preventDefault()
|
||
if (openRightWorkbench()) { setFloating(false); return }
|
||
setFloating(value => !value)
|
||
}
|
||
let panel = null
|
||
if (floating) {
|
||
const card = h('div', { className: 'ssw-float', role: 'dialog', 'aria-label': '三省六部工作台' },
|
||
h(SanshengWorkbench, { onClose: () => setFloating(false) }))
|
||
const canPortal = typeof document !== 'undefined' && document.body && isFn(createPortal)
|
||
panel = canPortal ? createPortal(card, document.body) : card
|
||
}
|
||
return h(Fragment, null,
|
||
h('span', {
|
||
className: 'ssw-nav-hit', role: 'presentation', title: '三省六部', onClick,
|
||
'aria-expanded': floating ? 'true' : 'false',
|
||
}, h(TreeIcon, { width: size, height: size })),
|
||
panel,
|
||
)
|
||
}
|
||
|
||
// 兜底:若宿主按整行点击切了主区,先把工作台打开到右侧并切回会话;
|
||
// 右侧打不开时就在主区直接渲染工作台(而不是空白),保证点击一定有反应。
|
||
function SanshengNavFallback() {
|
||
const [mode, setMode] = useState('pending')
|
||
useEffect(() => {
|
||
setMode(openRightWorkbench() ? 'docked' : 'inline')
|
||
}, [])
|
||
useEffect(() => {
|
||
if (mode !== 'docked') return
|
||
const layout = get('layout')
|
||
if (layout && isFn(layout.selectPanel)) {
|
||
try { layout.selectPanel(null) } catch { /* 忽略 */ }
|
||
}
|
||
}, [mode])
|
||
if (mode !== 'inline') return null
|
||
return h('div', { className: 'ssw-tab-body' }, h(SanshengWorkbench, {
|
||
onClose: () => {
|
||
const layout = get('layout')
|
||
if (layout && isFn(layout.selectPanel)) { try { layout.selectPanel(null) } catch { /* 忽略 */ } }
|
||
},
|
||
}))
|
||
}
|
||
|
||
function registerNavEntry() {
|
||
if (!ctx.slots || !isFn(ctx.slots.inject) || !isFn(ctx.slots.register)) {
|
||
console.warn('[sansheng] 宿主未提供 slots.inject / slots.register,无法注册左侧导航入口')
|
||
return
|
||
}
|
||
try {
|
||
ctx.slots.inject('main', () => ctx.slots.inject('sidebar.panellist', () => {
|
||
const disposers = []
|
||
const disposeAll = () => {
|
||
for (const dispose of disposers.splice(0)) { try { if (isFn(dispose)) dispose() } catch { /* 忽略 */ } }
|
||
}
|
||
try {
|
||
disposers.push(ctx.slots.register({ name: 'main', key: NAV_PANEL_ID, inject: () => ({}) }, SanshengNavFallback))
|
||
disposers.push(ctx.slots.register({ name: 'sidebar.panellist', id: NAV_PANEL_ID, order: NAV_ORDER, label: () => '三省六部' }, SanshengNavButton))
|
||
} catch (error) {
|
||
disposeAll()
|
||
console.warn('[sansheng] 注册左侧导航入口失败:', error && error.message ? error.message : error)
|
||
return undefined
|
||
}
|
||
return disposeAll
|
||
}))
|
||
} catch (error) {
|
||
console.warn('[sansheng] 注册左侧导航入口失败:', error && error.message ? error.message : error)
|
||
}
|
||
}
|
||
|
||
// 左侧导航行(宿主正式槽位,位置在记忆系统之后、更多之前)。
|
||
registerNavEntry()
|
||
|
||
// 右侧工作台标签类型:需在 apply 时就注册(宿主按类型 id 选正文 slot)。
|
||
registerRightTabType()
|
||
|
||
// dsh-go 原生面板:浏览器(无 dshGo 服务)或桥未就绪时,install 内部安静退出。
|
||
try {
|
||
installNativePanel(ctx)
|
||
} catch (error) {
|
||
console.warn('[sansheng] 原生面板注册失败:', error && error.message ? error.message : error)
|
||
}
|
||
}
|