168 lines
11 KiB
TypeScript
168 lines
11 KiB
TypeScript
// Memory tab: reads Mnemon (the single source of truth) through the read-only
|
||
// bridge. Global = runtime store, project = Memory Spaces. Mnemon entries have
|
||
// no id/category/session-source/revision, so those degrade to 「待核实」; write
|
||
// and delete are not exposed this round, so the delete affordance is disabled.
|
||
import * as React from 'react'
|
||
import { postJson, bodyError, messageOf } from '../api'
|
||
import { formatIso, memorySourceLabel, memoryCategoryLabel } from '../format'
|
||
import { styles } from '../styles'
|
||
import { Banner, Btn, IconBtn, Pill, Section } from '../components'
|
||
import { useApi } from './useApi'
|
||
import { mnemonDocuments, mnemonMemories, mnemonStatus } from '../mnemon'
|
||
import { scopeParams, type BrainScope } from './workspace'
|
||
|
||
const h = React.createElement
|
||
const PAGE_SIZE = 50
|
||
|
||
export function MemoryTab(props: BrainScope & { active?: boolean }): any {
|
||
const active = props.active !== false
|
||
const project = props.scope === 'project'
|
||
const scope = scopeParams(props)
|
||
const scopeLabel = project ? '项目' : '全局'
|
||
const [offset, setOffset] = React.useState(0)
|
||
const [search, setSearch] = React.useState('')
|
||
const [searchOpen, setSearchOpen] = React.useState(false)
|
||
const [notice, setNotice] = React.useState<any>(null)
|
||
const [pendingForget, setPendingForget] = React.useState<any>(null)
|
||
const [busy, setBusy] = React.useState('')
|
||
|
||
// Icon-expand search: collapsed shows only a magnifier in the section head.
|
||
// It stays expanded while a query is present so the filter is never hidden.
|
||
const searchExpanded = searchOpen || search !== ''
|
||
const searchRef = React.useRef<any>(null)
|
||
React.useEffect(() => {
|
||
const node = searchRef.current
|
||
if (searchExpanded && node !== null && typeof node.focus === 'function') node.focus()
|
||
}, [searchExpanded])
|
||
|
||
const status = useApi(() => mnemonStatus(props), { visible: active, pollMs: 15000 })
|
||
const memories = useApi(() => mnemonMemories(props), { visible: active, pollMs: project ? 30000 : undefined })
|
||
const documents = useApi(async () => project ? mnemonDocuments(props) : { documents: [] }, { visible: active && project })
|
||
|
||
// Mnemon's list can report more rows than its limited snapshot contains.
|
||
const available = memories.data?.items.length ?? 0
|
||
const lastOffset = Math.floor(Math.max(0, available - 1) / PAGE_SIZE) * PAGE_SIZE
|
||
const pageOffset = Math.min(offset, lastOffset)
|
||
React.useEffect(() => {
|
||
if (offset !== pageOffset) setOffset(pageOffset)
|
||
}, [offset, pageOffset])
|
||
const items = memories.data?.items.slice(pageOffset, pageOffset + PAGE_SIZE) ?? []
|
||
const needle = String(search).trim().toLowerCase()
|
||
const filtered = needle === '' ? items : items.filter((item) => {
|
||
const hay = [item.content, item.category, item.scope, ...(Array.isArray(item.tags) ? item.tags : [])].join(' ').toLowerCase()
|
||
return hay.indexOf(needle) >= 0
|
||
})
|
||
const total = memories.data?.total
|
||
const countLabel = total === undefined ? '—' : total > available ? '可浏览 ' + String(available) + ' 条 · Mnemon 报告 ' + String(total) + ' 条' : '共 ' + String(available) + ' 条'
|
||
|
||
const forget = async (item: any): Promise<void> => {
|
||
setBusy(item.id)
|
||
try {
|
||
const result = await postJson('/dsh-brain/local-memory/forget', { id: item.id, expectedRevision: item.revision, ...Object.fromEntries(scope) })
|
||
if (result.status !== 200 || result.body === null || result.body.ok !== true) {
|
||
setNotice({ tone: 'bad', text: bodyError(result, '删除失败') })
|
||
} else {
|
||
setNotice({ tone: 'ok', text: '已删除记忆条目。' })
|
||
setPendingForget(null)
|
||
memories.reload()
|
||
}
|
||
} catch (failure) {
|
||
setNotice({ tone: 'bad', text: messageOf(failure) })
|
||
} finally {
|
||
setBusy('')
|
||
}
|
||
}
|
||
|
||
const storageRoot = status.data?.storage?.activeRoot
|
||
const workspaceMode = status.data?.workspaceContext?.mode
|
||
|
||
return h('div', { style: { display: 'flex', flexDirection: 'column', gap: '12px' } },
|
||
status.error === null ? null : h(Banner, { tone: 'bad' }, status.error),
|
||
h(Section, { title: scopeLabel + '记忆空间', aside: h(Btn, { label: '刷新', variant: 'small', onClick: () => { status.reload(); memories.reload(); if (project) documents.reload() } }) },
|
||
h(Pill, { label: '数据源', value: status.status === 'loading' ? '读取中' : status.error !== null ? '读取失败' : 'Mnemon 已接入', tone: status.error !== null ? 'warn' : 'ok' }),
|
||
typeof storageRoot === 'string' && storageRoot !== '' ? h('p', { style: styles.hint }, String(storageRoot)) : null,
|
||
// Report the live storage mode; do not assume global vs per-workspace.
|
||
typeof workspaceMode === 'string' && workspaceMode !== '' ? h('p', { style: styles.hint }, '存储范围:' + String(workspaceMode)) : null,
|
||
),
|
||
h(Section, { title: total === undefined ? '记忆条目' : '记忆条目(' + String(available) + ')', hint: '数据来自 Mnemon(本轮只读);搜索在当前页内过滤,暂不开放删除。', aside: h('div', { style: styles.actions },
|
||
searchExpanded
|
||
? h('input', {
|
||
ref: searchRef,
|
||
style: Object.assign({}, styles.input, { width: '200px', flex: '0 1 auto' }),
|
||
type: 'text',
|
||
value: search,
|
||
placeholder: '搜索当前页',
|
||
spellCheck: false,
|
||
autoComplete: 'off',
|
||
'aria-label': '搜索当前页',
|
||
onChange: (event: any) => setSearch(event.target.value),
|
||
onKeyDown: (event: any) => { if (event.key === 'Escape' && search === '') setSearchOpen(false) },
|
||
onBlur: () => { if (search === '') setSearchOpen(false) },
|
||
})
|
||
: h(IconBtn, { glyph: '🔍', ariaLabel: '搜索当前页', onClick: () => setSearchOpen(true) }),
|
||
h(Btn, { label: '刷新', variant: 'small', onClick: () => memories.reload() }),
|
||
) },
|
||
notice === null ? null : h(Banner, { tone: notice.tone }, notice.text),
|
||
memories.error === null ? null : h(Banner, { tone: 'bad' }, memories.error),
|
||
memories.status === 'loading' && items.length === 0 ? h('p', { style: styles.hint }, '正在读取记忆…') : null,
|
||
filtered.length === 0 ? memories.data === null ? null : h('p', { style: styles.hint }, available === 0 && needle === '' ? 'Mnemon 未返回记忆条目。' : '当前页没有匹配的记忆条目。') : h('div', { style: { display: 'flex', flexDirection: 'column', gap: '8px' } },
|
||
filtered.map((item) => h('div', { key: item.id, style: styles.row },
|
||
h('div', { style: styles.rowHead },
|
||
h('div', { style: styles.pills },
|
||
// Attribution: the response carries scope (global/project). The
|
||
// project name is not in this payload, so project rows say 项目记忆
|
||
// rather than guessing a name.
|
||
h(Pill, { label: '归属', value: item.scope === 'global' ? '全局' : item.scope === 'project' ? '项目记忆' : '—', tone: 'muted' }),
|
||
// Mnemon runtime has no category field: mark 待核实, never invent one.
|
||
h(Pill, { label: '分类', value: item.category === undefined ? (item.mnemon === true ? '待核实' : '无分类') : memoryCategoryLabel(item.category), tone: 'muted' }),
|
||
h(Pill, { label: 'rev', value: item.revision ?? '—', tone: 'muted' }),
|
||
// Show the creation time when the backend provides it; otherwise
|
||
// fall back to the update time, clearly labelled, never guessed.
|
||
typeof item.createdAt === 'string' && item.createdAt !== ''
|
||
? h(Pill, { label: '创建', value: formatIso(item.createdAt), tone: 'muted' })
|
||
: h(Pill, { label: '更新', value: formatIso(item.updatedAt), tone: 'muted' }),
|
||
),
|
||
h('div', { style: styles.actions },
|
||
// Mnemon write/delete is not exposed this round: disable, don't fake.
|
||
pendingForget === item.id ? null : h(Btn, { label: '删除…', variant: 'small', disabled: item.mnemon === true, ariaLabel: item.mnemon === true ? '本轮只读,暂不支持删除 Mnemon 记忆' : undefined, onClick: () => { setPendingForget(item.id); setNotice(null) } }),
|
||
),
|
||
),
|
||
h('div', { style: styles.clamp2 }, String(item.content ?? '')),
|
||
// Readable source: a conversation renders as "11-27 18:33 的对话" when
|
||
// the creation time is verifiable; the full session id is never shown.
|
||
h('p', { style: styles.hint }, '来源:' + memorySourceLabel(item.source, item.createdAt)),
|
||
Array.isArray(item.tags) && item.tags.length > 0 ? h('p', { style: styles.hint }, '标签:' + item.tags.join('、')) : null,
|
||
pendingForget === item.id ? h('div', { style: styles.nested },
|
||
h('p', { style: styles.hint }, '确认删除这条记忆?此操作不可撤销。'),
|
||
h('div', { style: styles.actions },
|
||
h(Btn, { variant: 'danger', label: busy === item.id ? '删除中…' : '确认删除', disabled: busy !== '', onClick: () => { void forget(item) } }),
|
||
h(Btn, { variant: 'small', label: '取消', disabled: busy !== '', onClick: () => setPendingForget(null) }),
|
||
),
|
||
) : null,
|
||
)),
|
||
),
|
||
h('div', { style: styles.actions },
|
||
h(Btn, { label: '上一页', variant: 'small', disabled: pageOffset === 0, onClick: () => setOffset(pageOffset - PAGE_SIZE) }),
|
||
h('span', { style: styles.hint }, '第 ' + String(pageOffset / PAGE_SIZE + 1) + ' 页 · ' + countLabel),
|
||
h(Btn, { label: '下一页', variant: 'small', disabled: pageOffset >= lastOffset, onClick: () => setOffset(pageOffset + PAGE_SIZE) }),
|
||
),
|
||
),
|
||
project ? h(Section, { title: '文档(只读)', hint: '显示当前工作区的 Mnemon 文档标题与摘要。' },
|
||
documents.error === null ? null : h(Banner, { tone: 'bad' }, documents.error),
|
||
documents.status === 'loading' ? h('p', { style: styles.hint }, '正在读取文档…') : null,
|
||
documents.data === null ? null : documents.data.documents.length === 0 ? h('p', { style: styles.hint }, '当前项目还没有文档。') : h('div', { style: { display: 'flex', flexDirection: 'column', gap: '8px' } },
|
||
documents.data.documents.map((doc: any) => h('div', { key: doc.id, style: styles.row },
|
||
h('div', { style: styles.rowHead },
|
||
h('span', { style: styles.rowTitle }, String(doc.title ?? doc.id)),
|
||
h('div', { style: styles.pills },
|
||
h(Pill, { label: 'rev', value: doc.revision ?? '—', tone: 'muted' }),
|
||
h(Pill, { label: '更新', value: formatIso(doc.updatedAt), tone: 'muted' }),
|
||
),
|
||
),
|
||
h('div', { style: styles.clamp2 }, String(doc.content ?? '')),
|
||
)),
|
||
),
|
||
) : null,
|
||
)
|
||
}
|