167 lines
10 KiB
TypeScript
167 lines
10 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 { request, 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 { mnemonMemories, mnemonStatus, MNEMON } 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(async () => mnemonStatus(), { visible: active, pollMs: 15000 })
|
||
|
||
const memories = useApi(async () => mnemonMemories(props.scope, offset, PAGE_SIZE),
|
||
{ visible: active, pollMs: project ? 30000 : undefined, deps: [offset] })
|
||
|
||
const documents = useApi(async () => {
|
||
const result = await request(MNEMON.documents + '?' + scope.toString())
|
||
if (result.status !== 200 || result.body === null || result.body.ok !== true) throw new Error(bodyError(result, '读取 Mnemon 文档失败'))
|
||
const value = result.body.value ?? {}
|
||
return { documents: Array.isArray(value.items) ? value.items : Array.isArray(value.documents) ? value.documents : [] }
|
||
}, { visible: active && project })
|
||
|
||
const items: any[] = Array.isArray(memories.data?.items) ? memories.data!.items : []
|
||
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 ?? 0
|
||
|
||
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 未接入' : '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: '记忆条目(' + String(total) + ')', 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 ? h('p', { style: styles.hint }, total === 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: offset === 0 || memories.status === 'loading', onClick: () => setOffset(Math.max(0, offset - PAGE_SIZE)) }),
|
||
h('span', { style: styles.hint }, '第 ' + String(Math.floor(offset / PAGE_SIZE) + 1) + ' 页 · 共 ' + String(total) + ' 条'),
|
||
h(Btn, { label: '下一页', variant: 'small', disabled: offset + PAGE_SIZE >= total || memories.status === 'loading', onClick: () => setOffset(offset + PAGE_SIZE) }),
|
||
),
|
||
),
|
||
project ? h(Section, { title: '文档(只读)', hint: '项目文档由本地记忆库维护;这里只展示标题与摘要。' },
|
||
documents.error === null ? null : h(Banner, { tone: 'bad' }, documents.error),
|
||
(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,
|
||
)
|
||
}
|