merge: integrate dev into main

This commit is contained in:
2026-10-16 20:33:13 +08:00
110 changed files with 10707 additions and 142 deletions
+1608
View File
File diff suppressed because it is too large Load Diff
+21 -4
View File
@@ -1,6 +1,23 @@
{
"name": "nalati-rag-frontend", "private": true, "version": "0.1.0", "type": "module",
"scripts": {"dev": "vite", "build": "vue-tsc -b && vite build", "preview": "vite preview"},
"dependencies": {"lucide-vue-next": "^0.468.0", "vue": "^3.5.13"},
"devDependencies": {"@types/node": "^22.10.2", "@vitejs/plugin-vue": "^5.2.1", "typescript": "~5.7.2", "vite": "^6.0.5", "vue-tsc": "^2.2.0"}
"name": "nalati-rag-frontend",
"private": true,
"version": "0.1.0",
"type": "module",
"scripts": {
"dev": "vite",
"build": "vue-tsc -b && vite build",
"preview": "vite preview"
},
"dependencies": {
"lucide-vue-next": "^0.468.0",
"vue": "^3.5.13",
"vue-router": "^4.6.4"
},
"devDependencies": {
"@types/node": "^22.10.2",
"@vitejs/plugin-vue": "^5.2.1",
"typescript": "~5.7.2",
"vite": "^6.0.5",
"vue-tsc": "^2.2.0"
}
}
+22 -11
View File
@@ -1,20 +1,31 @@
<script setup lang="ts">
import { computed, onMounted, ref } from 'vue'
import { computed, onMounted, ref, watch } from 'vue'
import { Activity, BookOpen, Bot, CheckCircle2, ChevronRight, Database, FileText, Globe2, Link2, MessageSquareText, Plus, Search, Send, ShieldCheck, Sparkles, AlertCircle } from 'lucide-vue-next'
import { askQuestion, createKnowledge, getHealth, getKnowledge } from './api'
import { createKnowledge, createSource, getHealth, getKnowledge, getSources, type SourceItem } from './api'
import { retrieveHybrid } from './services/hybrid'
import { getCurrentUser } from './services/auth'
import { useRouter } from 'vue-router'
import type { SessionUser } from './types/auth'
type Page='chat'|'knowledge'|'sources'|'evaluation'
const page=ref<Page>('chat'), apiStatus=ref('检测中'), question=ref(''), busy=ref(false), search=ref(''), showForm=ref(false), error=ref(''), notice=ref('')
const messages=ref([{role:'assistant',content:'你好!我是边疆红驿文旅问答原型。当前后端仅为基础接口,尚未接入知识检索和大语言模型。'}] as {role:string;content:string;sources?:{title:string;source_url?:string}[]}[])
const router=useRouter(),currentUser=ref<SessionUser>(),page=ref<Page>('chat'), apiStatus=ref('检测中'), question=ref(''), busy=ref(false), search=ref(''), showForm=ref(false), error=ref(''), notice=ref('')
const messages=ref([{role:'assistant',content:'你好!我是边疆红驿文旅问答原型。当前后端仅为基础接口,尚未接入知识检索和大语言模型。'}] as {role:string;content:string;sources?:{title:string;source_url?:string|null}[]}[])
const items=ref<any[]>([]), form=ref({title:'',category:'旅游资源',content:'',source_url:''})
const nav=[{id:'chat',label:'智能问答',icon:MessageSquareText},{id:'knowledge',label:'知识库管理',icon:Database},{id:'sources',label:'来源与更新',icon:Globe2},{id:'evaluation',label:'实验评估',icon:Activity}] as const
const sources=ref<SourceItem[]>([]), sourceSearch=ref(''), showSourceForm=ref(false), sourceForm=ref({name:'',source_url:'',notes:''})
const nav=[{id:'chat',label:'智能问答',icon:MessageSquareText},{id:'knowledge',label:'知识库管理',icon:Database,adminOnly:true},{id:'sources',label:'来源与更新',icon:Globe2,adminOnly:true},{id:'evaluation',label:'实验评估',icon:Activity,adminOnly:true}] as const
const visibleNav=computed(()=>nav.filter(item=>!('adminOnly' in item)||!item.adminOnly||currentUser.value?.role==='admin'))
const filtered=computed(()=>items.value.filter(x=>`${x.title} ${x.category} ${x.content}`.toLowerCase().includes(search.value.toLowerCase())))
async function refresh(){try{items.value=await getKnowledge();error.value=''}catch{error.value='无法读取后端知识库,请确认 API 和 PostgreSQL 已启动。'}}
onMounted(async()=>{try{await getHealth();apiStatus.value='已连接'}catch{apiStatus.value='未连接'}await refresh()})
async function send(){const q=question.value.trim();if(!q||busy.value)return;messages.value.push({role:'user',content:q});question.value='';busy.value=true;try{const r=await askQuestion(q);messages.value.push({role:'assistant',content:r.answer,sources:r.sources})}catch{messages.value.push({role:'assistant',content:'暂时无法连接后端 API。请确认 FastAPI 已启动。'})}finally{busy.value=false}}
async function save(){error.value='';notice.value='';try{await createKnowledge({...form.value,...(form.value.source_url?{source_url:form.value.source_url}:{})});form.value={title:'',category:'旅游资源',content:'',source_url:''};showForm.value=false;notice.value='已保存为待审核条目,尚未进入检索索引。';await refresh()}catch(e){error.value=e instanceof Error?e.message:'保存失败'}}
async function refreshSources(){try{sources.value=(await getSources(sourceSearch.value)).items;error.value=''}catch{error.value='无法读取来源列表,请确认 API 和 PostgreSQL 已启动。'}}
async function saveSource(){error.value='';notice.value='';if(!sourceForm.value.name.trim()){error.value='请填写来源名称。';return}if(!validUrl(sourceForm.value.source_url)){error.value='来源网址必须是有效的 http(s) 地址。';return}try{await createSource({...sourceForm.value,name:sourceForm.value.name.trim(),...(sourceForm.value.source_url?{source_url:sourceForm.value.source_url}:{})});sourceForm.value={name:'',source_url:'',notes:''};showSourceForm.value=false;notice.value='来源已登记,可继续创建关联文档和知识条目。';await refreshSources()}catch(e){error.value=e instanceof Error?e.message:'保存失败'}}
let sourceSearchTimer:number|undefined
watch(sourceSearch,()=>{window.clearTimeout(sourceSearchTimer);sourceSearchTimer=window.setTimeout(refreshSources,260)})
onMounted(async()=>{try{currentUser.value=await getCurrentUser()}catch{router.replace('/login');return}try{await getHealth();apiStatus.value='已连接'}catch{apiStatus.value='未连接'}if(currentUser.value.role==='admin')await Promise.all([refresh(),refreshSources()])})
async function send(){const q=question.value.trim();if(!q||busy.value)return;messages.value.push({role:'user',content:q});question.value='';busy.value=true;try{const r=await retrieveHybrid({query:q,top_k:5,candidate_k:50});const content=r.status==='no_evidence'?'未检索到可用的已核验知识依据。请调整问题或补充审核后的资料。':`已通过 RRF 混合检索命中 ${r.total_hits} 条依据(关键词 ${r.lexical_total_hits},向量 ${r.vector_total_hits},${r.elapsed_ms.toFixed(1)} ms)。当前仅展示检索证据,尚未接入大语言模型生成回答。`;messages.value.push({role:'assistant',content,sources:r.results.map(hit=>({title:`${hit.title}:${hit.snippet}`,source_url:hit.source_url}))})}catch(e){messages.value.push({role:'assistant',content:e instanceof Error?e.message:'暂时无法连接混合检索服务。'})}finally{busy.value=false}}
function validUrl(value:string){try{if(value)new URL(value);return true}catch{return false}}
async function save(){error.value='';notice.value='';if(!form.value.title.trim()||!form.value.content.trim()){error.value='请填写知识标题和正文。';return}if(!validUrl(form.value.source_url)){error.value='来源网址必须是有效的 http(s) 地址。';return}try{await createKnowledge({...form.value,title:form.value.title.trim(),content:form.value.content.trim(),...(form.value.source_url?{source_url:form.value.source_url}:{})});form.value={title:'',category:'旅游资源',content:'',source_url:''};showForm.value=false;notice.value='已保存为待审核条目,尚未进入检索索引。';await refresh()}catch(e){error.value=e instanceof Error?e.message:'保存失败'}}
</script>
<template><div class="shell"><aside class="sidebar"><div class="brand"><div class="mark"><Bot :size="23"/></div><div><b>边疆红驿</b><small>NALATI KNOWLEDGE HUB</small></div></div><p class="muted label">工作空间</p><nav><button v-for="n in nav" :key="n.id" :class="{active:page===n.id}" @click="page=n.id"><component :is="n.icon" :size="18"/>{{n.label}}<ChevronRight v-if="page===n.id" class="chev" :size="15"/></button></nav><div class="side-bottom"><div class="tip"><ShieldCheck :size="17"/><div><b>可信知识服务</b><p>优先展示可核验来源,信息不足时明确提示。</p></div></div><p class="api">● API {{apiStatus}} <span>v0.1.0</span></p></div></aside><main><header><span>边疆红驿 / {{nav.find(n=>n.id===page)?.label}}</span><div><span class="pill">● 原型阶段</span><i>研</i></div></header><section class="content">
<div v-if="page==='chat'"><div class="heading"><div><small class="eyebrow"><Sparkles :size="14"/> LOCAL KNOWLEDGE ASSISTANT</small><h1>文旅知识,问得明白</h1><p>面向那拉提文旅与民宿服务的知识问答原型</p></div><span class="chip"><ShieldCheck :size="15"/> 来源可追溯 · 设计目标</span></div><div class="chat-layout"><div class="card chat"><div class="chat-head"><div class="mark"><Bot :size="20"/></div><div><b>边疆红驿助手</b><small>问答服务原型</small></div></div><div class="messages"><div v-for="(m,i) in messages" :key="i" class="message" :class="m.role"><small>{{m.role==='assistant'?'智能助手':'你'}}</small><p>{{m.content}}</p><div v-if="m.sources?.length" class="sources"><b><Link2 :size="14"/> 参考来源</b><a v-for="s in m.sources" :key="s.title" :href="s.source_url" target="_blank">{{s.title}}</a></div></div><p v-if="busy">正在请求后端…</p></div><form class="composer" @submit.prevent="send"><textarea v-model="question" placeholder="输入你想了解的文旅问题…" rows="2" @keydown.enter.exact.prevent="send"/><div><small>当前为基础接口,尚未接入真实检索</small><button class="primary" :disabled="busy||!question.trim()"><Send :size="15"/> 发送</button></div></form></div><aside class="suggest"><b><Sparkles :size="16"/> 你可以这样问</b><button @click="question='那拉提有哪些值得了解的旅游资源?'"><Globe2/>旅游资源 <ChevronRight/></button><button @click="question='有哪些经过核验的红色文化资料?'"><BookOpen/>红色文化 <ChevronRight/></button><button @click="question='民宿服务信息应如何核验?'"><ShieldCheck/>民宿服务 <ChevronRight/></button><div class="notice"><b><AlertCircle :size="15"/> 信息说明</b><p>本项目仍处于原型阶段。演示内容不代表已核验的地方文旅事实。</p></div></aside></div></div>
<template><div class="shell"><aside class="sidebar"><div class="brand"><div class="mark"><Bot :size="23"/></div><div><b>边疆红驿</b><small>NALATI KNOWLEDGE HUB</small></div></div><p class="muted label">功能列表</p><nav><button v-for="n in visibleNav" :key="n.id" :class="{active:page===n.id}" @click="page=n.id"><component :is="n.icon" :size="18"/>{{n.label}}<ChevronRight v-if="page===n.id" class="chev" :size="15"/></button><button @click="router.push('/profile')"><ShieldCheck :size="18"/>个人中心</button><button v-if="currentUser?.role==='admin'" @click="router.push('/indexes')"><Database :size="18"/>索引管理</button><button v-if="currentUser?.role==='admin'" @click="router.push('/admin')"><Activity :size="18"/>用户管理</button></nav><div class="quick-actions"><p class="muted label">快捷操作</p><button v-if="page==='knowledge'" class="side-action" @click="showForm=true"><Plus :size="16"/>新增知识</button><button v-if="page==='sources'" class="side-action" @click="showSourceForm=true"><Plus :size="16"/>新增来源</button><p v-if="page==='chat'" class="side-hint">选择示例问题,或直接开始提问。</p><p v-if="page==='evaluation'" class="side-hint">实验结果只展示真实运行数据。</p></div><div class="side-bottom"><div class="tip"><ShieldCheck :size="17"/><div><b>{{currentUser?.role==='admin'?'管理员':'已登录用户'}}</b><p>{{currentUser?.nickname||currentUser?.username||'正在载入账户'}}</p></div></div><p class="api">● API {{apiStatus}} <span>v0.1.0</span></p></div></aside><main><header><span>边疆红驿 / {{nav.find(n=>n.id===page)?.label}}</span><div><span class="pill">● {{currentUser?.role==='admin'?'管理员':'用户'}}</span><i>研</i></div></header><section class="content">
<div v-if="page==='chat'"><div class="heading"><div><small class="eyebrow"><Sparkles :size="14"/> LOCAL KNOWLEDGE ASSISTANT</small><h1>文旅知识,问得明白</h1><p>面向那拉提文旅与民宿服务的知识问答原型</p></div><span class="chip"><ShieldCheck :size="15"/> 来源可追溯 · 设计目标</span></div><div class="chat-layout"><div class="card chat"><div class="chat-head"><div class="mark"><Bot :size="20"/></div><div><b>边疆红驿助手</b><small>问答服务原型</small></div></div><div class="messages"><div v-for="(m,i) in messages" :key="i" class="message" :class="m.role"><small>{{m.role==='assistant'?'智能助手':'你'}}</small><p>{{m.content}}</p><div v-if="m.sources?.length" class="sources"><b><Link2 :size="14"/> 参考来源</b><a v-for="s in m.sources" :key="s.title" :href="s.source_url ?? undefined" target="_blank">{{s.title}}</a></div></div><p v-if="busy">正在请求后端…</p></div><form class="composer" @submit.prevent="send"><textarea v-model="question" placeholder="输入你想了解的文旅问题…" rows="2" @keydown.enter.exact.prevent="send"/><div><small>当前为基础接口,尚未接入真实检索</small><button class="primary" :disabled="busy||!question.trim()"><Send :size="15"/> 发送</button></div></form></div><aside class="suggest"><b><Sparkles :size="16"/> 你可以这样问</b><button @click="question='那拉提有哪些值得了解的旅游资源?'"><Globe2/>旅游资源 <ChevronRight/></button><button @click="question='有哪些经过核验的红色文化资料?'"><BookOpen/>红色文化 <ChevronRight/></button><button @click="question='民宿服务信息应如何核验?'"><ShieldCheck/>民宿服务 <ChevronRight/></button><div class="notice"><b><AlertCircle :size="15"/> 信息说明</b><p>本项目仍处于原型阶段。演示内容不代表已核验的地方文旅事实。</p></div></aside></div></div>
<div v-else-if="page==='knowledge'"><div class="heading"><div><small class="eyebrow"><Database :size="14"/> KNOWLEDGE MANAGEMENT</small><h1>知识库管理</h1><p>集中管理领域知识、来源和审核状态。</p></div><button class="primary" @click="showForm=!showForm"><Plus :size="16"/> 新增知识</button></div><div v-if="showForm" class="card form-card"><b>新增知识条目</b><form class="knowledge-form" @submit.prevent="save"><label>标题<input v-model="form.title" required maxlength="250"/></label><label>分类<select v-model="form.category"><option>红色文化</option><option>旅游资源</option><option>民宿服务</option><option>交通出行</option><option>其他</option></select></label><label class="wide">正文<textarea v-model="form.content" required rows="3"/></label><label class="wide">来源网址(可选)<input v-model="form.source_url" type="url" placeholder="https://..."/></label><div class="wide actions"><button type="button" class="secondary" @click="showForm=false">取消</button><button class="primary">保存条目</button></div></form></div><div class="stats"><div class="card stat"><small>知识条目</small><strong>{{items.length}}</strong><span>来自当前数据库</span></div><div class="card stat"><small>已核验</small><strong>{{items.filter(x=>x.verification_status==='verified').length}}</strong><span>需经过真实审核</span></div><div class="card stat"><small>待审核</small><strong>{{items.filter(x=>x.verification_status==='pending').length}}</strong><span>尚未进入检索索引</span></div></div><p v-if="notice" class="success">{{notice}}</p><p v-if="error" class="error">{{error}}</p><div class="card table-card"><div class="table-head"><div><b>知识条目</b><p>列表来自后端接口,不含预设真实资料。</p></div><label class="search"><Search :size="15"/><input v-model="search" placeholder="搜索知识"/></label></div><div class="scroll"><table><thead><tr><th>标题</th><th>分类</th><th>来源</th><th>状态</th><th>创建时间</th></tr></thead><tbody><tr v-for="x in filtered" :key="x.id"><td><b>{{x.title}}</b><small>{{x.content.slice(0,45)}}</small></td><td>{{x.category}}</td><td><a v-if="x.source_url" :href="x.source_url" target="_blank">打开来源</a><span v-else>未填写</span></td><td><em>{{x.verification_status==='pending'?'待审核':x.verification_status}}</em></td><td>{{new Date(x.created_at).toLocaleDateString()}}</td></tr><tr v-if="!filtered.length"><td colspan="5" class="empty">暂无条目,点击“新增知识”添加。</td></tr></tbody></table></div></div></div>
<div v-else-if="page==='sources'"><div class="heading"><div><small class="eyebrow"><Globe2 :size="14"/> SOURCE OPERATIONS</small><h1>来源与更新</h1><p>为后续网页采集、审核、向量生成和版本切换预留界面。</p></div><span class="pill">● 功能规划中</span></div><div class="notice wide"><b><AlertCircle :size="16"/> 当前状态</b><p>此页面为静态原型。尚未连接网页抓取、定时任务或 Embedding 流程,不会自动更新知识。</p></div><div class="stats"><div class="card stat"><small>来源总数</small><strong>—</strong><span>待接入</span></div><div class="card stat"><small>待处理任务</small><strong>—</strong><span>后台队列尚未实现</span></div><div class="card stat"><small>最近更新</small><strong>—</strong><span>待接入更新记录</span></div></div><div class="card roadmap"><b>后续更新流程</b><div><span>01 获取来源</span><ChevronRight/><span>02 核验内容</span><ChevronRight/><span>03 生成向量</span><ChevronRight/><span>04 发布版本</span></div></div></div>
<div v-else-if="page==='sources'"><div class="heading"><div><small class="eyebrow"><Globe2 :size="14"/> SOURCE OPERATIONS</small><h1>来源与更新</h1><p>登记可追溯来源,为文档采集和知识审核建立基础。</p></div><button class="primary" @click="showSourceForm=!showSourceForm"><Plus :size="16"/> 新增来源</button></div><div v-if="showSourceForm" class="card form-card"><b>登记来源</b><form class="knowledge-form" @submit.prevent="saveSource"><label>来源名称<input v-model="sourceForm.name" required maxlength="250" placeholder="例如:那拉提景区官网"/></label><label>来源网址(可选)<input v-model="sourceForm.source_url" type="url" placeholder="https://..."/></label><label class="wide">备注<textarea v-model="sourceForm.notes" rows="3" placeholder="记录来源用途、可靠性判断或待核验事项"/></label><div class="wide actions"><button type="button" class="secondary" @click="showSourceForm=false">取消</button><button class="primary">保存来源</button></div></form></div><p v-if="notice" class="success">{{notice}}</p><p v-if="error" class="error">{{error}}</p><div class="stats"><div class="card stat"><small>来源总数</small><strong>{{sources.length}}</strong><span>来自当前数据库</span></div><div class="card stat"><small>关联文档</small><strong>—</strong><span>文档工作台待接入</span></div><div class="card stat"><small>自动更新</small><strong class="pending">未启用</strong><span>当前不会自动抓取网页</span></div></div><div class="card table-card"><div class="table-head"><div><b>已登记来源</b><p>来源不是审核通过的证明,关键事实仍需交叉核验。</p></div><label class="search"><Search :size="15"/><input v-model="sourceSearch" placeholder="搜索名称或备注" @keyup.enter="refreshSources"/></label></div><div class="scroll"><table><thead><tr><th>名称</th><th>网址</th><th>备注</th><th>登记时间</th></tr></thead><tbody><tr v-for="source in sources" :key="source.id"><td><b>{{source.name}}</b></td><td><a v-if="source.source_url" :href="source.source_url" target="_blank" rel="noreferrer">打开来源</a><span v-else>未填写</span></td><td>{{source.notes||'—'}}</td><td>{{new Date(source.created_at).toLocaleDateString()}}</td></tr><tr v-if="!sources.length"><td colspan="4" class="empty">暂无来源,点击“新增来源”登记。</td></tr></tbody></table></div></div><div class="card roadmap"><b>来源处理边界</b><div><span>01 登记来源</span><ChevronRight/><span>02 人工核验</span><ChevronRight/><span>03 关联文档</span><ChevronRight/><span>04 后续检索</span></div></div></div>
<div v-else><div class="heading"><div><small class="eyebrow"><Activity :size="14"/> EVALUATION WORKSPACE</small><h1>实验评估</h1><p>展示实验方案与指标规划;当前不显示虚构实验结果。</p></div><span class="pill">● 尚未开展实验</span></div><div class="notice wide"><b><ShieldCheck :size="16"/> 实验原则</b><p>所有指标应来自真实测试问题、运行日志和明确的人工评分规则。下方仅列评价维度,不包含实验数值。</p></div><div class="stats"><div class="card stat"><small>回答正确性</small><strong class="pending">待测试</strong><span>依据人工评分规范</span></div><div class="card stat"><small>来源可追溯性</small><strong class="pending">待测试</strong><span>核对来源是否支持答案</span></div><div class="card stat"><small>响应时间与成本</small><strong class="pending">待测试</strong><span>记录耗时与实际费用</span></div></div><div class="card roadmap"><b>计划中的对照方案</b><div class="methods"><p><b>A 基础大语言模型</b><span>不提供项目知识库检索结果</span></p><p><b>B 关键词检索 RAG</b><span>关键词检索后生成答案</span></p><p><b>C 混合检索 RAG</b><span>融合关键词与向量语义检索</span></p></div></div></div><footer>边疆红驿 · 那拉提文旅智能问答 <span>工程原型 v0.1.0 · 尚非完整系统</span></footer></section></main></div></template>
+2
View File
@@ -0,0 +1,2 @@
<script setup lang="ts">import { RouterView } from 'vue-router';</script>
<template><RouterView/></template>
+24 -4
View File
@@ -1,4 +1,24 @@
export async function getHealth(){const r=await fetch('/api/health');if(!r.ok)throw new Error('health failed');return r.json()}
export async function askQuestion(question:string){const r=await fetch('/api/chat',{method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify({question})});if(!r.ok)throw new Error('chat failed');return r.json() as Promise<{answer:string;status:string;sources:{title:string;source_url?:string|null}[]}>}
export async function getKnowledge(){const r=await fetch('/api/knowledge');if(!r.ok)throw new Error('knowledge failed');return r.json() as Promise<any[]>}
export async function createKnowledge(payload:{title:string;category:string;content:string;source_url?:string}){const r=await fetch('/api/knowledge',{method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify(payload)});if(!r.ok)throw new Error('保存失败,请检查网址格式及后端状态');return r.json()}
import { apiRequest } from './services/session'
import type { VectorRetrievalResult } from './services/vectors'
import type { ChunkKeywordResult, HybridResult } from './services/hybrid'
export const getHealth = () => apiRequest<{status:string}>('/api/health')
export const askQuestion = (question:string) => apiRequest<{answer:string;status:string;sources:{title:string;source_url?:string|null}[]}>('/api/chat',{method:'POST',body:JSON.stringify({question})})
export const getKnowledge = () => apiRequest<{id:number;title:string;category:string;content:string;source_url:string|null;verification_status:string;version:number}[]>('/api/knowledge')
export const createKnowledge = (payload:{title:string;category:string;content:string;source_url?:string}) => apiRequest('/api/knowledge',{method:'POST',body:JSON.stringify(payload)},true)
export type VerificationStatus='pending'|'verified'|'rejected'
export type SourceItem={id:number;version:number;name:string;source_url:string|null;notes:string;created_at:string}
export function getSources(q=''){return apiRequest<{items:SourceItem[];total:number}>(`/api/sources?q=${encodeURIComponent(q)}`)}
export function createSource(payload:{name:string;source_url?:string;notes:string}){return apiRequest<SourceItem>('/api/sources',{method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify(payload)},true)}
export function reviewKnowledge(id:number,payload:{expected_version:number;verification_status:VerificationStatus;reviewer:string;verification_notes:string}){return apiRequest(`/api/knowledge/${id}/review`,{method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify(payload)},true)}
export type DocumentItem={id:number;version:number;source_id:number;title:string;category:string;content:string;collected_at:string;notes:string;created_at:string;updated_at:string;is_deleted:boolean}
export function getDocuments(q='',page=1,pageSize=20){return apiRequest<{items:DocumentItem[];total:number;page:number;page_size:number}>(`/api/documents?q=${encodeURIComponent(q)}&page=${page}&page_size=${pageSize}`)}
export function createDocument(payload:{source_id:number;title:string;category:string;content:string;collected_at:string;notes?:string}){return apiRequest<DocumentItem>('/api/documents',{method:'POST',body:JSON.stringify(payload)},true)}
export type RetrievalHit={rank:number;knowledge_id:number;knowledge_version:number;document_id:number|null;document_version:number|null;source_id:number|null;source_version:number|null;source_name:string|null;source_url:string;title:string;category:string;snippet:string;snippet_start:number;snippet_end:number;score:number;matched_terms:string[]}
export type RetrievalResult={run_id:string;query:string;mode:'keyword';status:'ok'|'no_evidence';top_k:number;category:string|null;query_terms:string[];corpus_size:number;corpus_fingerprint:string;total_hits:number;results:RetrievalHit[];elapsed_ms:number;created_at:string;config:{tokenizer:string;scorer:string;k1:number;b:number;title_weight:number;stopwords_version:string}}
export function retrieveKnowledge(payload:{query:string;mode?:'keyword';top_k?:number;category?:string}){return apiRequest<RetrievalResult>('/api/retrieval',{method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify(payload)})}
export type RetrievalRunResult = RetrievalResult | VectorRetrievalResult | ChunkKeywordResult | HybridResult
export function getRetrievalRun(runId:string){return apiRequest<RetrievalRunResult>(`/api/retrieval/runs/${encodeURIComponent(runId)}`)}
export function getRetrievalRuns(page=1,pageSize=20){return apiRequest<{items:RetrievalRunResult[];total:number;page:number;page_size:number}>(`/api/retrieval/runs?page=${page}&page_size=${pageSize}`)}
+2
View File
@@ -0,0 +1,2 @@
.search:focus-within{border-color:#8eaa91;box-shadow:0 0 0 3px #dcebdc}.knowledge-form input:focus,.knowledge-form select:focus,.knowledge-form textarea:focus{border-color:#7e9f83;box-shadow:0 0 0 3px #e4f0e4}.table-card tbody tr{transition:background .15s ease}.table-card tbody tr:hover{background:#fafbf7}.success,.error{animation:feedback-in .2s ease-out}@keyframes feedback-in{from{opacity:0;transform:translateY(-4px)}to{opacity:1;transform:translateY(0)}}
.quick-actions{margin-top:18px}.quick-actions .label{margin:0 0 8px}.side-action{width:100%;display:flex;align-items:center;gap:8px;border:1px solid #dbe6da;border-radius:9px;padding:10px 12px;background:#f1f7ef;color:#355c48;font-size:11px;font-weight:600}.side-action:hover{background:#e2efdf}.side-hint{margin:0 10px;color:#8a9086;font-size:10px;line-height:1.7}.heading>.primary{display:none}
+4 -2
View File
@@ -1,4 +1,6 @@
import { createApp } from 'vue'
import './style.css'
import App from './App.vue'
createApp(App).mount('#app')
import './enhancements.css'
import Root from './Root.vue'
import router from './router'
createApp(Root).use(router).mount('#app')
+19
View File
@@ -0,0 +1,19 @@
import { createRouter, createWebHistory } from 'vue-router'
import App from './App.vue'
import { getCurrentUser } from './services/auth'
import type { UserRole } from './types/auth'
let role:UserRole|undefined
const router=createRouter({history:createWebHistory(),routes:[
{path:'/',component:App},
{path:'/login',component:()=>import('./views/LoginView.vue'),meta:{public:true}},
{path:'/register',component:()=>import('./views/RegisterView.vue'),meta:{public:true}},
{path:'/profile',component:()=>import('./views/ProfileView.vue')},
{path:'/settings',component:()=>import('./views/AccountSettingsView.vue')},
{path:'/indexes',component:()=>import('./views/IndexManagementView.vue'),meta:{role:'admin'}},
{path:'/reviews',component:()=>import('./views/KnowledgeReviewView.vue'),meta:{role:'admin'}},
{path:'/documents',component:()=>import('./views/DocumentManagementView.vue'),meta:{role:'admin'}},
{path:'/admin',component:()=>import('./views/AdminView.vue'),meta:{role:'admin'}},
]})
router.beforeEach(async to=>{if(to.meta.public)return true;try{role=(await getCurrentUser()).role}catch{return {path:'/login',query:{redirect:to.fullPath}}}if(to.meta.role&&role!==to.meta.role)return {path:'/profile',query:{forbidden:'1'}};return true})
export default router
+17 -23
View File
@@ -1,26 +1,20 @@
import type { ChangePasswordPayload, CurrentUser, LoginPayload, RegisterPayload, UpdateProfilePayload } from '../types/auth'
import type { ChangePasswordPayload, CurrentUser, LoginPayload, RegisterPayload, SessionUser, UpdateProfilePayload } from '../types/auth'
import { apiRequest, ApiError, clearSessionToken } from './session'
export class AuthApiUnavailableError extends Error {
constructor(public readonly status: number, message: string) { super(message) }
export { ApiError as AuthApiUnavailableError }
export const register = (payload: RegisterPayload) => apiRequest<CurrentUser>('/api/auth/register', { method: 'POST', body: JSON.stringify(payload) })
export const login = async (payload: LoginPayload) => {
clearSessionToken()
return apiRequest<SessionUser>('/api/auth/login', { method: 'POST', body: JSON.stringify(payload) })
}
async function authRequest<T>(path: string, init: RequestInit = {}): Promise<T> {
const response = await fetch(path, {
credentials: 'include',
headers: { Accept: 'application/json', 'Content-Type': 'application/json', ...init.headers },
...init,
})
if (!response.ok) {
const body = await response.json().catch(() => null)
throw new AuthApiUnavailableError(response.status, body?.detail || `认证请求失败(${response.status})`)
}
return response.status === 204 ? undefined as T : response.json() as Promise<T>
export const getCurrentUser = () => apiRequest<SessionUser>('/api/auth/me')
export const updateMyProfile = (payload: UpdateProfilePayload) => apiRequest<CurrentUser>('/api/users/me', { method: 'PATCH', body: JSON.stringify(payload) }, true)
export const logout = async () => {
await apiRequest<void>('/api/auth/logout', { method: 'POST' }, true)
clearSessionToken()
}
export const register = (payload: RegisterPayload) => authRequest<CurrentUser>('/api/auth/register', { method: 'POST', body: JSON.stringify(payload) })
export const login = (payload: LoginPayload) => authRequest<CurrentUser>('/api/auth/login', { method: 'POST', body: JSON.stringify(payload) })
export const logout = () => authRequest<void>('/api/auth/logout', { method: 'POST' })
export const getCurrentUser = () => authRequest<CurrentUser>('/api/auth/me')
export const updateMyProfile = (payload: UpdateProfilePayload) => authRequest<CurrentUser>('/api/users/me', { method: 'PATCH', body: JSON.stringify(payload) })
export const changePassword = (payload: ChangePasswordPayload) => authRequest<void>('/api/auth/change-password', { method: 'POST', body: JSON.stringify(payload) })
export const getUsers = () => authRequest<CurrentUser[]>('/api/admin/users')
export const changePassword = async (payload: ChangePasswordPayload) => {
await apiRequest<void>('/api/auth/change-password', { method: 'POST', body: JSON.stringify(payload) }, true)
clearSessionToken()
}
export const getUsers = (limit = 100, offset = 0) => apiRequest<CurrentUser[]>(`/api/admin/users?limit=${limit}&offset=${offset}`)
+19
View File
@@ -0,0 +1,19 @@
import { apiRequest } from './session'
import type { RetrievalHit, RetrievalResult } from '../api'
import type { IndexVersion } from './indexes'
import type { EmbeddingSpace } from './vectors'
type ChunkHit = RetrievalHit & { chunk_id: string; chunk_ordinal: number }
type ChunkConfig = { ranking_unit: 'chunk'; lexical: RetrievalResult['config']; chunking: IndexVersion['config']; tie_break: 'knowledge_id,chunk_ordinal,chunk_id' }
type ChunkSnapshot = { run_id: string; query: string; status: 'ok' | 'no_evidence'; top_k: number; category: string | null; query_terms: string[]; text_index_version_id: string; text_generation: number; catalog_revision: number; corpus_fingerprint: string; corpus_size: number; total_hits: number; elapsed_ms: number; created_at: string }
export type ChunkKeywordResult = ChunkSnapshot & { mode: 'keyword_chunks'; results: ChunkHit[]; config: ChunkConfig }
export type RankedCandidate = { chunk_id: string; rank: number; score: number }
export type HybridResult = ChunkSnapshot & {
mode: 'hybrid'; vector_version_id: string; generation: number; lexical_total_hits: number; vector_total_hits: number;
lexical_candidates: RankedCandidate[]; vector_candidates: RankedCandidate[];
results: (ChunkHit & { lexical_rank: number | null; lexical_score: number | null; vector_rank: number | null; vector_score: number | null; lexical_contribution: number; vector_contribution: number })[];
config: ChunkConfig & { scorer: 'rrf-v1'; rrf_k: 60; weights: [1, 1]; candidate_k: number; vector_scorer: 'pgvector-cosine-exact-v1'; space: EmbeddingSpace }
}
type Request = { query: string; top_k?: number; category?: string }
export const retrieveKeywordChunks = (payload: Request & { mode?: 'keyword_chunks' }) => apiRequest<ChunkKeywordResult>('/api/retrieval/chunks', { method: 'POST', body: JSON.stringify(payload) })
export const retrieveHybrid = (payload: Request & { mode?: 'hybrid'; candidate_k?: number }) => apiRequest<HybridResult>('/api/retrieval/hybrid', { method: 'POST', body: JSON.stringify(payload) })
+16
View File
@@ -0,0 +1,16 @@
import { apiRequest } from './session'
import type { RetrievalHit } from '../api'
type Page<T> = { items: T[]; total: number; page: number; page_size: number }
export type IndexConfig = { splitter: 'unicode-window-v1'; chunk_size: number; overlap: number }
export type IndexVersion = { id: string; status: 'ready' | 'published' | 'superseded'; config: IndexConfig; corpus_fingerprint: string; catalog_revision: number; item_count: number; chunk_count: number; created_by: number; created_at: string; published_at: string | null }
export type ActiveIndex = { generation: number; catalog_revision: number; is_current: boolean; active_version: IndexVersion | null }
export type Chunk = { id: string; index_version_id: string; knowledge_id: number; ordinal: number; start_offset: number; end_offset: number; text: string; text_sha256: string; provenance: Pick<RetrievalHit, 'knowledge_id' | 'knowledge_version' | 'document_id' | 'document_version' | 'source_id' | 'source_version' | 'source_name' | 'source_url' | 'title' | 'category'> }
export type IndexPublication = { generation: number; previous_version_id: string | null; version_id: string; actor_id: number; published_at: string }
export const buildIndex = (config: Partial<Pick<IndexConfig, 'chunk_size' | 'overlap'>> = {}) => apiRequest<IndexVersion>('/api/indexes', { method: 'POST', body: JSON.stringify(config) }, true)
export const getActiveIndex = () => apiRequest<ActiveIndex>('/api/indexes/active')
export const getIndexVersions = (page = 1, pageSize = 20) => apiRequest<Page<IndexVersion>>(`/api/indexes?page=${page}&page_size=${pageSize}`)
export const getIndexVersion = (id: string) => apiRequest<IndexVersion>(`/api/indexes/${encodeURIComponent(id)}`)
export const publishIndex = (id: string, expectedGeneration: number) => apiRequest<ActiveIndex>(`/api/indexes/${encodeURIComponent(id)}/publish`, { method: 'POST', body: JSON.stringify({ expected_generation: expectedGeneration }) }, true)
export const getChunks = (id: string, page = 1, pageSize = 20, knowledgeId?: number) => apiRequest<Page<Chunk>>(`/api/indexes/${encodeURIComponent(id)}/chunks?page=${page}&page_size=${pageSize}${knowledgeId ? `&knowledge_id=${knowledgeId}` : ''}`)
export const getIndexPublications = (page = 1, pageSize = 20) => apiRequest<Page<IndexPublication>>(`/api/indexes/publications?page=${page}&page_size=${pageSize}`)
+20
View File
@@ -0,0 +1,20 @@
import { apiRequest } from './session'
import type { Chunk } from './indexes'
export type CompletionOptions = { model: string; output_tokens?: number; token_parameter?: 'max_completion_tokens' | 'max_tokens'; instruction_role?: 'system' | 'developer'; temperature?: number | null }
export type PrepareRagContext = { retrieval_run_id: string; completion: CompletionOptions; max_input_characters?: number; max_evidence?: number }
export type RagEvidence = Chunk['provenance'] & { citation_id: string; chunk_id: string; chunk_ordinal: number; retrieval_rank: number; text: string; text_sha256: string; start_offset: number; end_offset: number }
export type ChatCompletionsBody = { model: string; messages: { role: 'system' | 'developer' | 'user'; content: string }[]; stream: false; n: 1; store: false; max_completion_tokens?: number; max_tokens?: number; temperature?: number }
export type RagContext = {
id: string; kind: 'prepared_request'; model_called: false; status: 'prepared' | 'insufficient_evidence';
reason: 'candidates_available' | 'no_candidates' | 'context_budget'; retrieval_run_id: string;
retrieval_mode: 'keyword_chunks' | 'vector' | 'hybrid'; query: string; text_index_version_id: string;
text_generation: number; catalog_revision: number; vector_version_id: string | null; vector_generation: number | null;
corpus_fingerprint: string; prompt_version: 'nalati-evidence-v1'; completion: Required<CompletionOptions>;
max_input_characters: number; input_characters: number; max_evidence: number; evidence: RagEvidence[];
excluded: { chunk_id: string; reason: 'overlap' | 'budget' | 'evidence_limit' }[];
request_body: ChatCompletionsBody | null; request_sha256: string | null; created_at: string;
}
export const prepareRagContext = (payload: PrepareRagContext) => apiRequest<RagContext>('/api/rag/contexts', { method: 'POST', body: JSON.stringify(payload) }, true)
export const getRagContext = (id: string) => apiRequest<RagContext>(`/api/rag/contexts/${encodeURIComponent(id)}`)
export const getRagContexts = (page = 1, pageSize = 20) => apiRequest<{ items: RagContext[]; total: number; page: number; page_size: number }>(`/api/rag/contexts?page=${page}&page_size=${pageSize}`)
+28
View File
@@ -0,0 +1,28 @@
let csrfToken: string | null = null
export class ApiError extends Error {
constructor(public readonly status: number, message: string) { super(message) }
}
export function clearSessionToken() { csrfToken = null }
export async function apiRequest<T>(path: string, init: RequestInit = {}, protect = false): Promise<T> {
if (protect && !csrfToken) await apiRequest('/api/auth/me')
const headers = new Headers(init.headers)
headers.set('Accept', 'application/json')
if (init.body) headers.set('Content-Type', 'application/json')
if (protect && csrfToken) headers.set('X-CSRF-Token', csrfToken)
const response = await fetch(path, { ...init, credentials: 'include', headers })
if (!response.ok) {
if (response.status === 401) clearSessionToken()
const body: unknown = await response.json().catch(() => null)
const detail = body && typeof body === 'object' && 'detail' in body ? body.detail : null
throw new ApiError(response.status, typeof detail === 'string' ? detail : `请求失败(${response.status}),请检查登录状态或填写内容。`)
}
if (response.status === 204) return undefined as T
const data = await response.json()
if (path === '/api/auth/login' || path === '/api/auth/me') {
csrfToken = typeof data.csrf_token === 'string' ? data.csrf_token : null
}
return data as T
}
+18
View File
@@ -0,0 +1,18 @@
import { apiRequest } from './session'
import type { RetrievalHit } from '../api'
import type { IndexPublication } from './indexes'
type Page<T> = { items: T[]; total: number; page: number; page_size: number }
export type EmbeddingSpec = { model: string; revision: string; dimension: number; token_limit: number; query_instruction: string; implementation: string; checkpoint_format: string }
export type EmbeddingSpace = { id: string; dimension: number; spec: EmbeddingSpec }
export type VectorVersion = { id: string; text_index_version_id: string; space_id: string; dimension: number; chunk_count: number; status: 'ready' | 'published' | 'superseded'; created_by: number; created_at: string; published_at: string | null }
export type ActiveVectors = { generation: number; text_generation: number; catalog_revision: number; is_current: boolean; active_version: VectorVersion | null }
export type VectorRetrievalResult = { run_id: string; query: string; mode: 'vector'; status: 'ok' | 'no_evidence'; top_k: number; category: string | null; vector_version_id: string; text_index_version_id: string; generation: number; text_generation: number; corpus_fingerprint: string; corpus_size: number; total_hits: number; results: (RetrievalHit & { chunk_id: string; chunk_ordinal: number })[]; elapsed_ms: number; created_at: string; config: { scorer: 'pgvector-cosine-exact-v1'; ranking_unit: 'chunk'; space: EmbeddingSpace } }
export const buildVectorIndex = (textIndexVersionId: string) => apiRequest<VectorVersion>('/api/vector-indexes', { method: 'POST', body: JSON.stringify({ text_index_version_id: textIndexVersionId }) }, true)
export const getVectorVersions = (page = 1, pageSize = 20) => apiRequest<Page<VectorVersion>>(`/api/vector-indexes?page=${page}&page_size=${pageSize}`)
export const getVectorVersion = (id: string) => apiRequest<VectorVersion>(`/api/vector-indexes/${encodeURIComponent(id)}`)
export const getActiveVectors = () => apiRequest<ActiveVectors>('/api/vector-indexes/active')
export const getEmbeddingSpaces = (page = 1, pageSize = 20) => apiRequest<Page<EmbeddingSpace>>(`/api/vector-indexes/spaces?page=${page}&page_size=${pageSize}`)
export const publishVectorIndex = (id: string, expectedGeneration: number) => apiRequest<ActiveVectors>(`/api/vector-indexes/${encodeURIComponent(id)}/publish`, { method: 'POST', body: JSON.stringify({ expected_generation: expectedGeneration }) }, true)
export const getVectorPublications = (page = 1, pageSize = 20) => apiRequest<Page<IndexPublication>>(`/api/vector-indexes/publications?page=${page}&page_size=${pageSize}`)
export const retrieveVectors = (payload: { query: string; mode?: 'vector'; top_k?: number; category?: string }) => apiRequest<VectorRetrievalResult>('/api/retrieval/vector', { method: 'POST', body: JSON.stringify(payload) })
+3 -5
View File
@@ -1,16 +1,14 @@
export type UserRole = 'user' | 'admin'
export type CurrentUser = {
id: number
username: string
nickname: string | null
email: string | null
role: UserRole
created_at?: string
conversation_count?: number
created_at: string
}
export type SessionUser = CurrentUser & { csrf_token: string }
export type RegisterPayload = { username: string; password: string; email?: string; nickname?: string }
export type LoginPayload = { username: string; password: string }
export type UpdateProfilePayload = { nickname?: string; email?: string }
export type UpdateProfilePayload = { nickname?: string | null; email?: string | null }
export type ChangePasswordPayload = { current_password: string; new_password: string }
+94 -6
View File
@@ -1,8 +1,96 @@
<script setup lang="ts">
import { ref } from 'vue'
import { changePassword, updateMyProfile } from '../services/auth'
const nickname=ref(''), email=ref(''), currentPassword=ref(''), newPassword=ref(''), notice=ref(''), error=ref('')
async function saveProfile(){try{await updateMyProfile({nickname:nickname.value||undefined,email:email.value||undefined});notice.value='资料已更新。'}catch(e){error.value=e instanceof Error?e.message:'更新失败'}}
async function savePassword(){try{if(newPassword.value.length<8)throw new Error('新密码至少 8 位。');await changePassword({current_password:currentPassword.value,new_password:newPassword.value});notice.value='密码已更新。'}catch(e){error.value=e instanceof Error?e.message:'修改失败'}}
import { onMounted, ref } from 'vue'
import { useRouter } from 'vue-router'
import { changePassword, getCurrentUser, updateMyProfile } from '../services/auth'
import type { SessionUser } from '../types/auth'
const router = useRouter()
const user = ref<SessionUser>()
const profile = ref({ nickname: '', email: '' })
const password = ref({ current_password: '', new_password: '', confirm_password: '' })
const loading = ref(true)
const savingProfile = ref(false)
const savingPassword = ref(false)
const error = ref('')
const success = ref('')
onMounted(async () => {
try {
user.value = await getCurrentUser()
profile.value = { nickname: user.value.nickname ?? '', email: user.value.email ?? '' }
} catch (cause) {
error.value = cause instanceof Error ? cause.message : '无法读取账户资料'
} finally {
loading.value = false
}
})
async function saveProfile() {
error.value = ''
success.value = ''
if (profile.value.email && !/^\S+@\S+\.\S+$/.test(profile.value.email)) {
error.value = '请输入有效邮箱地址。'
return
}
savingProfile.value = true
try {
const updated = await updateMyProfile({ nickname: profile.value.nickname || null, email: profile.value.email || null })
if (user.value) user.value = { ...user.value, ...updated }
success.value = '基本资料已保存。'
} catch (cause) {
error.value = cause instanceof Error ? cause.message : '保存资料失败'
} finally {
savingProfile.value = false
}
}
async function savePassword() {
error.value = ''
success.value = ''
if (password.value.new_password.length < 15) {
error.value = '新密码至少需要 15 个字符。'
return
}
if (password.value.new_password !== password.value.confirm_password) {
error.value = '两次输入的新密码不一致。'
return
}
savingPassword.value = true
try {
await changePassword({ current_password: password.value.current_password, new_password: password.value.new_password })
password.value = { current_password: '', new_password: '', confirm_password: '' }
router.replace('/login?changed=1')
} catch (cause) {
error.value = cause instanceof Error ? cause.message : '修改密码失败'
} finally {
savingPassword.value = false
}
}
</script>
<template><main><h1>账户设置</h1><p v-if="notice">{{notice}}</p><p v-if="error">{{error}}</p><form @submit.prevent="saveProfile"><input v-model.trim="nickname" placeholder="昵称"/><input v-model.trim="email" type="email" placeholder="邮箱"/><button>保存资料</button></form><form @submit.prevent="savePassword"><input v-model="currentPassword" type="password" placeholder="当前密码"/><input v-model="newPassword" type="password" placeholder="新密码"/><button>修改密码</button></form></main></template>
<template>
<main>
<RouterLink to="/profile">返回个人中心</RouterLink>
<h1>账户设置</h1>
<p v-if="loading">正在读取账户资料…</p>
<template v-else>
<p v-if="error" role="alert">{{ error }}</p>
<p v-if="success" role="status">{{ success }}</p>
<form @submit.prevent="saveProfile">
<h2>基本资料</h2>
<label>用户名<input :value="user?.username" disabled /></label>
<label>昵称<input v-model.trim="profile.nickname" maxlength="80" autocomplete="nickname" /></label>
<label>邮箱<input v-model.trim="profile.email" type="email" maxlength="320" autocomplete="email" /></label>
<button :disabled="savingProfile">{{ savingProfile ? '保存中…' : '保存资料' }}</button>
</form>
<form @submit.prevent="savePassword">
<h2>修改密码</h2>
<label>当前密码<input v-model="password.current_password" type="password" required autocomplete="current-password" /></label>
<label>新密码<input v-model="password.new_password" type="password" required minlength="15" autocomplete="new-password" /></label>
<label>确认新密码<input v-model="password.confirm_password" type="password" required minlength="15" autocomplete="new-password" /></label>
<p>修改密码后会退出当前会话,请使用新密码重新登录。</p>
<button :disabled="savingPassword">{{ savingPassword ? '提交中…' : '修改密码' }}</button>
</form>
</template>
</main>
</template>
+52
View File
@@ -0,0 +1,52 @@
<script setup lang="ts">
import { onMounted, ref } from 'vue'
import { getUsers } from '../services/auth'
import type { CurrentUser } from '../types/auth'
const pageSize = 20
const users = ref<CurrentUser[]>([])
const offset = ref(0)
const loading = ref(false)
const error = ref('')
async function load(nextOffset = offset.value) {
loading.value = true
error.value = ''
try {
users.value = await getUsers(pageSize, nextOffset)
offset.value = nextOffset
} catch (cause) {
error.value = cause instanceof Error ? cause.message : '无法读取用户列表'
} finally {
loading.value = false
}
}
onMounted(() => load(0))
</script>
<template>
<main>
<h1>管理员用户管理</h1>
<p>用户数据由受服务端管理员权限保护的接口实时提供。</p>
<p><RouterLink to="/reviews">进入知识审核工作台</RouterLink> <RouterLink to="/documents">进入文档管理</RouterLink> <RouterLink to="/indexes">进入索引管理</RouterLink></p>
<p v-if="error" role="alert">{{ error }}</p>
<p v-else-if="loading">正在读取用户列表…</p>
<template v-else>
<table>
<thead><tr><th>用户名</th><th>昵称</th><th>邮箱</th><th>角色</th><th>注册时间</th></tr></thead>
<tbody>
<tr v-for="user in users" :key="user.id">
<td>{{ user.username }}</td><td>{{ user.nickname || '—' }}</td><td>{{ user.email || '—' }}</td><td>{{ user.role }}</td><td>{{ new Date(user.created_at).toLocaleString() }}</td>
</tr>
<tr v-if="!users.length"><td colspan="5">暂无用户记录。</td></tr>
</tbody>
</table>
<div>
<button :disabled="offset === 0" @click="load(Math.max(0, offset - pageSize))">上一页</button>
<span>第 {{ Math.floor(offset / pageSize) + 1 }} 页</span>
<button :disabled="users.length < pageSize" @click="load(offset + pageSize)">下一页</button>
</div>
</template>
</main>
</template>
@@ -0,0 +1,10 @@
<script setup lang="ts">
import { onMounted, ref } from 'vue'
import { createDocument, getDocuments, getSources, type DocumentItem, type SourceItem } from '../api'
const documents=ref<DocumentItem[]>([]), sources=ref<SourceItem[]>([]), query=ref(''), page=ref(1), total=ref(0), loading=ref(true), saving=ref(false), error=ref(''), notice=ref('')
const form=ref({source_id:0,title:'',category:'未分类',content:'',collected_at:new Date().toISOString().slice(0,16),notes:''})
async function refresh(next=page.value){loading.value=true;error.value='';try{const result=await getDocuments(query.value,next);documents.value=result.items;total.value=result.total;page.value=result.page;if(!sources.value.length)sources.value=(await getSources()).items}catch(cause){error.value=cause instanceof Error?cause.message:'无法读取文档'}finally{loading.value=false}}
async function submit(){error.value='';notice.value='';if(!form.value.source_id||!form.value.title.trim()||!form.value.content.trim()||!form.value.collected_at){error.value='请填写来源、标题、正文和采集时间。';return}saving.value=true;try{await createDocument({...form.value,title:form.value.title.trim(),content:form.value.content.trim(),collected_at:new Date(form.value.collected_at).toISOString()});notice.value='文档已创建,可在后续知识条目中关联并审核。';form.value={source_id:0,title:'',category:'未分类',content:'',collected_at:new Date().toISOString().slice(0,16),notes:''};await refresh(1)}catch(cause){error.value=cause instanceof Error?cause.message:'创建文档失败'}finally{saving.value=false}}
onMounted(()=>refresh(1))
</script>
<template><main><RouterLink to="/admin">返回管理员工作台</RouterLink><h1>文档管理</h1><p>文档必须关联已有来源;数据直接来自管理员受保护的 FastAPI 接口。</p><p v-if="error" role="alert">{{error}}</p><p v-if="notice" role="status">{{notice}}</p><form @submit.prevent="submit"><h2>新增文档</h2><label>来源<select v-model.number="form.source_id" required><option :value="0" disabled>请选择来源</option><option v-for="source in sources" :key="source.id" :value="source.id">{{source.name}}</option></select></label><label>标题<input v-model.trim="form.title" required maxlength="250"/></label><label>分类<input v-model.trim="form.category" required maxlength="80"/></label><label>采集时间<input v-model="form.collected_at" type="datetime-local" required/></label><label>正文<textarea v-model.trim="form.content" required maxlength="100000" rows="6"/></label><label>备注<textarea v-model.trim="form.notes" maxlength="10000" rows="2"/></label><button :disabled="saving">{{saving?'保存中…':'保存文档'}}</button></form><p v-if="loading">正在读取文档…</p><template v-else><label>搜索<input v-model="query" @keyup.enter="refresh(1)"/></label><button @click="refresh(1)">查询</button><table><thead><tr><th>标题</th><th>分类</th><th>来源 ID</th><th>采集时间</th></tr></thead><tbody><tr v-for="doc in documents" :key="doc.id"><td><b>{{doc.title}}</b><p>{{doc.content.slice(0,120)}}</p></td><td>{{doc.category}}</td><td>{{doc.source_id}}</td><td>{{new Date(doc.collected_at).toLocaleString()}}</td></tr><tr v-if="!documents.length"><td colspan="4">暂无文档。</td></tr></tbody></table><div><button :disabled="page===1" @click="refresh(page-1)">上一页</button><span>第 {{page}} 页,共 {{total}} 条</span><button :disabled="page*20>=total" @click="refresh(page+1)">下一页</button></div></template></main></template>
@@ -0,0 +1,86 @@
<script setup lang="ts">
import { onMounted, ref } from 'vue'
import { buildIndex, getActiveIndex, getIndexVersions, publishIndex, type ActiveIndex, type IndexVersion } from '../services/indexes'
import { buildVectorIndex, getActiveVectors, getVectorVersions, publishVectorIndex, type ActiveVectors, type VectorVersion } from '../services/vectors'
const textActive = ref<ActiveIndex>()
const vectorActive = ref<ActiveVectors>()
const textVersions = ref<IndexVersion[]>([])
const vectorVersions = ref<VectorVersion[]>([])
const loading = ref(true)
const buildingText = ref(false)
const buildingVector = ref<string>()
const publishing = ref<string>()
const error = ref('')
const notice = ref('')
const config = ref({ chunk_size: 800, overlap: 120 })
async function refresh() {
loading.value = true
error.value = ''
try {
const [text, texts, vectors, vectorList] = await Promise.all([getActiveIndex(), getIndexVersions(), getActiveVectors(), getVectorVersions()])
textActive.value = text
textVersions.value = texts.items
vectorActive.value = vectors
vectorVersions.value = vectorList.items
} catch (cause) {
error.value = cause instanceof Error ? cause.message : '无法读取索引状态'
} finally {
loading.value = false
}
}
async function buildText() {
error.value = ''; notice.value = ''
if (config.value.chunk_size <= 0 || config.value.overlap < 0 || config.value.overlap >= config.value.chunk_size) {
error.value = '切分长度必须大于 0,且重叠长度必须小于切分长度。'
return
}
buildingText.value = true
try {
const version = await buildIndex(config.value)
notice.value = `文本索引 ${version.id} 已构建为 ready,需确认后再发布。`
await refresh()
} catch (cause) { error.value = cause instanceof Error ? cause.message : '构建文本索引失败' } finally { buildingText.value = false }
}
async function publishText(version: IndexVersion) {
publishing.value = `text:${version.id}`; error.value = ''; notice.value = ''
try { await publishIndex(version.id, textActive.value?.generation ?? 0); notice.value = '文本索引已发布。'; await refresh() }
catch (cause) { error.value = cause instanceof Error ? cause.message : '发布文本索引失败' } finally { publishing.value = undefined }
}
async function buildVector(version: IndexVersion) {
buildingVector.value = version.id; error.value = ''; notice.value = ''
try { const created = await buildVectorIndex(version.id); notice.value = `向量索引 ${created.id} 已构建为 ready。`; await refresh() }
catch (cause) { error.value = cause instanceof Error ? cause.message : '构建向量索引失败' } finally { buildingVector.value = undefined }
}
async function publishVector(version: VectorVersion) {
publishing.value = `vector:${version.id}`; error.value = ''; notice.value = ''
try { await publishVectorIndex(version.id, vectorActive.value?.generation ?? 0); notice.value = '向量索引已发布。'; await refresh() }
catch (cause) { error.value = cause instanceof Error ? cause.message : '发布向量索引失败' } finally { publishing.value = undefined }
}
onMounted(refresh)
</script>
<template>
<main>
<RouterLink to="/">返回工作台</RouterLink>
<h1>索引管理</h1>
<p>操作直接调用管理员受保护接口;构建与发布会以服务端当前审核语料和代数校验为准。</p>
<p v-if="error" role="alert">{{ error }}</p><p v-if="notice" role="status">{{ notice }}</p>
<p v-if="loading">正在读取索引状态…</p>
<template v-else>
<section><h2>文本索引</h2><p>当前版本:{{ textActive?.active_version?.id || '未发布' }};代数:{{ textActive?.generation ?? 0 }}</p>
<form @submit.prevent="buildText"><label>切分长度<input v-model.number="config.chunk_size" type="number" min="1" required /></label><label>重叠长度<input v-model.number="config.overlap" type="number" min="0" required /></label><button :disabled="buildingText">{{ buildingText ? '构建中…' : '构建文本索引' }}</button></form>
<table><thead><tr><th>版本</th><th>状态</th><th>条目/片段</th><th>创建时间</th><th>操作</th></tr></thead><tbody><tr v-for="version in textVersions" :key="version.id"><td>{{ version.id }}</td><td>{{ version.status }}</td><td>{{ version.item_count }} / {{ version.chunk_count }}</td><td>{{ new Date(version.created_at).toLocaleString() }}</td><td><button v-if="version.status==='ready'" :disabled="publishing===`text:${version.id}`" @click="publishText(version)">发布</button><button v-if="version.status==='published'" :disabled="buildingVector===version.id" @click="buildVector(version)">{{ buildingVector===version.id?'构建中…':'构建向量索引' }}</button></td></tr><tr v-if="!textVersions.length"><td colspan="5">暂无文本索引。</td></tr></tbody></table>
</section>
<section><h2>向量索引</h2><p>当前版本:{{ vectorActive?.active_version?.id || '未发布' }};代数:{{ vectorActive?.generation ?? 0 }}</p>
<table><thead><tr><th>版本</th><th>文本版本</th><th>状态</th><th>片段数</th><th>操作</th></tr></thead><tbody><tr v-for="version in vectorVersions" :key="version.id"><td>{{ version.id }}</td><td>{{ version.text_index_version_id }}</td><td>{{ version.status }}</td><td>{{ version.chunk_count }}</td><td><button v-if="version.status==='ready'" :disabled="publishing===`vector:${version.id}`" @click="publishVector(version)">发布</button></td></tr><tr v-if="!vectorVersions.length"><td colspan="5">暂无向量索引;需先发布文本索引并启用本地 Embedding。</td></tr></tbody></table>
</section>
</template>
</main>
</template>
@@ -0,0 +1,20 @@
<script setup lang="ts">
import { onMounted, ref } from 'vue'
import { getKnowledge, reviewKnowledge } from '../api'
type Item = { id:number; version:number; title:string; category:string; content:string; source_url:string|null; verification_status:'pending'|'verified'|'rejected'; reviewer?:string|null; verification_notes?:string|null }
const items = ref<Item[]>([])
const selected = ref<Item>()
const reviewer = ref('')
const status = ref<'verified'|'rejected'>('verified')
const notes = ref('')
const loading = ref(true)
const submitting = ref(false)
const error = ref('')
const notice = ref('')
async function refresh(){ loading.value=true; error.value=''; try { items.value=(await getKnowledge()).filter(item=>item.verification_status==='pending') as Item[] } catch(cause){ error.value=cause instanceof Error?cause.message:'无法读取待审核知识' } finally { loading.value=false } }
function select(item:Item){ selected.value=item; reviewer.value=''; status.value='verified'; notes.value=''; error.value=''; notice.value='' }
async function submit(){ if(!selected.value)return; error.value=''; notice.value=''; if(!reviewer.value.trim()||!notes.value.trim()){error.value='请填写实际核验人和核验说明。';return} submitting.value=true; try { await reviewKnowledge(selected.value.id,{expected_version:selected.value.version,verification_status:status.value,reviewer:reviewer.value.trim(),verification_notes:notes.value.trim()}); notice.value='审核结果已保存。'; selected.value=undefined; await refresh() } catch(cause){error.value=cause instanceof Error?cause.message:'提交审核失败'} finally {submitting.value=false} }
onMounted(refresh)
</script>
<template><main><RouterLink to="/">返回工作台</RouterLink><h1>知识审核工作台</h1><p>只展示后端返回的待审核条目;提交会使用条目当前版本,避免覆盖他人更新。</p><p v-if="error" role="alert">{{error}}</p><p v-if="notice" role="status">{{notice}}</p><p v-if="loading">正在读取待审核条目…</p><template v-else><table><thead><tr><th>标题</th><th>分类</th><th>来源</th><th>操作</th></tr></thead><tbody><tr v-for="item in items" :key="item.id"><td><b>{{item.title}}</b><p>{{item.content.slice(0,120)}}</p></td><td>{{item.category}}</td><td><a v-if="item.source_url" :href="item.source_url" target="_blank" rel="noreferrer">打开来源</a><span v-else>未填写</span></td><td><button @click="select(item)">审核</button></td></tr><tr v-if="!items.length"><td colspan="4">暂无待审核条目。</td></tr></tbody></table><form v-if="selected" @submit.prevent="submit"><h2>审核:{{selected.title}}</h2><label>结论<select v-model="status"><option value="verified">通过核验</option><option value="rejected">驳回</option></select></label><label>核验人<input v-model.trim="reviewer" required maxlength="100" /></label><label>核验说明<textarea v-model.trim="notes" required maxlength="10000" rows="4" /></label><button type="button" @click="selected=undefined">取消</button><button :disabled="submitting">{{submitting?'提交中…':'保存审核'}}</button></form></template></main></template>
+1 -7
View File
@@ -1,7 +1 @@
<script setup lang="ts">
import { ref } from 'vue'
import { login } from '../services/auth'
const username=ref(''), password=ref(''), error=ref(''), loading=ref(false)
async function submit(){error.value='';if(!username.value||!password.value){error.value='请输入用户名和密码。';return}loading.value=true;try{await login({username:username.value,password:password.value})}catch(e){error.value=e instanceof Error?e.message:'登录失败'}finally{loading.value=false}}
</script>
<template><main><h1>登录</h1><form @submit.prevent="submit"><input v-model.trim="username" autocomplete="username" placeholder="用户名"/><input v-model="password" type="password" autocomplete="current-password" placeholder="密码"/><p v-if="error">{{error}}</p><button :disabled="loading">{{loading?'登录中…':'登录'}}</button></form></main></template>
<script setup lang="ts">import { ref } from 'vue';import { useRoute,useRouter } from 'vue-router';import { login } from '../services/auth';const username=ref(''),password=ref(''),error=ref(''),router=useRouter(),route=useRoute();async function submit(){try{await login({username:username.value,password:password.value});await router.replace(typeof route.query.redirect==='string'?route.query.redirect:'/')}catch(e){error.value=e instanceof Error?e.message:'登录失败'}}</script><template><main><h1>登录</h1><form @submit.prevent="submit"><input v-model="username" autocomplete="username" required placeholder="用户名"><input v-model="password" type="password" autocomplete="current-password" required placeholder="密码"><p v-if="error">{{error}}</p><button>登录</button></form><RouterLink to="/register">注册账户</RouterLink></main></template>
+1 -8
View File
@@ -1,8 +1 @@
<script setup lang="ts">
import { onMounted, ref } from 'vue'
import { getCurrentUser, logout } from '../services/auth'
import type { CurrentUser } from '../types/auth'
const user=ref<CurrentUser|null>(null), error=ref('')
onMounted(async()=>{try{user.value=await getCurrentUser()}catch(e){error.value=e instanceof Error?e.message:'无法读取个人资料'}})
</script>
<template><main><h1>个人中心</h1><p v-if="error">{{error}}</p><dl v-else-if="user"><dt>用户名</dt><dd>{{user.username}}</dd><dt>昵称</dt><dd>{{user.nickname||'未设置'}}</dd><dt>邮箱</dt><dd>{{user.email||'未设置'}}</dd><dt>角色</dt><dd>{{user.role}}</dd></dl><button @click="logout">退出登录</button></main></template>
<script setup lang="ts">import { onMounted,ref } from 'vue';import { getCurrentUser,logout } from '../services/auth';import { useRouter } from 'vue-router';import type { SessionUser } from '../types/auth';const user=ref<SessionUser>(),error=ref(''),router=useRouter();onMounted(async()=>{try{user.value=await getCurrentUser()}catch(e){error.value=e instanceof Error?e.message:'无法读取资料'}});async function signOut(){try{await logout()}finally{router.replace('/login')}}</script><template><main><h1>个人中心</h1><p v-if="error">{{error}}</p><dl v-else-if="user"><dt>用户名</dt><dd>{{user.username}}</dd><dt>昵称</dt><dd>{{user.nickname||'未设置'}}</dd><dt>邮箱</dt><dd>{{user.email||'未设置'}}</dd><dt>角色</dt><dd>{{user.role}}</dd><dt>注册时间</dt><dd>{{new Date(user.created_at).toLocaleString()}}</dd></dl><div><RouterLink to="/settings">账户设置</RouterLink><button @click="signOut">退出登录</button></div></main></template>
+1 -7
View File
@@ -1,7 +1 @@
<script setup lang="ts">
import { ref } from 'vue'
import { register } from '../services/auth'
const username=ref(''), password=ref(''), email=ref(''), error=ref('')
async function submit(){error.value='';if(username.value.length<3||password.value.length<8){error.value='用户名至少 3 位,密码至少 8 位。';return}try{await register({username:username.value,password:password.value,email:email.value||undefined})}catch(e){error.value=e instanceof Error?e.message:'注册失败'}}
</script>
<template><main><h1>注册</h1><form @submit.prevent="submit"><input v-model.trim="username" placeholder="用户名"/><input v-model.trim="email" type="email" placeholder="邮箱(可选)"/><input v-model="password" type="password" placeholder="密码"/><p v-if="error">{{error}}</p><button>创建账户</button></form></main></template>
<script setup lang="ts">import { ref } from 'vue';import { useRouter } from 'vue-router';import { register } from '../services/auth';const username=ref(''),password=ref(''),error=ref(''),router=useRouter();async function submit(){try{await register({username:username.value,password:password.value});await router.push('/login')}catch(e){error.value=e instanceof Error?e.message:'注册失败'}}</script><template><main><h1>注册</h1><form @submit.prevent="submit"><input v-model="username" required minlength="3" placeholder="用户名"><input v-model="password" required minlength="15" type="password" placeholder="至少 15 位密码"><p v-if="error">{{error}}</p><button>注册</button></form></main></template>