feat(ui): left-rail Brain panel with overview and connection tabs

This commit is contained in:
newbie 2026-11-25 10:29:42 +08:00
parent dfe31ac3f8
commit 891b19f809
16 changed files with 1508 additions and 356 deletions

File diff suppressed because it is too large Load Diff

View File

@ -284,6 +284,13 @@ export class BrainKernel {
mcp: this.isActive('mcp'),
localMemory: this.localMemory,
departments: this.departments,
bundles: {
cloudsync: this.isActive('cloudsync'),
memory: this.isActive('memory'),
skills: this.isActive('skills'),
mcp: this.isActive('mcp'),
'settings-ui': this.isActive('settings-ui'),
},
};
}
}

View File

@ -98,6 +98,7 @@ export function buildStatusPayload(deps) {
reporter: deps.reporter.snapshot(),
lastCheck: getLastCheck(),
capabilities: capabilities(deps),
bundles: deps.bundles ?? {},
...(deps.skills === undefined ? {} : { skills: deps.skills() }),
};
}

View File

@ -0,0 +1,64 @@
// Slim settings card: status summary + a jump into the Brain total panel.
import * as React from 'react'
import { API, request, messageOf } from './api'
import { styles } from './styles'
import { Pill, Banner, Btn } from './components'
const h = React.createElement
export function SettingsSummaryCard(props: { ctx?: any }): any {
const [status, setStatus] = React.useState<any>(null)
const [error, setError] = React.useState<string | null>(null)
React.useEffect(() => {
let cancelled = false
const load = (): void => {
request(API.status).then(
(result) => {
if (cancelled) return
if (result.status === 200 && result.body !== null && result.body.ok === true) {
setStatus(result.body)
setError(null)
} else {
setError('读取状态失败(HTTP ' + String(result.status) + ')')
}
},
(failure) => { if (!cancelled) setError(messageOf(failure)) },
)
}
load()
const timer = setInterval(load, 15000)
return () => {
cancelled = true
clearInterval(timer)
}
}, [])
function openPanel(): void {
const ctx = props.ctx
const layout = ctx === undefined || ctx === null ? undefined : ctx.layout
if (layout !== undefined && layout !== null && typeof layout.selectPanel === 'function') {
layout.selectPanel('dsh-brain')
return
}
if (typeof window !== 'undefined' && typeof window.open === 'function') window.open('/dsh-brain')
}
const settings = status?.settings ?? {}
return h('div', { style: styles.root, 'data-dsh-plugin': 'dsh-brain' },
h('div', { style: styles.sectionHead },
h('h4', { style: styles.sectionTitle }, '云端记忆'),
h('div', { style: styles.actions },
h(Btn, { variant: 'primary', label: '打开总面板', onClick: openPanel }),
),
),
h('p', { style: styles.hint }, '设置与连接内容已收进左侧栏 Brain 总面板的「连接与上报」页签。这里保留状态摘要和快捷入口。'),
error === null ? null : h(Banner, { tone: 'bad' }, error),
status === null ? h('p', { style: styles.hint }, '正在读取状态…') : h('div', { style: styles.pills },
h(Pill, { label: '服务', value: settings.baseUrlConfigured === false ? '未配置' : '已配置', tone: settings.baseUrlConfigured === false ? 'warn' : 'ok' }),
h(Pill, { label: '上报', value: settings.activityEnabled === true ? '开' : '关', tone: settings.activityEnabled === true ? 'ok' : 'muted' }),
h(Pill, { label: '记忆', value: settings.memoryEnabled === true ? '开' : '关', tone: settings.memoryEnabled === true ? 'ok' : 'muted' }),
h(Pill, { label: '本地记忆', value: settings.localMemoryEnabled === false ? '关' : '开', tone: settings.localMemoryEnabled === false ? 'muted' : 'ok' }),
),
)
}

View File

