348 lines
18 KiB
TypeScript
348 lines
18 KiB
TypeScript
// Overview tab — v3 design (artifacts/preview-overview-v3.html):
|
||
// totals + category mix, 7-day trend, processing checks, last recall, and a
|
||
// collapsed diagnostics area. Memory numbers come from Mnemon (the single
|
||
// source of truth) via the read-only bridge; anything Mnemon cannot verify
|
||
// (category mix, last recall) renders as 「待核实」 instead of a guessed value.
|
||
import * as React from 'react'
|
||
import { API, request, messageOf } from '../api'
|
||
import { formatTime, formatIso, formatBytes, memoryCategoryLabel } from '../format'
|
||
import { Btn } from '../components'
|
||
import { mnemonRuntimeAll, mnemonStatus } from '../mnemon'
|
||
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',
|
||
raw: '原话记录',
|
||
}
|
||
|
||
const pad2 = (n: number): string => (n < 10 ? '0' + String(n) : String(n))
|
||
const dayKeyOf = (d: Date): string => String(d.getFullYear()) + '-' + pad2(d.getMonth() + 1) + '-' + pad2(d.getDate())
|
||
|
||
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)),
|
||
)
|
||
}
|
||
|
||
interface TrendDay { key: string; label: string; full: string; count: number }
|
||
interface CheckRow { tone: 'ok' | 'warn' | 'muted'; name: string; meta: string }
|
||
|
||
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 [raw, setRaw] = React.useState<any>(null)
|
||
const [list, setList] = React.useState<any>(null)
|
||
const [error, setError] = React.useState<string | null>(null)
|
||
const [rawError, setRawError] = React.useState<string | null>(null)
|
||
const [listError, setListError] = React.useState<string | null>(null)
|
||
const [loadedAt, setLoadedAt] = React.useState<number | null>(null)
|
||
const [tick, setTick] = React.useState(0)
|
||
|
||
React.useEffect(() => {
|
||
if (!active) return
|
||
let cancelled = false
|
||
const load = async (): Promise<void> => {
|
||
// Each endpoint settles on its own: a failing auxiliary endpoint must not
|
||
// discard the primary status payload or blank the whole overview. A
|
||
// failed fetch keeps the last successful snapshot; loadedAt marks it.
|
||
const [statusSettled, capabilitiesSettled, memorySettled, rawSettled, listSettled] = await Promise.allSettled([
|
||
request(API.status),
|
||
request(API.capabilities),
|
||
mnemonStatus(),
|
||
request('/dsh-brain/raw/status'),
|
||
mnemonRuntimeAll(),
|
||
])
|
||
if (cancelled) return
|
||
let anyOk = false
|
||
if (statusSettled.status === 'fulfilled') {
|
||
const result = statusSettled.value
|
||
if (result.status === 200 && result.body !== null && result.body.ok === true) {
|
||
setStatus(result.body)
|
||
setError(null)
|
||
anyOk = true
|
||
} else {
|
||
setError('读取插件状态失败(HTTP ' + String(result.status) + ')')
|
||
}
|
||
} else {
|
||
setError(messageOf(statusSettled.reason))
|
||
}
|
||
if (capabilitiesSettled.status === 'fulfilled') {
|
||
const result = capabilitiesSettled.value
|
||
if (result.status === 200 && result.body !== null && result.body.ok === true) { setCapabilities(result.body); anyOk = true }
|
||
}
|
||
if (memorySettled.status === 'fulfilled') {
|
||
setMemory(memorySettled.value); anyOk = true
|
||
}
|
||
if (rawSettled.status === 'fulfilled') {
|
||
const result = rawSettled.value
|
||
if (result.status === 200 && result.body !== null && result.body.ok === true) { setRaw(result.body); setRawError(null); anyOk = true }
|
||
else setRawError('HTTP ' + String(result.status))
|
||
} else {
|
||
setRawError(messageOf(rawSettled.reason))
|
||
}
|
||
if (listSettled.status === 'fulfilled') {
|
||
setList(listSettled.value)
|
||
setListError(null)
|
||
anyOk = true
|
||
} else {
|
||
setListError(messageOf(listSettled.reason))
|
||
}
|
||
if (anyOk) setLoadedAt(Date.now())
|
||
}
|
||
void load()
|
||
const timer = setInterval(() => { void load() }, 15000)
|
||
return () => {
|
||
cancelled = true
|
||
clearInterval(timer)
|
||
}
|
||
}, [active, tick])
|
||
|
||
const refresh = (): void => { setTick((value) => value + 1) }
|
||
|
||
const settings = status?.settings ?? {}
|
||
const reporter = status?.reporter ?? {}
|
||
const skills = status?.skills
|
||
const bundles: Record<string, boolean> = status?.bundles ?? {}
|
||
const bundleKeys = Object.keys(bundles).length === 0 ? ['cloudsync', 'memory', 'skills', 'mcp', 'settings-ui'] : Object.keys(bundles)
|
||
const version = capabilities?.version ?? status?.capabilities?.version ?? '—'
|
||
|
||
// ---- totals / mix / trend, from Mnemon runtime --------------------------
|
||
const items: any[] = Array.isArray(list?.items) ? list.items : []
|
||
const total: number | null = list !== null && typeof list.total === 'number' ? list.total : null
|
||
const fullCoverage = list !== null && total !== null && items.length === total
|
||
// Mnemon runtime carries created_at, so the trend is real. It has no category
|
||
// field, so the mix stays 「待核实」 (categoriesAvailable false) — never invented.
|
||
const hasCreated = items.length > 0 && items.every((item) => typeof item.createdAt === 'string' && item.createdAt !== '')
|
||
const categoriesAvailable = list?.categoriesAvailable === true
|
||
|
||
let mix: { label: string; count: number }[] | null = null
|
||
if (fullCoverage && categoriesAvailable) {
|
||
const counts: Record<string, number> = {}
|
||
for (const item of items) {
|
||
const label = memoryCategoryLabel(item.category)
|
||
counts[label] = (counts[label] ?? 0) + 1
|
||
}
|
||
mix = Object.keys(counts).map((label) => ({ label, count: counts[label] })).sort((a, b) => b.count - a.count)
|
||
}
|
||
|
||
let trend: TrendDay[] | null = null
|
||
let todayAdded: number | null = null
|
||
let latestCreated: number | null = null
|
||
if (fullCoverage && (hasCreated || total === 0)) {
|
||
const counts: Record<string, number> = {}
|
||
let latest = 0
|
||
for (const item of items) {
|
||
const stamp = Date.parse(item.createdAt)
|
||
if (!Number.isFinite(stamp)) continue
|
||
if (stamp > latest) latest = stamp
|
||
const key = dayKeyOf(new Date(stamp))
|
||
counts[key] = (counts[key] ?? 0) + 1
|
||
}
|
||
latestCreated = latest > 0 ? latest : null
|
||
const now = new Date()
|
||
trend = []
|
||
for (let i = 6; i >= 0; i -= 1) {
|
||
const day = new Date(now.getFullYear(), now.getMonth(), now.getDate() - i)
|
||
const key = dayKeyOf(day)
|
||
trend.push({
|
||
key,
|
||
label: i === 6 ? pad2(day.getMonth() + 1) + '/' + pad2(day.getDate()) : pad2(day.getDate()),
|
||
full: String(day.getMonth() + 1) + ' 月 ' + String(day.getDate()) + ' 日',
|
||
count: counts[key] ?? 0,
|
||
})
|
||
}
|
||
todayAdded = trend[6].count
|
||
}
|
||
|
||
// ---- processing checks -------------------------------------------------
|
||
const rows: CheckRow[] = []
|
||
if (rawError !== null) {
|
||
rows.push({ tone: 'warn', name: '读取原话档案失败', meta: '可点右上「刷新」重试;详情见「原始记录」页签。' })
|
||
} else if (raw === null) {
|
||
rows.push({ tone: 'muted', name: '原话归档待核实', meta: '宿主未返回原话档案状态。' })
|
||
} else if (raw.enabled === false) {
|
||
rows.push({ tone: 'muted', name: '原话采集已关闭', meta: '在设置中开启后,对话原话会自动归档。' })
|
||
} else if ((raw.records ?? 0) === 0) {
|
||
rows.push({ tone: 'muted', name: '还没有原话记录', meta: '开启采集后,新的对话会自动归档到这里。' })
|
||
} else {
|
||
rows.push({ tone: 'ok', name: '原话已归档', meta: String(raw.sessions ?? 0) + ' 个会话 · ' + String(raw.records ?? 0) + ' 条记录 · 最近 ' + formatIso(raw.newestAt) })
|
||
}
|
||
if (status === null) {
|
||
rows.push({ tone: 'muted', name: '自动摘要待核实', meta: '宿主未返回设置,无法确认摘要开关。' })
|
||
} else if (settings.autoSummaryEnabled === false) {
|
||
rows.push({ tone: 'muted', name: '自动摘要已关闭', meta: '在设置中开启后,会自动提炼对话要点。' })
|
||
} else {
|
||
rows.push({ tone: 'muted', name: '摘要处理进度待核实', meta: '累计会话与轮数需检查点统计,接口补齐后显示。' })
|
||
}
|
||
const lastChecks: any[] = Array.isArray(status?.lastCheck?.checks) ? status.lastCheck.checks : []
|
||
const lastFailed = lastChecks.filter((check) => check.state !== 'ok' && check.state !== 'unconfigured').length
|
||
if (error !== null) {
|
||
rows.push({ tone: 'warn', name: '实时状态待核实', meta: '当前宿主未返回 Brain 状态。在目标宿主打开 Brain 后刷新,查看采集与召回状态。' })
|
||
} else if (status?.lastCheck === null || status?.lastCheck === undefined) {
|
||
rows.push({ tone: 'muted', name: '尚未检查', meta: '在「连接与上报」设置里运行一次连接检查,结果会显示在这里。' })
|
||
} else if (lastFailed === 0) {
|
||
rows.push({ tone: 'ok', name: '暂无已知异常', meta: '最近检查 ' + formatTime(status.lastCheck.at) + (lastChecks.length === 0 ? '' : ' · 全部通过') })
|
||
} else {
|
||
rows.push({ tone: 'warn', name: String(lastFailed) + ' 项检查异常', meta: '最近检查 ' + formatTime(status.lastCheck.at) + ' · 详情见「连接与上报」设置。' })
|
||
}
|
||
|
||
// ---- diagnostics -------------------------------------------------------
|
||
const tokenText = status === null ? '暂不可读取' : (() => {
|
||
const entries: [string, any][] = [['上报', status.tokens?.activity], ['记忆', status.tokens?.memory], ['摘要', status.tokens?.summary]]
|
||
if (entries.every(([, token]) => token?.configured === true)) return '上报、记忆、摘要均已配置'
|
||
return entries.map(([name, token]) => name + (token?.configured === true ? '已配置' : '未配置')).join(' · ')
|
||
})()
|
||
const rawDetail = rawError !== null ? '暂不可读取'
|
||
: raw === null ? '待核实'
|
||
: raw.enabled === false ? '采集已关闭'
|
||
: formatBytes(raw.bytes) + ' · ' + formatIso(raw.oldestAt) + ' 至 ' + formatIso(raw.newestAt)
|
||
const skillReceipt = skills === undefined || skills === null ? '暂无回执'
|
||
: '下发 ' + String(skills.downloaded?.length ?? 0) + ' 条 · 上传 ' + String(skills.uploaded?.length ?? 0) + ' 条'
|
||
+ ((skills.conflicts?.length ?? 0) > 0 ? ' · 待处理冲突 ' + String(skills.conflicts.length) + ' 条' : '')
|
||
const localMemoryText = memory === null ? 'Mnemon 未接入'
|
||
: (typeof memory.storage?.activeRoot === 'string' ? String(memory.storage.activeRoot) : '已接入')
|
||
+ (typeof memory.workspaceContext?.mode === 'string' ? ' · 存储范围 ' + String(memory.workspaceContext.mode) : '')
|
||
|
||
const diag: [string, any][] = [
|
||
['插件版本', version],
|
||
['原话档案', rawDetail],
|
||
['服务地址', status === null ? '暂不可读取' : settings.baseUrlConfigured === false ? '未配置' : (settings.baseUrlOrigin || '已配置')],
|
||
['磁盘令牌配置', tokenText],
|
||
['服务默认召回条数', status === null ? '暂不可读取' : String(settings.defaultK ?? '—')],
|
||
['本地记忆召回条数', status === null ? '暂不可读取' : String(settings.localMemoryK ?? '未配置')],
|
||
['技能同步回执', skillReceipt],
|
||
['已上报回合', status === null ? '待核实' : String(reporter.recorded ?? 0)],
|
||
['Mnemon 存储', localMemoryText],
|
||
['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' })),
|
||
)],
|
||
]
|
||
|
||
const trendMax = trend === null ? 1 : Math.max(1, ...trend.map((day) => day.count))
|
||
|
||
return h('div', { className: styles.overviewGrid },
|
||
h('div', { className: styles.ovHeader },
|
||
h('h4', { className: styles.ovTitle }, '记忆概览'),
|
||
h('div', { className: styles.ovHeadRight },
|
||
loadedAt === null ? null : h('p', { className: styles.hint }, '本机数据快照 ' + formatTime(loadedAt)),
|
||
h(Btn, { label: '刷新', variant: 'small', onClick: refresh }),
|
||
),
|
||
),
|
||
error === null ? null : h('div', { className: styles.error }, error),
|
||
|
||
h('section', { className: styles.card + ' ' + styles.ovSummary, 'aria-labelledby': 'ov-total-title' },
|
||
h('div', { className: styles.ovTotal },
|
||
h('h4', { id: 'ov-total-title', className: styles.ovCardTitle }, '全局记忆'),
|
||
list !== null
|
||
? h('p', { className: styles.ovBig }, String(total ?? '—'), h('small', {}, '条'))
|
||
: h('p', { className: styles.ovBig }, '—'),
|
||
list === null && listError !== null
|
||
? h('div', { className: styles.ovMetaBlock },
|
||
h('p', { className: styles.hint }, '全局记忆暂不可读(' + listError + ')'),
|
||
h(Btn, { label: '重试', variant: 'small', onClick: refresh }),
|
||
)
|
||
: total === 0
|
||
? h('p', { className: styles.ovMeta }, 'Mnemon 里还没有记忆条目。')
|
||
: h('p', { className: styles.ovMeta },
|
||
todayAdded === null ? '今日新增待核实' : h('strong', {}, '今日新增 ' + String(todayAdded) + ' 条'),
|
||
latestCreated === null ? '' : ' · 最近一条 ' + formatTime(latestCreated).slice(6, 11),
|
||
),
|
||
),
|
||
h('div', { className: styles.ovMix },
|
||
h('h4', { className: styles.ovCardTitle }, '记忆分类'),
|
||
mix === null
|
||
? h('p', { className: styles.hint }, list === null ? '分类统计暂不可读。' : !categoriesAvailable ? '分类待核实:Mnemon 记忆没有分类字段。' : '分类统计待核实。')
|
||
: mix.length === 0
|
||
? h('p', { className: styles.hint }, '暂无分类可显示。')
|
||
: h('div', { className: styles.ovMixBody },
|
||
h('div', { className: styles.mixBar, 'aria-hidden': 'true' },
|
||
mix.map((entry, index) => h('span', { key: entry.label, className: index === 0 ? styles.mixA : index === 1 ? styles.mixB : styles.mixC, style: { flex: String(entry.count) } })),
|
||
),
|
||
h('ul', { className: styles.mixKeys },
|
||
mix.map((entry, index) => h('li', { key: entry.label },
|
||
h('span', { 'aria-hidden': 'true', className: index === 0 ? styles.mixA : index === 1 ? styles.mixB : styles.mixC }),
|
||
entry.label + ' ' + String(entry.count) + ' 条',
|
||
)),
|
||
),
|
||
),
|
||
),
|
||
),
|
||
|
||
h('div', { className: styles.ovGrid },
|
||
h('section', { className: styles.card + ' ' + styles.ovTrend, 'aria-labelledby': 'ov-trend-title' },
|
||
h('h4', { id: 'ov-trend-title', className: styles.ovCardTitle }, '最近 7 天新增'),
|
||
trend === null
|
||
? h('div', { className: styles.ovPlaceholder },
|
||
h('p', { className: styles.ovPlaceholderTitle }, '待核实'),
|
||
h('p', { className: styles.hint }, listError !== null ? '暂时无法统计新增记忆。' : 'Mnemon 记忆带创建时间后,这里显示每日新增。'),
|
||
)
|
||
: h('figure', { className: styles.ovChart },
|
||
h('ul', { className: styles.plot, 'aria-label': '每日新增的全局记忆条数' },
|
||
trend.map((day) => h('li', {
|
||
key: day.key,
|
||
className: day.count === 0 ? styles.plotZero : '',
|
||
style: { '--height': (day.count === 0 ? 0 : Math.max(3, (day.count / trendMax) * 100)) + '%' },
|
||
},
|
||
h('span', { className: styles.srOnly }, day.full + ',' + String(day.count) + ' 条'),
|
||
h('span', { className: styles.plotSlot, 'aria-hidden': 'true' },
|
||
day.count === 0 ? null : h('span', { className: styles.plotBar }),
|
||
h('span', { className: styles.plotAmount }, String(day.count)),
|
||
),
|
||
h('time', { className: styles.plotDay, 'aria-hidden': 'true', dateTime: day.key }, day.label),
|
||
)),
|
||
),
|
||
h('figcaption', { className: styles.hint }, total === 0 ? '近 7 天没有新增。' : '按现存记忆的创建日期统计,今天截至快照时间。'),
|
||
),
|
||
),
|
||
|
||
h('section', { className: styles.card + ' ' + styles.ovChecks, 'aria-labelledby': 'ov-checks-title' },
|
||
h('h4', { id: 'ov-checks-title', className: styles.ovCardTitle }, '记录与处理'),
|
||
h('ul', { className: styles.rows },
|
||
rows.map((row) => h('li', { key: row.name, className: row.tone === 'warn' ? styles.rowAttention : '' },
|
||
h('span', { className: styles.dot + (row.tone === 'warn' ? ' ' + styles.dotWarn : row.tone === 'muted' ? ' ' + styles.dotMuted : ''), 'aria-hidden': 'true' }),
|
||
h('div', {},
|
||
h('p', { className: styles.rowName + (row.tone === 'warn' ? ' ' + styles.rowNameWarn : '') }, row.name),
|
||
h('p', { className: styles.hint }, row.meta),
|
||
),
|
||
)),
|
||
),
|
||
),
|
||
),
|
||
|
||
h('section', { className: styles.card + ' ' + styles.ovRecall, 'aria-labelledby': 'ov-recall-title' },
|
||
h('div', { className: styles.ovRecallHead },
|
||
h('h4', { id: 'ov-recall-title', className: styles.ovCardTitle }, '最近一次召回'),
|
||
h('p', { className: styles.ovRecallState }, '待核实'),
|
||
),
|
||
h('dl', { className: styles.recallMetrics },
|
||
['命中条数', '高', '中', '未知分档', '召回时间'].map((label) => h('div', { key: label },
|
||
h('dt', {}, label),
|
||
h('dd', { className: styles.recallMissing }, h('span', { 'aria-hidden': 'true' }, '—'), h('span', { className: styles.srOnly }, '待核实')),
|
||
)),
|
||
),
|
||
h('p', { className: styles.hint }, '当前未能取得 Mnemon 的最近一次召回结果。'),
|
||
),
|
||
|
||
h('details', { className: styles.card + ' ' + styles.ovDiag },
|
||
h('summary', { className: styles.ovDiagSummary }, '诊断详情'),
|
||
h('dl', { className: styles.diagGrid },
|
||
diag.map(([term, value]) => [
|
||
h('dt', { key: term + '-t' }, term),
|
||
h('dd', { key: term + '-d' }, value),
|
||
]),
|
||
),
|
||
),
|
||
)
|
||
}
|