699 lines
31 KiB
JavaScript
699 lines
31 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 { WorkbenchV2 } from './workbench-v2.js'
|
||
import { workspaceForSession, workspaceItemsFromSnapshot, sessionSummaryFromSnapshot } from './workspace.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', 'workspaces', 'uiWorkspace', 'uiConversation', 'slots', 'theme', 'layout', 'sidebarRightTabs', 'sidebarRight']
|
||
|
||
const PLUGIN_ID = 'dsh-sansheng'
|
||
const TAB_KIND = 'sansheng-workbench'
|
||
const TAB_TYPE_ID = 'dsh-sansheng:workbench'
|
||
const RIGHT_PIN_KEY = 'sansheng.right-workbench.pinned'
|
||
|
||
function readRightWorkbenchPinned() {
|
||
try { return typeof localStorage !== 'undefined' && localStorage.getItem(RIGHT_PIN_KEY) === '1' } catch { return false }
|
||
}
|
||
|
||
function writeRightWorkbenchPinned(value) {
|
||
try {
|
||
if (typeof localStorage === 'undefined') return
|
||
if (value) localStorage.setItem(RIGHT_PIN_KEY, '1')
|
||
else localStorage.removeItem(RIGHT_PIN_KEY)
|
||
} catch { /* 忽略 */ }
|
||
}
|
||
|
||
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' }))
|
||
|
||
// 每个席位一个简单线性图标,沿用外观方案的“图标 + 两字名称 + 状态点”卡片。
|
||
const SEAT_ICON_PATHS = {
|
||
lead: ['M12 12a4 4 0 1 0 0-8 4 4 0 0 0 0 8Z', 'M4.5 20c0-3.2 3.4-5 7.5-5s7.5 1.8 7.5 5'],
|
||
zhongshu: ['M7 3h7l4 4v14H7z', 'M14 3v4h4', 'M9.5 12h5', 'M9.5 16h5'],
|
||
shangshu: ['M4 4h6.5v6.5H4z', 'M13.5 4H20v6.5h-6.5z', 'M4 13.5h6.5V20H4z', 'M13.5 13.5H20V20h-6.5z'],
|
||
menxia: ['M12 3l7 3v6c0 4-3 7-7 9-4-2-7-5-7-9V6z', 'm9 12 2 2 4-4'],
|
||
libu: ['M12 11a3.5 3.5 0 1 0 0-7 3.5 3.5 0 0 0 0 7Z', 'M5 20c0-3 3-4.5 7-4.5s7 1.5 7 4.5'],
|
||
hubu: ['M4 5h16v14H4z', 'M4 10h16', 'M10 5v14'],
|
||
lipu: ['M7 3h10v18H7z', 'M10 8h4', 'M10 12h4', 'M10 16h4'],
|
||
bingbu: ['M4 5h16v12H4z', 'm8 13 3-6 5 6', 'M4 20h16'],
|
||
xingbu: ['M6 3h12v18l-6-3-6 3z', 'm9 10 2 2 4-4'],
|
||
gongbu: ['m8 8-4 4 4 4', 'm16 8 4 4-4 4', 'M13 5l-2 14'],
|
||
}
|
||
function SeatIcon(props) {
|
||
const paths = SEAT_ICON_PATHS[props && props.id] ?? SEAT_ICON_PATHS.lead
|
||
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',
|
||
className: 'ssw-seat-icon',
|
||
}, paths.map((d, index) => h('path', { key: index, d })))
|
||
}
|
||
|
||
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 sessionsSnapshot() {
|
||
return snapshotOf(get('sessions')?.list) ?? snapshotOf(get('sessions'))
|
||
}
|
||
|
||
function workspaceItems() {
|
||
const sources = [
|
||
get('workspaces')?.list,
|
||
get('uiWorkspace')?.workspaces,
|
||
get('workspaces'),
|
||
]
|
||
for (const source of sources) {
|
||
const items = workspaceItemsFromSnapshot(snapshotOf(source))
|
||
if (items.length) return items
|
||
}
|
||
return []
|
||
}
|
||
|
||
function sessionSummary(sessionId) {
|
||
return sessionSummaryFromSnapshot(sessionsSnapshot(), sessionId)
|
||
}
|
||
|
||
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)
|
||
}
|
||
return candidates.find(id => typeof id === 'string' && id) ?? null
|
||
}
|
||
|
||
// 某个会话所属的工作区。右侧标签、浮动面板和主区内嵌都把自己的 sessionId 传进来,
|
||
// 因此多工作区下不会再把「当前全局会话」误当成标签页里的会话。
|
||
function workspaceForSessionId(sessionId) {
|
||
const explicitId = typeof sessionId === 'string' && sessionId ? sessionId : null
|
||
const targetId = explicitId || currentSessionId()
|
||
const fromSession = workspaceForSession(workspaceItems(), targetId, sessionSummary(targetId))
|
||
if (fromSession) return fromSession
|
||
// 明确指定了别的会话时,不能退回「当前全局会话」的工作区,否则又会串项目。
|
||
if (explicitId && explicitId !== currentSessionId()) return null
|
||
return currentWorkspace()
|
||
}
|
||
|
||
function currentWorkspace() {
|
||
const items = workspaceItems()
|
||
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 rightMountedSessionId() {
|
||
const right = get('sidebarRight')
|
||
try {
|
||
if (right && isFn(right.mounted?.getSnapshot)) {
|
||
const mounted = right.mounted.getSnapshot()
|
||
if (typeof mounted === 'string' && mounted) return mounted
|
||
}
|
||
} catch { /* 忽略 */ }
|
||
return currentSessionId()
|
||
}
|
||
|
||
function activeRightTabId() {
|
||
const right = get('sidebarRight')
|
||
if (!right || !isFn(right.active)) return null
|
||
try {
|
||
const record = right.active()
|
||
if (!record) return null
|
||
if (typeof record === 'string') return record
|
||
return record.id || record.tabId || null
|
||
} catch { return null }
|
||
}
|
||
|
||
function findRightWorkbenchTab(sessionId) {
|
||
const right = get('sidebarRight')
|
||
if (!right || !isFn(right.openTabs?.getSnapshot)) return null
|
||
try {
|
||
const rows = right.openTabs.getSnapshot()
|
||
const targetSessionId = typeof sessionId === 'string' && sessionId ? sessionId : rightMountedSessionId()
|
||
// 关键:没有明确会话时不能匹配「所有会话」的工作台标签,否则新工作区会误抓旧会话的标签。
|
||
if (!targetSessionId) return null
|
||
const matches = (Array.isArray(rows) ? rows : []).filter(item => item && item.kind === TAB_KIND && item.sessionId === targetSessionId)
|
||
if (matches.length === 0) return null
|
||
const activeId = activeRightTabId()
|
||
return matches.find(item => item.tabId === activeId) || matches[0]
|
||
} catch { return null }
|
||
}
|
||
|
||
// 只在“还没有这个会话的工作台标签”时打开;已有标签只做必要的聚焦/展开,
|
||
// 已处于目标状态时一律不动作,避免切换会话时重复 openTab/focus 造成整块刷新。
|
||
function revealRightTab(sessionId) {
|
||
const right = get('sidebarRight')
|
||
if (!right) return false
|
||
try {
|
||
const row = findRightWorkbenchTab(sessionId)
|
||
if (!row) return false
|
||
const activeId = activeRightTabId()
|
||
if (activeId !== row.tabId && isFn(right.focus)) right.focus(row.tabId)
|
||
if (isFn(right.isExpanded) && !right.isExpanded() && isFn(right.toggleExpanded)) right.toggleExpanded()
|
||
// focus/toggle 可能是宿主在会话 surface 尚未 mint 时的 silent no-op。
|
||
// 只有“目标标签真的 active 且右栏真的展开”才算成功,否则交给退避重试。
|
||
const activeNow = activeRightTabId()
|
||
if (activeNow !== row.tabId) return false
|
||
if (isFn(right.isExpanded) && !right.isExpanded()) return false
|
||
scheduleWorkbenchVisibility(sessionId)
|
||
return true
|
||
} catch (error) {
|
||
console.warn('[sansheng] 展开右侧栏失败:', error && error.message ? error.message : error)
|
||
return false
|
||
}
|
||
}
|
||
|
||
// 单次补聚焦只用于“标签异步落位”的短窗口;每次先确认标签真的存在,绝不在已有标签时重复 openTab。
|
||
function scheduleRevealRightTab(sessionId) {
|
||
for (const delay of [120, 420, 900, 1600]) {
|
||
setTimeout(() => {
|
||
if (!rightWorkbenchPinned) return
|
||
revealRightTab(sessionId)
|
||
}, delay)
|
||
}
|
||
}
|
||
|
||
// 右侧栏是宿主的独立布局列:新会话切换后,sidebarRight 可能先报“已展开”,
|
||
// 但这一列的 DOM 实际宽度仍是 0(旧会话 surface 的布局快照滞后)。
|
||
// 这种状态 focus/toggle 的服务层返回值不可靠,用工作台 DOM 宽度做最终判据,
|
||
// 并在短窗口内补一次 toggle,让新会话的右栏真正展开。
|
||
function workbenchVisible(sessionId) {
|
||
if (typeof document === 'undefined') return true
|
||
try {
|
||
// 每个会话在右栏各有自己的挂载节点;旧会话节点即使可见,也不代表当前会话可见。
|
||
const hosts = Array.from(document.querySelectorAll('.ssw-tab-body[data-session-id]'))
|
||
const scoped = sessionId ? hosts.filter(el => el.getAttribute('data-session-id') === sessionId) : hosts
|
||
if (sessionId && scoped.length === 0) return false
|
||
const candidates = scoped.length ? scoped : Array.from(document.querySelectorAll('.ssw-tab-body'))
|
||
return candidates.some(host => {
|
||
const node = host.querySelector('.ssv2')
|
||
if (!node) return false
|
||
const rect = node.getBoundingClientRect()
|
||
return rect.width > 0 && rect.height > 0
|
||
})
|
||
} catch { return true }
|
||
}
|
||
|
||
function scheduleWorkbenchVisibility(sessionId) {
|
||
for (const delay of [180, 600, 1200]) {
|
||
setTimeout(() => {
|
||
if (!rightWorkbenchPinned) return
|
||
try {
|
||
if (workbenchVisible(sessionId)) return
|
||
const right = get('sidebarRight')
|
||
const row = findRightWorkbenchTab(sessionId)
|
||
if (!right || !row || activeRightTabId() !== row.tabId) return
|
||
// 宿主布局列和 rightbar surface 是两层状态:surface 可能已 expanded,
|
||
// 但布局列仍为 0。直接报告一次可见 track,随后仍留给宿主自己收敛。
|
||
const layout = get('layout')
|
||
if (layout && isFn(layout.openRightbar)) layout.openRightbar(true, false)
|
||
else if (isFn(right.toggleExpanded)) right.toggleExpanded()
|
||
} catch { /* 忽略 */ }
|
||
}, delay)
|
||
}
|
||
}
|
||
|
||
function tryOpenRightTab(sessionId) {
|
||
const targetSessionId = (typeof sessionId === 'string' && sessionId) ? sessionId : rightMountedSessionId()
|
||
const existing = findRightWorkbenchTab(targetSessionId)
|
||
if (existing) return revealRightTab(targetSessionId)
|
||
// 桌面版右栏由 dsh-better-sidebar 接管:它自己的 openTab 会排队等待会话面板挂载,
|
||
// 主区正被切走时也不会丢;直接调宿主 sidebarRight 反而会因“没有挂载的会话面板”失败。
|
||
// 显式传 scope:新会话刚建立时 bs 的 active snapshot 可能还停在旧会话,不能靠猜。
|
||
const bs = get('betterSidebar')
|
||
if (bs && isFn(bs.openTab)) {
|
||
try {
|
||
if (!targetSessionId) return false
|
||
const summary = sessionSummary(targetSessionId)
|
||
const scope = { sessionId: targetSessionId }
|
||
if (summary && typeof summary.cwd === 'string' && summary.cwd) scope.cwd = summary.cwd
|
||
bs.openTab({ type: TAB_KIND, title: '三省六部' }, scope)
|
||
scheduleRevealRightTab(targetSessionId)
|
||
return true
|
||
} catch (error) {
|
||
console.warn('[sansheng] better-sidebar 打开失败,改用宿主接口:', error && error.message ? error.message : error)
|
||
}
|
||
}
|
||
const right = get('sidebarRight')
|
||
if (!right || !isFn(right.openTab)) return false
|
||
if (!ensureRightTab()) return false
|
||
try {
|
||
// 原生接口的 openTab 只能作用于 on-screen 会话;目标会话尚未 adopt 时,
|
||
// 如果宿主暴露了 openTabIn(跨会话目标通道)就用它,否则退回 openTab 并靠退避重试。
|
||
const mountedId = rightMountedSessionId()
|
||
if (targetSessionId && targetSessionId !== mountedId && isFn(right.openTabIn)) right.openTabIn(targetSessionId, TAB_KIND)
|
||
else right.openTab(TAB_KIND)
|
||
} catch (error) {
|
||
console.warn('[sansheng] 打开右侧标签失败,改用浮动面板:', error && error.message ? error.message : error)
|
||
return false
|
||
}
|
||
revealRightTab(targetSessionId)
|
||
scheduleRevealRightTab(targetSessionId)
|
||
return true
|
||
}
|
||
function SanshengTabBody(props) {
|
||
const sessionId = props && props.sessionId
|
||
return h('div', { className: 'ssw-tab-body', 'data-session-id': sessionId || undefined }, h(SanshengWorkbench, { sessionId }))
|
||
}
|
||
function SanshengTabTitle() {
|
||
return h('span', { className: 'ssw-tab-title' }, '三省六部')
|
||
}
|
||
// 宿主按 definition.id 选 slot(TabSlot: entryKey=definition.id),因此 slot key 必须等于类型 id。
|
||
function registerRightTabType() {
|
||
// 桌面版:向 better-sidebar 注册一个原生右侧标签(它自己负责正文/标题与落位)。
|
||
try {
|
||
const bs = get('betterSidebar')
|
||
if (bs && isFn(bs.registerTab)) {
|
||
const dispose = bs.registerTab({
|
||
id: TAB_KIND,
|
||
title: '三省六部',
|
||
description: '十席角色与独立会话的当前项目工作台',
|
||
icon: (size) => h(TreeIcon, { width: size, height: size }),
|
||
order: 32,
|
||
single: true,
|
||
component: (tabProps) => {
|
||
const scope = tabProps && tabProps.scope ? tabProps.scope : null
|
||
const sessionId = scope && scope.sessionId
|
||
return h('div', { className: 'ssw-tab-body', 'data-session-id': sessionId || undefined }, h(SanshengWorkbench, { sessionId }))
|
||
},
|
||
})
|
||
return () => { try { if (isFn(dispose)) dispose() } catch { /* 忽略 */ } }
|
||
}
|
||
} catch (error) {
|
||
console.warn('[sansheng] 注册 better-sidebar 标签失败:', error && error.message ? error.message : error)
|
||
}
|
||
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: () => '三省六部',
|
||
guide: [{
|
||
id: `${TAB_TYPE_ID}:guide`, order: 32, title: () => '三省六部',
|
||
description: () => '十席角色与独立会话的当前项目工作台', icon: TreeIcon,
|
||
}],
|
||
})
|
||
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)
|
||
}
|
||
}
|
||
|
||
// 工作台会随宿主会话切换而重挂载;按项目记住选中的部门,避免又跳回丞相。
|
||
const selectedSeatCache = new Map()
|
||
let lastSelectedSeatId = SEAT_IDS[0]
|
||
let rightWorkbenchPinned = readRightWorkbenchPinned()
|
||
|
||
// ---------- 工作台组件 ----------
|
||
// 工作台 v2:视觉与交互按用户提供的设计稿实现,数据全部走真实 host API。
|
||
function SanshengWorkbench(props) {
|
||
const sessionId = props && props.sessionId
|
||
const resolveWorkspace = useCallback(() => workspaceForSessionId(sessionId), [sessionId])
|
||
return h(WorkbenchV2, {
|
||
sessionId,
|
||
onClose: props && props.onClose,
|
||
resolveWorkspace,
|
||
navigateToSession,
|
||
openRightTab: tryOpenRightTab,
|
||
selectionCache: selectedSeatCache,
|
||
getLastSeatId: () => lastSelectedSeatId,
|
||
setLastSeatId: id => { lastSelectedSeatId = id },
|
||
})
|
||
}
|
||
|
||
// ---------- 左侧导航入口 ----------
|
||
// 宿主正式扩展点是 sidebar.panellist:一行导航 + 一个同名 keyed main 页(插件/任务看板/记忆系统同机制)。
|
||
// 位置钉在记忆系统(order 30)与技能管理(31)之后、宿主「更多」之前。
|
||
const NAV_PANEL_ID = 'sansheng-workbench'
|
||
const NAV_ORDER = 32
|
||
|
||
function openRightWorkbench(sessionId) {
|
||
const opened = tryOpenRightTab(sessionId)
|
||
if (opened) { rightWorkbenchPinned = true; writeRightWorkbenchPinned(true) }
|
||
return opened
|
||
}
|
||
|
||
function closeRightWorkbench() {
|
||
rightWorkbenchPinned = false
|
||
writeRightWorkbenchPinned(false)
|
||
const right = get('sidebarRight')
|
||
const row = findRightWorkbenchTab()
|
||
if (row && right && isFn(right.close)) {
|
||
try { right.close(row.tabId); return } catch { /* 忽略 */ }
|
||
}
|
||
const layout = get('layout')
|
||
if (layout && isFn(layout.selectPanel)) {
|
||
try { layout.selectPanel(null); return } catch { /* 换下一个候选 */ }
|
||
}
|
||
if (right && isFn(right.closeTab)) {
|
||
try { right.closeTab(TAB_KIND); return } catch { /* 忽略 */ }
|
||
}
|
||
}
|
||
|
||
// 右侧栏按会话保存布局;切换部门打开新会话后,把固定工作台重新挂到新会话。
|
||
// 新建会话的 store 是异步 mint 的:mounted 先变,sidebarRight 还会短暂报
|
||
// “no session surface is mounted”。这里只重试“缺标签”的那一次打开;
|
||
// 已有标签只做必要的聚焦/展开,绝不对同一会话重复 openTab。
|
||
function installRightDockPinning() {
|
||
const right = get('sidebarRight')
|
||
if (!right || !isFn(right.mounted?.subscribe)) return
|
||
const delays = [60, 140, 280, 560, 1000, 1800, 3000]
|
||
let timer = null
|
||
let attempt = 0
|
||
const clear = () => {
|
||
if (timer !== null) { clearTimeout(timer); timer = null }
|
||
}
|
||
const ensure = () => {
|
||
timer = null
|
||
if (!rightWorkbenchPinned) { attempt = 0; return }
|
||
try {
|
||
const sessionId = rightMountedSessionId()
|
||
if (findRightWorkbenchTab(sessionId)) {
|
||
// 标签存在不代表已经展开:新会话的右栏 surface 可能尚未 mint,
|
||
// reveal 会短暂失败。失败时继续退避重试,不能把“找到标签”当成成功。
|
||
if (revealRightTab(sessionId)) { attempt = 0; return }
|
||
}
|
||
if (openRightWorkbench(sessionId)) {
|
||
attempt = 0
|
||
return
|
||
}
|
||
} catch { /* 会话尚未挂载时,继续按退避重试 */ }
|
||
if (attempt < delays.length - 1) {
|
||
attempt += 1
|
||
timer = setTimeout(ensure, delays[attempt])
|
||
}
|
||
}
|
||
const kick = () => {
|
||
if (!rightWorkbenchPinned) return
|
||
clear()
|
||
attempt = 0
|
||
timer = setTimeout(ensure, delays[0])
|
||
}
|
||
const stop = right.mounted.subscribe(kick)
|
||
// 用户也可能从右侧栏 guide 入口直接打开工作台;此时没有经过 openRightWorkbench,
|
||
// 需要观察 openTabs 把“已经打开”记成固定状态,否则切一次会话就被宿主收起。
|
||
let stopTabs = null
|
||
const discoverPinnedTab = () => {
|
||
try {
|
||
const sessionId = rightMountedSessionId()
|
||
if (!sessionId || !findRightWorkbenchTab(sessionId)) return
|
||
if (!rightWorkbenchPinned) { rightWorkbenchPinned = true; writeRightWorkbenchPinned(true) }
|
||
kick()
|
||
} catch { /* 忽略 */ }
|
||
}
|
||
if (isFn(right.openTabs?.subscribe)) stopTabs = right.openTabs.subscribe(discoverPinnedTab)
|
||
if (rightWorkbenchPinned) kick()
|
||
if (isFn(ctx.effect)) ctx.effect(() => {
|
||
clear()
|
||
stop()
|
||
try { if (isFn(stopTabs)) stopTabs() } catch { /* 忽略 */ }
|
||
})
|
||
}
|
||
|
||
// 导航行内容(宿主只把这里当图标渲染,标签由宿主按 label() 画)。
|
||
// 点击只开右侧工作台,并阻止冒泡,避免宿主把主区切成面板页——中央原生聊天因此保持原样。
|
||
function SanshengNavButton(props) {
|
||
const size = props && typeof props.size === 'number' ? props.size : 16
|
||
const [floating, setFloating] = useState(false)
|
||
const stop = (event) => {
|
||
if (event && isFn(event.stopPropagation)) event.stopPropagation()
|
||
}
|
||
const onClick = (event) => {
|
||
if (event && isFn(event.stopPropagation)) event.stopPropagation()
|
||
if (event && isFn(event.preventDefault)) event.preventDefault()
|
||
if (openRightWorkbench(currentSessionId())) { setFloating(false); return }
|
||
setFloating(value => !value)
|
||
}
|
||
let panel = null
|
||
if (floating) {
|
||
const card = h('div', { className: 'ssw-float', role: 'dialog', 'aria-label': '三省六部工作台' },
|
||
h(SanshengWorkbench, { sessionId: currentSessionId(), 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,
|
||
onPointerDown: stop, onMouseDown: stop,
|
||
'aria-expanded': floating ? 'true' : 'false',
|
||
}, h(TreeIcon, { width: size, height: size })),
|
||
panel,
|
||
)
|
||
}
|
||
|
||
// 兜底:若宿主按整行点击切了主区,先把工作台打开到右侧并切回会话;
|
||
// 右侧打不开时就在主区直接渲染工作台(而不是空白),保证点击一定有反应。
|
||
function backToChat() {
|
||
const layout = get('layout')
|
||
if (layout && isFn(layout.selectPanel)) { try { layout.selectPanel(null) } catch { /* 忽略 */ } }
|
||
}
|
||
function SanshengNavFallback() {
|
||
// 点击左侧「三省六部」整行时,优先把工作台停靠到右侧;打不开就在主区内嵌显示。
|
||
// 关键:openRightWorkbench 必须在组件仍挂载时同步尝试。旧逻辑先 backToChat,
|
||
// 组件随即卸载,定时器里的 setMode('inline') 落在已卸载实例上,主区就永远空白。
|
||
const hasBetterSidebar = !!get('betterSidebar')
|
||
const [mode, setMode] = useState('pending')
|
||
useEffect(() => {
|
||
let opened = false
|
||
try { opened = openRightWorkbench(currentSessionId()) } catch { opened = false }
|
||
if (opened) {
|
||
setMode('docked')
|
||
backToChat()
|
||
return undefined
|
||
}
|
||
if (!hasBetterSidebar) {
|
||
setMode('inline')
|
||
return undefined
|
||
}
|
||
// 桌面右栏宿主:先切回会话,再等会话重新挂载后重试打开右栏。
|
||
// 这些定时器不随本组件卸载取消,否则切回会话就把自己“清理”掉了。
|
||
backToChat()
|
||
let openedLater = false
|
||
for (const delay of [200, 600, 1200, 2000]) {
|
||
setTimeout(() => {
|
||
try { if (!openedLater && openRightWorkbench(currentSessionId())) { openedLater = true; backToChat() } } catch { /* 忽略 */ }
|
||
}, delay)
|
||
}
|
||
setTimeout(() => { if (!openedLater) setMode('inline') }, 2600)
|
||
return undefined
|
||
}, [])
|
||
useEffect(() => {
|
||
if (mode !== 'docked') return
|
||
backToChat()
|
||
const timer = setTimeout(backToChat, 700)
|
||
return () => clearTimeout(timer)
|
||
}, [mode])
|
||
if (mode === 'pending') return null
|
||
if (mode === 'docked') return null
|
||
return h('div', { className: 'ssw-tab-body' },
|
||
h('div', { className: 'ssw-inline-bar' },
|
||
h('span', null, '工作台 · 内嵌模式'),
|
||
h('button', { type: 'button', className: 'ssw-link', onClick: backToChat }, '返回对话'),
|
||
),
|
||
h(SanshengWorkbench, { sessionId: currentSessionId() }),
|
||
)
|
||
}
|
||
|
||
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()
|
||
installRightDockPinning()
|
||
|
||
// dsh-go 原生面板:浏览器(无 dshGo 服务)或桥未就绪时,install 内部安静退出。
|
||
try {
|
||
installNativePanel(ctx)
|
||
} catch (error) {
|
||
console.warn('[sansheng] 原生面板注册失败:', error && error.message ? error.message : error)
|
||
}
|
||
}
|