@ -3,26 +3,35 @@ import * as React from 'react'
import { messageOf } from './api'
import { CardBoundary } from './components'
import { SettingsCard } from './SettingsCard'
import { SettingsSummaryCard } from './SettingsSummaryCard'
import { registerBrainPanel } from './panel/register'
const h = React.createElement
export const inject = ['slots']
export function apply(ctx: any): void {
const card = function () {
const summaryCard = function () {
return h(CardBoundary as any, null, h(SettingsSummaryCard as any, { ctx }))
}
// The plugin bundle config page keeps the full settings card; the generic
// settings section is now only the status summary with a jump button.
const configCard = function () {
return h(CardBoundary as any, null, h(SettingsCard as any, null))
}
const register = function (seat: string, options: any) {
const register = function (seat: string, options: any, component: any) {
try {
ctx.slots.inject(seat, function () {
return ctx.slots.register(options, card)
return ctx.slots.register(options, component)
})
} catch (failure) {
if (typeof console !== 'undefined') console.warn('[dsh-brain] slot ' + seat + ' unavailable: ' + messageOf(failure))
}
}
register('plugins.bundle.config', { name: 'plugins.bundle.config', key: 'dsh-brain' }, configCard)
register('settings.section', {
name: 'settings.section',
id: 'dsh-brain',
@ -30,9 +39,14 @@ export function apply(ctx: any): void {
label: function () {
return '云端记忆'
},
})
}, summaryCard)
register('plugins.bundle.config', { name: 'plugins.bundle.config', key: 'dsh-brain' })
try {
if (typeof ctx.effect === 'function') ctx.effect(() => registerBrainPanel(ctx), 'dsh-brain: panel')
else registerBrainPanel(ctx)
} catch (failure) {
if (typeof console !== 'undefined') console.warn('[dsh-brain] panel registration failed: ' + messageOf(failure))
}
}
export const name = 'dsh-brain'

View File

@ -0,0 +1,225 @@
/* Adapted from dsh-mnemon MnemonWorkspace.module.css (MIT), see vendor/dsh-mnemon/LICENSE. */
.nativeWorkspace {
box-sizing: border-box;
position: relative;
z-index: 2;
display: flex;
width: 100%;
height: 100%;
min-width: 0;
min-height: 0;
overflow: hidden;
flex: 1 1 auto;
padding-block-start: var(--dsh-frame-top-clearance, 0px);
}
.nativeWorkspace > * {
min-width: 0;
flex: 1 1 auto;
}
.windowDragBand {
position: absolute;
inset: 0 0 auto;
height: var(--dsh-frame-top-clearance, 0px);
}
.panelInner {
display: flex;
flex-direction: column;
gap: 14px;
padding: 18px 20px 24px;
overflow: auto;
font-size: 13px;
line-height: 1.55;
color: var(--dsw-alias-label-primary, inherit);
}
.header {
display: flex;
align-items: flex-start;
justify-content: space-between;
gap: 12px;
flex-wrap: wrap;
}
.titleBlock {
display: flex;
flex-direction: column;
gap: 2px;
min-width: 0;
}
.title {
margin: 0;
font-size: 16px;
font-weight: 650;
letter-spacing: 0.01em;
}
.subtitle {
margin: 0;
font-size: 11.5px;
opacity: 0.58;
}
.tabBar {
display: flex;
gap: 4px;
padding: 3px;
border-radius: 13px;
border: 1px solid var(--dsw-alias-border-subtle, rgba(127,127,127,0.22));
background: var(--dsw-alias-bg-subtle, rgba(127,127,127,0.06));
flex-wrap: wrap;
}
.tab {
flex: 1 1 auto;
min-width: 88px;
font: inherit;
font-size: 12.5px;
padding: 7px 12px;
border-radius: 10px;
border: 1px solid transparent;
background: transparent;
color: inherit;
cursor: pointer;
white-space: nowrap;
}
.tabActive {
border: 1px solid var(--dsw-alias-border-subtle, rgba(127,127,127,0.30));
background: var(--dsw-alias-interactive-bg-hover, rgba(127,127,127,0.14));
box-shadow: 0 1px 3px rgba(0,0,0,0.10);
font-weight: 600;
}
.content {
display: flex;
flex-direction: column;
gap: 12px;
min-width: 0;
}
.placeholder {
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
gap: 8px;
padding: 48px 16px;
border: 1px dashed var(--dsw-alias-border-subtle, rgba(127,127,127,0.30));
border-radius: 16px;
opacity: 0.65;
}
.placeholderTitle {
margin: 0;
font-size: 14px;
font-weight: 600;
}
.placeholderHint {
margin: 0;
font-size: 12px;
}
.overviewGrid {
display: flex;
flex-direction: column;
gap: 12px;
}
.card {
display: flex;
flex-direction: column;
gap: 10px;
border: 1px solid var(--dsw-alias-border-subtle, rgba(127,127,127,0.22));
border-radius: 16px;
padding: 16px 18px;
min-width: 0;
}
.cardHead {
display: flex;
align-items: center;
justify-content: space-between;
gap: 10px;
flex-wrap: wrap;
}
.cardTitle {
margin: 0;
font-size: 13.5px;
font-weight: 650;
}
.pills {
display: flex;
flex-wrap: wrap;
gap: 8px;
}
.pill {
display: inline-flex;
align-items: center;
gap: 6px;
padding: 3px 10px;
border-radius: 999px;
border: 1px solid var(--dsw-alias-border-subtle, rgba(127,127,127,0.35));
font-size: 12px;
white-space: nowrap;
}
.pillLabel {
opacity: 0.75;
}
.pillValue {
font-weight: 600;
}
.ok { border-color: rgba(22,163,74,0.55); background: rgba(22,163,74,0.12); }
.bad { border-color: rgba(220,38,38,0.55); background: rgba(220,38,38,0.12); }
.warn { border-color: rgba(217,119,6,0.55); background: rgba(217,119,6,0.12); }
.muted { }
.hint {
margin: 0;
font-size: 11.5px;
opacity: 0.58;
}
.error {
padding: 10px 13px;
border-radius: 11px;
border: 1px solid rgba(220,38,38,0.55);
background: rgba(220,38,38,0.12);
font-size: 12.5px;
}
.statRow {
display: flex;
align-items: baseline;
flex-wrap: wrap;
}
.stat {
display: inline-flex;
align-items: baseline;
gap: 6px;
padding-right: 18px;
margin-right: 18px;
border-right: 1px solid var(--dsw-alias-border-subtle, rgba(127,127,127,0.20));
}
.statLast {
display: inline-flex;
align-items: baseline;
gap: 6px;
}
.statNum {
font-size: 17px;
font-weight: 700;
}

View File

@ -0,0 +1,59 @@
// Brain total panel: the shell-rendered centre page of the dsh-brain bundle.
import * as React from 'react'
import { Overview } from './Overview'
import { SettingsCard } from '../SettingsCard'
import styles from './BrainPanel.module.css'
const h = React.createElement
const TABS = [
{ id: 'overview', label: '概览' },
{ id: 'memory', label: '记忆' },
{ id: 'departments', label: '部门' },
{ id: 'skills', label: '技能' },
{ id: 'mcp', label: 'MCP' },
{ id: 'connection', label: '连接与上报' },
] as const
function Placeholder(props: { title: string }): any {
return h('div', { className: styles.placeholder },
h('h3', { className: styles.placeholderTitle }, props.title),
h('p', { className: styles.placeholderHint }, '即将上线'),
)
}
export function BrainPanel(props: { ctx?: any; panelId?: string; usePanelInfo?: any }): any {
const [tab, setTab] = React.useState('overview')
const panelId = props.panelId ?? 'dsh-brain'
const usePanelInfo = props.usePanelInfo
const active = usePanelInfo === undefined ? true : usePanelInfo((info: { activePanelId: string | null }) => info.activePanelId === panelId)
let content: any
if (tab === 'overview') content = h(Overview, { active })
else if (tab === 'connection') content = h(SettingsCard, null)
else if (tab === 'memory') content = h(Placeholder, { title: '记忆' })
else if (tab === 'departments') content = h(Placeholder, { title: '部门' })
else if (tab === 'skills') content = h(Placeholder, { title: '技能' })
else content = h(Placeholder, { title: 'MCP' })
return h('div', { className: styles.nativeWorkspace, 'data-dsh-plugin': 'dsh-brain', 'data-dsh-part': 'brain-panel' },
h('div', { className: styles.windowDragBand, 'data-window-drag': true, 'aria-hidden': 'true' }),
h('div', { className: styles.panelInner },
h('div', { className: styles.header },
h('div', { className: styles.titleBlock },
h('h3', { className: styles.title }, 'Brain'),
h('p', { className: styles.subtitle }, '本地记忆、部门与连接的总面板'),
),
),
h('div', { className: styles.tabBar, role: 'tablist', 'aria-label': 'Brain 面板页签' },
TABS.map((item) => h('button', {
key: item.id,
type: 'button',
role: 'tab',
'aria-selected': tab === item.id,
className: tab === item.id ? styles.tab + ' ' + styles.tabActive : styles.tab,
onClick: () => setTab(item.id),
}, item.label)),
),
h('div', { className: styles.content }, content),
),
)
}

View File

@ -0,0 +1,114 @@
// Overview tab: status + capabilities aggregation.
import * as React from 'react'
import { API, request, messageOf } from '../api'
import { formatTime } from '../format'
import styles from './BrainPanel.module.css'
const h = React.createElement
const BUNDLE_LABELS: Record<string, string> = {
cloudsync: '云同步',
memory: '记忆',
skills: '技能',
mcp: 'MCP',
'settings-ui': '设置 UI',
ui: '设置 UI',
}
function Pill(props: { label: string; value: any; tone?: 'ok' | 'bad' | 'warn' | 'muted' }): any {
const tone = props.tone === undefined ? styles.muted : props.tone === 'ok' ? styles.ok : props.tone === 'bad' ? styles.bad : props.tone === 'warn' ? styles.warn : styles.muted
return h('span', { className: styles.pill + ' ' + tone },
h('span', { className: styles.pillLabel }, props.label),
h('span', { className: styles.pillValue }, String(props.value)),
)
}
function Card(props: { title: string; children?: any }): any {
return h('div', { className: styles.card },
h('div', { className: styles.cardHead }, h('h4', { className: styles.cardTitle }, props.title)),
props.children,
)
}
export function Overview(props: { active?: boolean }): any {
const active = props.active !== false
const [status, setStatus] = React.useState<any>(null)
const [capabilities, setCapabilities] = React.useState<any>(null)
const [memory, setMemory] = React.useState<any>(null)
const [error, setError] = React.useState<string | null>(null)
React.useEffect(() => {
if (!active) return
let cancelled = false
const load = async (): Promise<void> => {
try {
const [statusResult, capabilitiesResult, memoryResult] = await Promise.all([
request(API.status),
request(API.capabilities),
request('/dsh-brain/local-memory/status'),
])
if (cancelled) return
if (statusResult.status === 200 && statusResult.body !== null && statusResult.body.ok === true) {
setStatus(statusResult.body)
setError(null)
} else {
setError('读取插件状态失败(HTTP ' + String(statusResult.status) + ')')
}
if (capabilitiesResult.status === 200 && capabilitiesResult.body !== null && capabilitiesResult.body.ok === true) setCapabilities(capabilitiesResult.body)
if (memoryResult.status === 200 && memoryResult.body !== null && memoryResult.body.ok === true) setMemory(memoryResult.body)
else setMemory(null)
} catch (failure) {
if (!cancelled) setError(messageOf(failure))
}
}
void load()
const timer = setInterval(() => { void load() }, 15000)
return () => {
cancelled = true
clearInterval(timer)
}
}, [active])
const bundles: Record<string, boolean> = status?.bundles ?? {}
const bundleKeys = Object.keys(bundles).length === 0 ? ['cloudsync', 'memory', 'skills', 'mcp', 'settings-ui'] : Object.keys(bundles)
const settings = status?.settings ?? {}
const reporter = status?.reporter ?? {}
const skills = status?.skills ?? {}
const memorySpaces = memory?.spaces ?? {}
const version = capabilities?.version ?? status?.capabilities?.version ?? '—'
return h('div', { className: styles.overviewGrid },
error === null ? null : h('div', { className: styles.error }, error),
h(Card, { title: '版本与构建' },
h('div', { className: styles.pills },
h(Pill, { label: '版本', value: version }),
h(Pill, { label: '服务', value: settings.baseUrlConfigured === false ? '未配置' : (settings.baseUrlOrigin || '已配置'), tone: settings.baseUrlConfigured === false ? 'warn' : 'muted' }),
h(Pill, { label: '上报', value: settings.activityEnabled === true ? '开' : '关', tone: settings.activityEnabled === true ? 'ok' : 'muted' }),
h(Pill, { label: '记忆', value: settings.memoryEnabled === true ? '开' : '关', tone: settings.memoryEnabled === true ? 'ok' : 'muted' }),
),
status?.lastCheck === null || status?.lastCheck === undefined ? null : h('p', { className: styles.hint }, '最近检查:' + formatTime(status.lastCheck.at) + ' · ' + String(status.lastCheck.status ?? '')),
),
h(Card, { title: '五个 bundle 开关态' },
h('div', { className: styles.pills },
bundleKeys.map((key) => h(Pill, { key, label: BUNDLE_LABELS[key] ?? key, value: bundles[key] === true ? '启用' : bundles[key] === false ? '停用' : '未知', tone: bundles[key] === true ? 'ok' : bundles[key] === false ? 'bad' : 'muted' })),
),
),
h(Card, { title: '本地记忆' },
h('div', { className: styles.pills },
h(Pill, { label: '状态', value: memory === null ? '不可用' : '已启用', tone: memory === null ? 'warn' : 'ok' }),
h(Pill, { label: '全局空间', value: memorySpaces.global === undefined ? '—' : (memorySpaces.global.exists === false ? '未创建' : '就绪'), tone: memorySpaces.global?.exists === false ? 'muted' : 'ok' }),
h(Pill, { label: '项目空间', value: memorySpaces.project === undefined ? '—' : (memorySpaces.project.exists === false ? '未创建' : '就绪'), tone: memorySpaces.project?.exists === false ? 'muted' : 'ok' }),
h(Pill, { label: '云同步', value: memory?.cloudSyncEnabled === true ? '开' : '关', tone: memory?.cloudSyncEnabled === true ? 'ok' : 'muted' }),
),
memory === null ? h('p', { className: styles.hint }, '本地记忆状态路由不可用;启用「本地记忆」后此处会显示空间状态。') : null,
),
h(Card, { title: '同步统计' },
h('div', { className: styles.statRow },
h('span', { className: styles.stat }, h('span', { className: styles.statNum }, String(reporter.reportedTurns ?? 0)), h('span', { className: styles.hint }, '已上报回合')),
h('span', { className: styles.stat }, h('span', { className: styles.statNum }, String(skills.downloaded?.length ?? 0)), h('span', { className: styles.hint }, '技能下载')),
h('span', { className: styles.stat }, h('span', { className: styles.statNum }, String(skills.uploaded?.length ?? 0)), h('span', { className: styles.hint }, '技能上传')),
h('span', { className: styles.statLast }, h('span', { className: styles.statNum }, String(skills.conflicts?.length ?? 0)), h('span', { className: styles.hint }, '待处理冲突')),
),
),
)
}

View File

@ -0,0 +1,34 @@
// Adapted from dsh-mnemon memory-icon.tsx (MIT), see vendor/dsh-mnemon/LICENSE.
import * as React from 'react'
const BRAIN_ICON_PATHS = [
'M8 3.4C8 2.2 7.2 1.5 6.2 1.5C5.2 1.5 4.4 2.2 4.3 3.2C2.8 3.2 1.9 4.4 2.2 5.8C.9 6.8 1 8.8 2.4 9.6C2.1 11 3.1 12.2 4.5 12.2C4.8 14.7 8 14.9 8 12.3C8 14.9 11.2 14.7 11.5 12.2C12.9 12.2 13.9 11 13.6 9.6C15 8.8 15.1 6.8 13.8 5.8C14.1 4.4 13.2 3.2 11.7 3.2C11.6 2.2 10.8 1.5 9.8 1.5C8.8 1.5 8 2.2 8 3.4Z',
'M8 3.4v8.9',
'M4.3 3.2C4.2 4.1 4.7 4.8 5.5 5.1M11.7 3.2C11.8 4.1 11.3 4.8 10.5 5.1',
'M2.4 9.6C3.2 10 4.4 9.7 4.8 8.8M13.6 9.6C12.8 10 11.6 9.7 11.2 8.8',
'M4.5 12.2C4.4 11.2 4.9 10.5 5.7 10.2M11.5 12.2C11.6 11.2 11.1 10.5 10.3 10.2',
] as const
const h = React.createElement
export function BrainIcon({ size = 18, ...marker }: { size?: number } & Record<string, unknown>): any {
return h(
'svg',
{
...marker,
'data-dsh-panel-entry': 'dsh-brain',
'data-dsh-plugin': 'dsh-brain',
'data-dsh-part': 'sidebar-icon',
'aria-hidden': 'true',
viewBox: '0 0 16 16',
width: size,
height: size,
fill: 'none',
stroke: 'currentColor',
strokeWidth: '1',
strokeLinecap: 'round',
strokeLinejoin: 'round',
},
BRAIN_ICON_PATHS.map((path) => h('path', { key: path, d: path })),
)
}

View File

@ -0,0 +1,84 @@
// Adapted from dsh-mnemon native-sidebar.tsx (MIT), see vendor/dsh-mnemon/LICENSE.
// Registers the Brain panel on the two native shell seats:
// sidebar.panellist -> the left-rail row (glyph only)
// main -> the centre panel mounted while selected
// Both are lazy seats: when the shell does not provide them the inject callback
// simply never runs and the settings card fallback stays in place.
import * as React from 'react'
import { BrainIcon } from './brain-icon'
import { BrainPanel } from './BrainPanel'
export const PANEL_ID = 'dsh-brain'
export const PANEL_ORDER = 30
interface LayoutPanelInfo {
getSnapshot(): { activePanelId: string | null }
subscribe(listener: () => void): () => void
}
export interface BrainPanelSeatFace {
panelId: string
ctx: any
usePanelInfo?: <T>(selector: (info: { activePanelId: string | null }) => T) => T
}
function makeUsePanelInfo(ctx: any, panelId: string): (<T>(selector: (info: { activePanelId: string | null }) => T) => T) {
return function usePanelInfo<T>(selector: (info: { activePanelId: string | null }) => T): T {
const panelInfo = ctx?.layout?.panelInfo as LayoutPanelInfo | undefined
const read = (): T => selector(panelInfo === undefined ? { activePanelId: panelId } : panelInfo.getSnapshot())
const [value, setValue] = React.useState<T>(read)
React.useEffect(() => {
if (panelInfo === undefined) return
const update = (): void => setValue(read())
update()
return panelInfo.subscribe(update)
}, [panelInfo, panelId])
return value
}
}
export function registerBrainPanel(ctx: any): () => void {
let stopNative: (() => void) | undefined
let disposed = false
try {
stopNative = ctx.slots.inject('main', () =>
ctx.slots.inject('sidebar.panellist', () => {
const usePanelInfo = makeUsePanelInfo(ctx, PANEL_ID)
const panel = (props: any) => React.createElement(BrainPanel, { ...props, ctx, panelId: PANEL_ID, usePanelInfo })
const icon = (props: any) => React.createElement(BrainIcon, { size: props?.size ?? 18 })
const stopMain = ctx.slots.register({ name: 'main', key: PANEL_ID, inject: () => ({ panelId: PANEL_ID }) }, panel as never)
let stopIcon: (() => void) | undefined
try {
stopIcon = ctx.slots.register({
name: 'sidebar.panellist',
id: PANEL_ID,
order: PANEL_ORDER,
label: () => 'Brain',
locale: 'dsh-brain',
}, icon as never)
} catch (failure) {
stopMain?.()
throw failure
}
return () => {
stopIcon?.()
stopMain?.()
}
}),
)
} catch (failure) {
if (typeof console !== 'undefined') {
console.info('[dsh-brain] sidebar panel seats unavailable; the settings card fallback stays active: ' + (failure instanceof Error ? failure.message : String(failure)))
}
}
return () => {
if (disposed) return
disposed = true
try {
stopNative?.()
} catch {
/* a seat disposer must never break plugin teardown */
}
stopNative = undefined
}
}

89
src-client/panel/seat.ts Normal file
View File

@ -0,0 +1,89 @@
// Adapted from dsh-mnemon (MIT), see vendor/dsh-mnemon/LICENSE.
// Minimal external-store / held-seat primitives used by the Brain panel seats.
export class ExternalStore<T> {
protected snapshot: T
private readonly listeners = new Set<() => void>()
constructor(initial: T) {
this.snapshot = initial
}
readonly getSnapshot = (): T => this.snapshot
readonly subscribe = (listener: () => void): (() => void) => {
this.listeners.add(listener)
return () => {
this.listeners.delete(listener)
}
}
protected get listenerCount(): number {
return this.listeners.size
}
protected setSnapshot(next: T, force = false): void {
if (!force && Object.is(next, this.snapshot)) return
this.snapshot = next
this.notify()
}
protected notify(): void {
for (const listener of [...this.listeners]) listener()
}
}
export class HeldSeat<T> extends ExternalStore<T | undefined> {
private owner: symbol | undefined
constructor() {
super(undefined)
}
protected hold(value: T): () => void {
const token = Symbol('held-seat')
this.owner = token
this.setSnapshot(value)
return () => {
if (this.owner !== token) return
this.owner = undefined
this.setSnapshot(undefined)
}
}
}
export interface RafCoalescer {
schedule(): void
flush(): void
cancel(): void
readonly pending: boolean
}
export function createRafCoalescer(run: () => void): RafCoalescer {
let frameId: number | undefined
let microtaskToken: object | undefined
return {
schedule(): void {
if (typeof requestAnimationFrame === 'function') {
if (frameId !== undefined) return
frameId = requestAnimationFrame(() => { frameId = undefined; run() })
return
}
if (microtaskToken !== undefined) return
microtaskToken = {}
queueMicrotask(() => { microtaskToken = undefined; run() })
},
flush(): void {
this.cancel()
run()
},
cancel(): void {
if (frameId !== undefined && typeof cancelAnimationFrame === 'function') cancelAnimationFrame(frameId)
frameId = undefined
microtaskToken = undefined
},
get pending(): boolean {
return frameId !== undefined || microtaskToken !== undefined
},
}
}

4
src-client/types.d.ts vendored Normal file
View File

@ -0,0 +1,4 @@
declare module '*.module.css' {
const classes: Record<string, string>
export default classes
}

View File

@ -314,6 +314,13 @@ export class BrainKernel {
mcp: this.isActive('mcp'),
localMemory: this.localMemory,
departments: this.departments,
bundles: {
cloudsync: this.isActive('cloudsync'),
memory: this.isActive('memory'),
skills: this.isActive('skills'),
mcp: this.isActive('mcp'),
'settings-ui': this.isActive('settings-ui'),
},
}
}
}

