// Raw records tab: search original messages and browse captured sessions. import * as React from 'react' import { request, messageOf } from '../api' import { formatBytes, formatTime } from '../format' import { Banner, Btn, Pill } from '../components' import { useApi } from './useApi' const h = React.createElement const ROLE_USER = 'user' const ROLE_ASSISTANT = 'assistant' function roleLabel(role: string): string { return role === ROLE_USER ? '你' : role === ROLE_ASSISTANT ? '助手' : role } function shortId(value: unknown): string { const text = String(value ?? '') if (text.length <= 18) return text || '—' return text.slice(0, 10) + '…' + text.slice(-5) } function when(value: unknown): string { if (typeof value === 'number' && Number.isFinite(value)) return formatTime(value) if (typeof value === 'string' && value !== '') { const parsed = Date.parse(value) return Number.isFinite(parsed) ? formatTime(parsed) : value } return '—' } function metric(label: string, value: unknown): any { return h('div', { style: s.metric }, h('div', { style: s.metricLabel }, label), h('div', { style: s.metricValue }, String(value ?? '—')), ) } const s: Record = { page: { display: 'flex', flexDirection: 'column', gap: '14px' }, hero: { display: 'flex', gap: '18px', flexWrap: 'wrap', alignItems: 'stretch', padding: '20px 22px', borderRadius: '18px', border: '1px solid rgba(127,127,127,0.22)', background: 'linear-gradient(135deg, rgba(99,102,241,0.14), rgba(139,92,246,0.06) 58%, transparent)', }, heroText: { flex: '1 1 260px', minWidth: '240px', display: 'flex', flexDirection: 'column', gap: '5px' }, kicker: { fontSize: '10.5px', letterSpacing: '.16em', fontWeight: 700, color: '#6366f1', opacity: 0.9 }, heroTitle: { margin: 0, fontSize: '22px', lineHeight: 1.2, fontWeight: 720 }, heroSub: { margin: 0, fontSize: '12px', opacity: 0.62, lineHeight: 1.6, maxWidth: '540px' }, metrics: { display: 'grid', gridTemplateColumns: 'repeat(2, minmax(84px, 1fr))', gap: '8px', flex: '0 1 280px', minWidth: '220px' }, metric: { border: '1px solid rgba(127,127,127,0.18)', borderRadius: '12px', padding: '10px 12px', background: 'rgba(127,127,127,0.07)' }, metricLabel: { fontSize: '10.5px', letterSpacing: '.08em', opacity: 0.55, fontWeight: 600 }, metricValue: { fontSize: '19px', fontWeight: 720, fontVariantNumeric: 'tabular-nums', marginTop: '2px' }, toolbar: { display: 'flex', gap: '8px', flexWrap: 'wrap', alignItems: 'center' }, searchBox: { display: 'flex', alignItems: 'center', gap: '8px', flex: '1 1 320px', minWidth: '240px', border: '1px solid rgba(127,127,127,0.28)', borderRadius: '12px', padding: '3px 10px', background: 'rgba(127,127,127,0.05)' }, searchGlyph: { fontSize: '16px', opacity: 0.5, flex: '0 0 auto' }, searchInput: { font: 'inherit', fontSize: '13px', padding: '7px 2px', border: 'none', outline: 'none', background: 'transparent', color: 'inherit', width: '100%', minWidth: 0 }, chips: { display: 'flex', gap: '4px', padding: '2px', borderRadius: '9px', border: '1px solid rgba(127,127,127,0.18)' }, chip: { font: 'inherit', fontSize: '11.5px', padding: '5px 9px', borderRadius: '7px', border: '1px solid transparent', background: 'transparent', color: 'inherit', cursor: 'pointer' }, chipActive: { border: '1px solid rgba(99,102,241,0.45)', background: 'rgba(99,102,241,0.14)', fontWeight: 600 }, layout: { display: 'grid', gridTemplateColumns: 'minmax(240px, .78fr) minmax(0, 1.55fr)', gap: '12px', alignItems: 'start' }, card: { border: '1px solid rgba(127,127,127,0.22)', borderRadius: '16px', padding: '16px', minWidth: 0, display: 'flex', flexDirection: 'column', gap: '10px' }, cardHead: { display: 'flex', alignItems: 'baseline', justifyContent: 'space-between', gap: '8px', flexWrap: 'wrap' }, cardTitle: { margin: 0, fontSize: '13.5px', fontWeight: 650 }, hint: { margin: 0, fontSize: '11.5px', opacity: 0.58, lineHeight: 1.55 }, sessionList: { display: 'flex', flexDirection: 'column', gap: '6px', maxHeight: '620px', overflow: 'auto' }, session: { display: 'flex', flexDirection: 'column', gap: '5px', padding: '10px 11px', borderRadius: '11px', border: '1px solid rgba(127,127,127,0.14)', cursor: 'pointer', background: 'transparent' }, sessionActive: { border: '1px solid rgba(99,102,241,0.55)', background: 'rgba(99,102,241,0.10)' }, sessionTitle: { fontWeight: 600, fontSize: '12.5px', overflowWrap: 'anywhere' }, sessionMeta: { display: 'flex', gap: '8px', flexWrap: 'wrap', alignItems: 'baseline', fontSize: '11px', opacity: 0.6 }, sessionSnippet: { fontSize: '11.5px', opacity: 0.72, overflow: 'hidden', display: '-webkit-box', WebkitLineClamp: 2, WebkitBoxOrient: 'vertical', lineHeight: 1.45 }, main: { display: 'flex', flexDirection: 'column', gap: '10px', minWidth: 0 }, resultList: { display: 'flex', flexDirection: 'column', gap: '6px' }, result: { display: 'flex', flexDirection: 'column', gap: '5px', padding: '10px 12px', borderRadius: '11px', border: '1px solid rgba(127,127,127,0.14)', cursor: 'pointer' }, resultHead: { display: 'flex', gap: '8px', flexWrap: 'wrap', alignItems: 'baseline' }, resultSnippet: { fontSize: '12px', lineHeight: 1.55, whiteSpace: 'pre-wrap', overflowWrap: 'anywhere' }, messageList: { display: 'flex', flexDirection: 'column', gap: '9px' }, message: { display: 'flex', flexDirection: 'column', gap: '5px', padding: '10px 12px', borderRadius: '11px', border: '1px solid rgba(127,127,127,0.12)', borderLeft: '3px solid rgba(99,102,241,0.65)', background: 'rgba(127,127,127,0.035)' }, messageAssistant: { borderLeft: '3px solid rgba(16,185,129,0.7)' }, msgHead: { display: 'flex', gap: '9px', flexWrap: 'wrap', alignItems: 'baseline' }, role: { fontSize: '11px', fontWeight: 700, padding: '1px 7px', borderRadius: '999px', background: 'rgba(99,102,241,0.14)', color: 'inherit' }, roleAssistant: { background: 'rgba(16,185,129,0.14)' }, msgMeta: { fontSize: '10.5px', opacity: 0.52 }, msgText: { fontSize: '12.5px', lineHeight: 1.65, whiteSpace: 'pre-wrap', overflowWrap: 'anywhere' }, empty: { border: '1px dashed rgba(127,127,127,0.3)', borderRadius: '14px', padding: '26px 20px', textAlign: 'center', color: 'inherit', opacity: 0.72, fontSize: '12.5px' }, selectedBar: { display: 'flex', alignItems: 'baseline', gap: '8px', flexWrap: 'wrap' }, } export function RawTab(props: { active?: boolean }): any { const active = props.active !== false const [query, setQuery] = React.useState('') const [role, setRole] = React.useState('') const [searchResult, setSearchResult] = React.useState(null) const [searchError, setSearchError] = React.useState(null) const [searching, setSearching] = React.useState(false) const [selected, setSelected] = React.useState(null) const [detail, setDetail] = React.useState(null) const [detailError, setDetailError] = React.useState(null) const [detailLoading, setDetailLoading] = React.useState(false) const status = useApi(async () => { const result = await request('/dsh-brain/raw/status') if (result.status === 404) throw new Error('原始记录接口还没加载:请完全退出并重启 DSH。') if (result.status !== 200 || result.body === null || result.body.ok !== true) throw new Error('读取原始记录状态失败(HTTP ' + String(result.status) + ')') return result.body }, { visible: active, pollMs: 15000 }) const sessions = useApi(async () => { const result = await request('/dsh-brain/raw/sessions?limit=30') if (result.status === 404) throw new Error('原始记录接口还没加载:请完全退出并重启 DSH。') if (result.status !== 200 || result.body === null || result.body.ok !== true) throw new Error('读取原始会话失败(HTTP ' + String(result.status) + ')') return result.body }, { visible: active }) const runSearch = async (): Promise => { const value = query.trim() if (value === '') { setSearchResult(null); setSearchError('先输入要搜索的关键词。'); return } setSearching(true) setSearchError(null) try { const params = new URLSearchParams({ q: value, k: '30' }) if (role !== '') params.set('role', role) const result = await request('/dsh-brain/raw/search?' + params.toString()) if (result.status !== 200 || result.body === null || result.body.ok !== true) throw new Error('搜索原始记录失败(HTTP ' + String(result.status) + ')') setSearchResult(result.body) } catch (failure) { setSearchError(messageOf(failure)) } finally { setSearching(false) } } const openSession = async (sessionId: string, seq?: number): Promise => { setSelected({ sessionId, ...(seq === undefined ? {} : { seq }) }) setDetail(null) setDetailError(null) setDetailLoading(true) try { const params = new URLSearchParams({ session_id: sessionId, limit: '100' }) if (seq !== undefined) params.set('seq', String(seq)) const result = await request('/dsh-brain/raw/session?' + params.toString()) if (result.status !== 200 || result.body === null || result.body.ok !== true) throw new Error('读取会话失败(HTTP ' + String(result.status) + ')') setDetail(result.body) } catch (failure) { setDetailError(messageOf(failure)) } finally { setDetailLoading(false) } } const sessionRows: any[] = Array.isArray(sessions.data?.sessions) ? sessions.data.sessions : [] const matches: any[] = Array.isArray(searchResult?.matches) ? searchResult.matches : [] const detailItems: any[] = Array.isArray(detail?.items) ? detail.items : [] const disabled = status.data?.enabled === false return h('div', { style: s.page }, status.error === null ? null : h(Banner, { tone: 'bad' }, status.error), disabled ? h(Banner, { tone: 'warn' }, '原始记录层当前已停用:在「设置 → 插件」中启用 dsh-brain-raw 子插件后重启 DSH。') : null, h('div', { style: s.hero }, h('div', { style: s.heroText }, h('div', { style: s.kicker }, 'RAW MEMORY · 原话档案'), h('h3', { style: s.heroTitle }, '原始记录'), h('p', { style: s.heroSub }, '这里不筛摘要、不改写,只按会话保存真实对话。记忆条目说不清时,回到原话里核对。'), ), h('div', { style: s.metrics }, metric('记录', status.status === 'loading' ? '…' : status.data?.records ?? 0), metric('会话', status.status === 'loading' ? '…' : status.data?.sessions ?? 0), metric('占用', status.status === 'loading' ? '…' : formatBytes(status.data?.bytes ?? 0)), metric('保留', status.status === 'loading' ? '…' : String(status.data?.retentionDays ?? '—') + ' 天'), ), ), status.data?.dir === undefined ? null : h('p', { style: s.hint }, '保存目录:' + String(status.data.dir)), h('div', { style: s.toolbar }, h('div', { style: s.searchBox }, h('span', { style: s.searchGlyph }, '⌕'), h('input', { style: s.searchInput, type: 'text', value: query, placeholder: '搜索原话,例如:预算、接口、苹果…', spellCheck: false, onChange: (event: any) => setQuery(event.target.value), onKeyDown: (event: any) => { if (event.key === 'Enter') void runSearch() }, }), ), h('div', { style: s.chips, role: 'tablist', 'aria-label': '原始记录角色筛选' }, [['', '全部'], ['user', '你'], ['assistant', '助手']].map((item) => h('button', { key: item[0], type: 'button', role: 'tab', 'aria-selected': role === item[0], style: role === item[0] ? Object.assign({}, s.chip, s.chipActive) : s.chip, onClick: () => setRole(item[0]), }, item[1])), ), h(Btn, { label: searching ? '搜索中…' : '搜索', variant: 'primary', disabled: searching, onClick: () => { void runSearch() } }), searchResult === null ? null : h(Btn, { label: '清空结果', variant: 'small', onClick: () => { setSearchResult(null); setSearchError(null) } }), ), searchError === null ? null : h(Banner, { tone: 'bad' }, searchError), searchResult === null ? null : h('div', { style: s.card }, h('div', { style: s.cardHead }, h('h4', { style: s.cardTitle }, '搜索结果(' + String(searchResult.total ?? matches.length) + ')'), h('span', { style: s.hint }, searchResult.truncated === true ? '结果过多,已截断' : '点击结果查看原话'), ), matches.length === 0 ? h('div', { style: s.empty }, '没有找到匹配的原话。') : h('div', { style: s.resultList }, matches.map((item: any, index: number) => h('div', { key: String(item.sessionId) + ':' + String(item.seq ?? index) + ':' + String(index), style: s.result, onClick: () => { void openSession(String(item.sessionId), typeof item.seq === 'number' ? item.seq : undefined) }, }, h('div', { style: s.resultHead }, h(Pill, { label: '角色', value: roleLabel(String(item.role)), tone: 'muted' }), h(Pill, { label: '会话', value: shortId(item.sessionId), tone: 'muted' }), item.seq === undefined ? null : h(Pill, { label: 'seq', value: item.seq, tone: 'muted' }), h('span', { style: s.msgMeta }, when(item.time ?? item.createdAt)), ), h('div', { style: s.resultSnippet }, String(item.snippet ?? '')), )), ), ), h('div', { style: s.layout }, h('div', { style: s.card }, h('div', { style: s.cardHead }, h('h4', { style: s.cardTitle }, '最近会话'), h(Btn, { label: '刷新', variant: 'small', onClick: () => { status.reload(); sessions.reload() } }), ), sessions.error === null ? null : h(Banner, { tone: 'bad' }, sessions.error), sessionRows.length === 0 ? h('div', { style: s.empty }, '还没有原始记录。重启 DSH 后,新的对话会开始采集。') : h('div', { style: s.sessionList }, sessionRows.map((item: any) => h('div', { key: String(item.sessionId), style: selected?.sessionId === item.sessionId ? Object.assign({}, s.session, s.sessionActive) : s.session, onClick: () => { void openSession(String(item.sessionId)) }, }, h('div', { style: s.sessionTitle }, shortId(item.sessionId)), h('div', { style: s.sessionMeta }, h('span', null, String(item.records ?? 0) + ' 条'), h('span', null, when(item.lastAt)), h('span', null, formatBytes(item.bytes ?? 0)), ), item.latestSnippet === undefined ? null : h('div', { style: s.sessionSnippet }, String(item.latestSnippet)), )), ), ), h('div', { style: s.card }, selected === null ? h('div', { style: s.empty }, '从左侧选择一个会话,或在上方搜索原话。') : h('div', { style: s.main }, h('div', { style: s.cardHead }, h('h4', { style: s.cardTitle }, '会话 ' + shortId(selected.sessionId)), h('div', { style: s.chips }, h(Pill, { label: '总记录', value: detailLoading ? '…' : detail?.total ?? '—', tone: 'muted' }), selected.seq === undefined ? null : h(Pill, { label: 'seq', value: selected.seq, tone: 'muted' }), h(Btn, { label: '查看整个会话', variant: 'small', onClick: () => { void openSession(String(selected.sessionId)) } }), ), ), detailError === null ? null : h(Banner, { tone: 'bad' }, detailError), detailLoading ? h('p', { style: s.hint }, '正在读取原话…') : null, !detailLoading && detailError === null && detailItems.length === 0 ? h('div', { style: s.empty }, '这个会话还没有原始记录。') : null, detailItems.length === 0 ? null : h('div', { style: s.messageList }, detailItems.map((item: any, index: number) => h('div', { key: String(item.messageId ?? item.seq ?? index), style: item.role === ROLE_ASSISTANT ? Object.assign({}, s.message, s.messageAssistant) : s.message, }, h('div', { style: s.msgHead }, h('span', { style: item.role === ROLE_ASSISTANT ? Object.assign({}, s.role, s.roleAssistant) : s.role }, roleLabel(String(item.role))), item.seq === undefined ? null : h('span', { style: s.msgMeta }, 'seq ' + String(item.seq)), item.turn === undefined ? null : h('span', { style: s.msgMeta }, 'turn ' + String(item.turn)), h('span', { style: s.msgMeta }, when(item.time ?? item.createdAt)), ), h('div', { style: s.msgText }, String(item.text ?? '')), )), ), ), ), ), ) }