import { useEffect, useMemo, useRef, useState } from 'react'
import type { DragEvent, KeyboardEvent as ReactKeyboardEvent } from 'react'
import { Link, useNavigate, useParams } from 'react-router-dom'
import {
BookOpen, Brain, Check, ClipboardType, FileCode, FileText, Globe, Pencil, Plus, Presentation, Search, Sparkles, Upload,
X,
} from 'lucide-react'
import clsx from 'clsx'
import { api, ApiError } from '../api/client'
import type { KbHit, KbSearchResult, ReindexJob, UploadProgress } from '../api/client'
import { useCatalog, useOnReconnect } from '../store/catalog'
import {
confirmDialog, deferDelete, DeleteButton, EmptyState, ErrorState, Field, IconButton, isComposing, Modal,
PageHeader, promptDialog, SectionBar, Skeleton, Spinner, StatusBadge, TabPanel, Tabs, toast, useRadioGroup,
useTabRoute, useTicker, withoutDeferred,
} from '../components/ui'
import { humanizeError } from '../lib/errors'
import {
formatBytes, formatDateTime, formatDuration, formatNumber, formatRelative, formatTime, NONE, parseServerTime, shortId,
} from '../lib/format'
import { matchShortcut } from '../lib/keys'
import { runName } from '../lib/terms'
import { useRunClock } from '../run/useRunClock'
import type { KbDocument, MemoryItem, MemorySource, Skill } from '../types'
import { UploadMeter } from './DataSourcesTab'
// 提到模块级:tab 名同时是 URL 的最后一段,两处各写一份迟早对不上
const TABS = [
{ key: 'kb', label: '知识库' },
{ key: 'memory', label: '长期记忆' },
{ key: 'skills', label: '方法论 Skill' },
]
export function KnowledgePage() {
const [tab, setTab] = useTabRoute(TABS.map((t) => t.key), 'kb')
return (
}
title="知识"
subtitle="Agent 运行时可读取的内容:知识库、长期记忆和方法论 Skill"
/>
{tab === 'kb' && }
{tab === 'memory' && }
{tab === 'skills' && }
)
}
// -------------------------------------------------------------------------
type EmbeddingInfo = Awaited>
function useEmbedding(collection: string) {
const [info, setInfo] = useState(null)
const refresh = async () => {
const next = await api.kb.embedding(collection).catch(() => null)
if (next) setInfo(next)
return next
}
useEffect(() => { void refresh() }, [collection])
useOnReconnect(() => void refresh())
return { info, refresh }
}
/** 向量模型现在能不能用:和数据源、模型接入同一套剪影,但说的是「语义检索」 */
function SemanticPill({ info }: { info: EmbeddingInfo }) {
const [status, text, color] = info.fallback
? ['failed', '已回退到本地哈希 · 不支持语义检索', 'var(--err)']
: info.has_semantics === false
? ['skipped', '本地哈希 · 不支持语义检索', 'var(--warn)']
: ['done', '语义检索 · 正常', 'var(--text-dim)']
return (
{text}
)
}
/**
* 当前用哪个 embedder,以及有多少条向量已经对不上。
*
* 在此之前切换 embedding 模型的唯一开关是 AGENTLAB_USE_OPENAI_EMBEDDINGS——
* 一个没有界面、没人会发现的环境变量。于是所有人都在用那个没有语义能力的
* 哈希向量(同义改写一条都召不回),而 alpha 默认还给了它一半权重。
*
* 换模型之后存量向量就和查询对不上了,检索会整体退回纯关键词。这一条必须
* 显眼:少了一半能力却不说,用户只会觉得"最近搜得不准"。
*/
function EmbedderBar({ info, collection, refresh, onChanged }: {
info: EmbeddingInfo | null
collection: string
refresh: () => Promise
onChanged: () => void | Promise
}) {
const collections = useCatalog((s) => s.collections)
const [busy, setBusy] = useState<'' | 'pick' | 'probe' | 'rebuild'>('')
const [editing, setEditing] = useState(false)
const [baseUrl, setBaseUrl] = useState('')
const [models, setModels] = useState([])
const [model, setModel] = useState('')
// 在看的那次重建(后台跑,轮询进度)。只有看着它跑完的,才报「重建完了」
const [job, setJob] = useState(null)
const [jobFailed, setJobFailed] = useState(null)
const running = job?.state === 'running'
// 重建途中换模型,前半截是旧模型建的、后半截是新的:跑着的时候把换模型也锁上
const locked = !!busy || running
const clock = useRunClock(running)
useEffect(() => {
if (info) { setBaseUrl(info.base_url || ''); setModel(info.model || '') }
}, [info?.base_url, info?.model])
// 进页先看一眼:刷新之前、或者别的标签页点的重建可能还在跑,接着显示它的进度
useEffect(() => {
let live = true
api.kb.reindexStatus().then((j) => { if (live && j.state === 'running') setJob(j) }, () => {})
return () => { live = false }
}, [])
// 一秒问一次进度,拿到的就是后端按批记下的真实数字,不在两次之间插值
useEffect(() => {
if (!running) return
let live = true
const t = setTimeout(async () => {
let next: ReindexJob | { state: 'idle' }
try {
next = await api.kb.reindexStatus()
} catch {
// 这一拍没问到(后端抖了一下):原样再排一拍
if (live) setJob((j) => (j ? { ...j } : j))
return
}
if (!live) return
if (next.state === 'running') { setJob(next); return }
setJob(null)
if (next.state === 'idle') {
// 进度只记在后端进程里:重启过就没了,重建多半也没做完
toast.warn('服务端已重启,本次重建进度已丢失。请查看剩余待重建的数量,如有需要请再次重建索引')
} else if (next.state === 'failed') {
setJobFailed(next)
} else {
const r = next.result
const mem = r?.memories_reindexed ?? 0
toast.ok(`已用 ${r?.embedder ?? '当前模型'} 重建 ${formatNumber(r?.reindexed ?? 0)} 段知识` + (mem ? ` 和 ${formatNumber(mem)} 条记忆` : ''))
}
await refresh()
await onChanged()
}, 1000)
return () => { live = false; clearTimeout(t) }
}, [job])
if (!info) return
// 记忆和知识库共用一个 embedder,换模型时一起失效。只报一个的话,
// 用户点完重建还是想不起事,而且不知道为什么
const staleChunks = info.stale_chunks ?? 0
const staleMemories = info.stale_memories ?? 0
// 没建倒排的片段也归这个按钮管:它们走全表扫,结果对但慢,而重建正好
// 把倒排一起建了。按钮只认"向量对不上"的话,这些片段永远等不到人来点
const unindexed = info.unindexed_chunks ?? 0
const stale = staleChunks + staleMemories + unindexed
// 配了语义模型、实际在用本地哈希:保存的配置没生效(多半是启动时本机的模型服务
// 还没起),服务后来起了也不会自己连上。以前这里按"配的是不是 local"判断,于是
// 既不说没有语义能力,还高亮"重建索引"——那些"对不上"的向量正是那个模型建好的,
// 一点就拿哈希覆盖掉,连上之后还得再重建一遍
const fallback = !!info.fallback
const staleParts = [
staleChunks ? `${formatNumber(staleChunks)} 段知识` : '',
staleMemories ? `${formatNumber(staleMemories)} 条记忆` : '',
].filter(Boolean).join('、')
const pick = async (kind: string, m = '', url = '', done = '切换到') => {
setBusy('pick')
try {
const out = await api.kb.setEmbedding({ kind, model: m, base_url: url })
// 换模型之后维度多半变了,存量向量全部作废——这件事要当场说,
// 而不是等用户发现"最近搜得不准"
const n = (out.stale_chunks ?? 0) + (out.stale_memories ?? 0)
toast.ok(`已${done} ${out.embedder}(${out.dim} 维)` + (n ? `,${n} 条存量向量需要重建` : ''))
setEditing(false)
await refresh()
} catch (e) {
// 400 里写的是"连不上哪个地址""哪个模型名不对",都能照着做
toast.error(e)
} finally { setBusy('') }
}
/**
* 切到本地哈希是全局降级:知识库和记忆一起退回纯关键词,所有工作流的检索
* 节点都受影响。以前它是一行普通按钮,点下去立刻生效,后果要等事后的 toast
* 才说出来。
*/
const pickLocal = async () => {
const chunks = collections.reduce((n, c) => n + (c.chunks ?? 0), 0)
const memories = (await api.memory.scopes().catch(() => [])).reduce((n, s) => n + (s.count ?? 0), 0)
const ok = await confirmDialog({
title: '将向量模型切换为本地哈希?',
danger: true,
body: '本地哈希无需配置、不联网、免费,但基于词频哈希,不支持语义检索。',
consequences: [
`${formatNumber(chunks)} 段知识、${formatNumber(memories)} 条记忆的向量与本地哈希不匹配:检索和召回将回退为纯关键词,直至重建索引`,
'无法检索同义表达:例如搜索「管理员」无法匹配「平台角色」',
'知识库和长期记忆将一并切换,所有工作流的检索节点都会受影响',
],
requireText: '本地哈希',
confirmLabel: '切换到本地哈希',
})
if (ok) await pick('local')
}
/** 换成另一个语义模型:维度多半会变,存量向量要重建。和当前配置一样的(重新连接)不问 */
const pickModel = async (m: string, url: string) => {
const same = info.kind === 'openai' && m === info.model && url === (info.base_url || '')
if (!same) {
const ok = await confirmDialog({
title: `更换为 ${m}?`,
consequences: ['存量向量由原模型生成,更换后需要重建索引;重建完成前,这部分内容回退为关键词检索'],
confirmLabel: '更换模型',
})
if (!ok) return
}
await pick('openai', m, url, same ? '重新连接' : '切换到')
}
const probe = async () => {
setBusy('probe')
try {
const out = await api.kb.probeEmbedding(baseUrl)
setModels(out.models)
if (out.models.length === 1) setModel(out.models[0])
if (!out.models.length) toast.warn('该地址下没有可用模型')
} catch (e) {
toast.error(e)
} finally { setBusy('') }
}
/**
* 后台重建:立刻回来,进度靠轮询。几千段配远端 embedding 要好几分钟,以前整个
* 请求压着,按钮上只有一个不知道还要多久的计时
*/
const rebuild = async () => {
setJobFailed(null)
setBusy('rebuild')
try {
setJob(await api.kb.startReindex(collection))
} catch (e) {
if (e instanceof ApiError && e.status === 409) {
// 已经有一次在跑(别的标签页,或者别人点的):不再起第二次,接着看它的进度
toast.info(e.message)
const cur = await api.kb.reindexStatus().catch(() => null)
if (cur?.state === 'running') setJob(cur)
} else {
toast.error(e)
}
} finally { setBusy('') }
}
return (
向量模型
{info.embedder} · {info.dim} 维
{/* 看实际在用的那个,不看配的是什么 */}
{(running || (stale > 0 && !fallback)) && (
)}
{running && job && }
{jobFailed && !running && (
void rebuild()} />
)}
{fallback && (
已配置 {info.model}({info.base_url || 'api.openai.com'}),但连接失败,
当前使用本地哈希向量:检索只匹配字面,无法识别同义表达。
{info.fallback_reason &&
{info.fallback_reason}
}
{staleParts && (
这 {staleParts}由 {info.model} 生成,向量完好,请暂缓重建:此时重建会使用本地哈希覆盖它们。
重新连接后将自动恢复语义检索。
)}
服务恢复后点击此处重新连接,无需重启。
)}
{editing && (
自定义端点 — 任何兼容 OpenAI /v1/embeddings 接口的服务:本机的 LM Studio、Ollama、vLLM、TEI,或自建网关
setBaseUrl(e.target.value)} />
{/* 模型名手填太容易错:LM Studio 里叫 text-embedding-qwen3-embedding-4b,
不是 Qwen3-Embedding-4B。填错的表现是切换时 404,人还以为服务没起 */}
{!!models.length && (
)}
地址留空则使用 api.openai.com(需要 OPENAI_API_KEY,按量计费)。更换模型后维度通常会变化,存量向量需要重建。
)}
{!fallback && staleParts && (
有 {staleParts}的向量由其他模型生成,与当前的 {info.embedder} 不匹配:检索、召回这些内容时
将回退为纯关键词(无法识别同义表达),重建索引后恢复。
)}
{unindexed > 0 && !staleParts && (
有 {formatNumber(unindexed)} 段尚未建立倒排索引,检索时将回退为全表扫描,结果正确但速度较慢,重建索引即可解决。
)}
{info.kind !== 'openai' && stale === 0 && (
本地向量无需联网和配置,但基于词频哈希,不支持语义检索,例如搜索「管理员」无法匹配「平台角色」。
正式使用知识库时,建议切换到上方的语义向量模型。
)}
)
}
/**
* 重建索引的进度:后端按批(64 条一批)记下的真实数字,不插值。
*
* 三段:知识片段的向量 → 倒排索引 → 记忆的向量。倒排那一段后端没有分批进度,
* 条停在片段做完的位置,写明「这一步没有分批进度」,不去假装它在走
*/
function ReindexProgress({ job, now }: { job: ReindexJob; now: number }) {
const started = parseServerTime(job.started_at)?.getTime()
const pct = job.total > 0 ? Math.min(1, job.done / job.total) : null
const step = job.phase === 'index'
? '正在重建倒排索引'
: job.phase === 'memories'
? `正在重算记忆的向量 · ${formatNumber(job.memories.done)} / ${formatNumber(job.memories.total)} 条`
: `正在重算知识片段的向量 · ${formatNumber(job.chunks.done)} / ${formatNumber(job.chunks.total)} 段`
return (
{step}
{pct != null && <>合计 {formatNumber(job.done)} / {formatNumber(job.total)} · {Math.round(pct * 100)}% · >}
已用 {started ? formatDuration(Math.max(0, now - started)) : NONE}
{pct != null && (
{/* 用 scaleX 推进而不是改 width:只动 transform,不触发重排 */}
)}
{job.phase === 'index'
? '片段向量已计算完成,正在完整重建倒排索引。这一步没有分批进度,数据量较大时需要等待一段时间。'
: `${job.collection ? `仅重建「${job.collection}」的片段;` : ''}记忆和知识库共用同一个向量模型,将一并重建。可以离开此页面,返回后仍可查看进度。`}
)
}
// -------------------------------------------------------------------------
function KbTab() {
// 地址上带了文档 id 就看那一份的详情。集合是筛选条件不是位置,所以不进 URL
const { id } = useParams()
if (id) return
return
}
/** 按扩展名挑图标:一眼分得出 PPT、PDF 和代码 */
function DocIcon({ doc }: { doc: KbDocument }) {
const ext = extOf(doc.source || doc.title)
const Icon = !doc.source ? ClipboardType
: ext === 'pptx' ? Presentation
: ext === 'html' || ext === 'htm' ? Globe
: ['py', 'ts', 'js', 'json', 'yaml', 'yml'].includes(ext) ? FileCode
: FileText
return
}
const extOf = (name: string) => (/\.([a-z0-9]+)$/i.exec(name ?? '')?.[1] ?? '').toLowerCase()
/**
* 一份文档被切成了什么样。
*
* 切块这一层做了不少事——按行边界留重叠、跨块把表头续上(后端 memory/kb.py
* 的 chunk_text),而在此之前结果在界面上一处都看不见。检索不准的时候第一个
* 该看的就是它:表头有没有续上、重叠对不对、哪一段被截断了。
*/
function DocDetail({ docId }: { docId: string }) {
const navigate = useNavigate()
const [data, setData] = useState> | null>(null)
const [error, setError] = useState(null)
const [flash, setFlash] = useState(null)
useEffect(() => {
let live = true
void api.kb.document(docId)
.then((d) => { if (live) setData(d) })
.catch((e) => { if (live) setError(e) })
return () => { live = false }
}, [docId])
// 从检索结果跳过来时带着 #chunk-N:落到那一段并闪一下
useEffect(() => {
if (!data) return
const m = /^#chunk-(\d+)$/.exec(location.hash)
if (m) jump(Number(m[1]))
}, [data])
const jump = (ordinal: number) => {
document.getElementById(`chunk-${ordinal}`)?.scrollIntoView({ block: 'center', behavior: 'smooth' })
setFlash(ordinal)
setTimeout(() => setFlash((f) => (f === ordinal ? null : f)), 1400)
}
const back = (
)
if (error) {
const gone = humanizeError(error).status === 404
return (
{back}
{gone
? } title="该文档不存在" body="可能已被删除,请返回知识库查看。" />
: }
)
}
if (!data) return {back}
const doc = data.document
// 一份文档里混着两个模型建的向量是真会发生的(换模型之后只重建了一部分),
// 而那会让检索对这部分内容悄悄退回关键词
const models = [...new Set(data.chunks.map((c) => c.embed_model).filter(Boolean))]
const noVector = data.chunks.filter((c) => !c.has_vector).length
return (
{back}
{doc.title}
{doc.collection}
{doc.source && doc.source !== doc.title && {doc.source}}
{formatNumber(data.chunks.length)} 个片段
{doc.created_at && {formatTime(doc.created_at)}}
{models.map((m) => {m})}
{models.length > 1 && (
该文档包含两个模型生成的向量,与当前模型不匹配的部分将回退为关键词检索
)}
{noVector > 0 && {noVector} 段尚无向量}
{data.chunks.length > 0 &&
}
{!data.chunks.length && (
} title="尚未切块"
body={doc.status === 'processing' ? '正在处理,稍后刷新' : doc.error || '该文档未生成任何片段'} />
)}
{data.chunks.map((c) => (
片段 {c.ordinal}
{formatNumber(c.chars)} 字
{c.token_len > 0 && {formatNumber(c.token_len)} token}
{!c.has_vector && 没有向量}
{c.truncated && (仅显示开头部分)}
{c.content}
))}
)
}
/**
* 切块地图:一格一个片段,高度是字数,没向量的标 warn,混了第二个模型的打斜纹。
* 整份文档切得匀不匀、哪几段没向量,一眼看完,不用往下翻几百张卡片。
*/
function ChunkMap({ chunks, models, onPick }: {
chunks: { ordinal: number; chars: number; has_vector: boolean; embed_model: string }[]
models: string[]
onPick: (ordinal: number) => void
}) {
const max = Math.max(1, ...chunks.map((c) => c.chars))
const main = models[0]
const shown = chunks.slice(0, 3000)
return (
{/* 每一格都能点(跳到那一段),是按钮,不是列表项:role=listitem 会把按钮语义盖掉 */}
{shown.map((c) => {
const h = 6 + Math.round((c.chars / max) * 18)
const other = models.length > 1 && c.embed_model && c.embed_model !== main
return (
每格代表一个片段,高度表示字数(最长 {formatNumber(max)} 字)
没有向量
{models.length > 1 && 斜纹:非 {main} 生成}
{chunks.length > shown.length && 仅显示前 {formatNumber(shown.length)} 段}
点击格子可跳转到对应片段
)
}
/** 后端 /kb/formats 拿不到时的兜底,和后端解析器保持一致 */
const FALLBACK_FORMATS = {
extensions: ['.docx', '.pdf', '.pptx', '.htm', '.html', '.txt', '.md', '.markdown', '.json', '.log', '.yaml', '.yml', '.py', '.ts', '.js'],
tabular: ['.csv', '.tsv', '.xls', '.xlsx'],
legacy: ['.doc', '.ppt', '.xls'],
}
interface Uploading {
key: number; name: string; size: number
/** 轮到它、开始发的时刻。一次传一个,排在后面的还没开始 */
startedAt?: number
progress?: UploadProgress
/** 字节发完的时刻:之后是后端在解析、切块 */
sentAt?: number
}
function KbList() {
const navigate = useNavigate()
const refreshCatalog = useCatalog((s) => s.refresh)
const [collection, setCollection] = useState('default')
const [collections, setCollections] = useState<{ collection: string; documents: number; chunks: number }[]>([])
const [docs, setDocs] = useState(null)
const [docsError, setDocsError] = useState(null)
const [formats, setFormats] = useState> | null>(null)
const [adding, setAdding] = useState(false)
const [uploads, setUploads] = useState([])
const [dragging, setDragging] = useState(false)
const fileRef = useRef(null)
const uploadSeq = useRef(0)
const aborts = useRef(new Map())
const { info, refresh: refreshInfo } = useEmbedding(collection)
const load = async () => {
const [cs, ds] = await Promise.allSettled([api.kb.collections(), api.kb.documents(collection)])
if (cs.status === 'fulfilled') setCollections(cs.value)
// 还在撤销窗口里的文档 DELETE 没发,后端照样返回它:滤掉,不然轮询一刷就回来了
if (ds.status === 'fulfilled') { setDocs(withoutDeferred(ds.value, '/api/kb/documents')); setDocsError(null) }
else setDocsError(ds.reason)
}
useEffect(() => { setDocs(null); void load() }, [collection])
useEffect(() => { api.kb.formats().then(setFormats, () => {}) }, [])
useOnReconnect(() => { void load(); if (!formats) api.kb.formats().then(setFormats, () => {}) })
// 有文档还在切块就接着轮询。一个 10MB 文档配上远端 embedding 要几十分钟,
// 不轮询的话界面会一直停在"处理中",人以为卡死了
useEffect(() => {
if (!docs?.some((d) => d.status === 'processing')) return
const timer = setInterval(() => { void load() }, 2000)
return () => clearInterval(timer)
}, [docs, collection])
const fmt = formats ?? FALLBACK_FORMATS
const accept = formats?.accept ?? FALLBACK_FORMATS.extensions.join(',')
const upload = async (files: File[]) => {
if (!files.length) return
const toData = { label: '去数据源上传表格', onClick: () => navigate('/data/tables') }
const ok: File[] = []
for (const file of files) {
const ext = `.${extOf(file.name)}`
// 表格进知识库只会被切成文本:聚合算不了、数字也回指不了,那条路要走数据源。
// 选文件框里已经不放行,拖进来的还得在这里拦
if (fmt.tabular.includes(ext)) {
toast.error(`${file.name} 是表格文件,不能导入知识库。请上传到数据源,以便用 SQL 计算并追溯出处`, { action: toData })
} else if (fmt.legacy.includes(ext)) {
toast.error(`${file.name} 是旧版二进制格式(${ext}),请先另存为 ${ext}x 后再上传`)
} else if (!fmt.extensions.includes(ext)) {
toast.error(`${file.name}:知识库不支持 ${ext} 文件。支持的格式:${fmt.extensions.join(' ')}`)
} else {
ok.push(file)
}
}
if (!ok.length) return
const items = ok.map((f) => ({ key: ++uploadSeq.current, name: f.name, size: f.size, file: f }))
for (const item of items) aborts.current.set(item.key, new AbortController())
setUploads((u) => [...items.map(({ file: _f, ...rest }) => rest), ...u])
const patch = (key: number, next: (x: Uploading) => Partial) =>
setUploads((u) => u.map((x) => (x.key === key ? { ...x, ...next(x) } : x)))
// 一次传一个:并发传几个大文件,每个都慢,谁都等不到「处理中」
for (const item of items) {
const ctl = aborts.current.get(item.key)
try {
if (!ctl || ctl.signal.aborted) continue
patch(item.key, () => ({ startedAt: Date.now() }))
await api.kb.upload(item.file, collection, {
signal: ctl.signal,
onProgress: (p) => patch(item.key, (x) => ({ progress: p, sentAt: x.sentAt ?? (p.sent ? Date.now() : undefined) })),
})
await load()
} catch (e) {
// 人点的取消:不算出错
if (e instanceof DOMException && e.name === 'AbortError') continue
const h = humanizeError(e)
const text = `${item.name} 上传失败:${h.reason ? `${h.title},${h.reason}` : h.title}`
toast.error(text, { detail: h.raw, action: /表格|数据源/.test(text) ? toData : undefined })
} finally {
aborts.current.delete(item.key)
setUploads((u) => u.filter((x) => x.key !== item.key))
}
}
await load()
await refreshCatalog()
}
// 排着队的直接拿掉;在传的由上面那个循环收尾(它会拿到 AbortError)
const cancelUpload = (key: number) => {
aborts.current.get(key)?.abort()
setUploads((u) => u.filter((x) => x.key !== key || !!x.startedAt))
}
const newCollection = async () => {
const name = await promptDialog({
title: '新建知识库', label: '名称', placeholder: '例如 product_faq',
validate: (v) => (collections.some((c) => c.collection === v) ? '该知识库已存在'
: /^[\w.-]{1,64}$/.test(v) ? null : '只能包含字母、数字、下划线、点和短横线'),
confirmLabel: '创建并切换',
})
if (name) setCollection(name)
}
const removeDoc = (doc: KbDocument) => deferDelete({
what: `「${doc.title}」`,
url: `/api/kb/documents/${doc.id}`,
hide: () => setDocs((ds) => ds && ds.filter((d) => d.id !== doc.id)),
restore: () => void load(),
commit: () => api.kb.remove(doc.id),
done: () => { void load(); void refreshCatalog() },
})
const hasFiles = (e: DragEvent) => Array.from(e.dataTransfer?.types ?? []).includes('Files')
const known = collections.some((c) => c.collection === collection)
const current = collections.find((c) => c.collection === collection)
const choices = [...collections, ...(known ? [] : [{ collection, documents: 0, chunks: 0 }])]
const radio = useRadioGroup(choices.map((c) => c.collection), collection, setCollection)
return (
{choices.map((c) => {
const on = c.collection === collection
return (
)
})}
{/* 能收什么以后端解析器为准(/kb/formats):以前这里手写一份,漏了 .pptx
却放了 .csv——PPT 选不中,CSV 选得中但必被拒 */}
{ const fs = Array.from(e.target.files ?? []); e.target.value = ''; void upload(fs) }} />
{ if (hasFiles(e)) { e.preventDefault(); setDragging(true) } }}
onDragLeave={(e) => { if (!e.currentTarget.contains(e.relatedTarget as Node)) setDragging(false) }}
onDrop={(e) => { if (!hasFiles(e)) return; e.preventDefault(); setDragging(false); void upload(Array.from(e.dataTransfer.files)) }}
>
文档
{current && {formatNumber(current.documents)} 篇 · {formatNumber(current.chunks)} 段}
可直接拖入文件
{dragging && (
松开即上传到「{collection}」
)}
{uploads.map((u) => cancelUpload(u.key)} />)}
{docs === null ? (
docsError ? void load()} className="m-3" />
:
) : !docs.length && !uploads.length ? (
}
title={known ? '该知识库暂无文档' : `新知识库「${collection}」`}
body="上传 PDF、Word、PPT、网页或文本后,将自动切块并建立索引。Excel / CSV 文件请上传到数据源。"
action={
}
/>
) : (
{docs.map((doc) => removeDoc(doc)} />)}
)}
setAdding(false)}
onSaved={async () => { setAdding(false); await load(); await refreshCatalog() }} />
)
}
/**
* 上传占位行:真实的字节进度,发完之后写「处理中」。字节没发完之前可以取消——
* 后端收不全就什么都不会建;发完了后端已经在切块,取消只会让人以为没传上
*/
function UploadingRow({ item, onCancel }: { item: Uploading; onCancel: () => void }) {
const now = useRunClock(true)
const sent = !!item.progress?.sent
return (
{item.startedAt ?
:
}
{item.name}
{formatBytes(item.size)}
{!sent && (
)}
)
}
/** 处理进度的速率:同一份文档前后两次轮询之间走了多少段,推出还要多久。只用真实进度,不插值 */
const progressSeen = new Map()
function DocRow({ doc, onRemove }: { doc: KbDocument; onRemove: () => void }) {
const navigate = useNavigate()
const processing = doc.status === 'processing'
const progress = doc.meta?.progress
const now = Date.now()
let eta: number | null = null
if (processing && progress?.total) {
const first = progressSeen.get(doc.id)
if (!first) progressSeen.set(doc.id, { at: now, done: progress.done })
else if (progress.done > first.done && now - first.at > 3000) {
const rate = (progress.done - first.done) / (now - first.at)
eta = (progress.total - progress.done) / rate
}
} else {
progressSeen.delete(doc.id)
}
const ext = extOf(doc.source || '')
const meta = [
doc.source && doc.source !== doc.title ? doc.source : null,
doc.source ? (ext ? ext.toUpperCase() : null) : '粘贴的文本',
`${formatNumber(doc.chunk_count)} 个片段`,
doc.created_at ? formatTime(doc.created_at) : null,
].filter(Boolean).join(' · ')
const pct = progress?.total ? Math.min(100, (progress.done / progress.total) * 100) : null
return (
)
}
/**
* 检索调试台:预演 agent 的 kb_search 会拿到什么。
*
* α 的初值取运行时实际用的 default_alpha(以前写死 0,也就是纯关键词,而运行时
* 是 0.5——调试台和运行时对不上,人会照着错的命中去调知识库)。偏离时标出来,
* 一键回到运行时的值。
*/
function KbSearch({ collection, info }: { collection: string; info: EmbeddingInfo | null }) {
const runtime = info?.default_alpha ?? null
const [query, setQuery] = useState('')
const [alpha, setAlpha] = useState(null)
const [busy, setBusy] = useState(false)
const [res, setRes] = useState(null)
// 集合切换、或运行时默认值变了(换了 embedder),就回到运行时的值
useEffect(() => { if (runtime != null) setAlpha(runtime) }, [collection, runtime])
const a = alpha ?? runtime ?? 0.5
const search = async () => {
if (!query.trim()) { setRes(null); return }
setBusy(true)
try {
setRes(await api.kb.search(query, collection, a))
} catch (e) {
toast.error(e)
} finally {
setBusy(false)
}
}
const off = runtime != null && Math.abs(a - runtime) > 1e-9
return (
检索调试台
预览 Agent 检索知识库时会得到的结果
setQuery(e.target.value)}
onKeyDown={(e) => { if (e.key === 'Enter' && !isComposing(e)) void search() }} />
{off && (
与运行时不同(运行时 α = {runtime}),命中结果将与 Agent 实际获得的不同 ·{' '}
)}
{res && (
{res.results.length} 条命中 · 按 α = {(res.alpha ?? a).toFixed(2)} 检索
{!!res.degraded?.length && (
已回退为关键词检索:{res.degraded[0]}
)}
{res.results.some((h) => h.contrib) && (
总分 =
语义贡献 +
关键词贡献
)}
{!res.results.length &&
没有命中
}
{res.results.map((hit) =>
)}
)}
)
}
/**
* 贡献条的两种颜色:分类色,只说「哪一路检索」,不表达状态(ok / warn / err /
* accent 留给状态)。取值在 index.css 的主题令牌里,亮暗各一套
*/
const VIA_SEMANTIC = 'var(--via-semantic)'
const VIA_KEYWORD = 'var(--via-keyword)'
function Swatch({ color }: { color: string }) {
return
}
/**
* 一条命中。总分是候选集上归一化后的混合分(0–1),拆成两段:语义那一路贡献了
* 多少、关键词那一路贡献了多少(两段之和就是总分,后端按 α 加权后给的)。人一眼
* 看得出这条是靠哪一路捞上来的,调 α 时知道在动哪一段。
*
* 原始分另外写成数:语义是余弦(0–1),关键词是 BM25(没有上界,画条会误导)。
* 老后端没有 contrib,就退回一根总分条
*/
function HitCard({ hit }: { hit: KbHit }) {
const vec = typeof hit.signals?.vector === 'number' ? hit.signals.vector : null
const kw = typeof hit.signals?.keyword === 'number' ? hit.signals.keyword : null
const c = hit.contrib
const only = vec && !kw ? '只靠语义命中' : kw && !vec ? '只靠关键词命中' : null
const raw = (v: number | null, digits: number) => (v == null ? '—' : v.toFixed(digits))
return (
{hit.title}
片段 {hit.ordinal}
{only && {only}}
总分
{c ? : }
{Number(hit.score).toFixed(3)}
{c ? (
语义 +{Math.max(0, c.vector).toFixed(3)}
(余弦 {raw(vec, 3)})
关键词 +{Math.max(0, c.keyword).toFixed(3)}
(BM25 {raw(kw, 2)})
) : (
语义余弦 {raw(vec, 3)}
关键词 BM25 {raw(kw, 2)}
)}
{hit.content}
)
}
/**
* 总分拆成两段的条:整根轨道是 1 分,两段依次排开,中间留 2px 缝。关键词那段是
* 后端用减法算出来的,四舍五入可能出一点点负数,画的时候当 0
*/
function ContribBar({ vector, keyword }: { vector: number; keyword: number }) {
const v = Math.max(0, Math.min(1, vector))
const k = Math.max(0, Math.min(1 - v, keyword))
return (
{v > 0 && }
{k > 0 && }
)
}
function Bar({ value, thin = false }: { value: number; thin?: boolean }) {
const pct = Math.max(0, Math.min(1, Number(value) || 0)) * 100
return (
)
}
function AddDocModal({ open, collection, onClose, onSaved }: {
open: boolean; collection: string; onClose: () => void; onSaved: () => void
}) {
const [title, setTitle] = useState('')
const [content, setContent] = useState('')
const [busy, setBusy] = useState(false)
const submit = async () => {
setBusy(true)
try {
await api.kb.ingest({ collection, title, content })
setTitle(''); setContent('')
onSaved()
toast.ok('已导入并建立索引')
} catch (e) {
toast.error(e)
} finally {
setBusy(false)
}
}
return (
>}>
{(p) => setTitle(e.target.value)} placeholder="可留空" />}
{(p) => (
)
}
// -------------------------------------------------------------------------
const MEMORY_KIND: Record = { fact: '事实', preference: '偏好', episode: '经历' }
const IMPORTANCE_STEPS = [0.2, 0.4, 0.6, 0.8, 1]
/** 重要度五格刻度:比「0.5」这样的裸数字好比较 */
function Importance({ value }: { value: number }) {
const filled = Math.max(0, Math.min(5, Math.round((Number(value) || 0) * 5)))
return (
重要度
{IMPORTANCE_STEPS.map((_, i) => (
))}
)
}
/** 记忆从哪来:审查「这条口径能不能信」的第一件事 */
function MemorySourceLine({ item }: { item: MemoryItem }) {
// 老后端没有 source,只在 meta 里记了 run_id / node_id
const src: MemorySource | null = item.source
?? (item.meta?.run_id ? { kind: 'run', run_id: item.meta.run_id, node_id: item.meta.node_id } : null)
if (!src) return null
if (src.kind === 'manual') return 手动添加
if (src.kind === 'playground') return 在工具库中写入
if (src.kind !== 'run' || !src.run_id) return {src.kind}
const bits = [src.node_label || src.node_id, src.workflow_name && runName(src)].filter(Boolean).join(' · ')
const label = <>运行 {shortId(src.run_id)}{bits ? ` · ${bits}` : ''}>
return src.run_exists === false ? (
来源:{label}(运行已删除)
) : (
来源:{label}
)
}
type MemorySort = 'created' | 'recalled' | 'count'
function MemoryTab() {
const [scope, setScope] = useState('default')
const [scopes, setScopes] = useState<{ scope: string; count: number }[]>([])
const [items, setItems] = useState(null)
const [error, setError] = useState(null)
const [text, setText] = useState('')
const [kind, setKind] = useState('fact')
const [writing, setWriting] = useState(false)
const [query, setQuery] = useState('')
const [recalling, setRecalling] = useState(false)
const [hits, setHits] = useState(null)
const [filter, setFilter] = useState('')
const [sort, setSort] = useState('created')
useTicker(60_000)
const load = async () => {
const [ss, list] = await Promise.allSettled([api.memory.scopes(), api.memory.list(scope)])
if (ss.status === 'fulfilled') setScopes(ss.value)
if (list.status === 'fulfilled') { setItems(withoutDeferred(list.value, '/api/memory')); setError(null) }
else if (items) toast.error(list.reason)
else setError(list.reason)
}
useEffect(() => { setItems(null); setHits(null); void load() }, [scope])
useOnReconnect(load)
const write = async () => {
const content = text.trim()
if (!content || writing) return
setWriting(true)
try {
await api.memory.add({ content, scope, kind })
setText('')
await load()
toast.ok('已写入记忆')
} catch (e) {
toast.error(e)
} finally {
setWriting(false)
}
}
// 回忆调试只看不计数(peek):真实召回会给命中项 use_count += 1 并影响下次排序
const recall = async () => {
if (!query.trim()) { setHits(null); return }
setRecalling(true)
try {
setHits((await api.memory.recall(query, { scope })).results ?? [])
} catch (e) {
toast.error(e)
} finally {
setRecalling(false)
}
}
const remove = async (item: MemoryItem) => {
const ok = await confirmDialog({
title: '删除这条记忆?',
body: {item.content},
consequences: [
'Agent 将无法再召回这条记忆,依据此口径计算的结果可能发生变化',
'删除后 5 秒内可以撤销',
],
danger: true,
confirmLabel: '删除记忆',
})
if (!ok) return
deferDelete({
what: '一条记忆',
url: `/api/memory/${item.id}`,
hide: () => setItems((xs) => xs && xs.filter((x) => x.id !== item.id)),
restore: () => void load(),
commit: () => api.memory.remove(item.id),
done: () => void load(),
})
}
const newScope = async () => {
const name = await promptDialog({
title: '新建记忆作用域', label: '名称', placeholder: '例如 finance',
validate: (v) => (/^[\w.-]{1,64}$/.test(v) ? null : '只能包含字母、数字、下划线、点和短横线'),
confirmLabel: '创建并切换',
})
if (name) setScope(name)
}
const shown = useMemo(() => {
const needle = filter.trim().toLowerCase()
const list = (items ?? []).filter((i) => !needle || i.content.toLowerCase().includes(needle))
const t = (v?: string | null) => parseServerTime(v)?.getTime() ?? 0
return [...list].sort((a, b) => sort === 'count' ? b.use_count - a.use_count
: sort === 'recalled' ? t(b.last_used_at) - t(a.last_used_at)
: t(b.created_at) - t(a.created_at))
}, [items, filter, sort])
const knownScope = scopes.some((s) => s.scope === scope)
const scopeChoices = [...scopes, ...(knownScope ? [] : [{ scope, count: 0 }])]
const radio = useRadioGroup(scopeChoices.map((s) => s.scope), scope, setScope)
return (
{scopeChoices.map((s) => {
const on = s.scope === scope
return (
)
})}
setQuery(e.target.value)}
onKeyDown={(e) => { if (e.key === 'Enter' && !isComposing(e)) void recall() }} />
仅预览,不计入召回次数:调试不会影响 Agent 后续的召回排序。
{hits && (
{!hits.length &&
没有召回任何记忆
}
{hits.map((h) => (
{Number(h.score).toFixed(3)}
{h.content}
))}
)}
{items === null ? (
error ?
void load()} /> :
) : !items.length ? (
} title={knownScope ? '该作用域暂无记忆' : `新作用域「${scope}」`}
body="记忆跨运行保留,Agent 可通过记忆工具自行读写,也可以在上方手动写入。" />
) : (
<>
{shown.map((item) => (
void remove(item)}
onSaved={(next) => setItems((xs) => xs && xs.map((x) => (x.id === next.id ? { ...x, ...next } : x)))} />
))}
{!shown.length && 没有匹配「{filter}」的记忆
}
>
)}
)
}
function MemoryRow({ item, onRemove, onSaved }: {
item: MemoryItem; onRemove: () => void; onSaved: (next: MemoryItem) => void
}) {
const [editing, setEditing] = useState(false)
const [draft, setDraft] = useState({ content: item.content, kind: item.kind, importance: item.importance })
const [busy, setBusy] = useState(false)
const start = () => {
setDraft({ content: item.content, kind: item.kind, importance: item.importance })
setEditing(true)
}
const save = async () => {
const content = draft.content.trim()
if (!content || busy) return
setBusy(true)
try {
// 原地改:来源、记下的时间和召回记录都保留;改了内容后端会重算向量
const next = await api.memory.update(item.id, { content, kind: draft.kind, importance: draft.importance })
onSaved(next ?? { ...item, ...draft, content })
setEditing(false)
toast.ok('已更新这条记忆')
} catch (e) {
toast.error(e)
} finally {
setBusy(false)
}
}
const onKey = (e: ReactKeyboardEvent) => {
if (isComposing(e)) return
if (matchShortcut(e.nativeEvent, 'Mod+Enter')) { e.preventDefault(); void save() }
else if (e.key === 'Escape') { e.preventDefault(); e.stopPropagation(); setEditing(false) }
}
return (
{editing ? (
) : (
{item.content}
)}
{MEMORY_KIND[item.kind] ?? item.kind}
被召回 {formatNumber(item.use_count)} 次
{item.created_at && (
写入于 {formatTime(item.created_at)}
)}
{item.last_used_at ? `上次召回 ${formatRelative(item.last_used_at)}` : '尚未被召回'}
{!editing && (
} className="text-faint" onClick={start} />
)}
)
}
// -------------------------------------------------------------------------
function SkillsTab() {
// catalog 随时会被别处刷新(重连、别的页面保存):撤销窗口里的那条要滤掉,不然刷一下就回来了
const skills = withoutDeferred(useCatalog((s) => s.skills), '/api/skills')
const refresh = useCatalog((s) => s.refresh)
const [editing, setEditing] = useState | null>(null)
useEffect(() => { void refresh() }, [])
const remove = (skill: Skill) => deferDelete({
what: ` Skill「${skill.name}」`,
url: `/api/skills/${skill.id}`,
// catalog 里的 Skill 是全站共用的:先从那里拿掉,撤销时刷新回来
hide: () => useCatalog.setState((s) => ({ skills: s.skills.filter((x) => x.id !== skill.id) })),
restore: () => void refresh(),
commit: () => api.skills.remove(skill.id),
done: () => void refresh(),
})
const create = () => setEditing({ examples: [], tags: [], enabled: true })
return (
{!skills.length ? (
}
title="还没有 Skill"
source="skills"
body="将「先给结论、区分事实与推断」「口径卡的写法」这类工作方法写成 Skill,挂载到节点上复用。"
action={
}
/>
) : (
{skills.map((skill) => (
{skill.name}
{skill.tags?.map((t) =>
{t})}
{!skill.enabled &&
已停用}
remove(skill)} />
{skill.description && {skill.description}
}
{skill.instructions}
))}
)}
{editing && (
setEditing(null)}
onSaved={async (name) => { setEditing(null); await refresh(); toast.ok(`已保存 Skill「${name}」`) }} />
)}
)
}
/** 「质量,工艺」「质量,工艺」都拆成两个标签 */
const splitTags = (raw: string) => raw.split(/[,,、]/).map((s) => s.trim()).filter(Boolean)
/**
* 标签输入:回车或逗号(中英文都认)生成一个标签,退格删最后一个。
*
* 以前 value 是 tags.join(',')、onChange 当场 split,刚敲下的逗号立刻被吃掉,
* 逐字输入「质量,工艺」得到的是「质量工艺」一个标签。现在输入框保留原文,
* 遇到分隔符才收成标签;组字期间不收(拼音里没有逗号,但选词的回车不能当提交)。
*/
function TagInput({ id, tags, text, onTags, onText, suggestions }: {
id?: string
tags: string[]
text: string
onTags: (tags: string[]) => void
onText: (text: string) => void
suggestions: string[]
}) {
const commit = (raw: string) => {
const parts = splitTags(raw)
if (parts.length) onTags([...new Set([...tags, ...parts])])
onText('')
}
return (
(e.currentTarget.querySelector('input') as HTMLInputElement | null)?.focus()}>
{tags.map((t) => (
{t}
))}
{
const v = e.target.value
const composing = (e.nativeEvent as InputEvent).isComposing
if (!composing && /[,,、]/.test(v)) {
// 分隔符前面的收成标签,最后一个分隔符后面的留在框里接着敲
const cut = Math.max(v.lastIndexOf(','), v.lastIndexOf(','), v.lastIndexOf('、'))
const parts = splitTags(v.slice(0, cut))
if (parts.length) onTags([...new Set([...tags, ...parts])])
onText(v.slice(cut + 1))
} else {
onText(v)
}
}}
onKeyDown={(e) => {
if (isComposing(e)) return
if (e.key === 'Enter') { e.preventDefault(); commit(text) }
else if (e.key === 'Backspace' && !text && tags.length) onTags(tags.slice(0, -1))
}}
onBlur={() => { if (text.trim()) commit(text) }}
/>
)
}
function SkillEditor({ skill, onClose, onSaved }: {
skill: Partial; onClose: () => void; onSaved: (name: string) => void
}) {
const skills = useCatalog((s) => s.skills)
const [initial] = useState(() => ({
name: skill.name ?? '', description: skill.description ?? '',
instructions: skill.instructions ?? '', tags: skill.tags ?? [],
examples: skill.examples ?? [], suggested_tools: skill.suggested_tools ?? [],
enabled: skill.enabled ?? true,
}))
const [form, setForm] = useState(initial)
const [tagText, setTagText] = useState('')
const [busy, setBusy] = useState(false)
const suggestions = [...new Set(skills.flatMap((s) => s.tags ?? []))]
const dirty = JSON.stringify(form) !== JSON.stringify(initial) || !!tagText.trim()
const submit = async () => {
if (!form.name.trim() || busy) return
setBusy(true)
// 框里还没收成标签的那半截也算上:点保存之前不必先按回车
const body = { ...form, tags: [...new Set([...form.tags, ...splitTags(tagText)])] }
try {
if (skill.id) await api.skills.update(skill.id, body)
else await api.skills.create(body)
onSaved(body.name)
} catch (e) {
toast.error(e)
} finally {
setBusy(false)
}
}
return (
>}>
{(p) => setForm({ ...form, name: e.target.value })} />}
{(p) => (
setForm({ ...form, description: e.target.value })} />
)}
{(p) => (
setForm((f: any) => ({ ...f, tags }))} onText={setTagText} />
)
}