View File

@ -84,6 +84,8 @@ export interface RouteDeps {
localMemory?: LocalMemoryManager
/** Department registry (P1.5), when wired in. */
departments?: DepartmentManager
/** Bundle activation states reported to the total panel. */
bundles?: Record<string, boolean>
}
/** One feature flag the card reads before it renders a control. */
@ -190,6 +192,7 @@ export function buildStatusPayload(deps: RouteDeps): Record<string, unknown> {
reporter: deps.reporter.snapshot(),
lastCheck: getLastCheck(),
capabilities: capabilities(deps),
bundles: deps.bundles ?? {},
...(deps.skills === undefined ? {} : { skills: deps.skills() }),
}
}

View File

@ -1,6 +1,57 @@
import type { UserConfig } from 'tsdown'
import { readFile } from 'node:fs/promises'
import { dirname, relative, resolve as resolvePath } from 'node:path'
import type { UserConfig, TsdownPlugin } from 'tsdown'
const PLUGIN_ID = 'dsh-brain'
const CSS_VIRTUAL_PREFIX = '\0dsh-brain-css:'
const CSS_VIRTUAL_SUFFIX = '.mjs'
function cssHash(value: string): string {
let hash = 2166136261
for (let index = 0; index < value.length; index += 1) {
hash ^= value.charCodeAt(index)
hash = Math.imul(hash, 16777619)
}
return (hash >>> 0).toString(36)
}
/** Minimal CSS-modules inliner: scope class names, inject one <style> tag. */
function brainCssPlugin(): TsdownPlugin {
return {
name: 'dsh-brain-css-modules-inline',
resolveId(source: string, importer: string | undefined) {
if (!source.endsWith('.module.css')) return null
const absolute = importer === undefined ? source : resolvePath(dirname(importer), source)
return CSS_VIRTUAL_PREFIX + absolute + CSS_VIRTUAL_SUFFIX
},
async load(virtualId: string) {
if (!virtualId.startsWith(CSS_VIRTUAL_PREFIX)) return null
const fileId = virtualId.slice(CSS_VIRTUAL_PREFIX.length, -CSS_VIRTUAL_SUFFIX.length)
this.addWatchFile(fileId)
const source = await readFile(fileId, 'utf8')
const filename = relative(process.cwd(), fileId).replaceAll('\\', '/')
const classMap: Record<string, string> = {}
for (const match of source.matchAll(/\.([A-Za-z_][A-Za-z0-9_-]*)/g)) {
const local = match[1]
if (classMap[local] === undefined) classMap[local] = 'dshbrain_' + cssHash(filename + ':' + local)
}
let css = source
for (const local of Object.keys(classMap).sort((left, right) => right.length - left.length)) {
css = css.replace(new RegExp('\\.' + local + '(?![\\w-])', 'g'), '.' + classMap[local])
}
return [
'const css = ' + JSON.stringify(css) + ';',
'const tagId = ' + JSON.stringify(filename) + ';',
'if (typeof document !== "undefined" && typeof document.querySelector === "function" && typeof document.createElement === "function") {',
' let tag = document.querySelector("style[data-plugin-css=" + JSON.stringify(tagId) + "]");',
' if (!tag) { tag = document.createElement("style"); tag.dataset.pluginCss = tagId; document.head.appendChild(tag); }',
' if (tag.textContent !== css) tag.textContent = css;',
'}',
'export default ' + JSON.stringify(classMap) + ';',
].join('\n')
},
}
}
export default {
name: PLUGIN_ID + '/client',
@ -16,7 +67,7 @@ export default {
clean: false,
deps: { neverBundle: [/^react(?:\/.*)?$/, /^react-dom(?:\/.*)?$/] },
define: { 'process.env.NODE_ENV': '"production"' },
plugins: [],
plugins: [brainCssPlugin()],
outputOptions: {
banner: `window.__ModuleLoader__.load({ id: '${PLUGIN_ID}', factory: (require) => {`,
intro: 'var module = { exports: {} }; var exports = module.exports;',

View File

@ -1,7 +1,8 @@
// U0 client-build verification: the bundled client must keep the
// __ModuleLoader__ contract, load like the legacy hand-written file, and
// register the same settings seats with the same option shapes.
import { execFileSync } from 'node:child_process'
// Client-build verification.
// U0: the bundled client keeps the __ModuleLoader__ contract, loads like the
// legacy hand-written file, and registers the same settings seats.
// U1: the Brain panel registers on both native seats (main + sidebar.panellist)
// and degrades silently when a seat is missing.
import { existsSync, readFileSync } from 'node:fs'
import { createRequire } from 'node:module'
import vm from 'node:vm'
@ -18,12 +19,13 @@ function check(name, ok, detail = '') {
const bundle = readFileSync(new URL('./client/index.js', import.meta.url), 'utf8')
check('client bundle uses the __ModuleLoader__ contract', bundle.includes('__ModuleLoader__.load'))
check('client bundle id stays dsh-brain', /id:\s*['"]dsh-brain['"]/.test(bundle))
for (const seat of ['settings.section', 'plugins.bundle.config']) {
for (const seat of ['settings.section', 'plugins.bundle.config', 'sidebar.panellist']) {
check('client bundle registers ' + seat, bundle.includes(seat))
}
for (const label of ['连接与上报', '技能管理', 'MCP 管理']) {
for (const label of ['连接与上报', '技能管理', 'MCP 管理', '概览', '部门']) {
check('client bundle keeps tab label ' + label, bundle.includes(label))
}
check('client bundle keeps the panel semantic anchor', bundle.includes('data-dsh-panel-entry') && bundle.includes('data-dsh-plugin'))
check('client bundle is a single file with only react externals', (() => {
const requires = [...bundle.matchAll(/require\(\s*['"]([^'"]+)['"]\s*\)/g)].map((match) => match[1])
return requires.every((name) => name === 'react' || name === 'react/jsx-runtime')
@ -34,9 +36,7 @@ function loadBundle(file) {
let definition = null
const sandbox = {
window: {
__ModuleLoader__: {
load(value) { definition = value },
},
__ModuleLoader__: { load(value) { definition = value } },
localStorage: { getItem: () => null, setItem: () => {} },
open: () => undefined,
},
@ -57,57 +57,74 @@ function loadBundle(file) {
})
}
function registrationShape(file) {
function exercise(file) {
const mod = loadBundle(file)
const records = []
let component = null
const registrations = []
const ctx = {
slots: {
inject(seat, callback) {
component = null
const value = callback()
records.push({ seat, value, component })
},
register(options, registeredComponent) {
component = registeredComponent
return options
inject(seat, callback) { callback() },
register(options, component) {
registrations.push({ seat: options.name, options, component })
return () => {}
},
},
effect(setup) {
const dispose = typeof setup === 'function' ? setup() : undefined
return typeof dispose === 'function' ? dispose : () => {}
},
}
mod.apply(ctx)
return { name: mod.name, inject: mod.inject, registrations }
}
function shapeOf(entry) {
return {
name: mod.name,
inject: mod.inject,
records: records.map((entry) => ({
seat: entry.seat,
name: entry.value.name,
id: entry.value.id,
key: entry.value.key,
order: entry.value.order,
label: typeof entry.value.label === 'function' ? entry.value.label() : undefined,
})),
components: records.map((entry) => entry.component),
seat: entry.seat,
name: entry.options.name,
id: entry.options.id,
key: entry.options.key,
order: entry.options.order,
label: typeof entry.options.label === 'function' ? entry.options.label() : undefined,
inject: typeof entry.options.inject === 'function' ? 'function' : undefined,
}
}
const current = registrationShape('client/index.js')
check('apply registers exactly the settings seats', current.records.length === 2)
check('settings.section keeps its id/order/label', JSON.stringify(current.records[0]) === JSON.stringify({ seat: 'settings.section', name: 'settings.section', id: 'dsh-brain', key: undefined, order: 100, label: '云端记忆' }))
check('plugins.bundle.config keeps its key', JSON.stringify(current.records[1]) === JSON.stringify({ seat: 'plugins.bundle.config', name: 'plugins.bundle.config', id: undefined, key: 'dsh-brain', order: undefined, label: undefined }))
const current = exercise('client/index.js')
const seats = current.registrations.map((entry) => entry.seat)
check('apply registers settings + panel seats', ['settings.section', 'plugins.bundle.config', 'main', 'sidebar.panellist'].every((seat) => seats.includes(seat)), JSON.stringify(seats))
const bySeat = Object.fromEntries(current.registrations.map((entry) => [entry.seat, entry]))
check('settings.section keeps its id/order/label', JSON.stringify(shapeOf(bySeat['settings.section'])) === JSON.stringify({ seat: 'settings.section', name: 'settings.section', id: 'dsh-brain', key: undefined, order: 100, label: '云端记忆', inject: undefined }))
check('plugins.bundle.config keeps its key', JSON.stringify(shapeOf(bySeat['plugins.bundle.config'])) === JSON.stringify({ seat: 'plugins.bundle.config', name: 'plugins.bundle.config', id: undefined, key: 'dsh-brain', order: undefined, label: undefined, inject: undefined }))
check('main panel uses the dsh-brain panel key', bySeat['main'] !== undefined && bySeat['main'].options.key === 'dsh-brain' && typeof bySeat['main'].options.inject === 'function')
check('sidebar panellist row uses id dsh-brain at order 30 with Brain label', bySeat['sidebar.panellist'] !== undefined && bySeat['sidebar.panellist'].options.id === 'dsh-brain' && bySeat['sidebar.panellist'].options.order === 30 && bySeat['sidebar.panellist'].options.label() === 'Brain')
check('module exports name dsh-brain', current.name === 'dsh-brain' && Array.isArray(current.inject) && current.inject.includes('slots'))
// Each registered callback must produce a renderable React element without a DOM.
let rendered = 0
for (const component of current.components) {
const element = typeof component === 'function' ? React.createElement(component) : null
for (const entry of current.registrations) {
const element = typeof entry.component === 'function' ? React.createElement(entry.component) : null
if (element !== null && typeof element === 'object' && element.type !== undefined) rendered += 1
}
check('registered components render without throwing', rendered === current.components.length)
check('registered components render without throwing', rendered === current.registrations.length)
let silentThrew = false
try {
const mod = loadBundle('client/index.js')
mod.apply({ slots: { inject() {}, register() { throw new Error('must not register') } }, effect(setup) { if (typeof setup === 'function') setup() } })
} catch { silentThrew = true }
check('missing panel seats degrade silently', !silentThrew)
let rejectThrew = false
try {
const mod = loadBundle('client/index.js')
mod.apply({ slots: { inject() { throw new Error('seat unavailable') }, register() { return () => {} } }, effect(setup) { if (typeof setup === 'function') setup() } })
} catch { rejectThrew = true }
check('rejecting panel seats degrade without throwing', !rejectThrew)
const legacyFile = new URL('./artifacts/analysis/client-legacy.js', import.meta.url)
if (existsSync(legacyFile)) {
const legacy = registrationShape(legacyFile)
check('migration preserves apply registration shape', JSON.stringify({ name: current.name, inject: current.inject, records: current.records }) === JSON.stringify({ name: legacy.name, inject: legacy.inject, records: legacy.records }), JSON.stringify({ current, legacy }))
const legacy = exercise(legacyFile)
const pickSettingsSeats = (value) => value.registrations.filter((entry) => entry.seat === 'settings.section' || entry.seat === 'plugins.bundle.config').map(shapeOf).sort((left, right) => left.seat.localeCompare(right.seat))
check('migration preserves settings registration shape', JSON.stringify(pickSettingsSeats(current)) === JSON.stringify(pickSettingsSeats(legacy)), JSON.stringify({ current: pickSettingsSeats(current), legacy: pickSettingsSeats(legacy) }))
} else {
console.log('SKIP legacy comparison (artifacts/analysis/client-legacy.js missing)')
}