<template>
|
<div class="chat-view">
|
<!-- 顶部栏 -->
|
<div class="chat-header">
|
<div class="chat-header-left">
|
<n-button quaternary size="small" class="header-btn" @click="$emit('toggle-sidebar')">
|
☰
|
</n-button>
|
<div class="chat-title-area">
|
<div class="chat-title">{{ chat?.title || '新对话' }}</div>
|
<div class="chat-subtitle">
|
<span>{{ modelName }}</span>
|
<span v-if="boundCollections.length" class="rag-badge">
|
知识库 {{ boundCollections.length }}
|
</span>
|
</div>
|
</div>
|
</div>
|
|
<div class="chat-header-right">
|
<n-button quaternary size="small" class="header-btn" @click="showSettings = true">
|
参数
|
</n-button>
|
<n-button quaternary size="small" class="header-btn" @click="showRag = true">
|
知识库
|
</n-button>
|
</div>
|
</div>
|
|
<!-- 消息区 -->
|
<div ref="scrollRef" class="message-list">
|
<div v-if="!chatId" class="welcome">
|
<div class="welcome-logo">CW</div>
|
<h2 class="welcome-title">Custom-WebUI</h2>
|
<p class="welcome-sub">
|
选择左侧的对话,或点击「新对话」开始<br />
|
支持流式输出、消息分支、以及知识库检索增强
|
</p>
|
</div>
|
|
<template v-else>
|
<div v-if="path.length === 0 && !streaming" class="welcome">
|
<div class="welcome-logo">CW</div>
|
<h2 class="welcome-title">开始新的对话</h2>
|
<p class="welcome-sub">在下方输入你的问题,回复会以流式方式逐字显示</p>
|
</div>
|
|
<MessageItem
|
v-for="msg in path"
|
:key="msg.id"
|
:message="msg"
|
:is-streaming="msg.id === chatStore.streamingMessageId"
|
:branch-info="chatStore.getBranchPosition(msg)"
|
:user-initial="userInitial"
|
@switch-branch="(delta) => chatStore.switchBranch(msg, delta)"
|
@edit="(content) => handleEdit(msg, content)"
|
@regenerate="() => handleRegenerate(msg)"
|
@delete="() => handleDelete(msg)"
|
/>
|
</template>
|
</div>
|
|
<!-- 错误提示 -->
|
<div v-if="chatStore.streamError" class="stream-error">
|
<span>{{ chatStore.streamError }}</span>
|
<button class="error-close" @click="chatStore.streamError = ''">×</button>
|
</div>
|
|
<!-- 输入区 -->
|
<div class="composer">
|
<div class="composer-inner">
|
<!-- 待发送的图片:显示缩略图与识别出的文字,发送前可删 -->
|
<div v-if="pendingImages.length" class="pending-images">
|
<div v-for="img in pendingImages" :key="img.key" class="pending-image">
|
<img :src="img.previewUrl" class="pending-thumb" alt="待发送图片" />
|
<div class="pending-info">
|
<div class="pending-name">{{ img.filename }}</div>
|
<div class="pending-status" :class="img.status">
|
<template v-if="img.status === 'ocr'">识别中… {{ img.progress }}%</template>
|
<template v-else-if="img.status === 'done'">
|
已识别 {{ img.text.length }} 字
|
</template>
|
<template v-else-if="img.status === 'empty'">
|
未识别到文字(仍可作为图片发送)
|
</template>
|
<template v-else>识别失败:{{ img.error }}</template>
|
</div>
|
</div>
|
<button class="pending-remove" title="移除" @click="removePendingImage(img.key)">×</button>
|
</div>
|
</div>
|
|
<n-input
|
ref="inputRef"
|
v-model:value="draft"
|
type="textarea"
|
:autosize="{ minRows: 1, maxRows: 8 }"
|
:placeholder="composerPlaceholder"
|
:disabled="!chatId"
|
@keydown="handleKeydown"
|
@paste="handlePaste"
|
/>
|
|
<!-- 隐藏的文件选择框:accept 只列图片类型 -->
|
<input
|
ref="imageInputRef"
|
type="file"
|
class="hidden-image-input"
|
multiple
|
:accept="imageAccept"
|
@change="handleImageSelect"
|
/>
|
|
<div class="composer-actions">
|
<label class="rag-toggle">
|
<n-switch v-model:value="useRag" size="small" :disabled="!hasRag" />
|
<span class="rag-toggle-label" :class="{ disabled: !hasRag }">
|
{{ hasRag ? '启用知识库' : '未绑定知识库' }}
|
</span>
|
</label>
|
|
<div class="composer-buttons">
|
<!-- <n-button-->
|
<!-- size="small"-->
|
<!-- :disabled="!chatId || chatStore.streaming"-->
|
<!-- :loading="pendingImages.some((i) => i.status === 'ocr')"-->
|
<!-- title="上传图片,识别其中文字后一并对话"-->
|
<!-- @click="pickImage"-->
|
<!-- >-->
|
<!-- 图片-->
|
<!-- </n-button>-->
|
<n-button
|
v-if="chatStore.streaming"
|
size="small"
|
@click="chatStore.stopStreaming()"
|
>
|
停止生成
|
</n-button>
|
<n-button
|
type="primary"
|
size="small"
|
:disabled="!canSend"
|
:loading="chatStore.streaming"
|
@click="handleSend"
|
>
|
发送
|
</n-button>
|
</div>
|
</div>
|
</div>
|
<div class="composer-hint">
|
Enter 发送,Shift + Enter 换行 · 可直接粘贴截图
|
</div>
|
</div>
|
|
<!-- 模型参数抽屉 -->
|
<n-drawer v-model:show="showSettings" :width="400" placement="right">
|
<n-drawer-content title="模型参数" closable>
|
<n-form label-placement="top">
|
<n-form-item label="模型名称">
|
<n-input v-model:value="metaForm.modelName" placeholder="留空使用后端默认模型" />
|
</n-form-item>
|
<n-form-item :label="`温度 temperature:${metaForm.temperature}`">
|
<n-slider v-model:value="metaForm.temperature" :min="0" :max="2" :step="0.1" />
|
</n-form-item>
|
<n-form-item :label="`核采样 top_p:${metaForm.topP}`">
|
<n-slider v-model:value="metaForm.topP" :min="0" :max="1" :step="0.05" />
|
</n-form-item>
|
<n-form-item label="上下文窗口 num_ctx">
|
<n-input-number v-model:value="metaForm.numCtx" :min="512" :max="131072" :step="512" />
|
</n-form-item>
|
<n-form-item label="系统提示词">
|
<n-input
|
v-model:value="metaForm.systemPrompt"
|
type="textarea"
|
:autosize="{ minRows: 4, maxRows: 10 }"
|
placeholder="例如:你是一个严谨的技术助手,回答尽量简洁。"
|
/>
|
</n-form-item>
|
</n-form>
|
<template #footer>
|
<n-button type="primary" :loading="savingMeta" @click="saveMeta">保存参数</n-button>
|
</template>
|
</n-drawer-content>
|
</n-drawer>
|
|
<!-- 知识库抽屉 -->
|
<n-drawer v-model:show="showRag" :width="520" placement="right">
|
<n-drawer-content title="知识库设置" closable>
|
<n-alert v-if="!ragEnabled" type="warning" :bordered="false" class="rag-alert">
|
后端配置中 RAG 功能已关闭(webui.rag.enabled=false),检索不会生效。
|
</n-alert>
|
<n-alert v-else-if="!ragAvailable" type="warning" :bordered="false" class="rag-alert">
|
RAG 服务当前不可用({{ ragBaseUrl }})。请启动 Python 服务:<br />
|
<code>cd rag-service && uvicorn main:app --host 0.0.0.0 --port 8000</code>
|
</n-alert>
|
|
<p class="rag-section-title">上传新文档</p>
|
<FileUpload
|
:chat-id="chatId"
|
@uploaded="handleUploaded"
|
@category-created="handleCategoryCreated"
|
/>
|
|
<!--
|
整类绑定区:把「绑定知识库」从逐个勾选变成一次点击。
|
绑的是分类 id,后端检索时才展开 —— 之后往分类里新增文档,
|
这个会话会自动检索到,不用回来重新绑定。
|
-->
|
<p class="rag-section-title">
|
分类绑定
|
<span class="section-hint">一次绑定整个分类</span>
|
<n-button text size="tiny" class="section-refresh" @click="refreshRagState(props.chatId)">
|
刷新
|
</n-button>
|
</p>
|
<div v-if="categories.length === 0" class="empty-hint">
|
还没有分类。上传文档时可选择或新建分类,之后即可整类绑定。
|
</div>
|
<div v-for="category in categories" v-else :key="category.id" class="category-row">
|
<div class="category-row-main">
|
<div class="category-name">
|
{{ category.name }}
|
<span v-if="category.isGlobal" class="global-badge">全局</span>
|
</div>
|
<div class="category-meta">
|
{{ category.ingestedCount }}/{{ category.fileCount }} 篇已入库
|
<span v-if="category.ingestedCount === 0" class="file-status pending">
|
· 无已入库文档,绑定后检索不到内容
|
</span>
|
</div>
|
</div>
|
<n-button
|
size="tiny"
|
:disabled="category.ingestedCount === 0"
|
:type="isCategoryBound(category.id) ? 'primary' : 'default'"
|
:loading="categoryBindingId === category.id"
|
@click="toggleCategoryBinding(category)"
|
>
|
{{ isCategoryBound(category.id) ? '已绑定' : '绑定整类' }}
|
</n-button>
|
</div>
|
|
<p class="rag-section-title">
|
我的知识库
|
<span class="section-hint">也可单独绑定某篇</span>
|
</p>
|
<div v-if="files.length === 0" class="empty-hint">还没有上传任何文档</div>
|
<div v-for="file in files" :key="file.id" class="file-row">
|
<div class="file-row-main">
|
<div class="file-name">
|
{{ file.filename }}
|
<!-- 全局知识库由管理员维护,普通用户只能绑定使用 -->
|
<span v-if="file.isGlobal" class="global-badge">全局</span>
|
</div>
|
<div class="file-meta">
|
{{ formatSize(file.fileSize) }}
|
<span v-if="file.categoryName" class="file-category">· {{ file.categoryName }}</span>
|
<span v-if="file.ingested" class="file-status ok">
|
· 已入库 {{ file.chunkCount }} 块
|
</span>
|
<span v-else-if="file.ingestMessage" class="file-status fail">
|
· {{ file.ingestMessage }}
|
</span>
|
<span v-else class="file-status pending">· 未向量化</span>
|
</div>
|
</div>
|
<div class="file-row-actions">
|
<n-button
|
v-if="!file.ingested && file.canManage"
|
size="tiny"
|
:loading="ingestingId === file.id"
|
@click="handleIngest(file)"
|
>
|
向量化
|
</n-button>
|
<n-button
|
v-if="file.collectionName"
|
size="tiny"
|
:type="isCollectionActive(file.collectionName) ? 'primary' : 'default'"
|
@click="toggleBinding(file.collectionName)"
|
>
|
{{ isCollectionActive(file.collectionName) ? '已绑定' : '绑定' }}
|
</n-button>
|
<n-button
|
v-if="file.canManage"
|
size="tiny"
|
type="error"
|
quaternary
|
@click="handleDeleteFile(file)"
|
>
|
删除
|
</n-button>
|
</div>
|
</div>
|
|
<template #footer>
|
<div class="rag-footer">
|
<span class="text-secondary">
|
已绑定 {{ boundCollections.length }} 个知识库,聊天时会自动检索
|
</span>
|
</div>
|
</template>
|
</n-drawer-content>
|
</n-drawer>
|
</div>
|
</template>
|
|
<script setup>
|
import { computed, nextTick, onBeforeUnmount, onMounted, reactive, ref, watch } from 'vue'
|
import {
|
NAlert,
|
NButton,
|
NDrawer,
|
NDrawerContent,
|
NForm,
|
NFormItem,
|
NInput,
|
NInputNumber,
|
NSlider,
|
NSwitch,
|
useDialog,
|
useMessage
|
} from 'naive-ui'
|
import MessageItem from './MessageItem.vue'
|
import FileUpload from './FileUpload.vue'
|
import {
|
bindCategory,
|
listCategories,
|
listCategoryBindings
|
} from '@/api/categoryApi'
|
import { IMAGE_EXTENSIONS, recognizeImage, storeAttachmentText } from '@/api/fileApi'
|
import { useChatStore } from '@/stores/chatStore'
|
import { useAuthStore } from '@/stores/authStore'
|
import {
|
bindCollections,
|
deleteFile,
|
ingestFile,
|
listBindings,
|
listFiles,
|
ragHealth
|
} from '@/api/fileApi'
|
|
const emit = defineEmits(['toggle-sidebar'])
|
|
const props = defineProps({
|
chatId: { type: Number, default: null }
|
})
|
|
const chatStore = useChatStore()
|
const auth = useAuthStore()
|
const message = useMessage()
|
const dialog = useDialog()
|
|
const draft = ref('')
|
const useRag = ref(true)
|
const scrollRef = ref(null)
|
const inputRef = ref(null)
|
|
const showSettings = ref(false)
|
const showRag = ref(false)
|
const savingMeta = ref(false)
|
|
const files = ref([])
|
const boundCollections = ref([])
|
const ingestingId = ref(null)
|
/** 可见分类(带 fileCount / ingestedCount / collectionNames) */
|
const categories = ref([])
|
/** 该会话已绑定的分类 id */
|
const boundCategoryIds = ref([])
|
/** 正在绑定/解绑的分类 id,用于按钮 loading */
|
const categoryBindingId = ref(null)
|
|
const ragEnabled = ref(true)
|
const ragAvailable = ref(true)
|
const ragBaseUrl = ref('')
|
|
const chat = computed(() => chatStore.activeChat)
|
const path = computed(() => chatStore.path)
|
const userInitial = computed(() => (auth.displayName || 'U').charAt(0).toUpperCase())
|
|
/**
|
* 当前是否正在流式生成。
|
*
|
* 模板里用 `streaming` 而不是直接写 `chatStore.streaming`,
|
* 一是可读性,二是将来若要加「已发送但首个 token 未到」这类派生状态,
|
* 只需改这一处。
|
*
|
* 注意:这个 computed 是必须的 —— 之前模板引用了 `streaming` 却没定义,
|
* Vue 只会在控制台打一条 warning,页面照常渲染但该条件恒为
|
* undefined(falsy),表现为空会话时欢迎语与消息区同时出现。
|
*/
|
const streaming = computed(() => chatStore.streaming)
|
|
/**
|
* 当前会话「实际生效」的全部集合 = 单篇绑定的集合 ∪ 已绑定分类展开出的集合。
|
*
|
* 这个计算属性是修一个严重 bug 的关键。之前状态是分散的:
|
* - hasRag 只看 boundCollections(单篇绑定)
|
* - 分类绑定只写在 boundCategoryIds 里
|
* 于是「绑定整类」之后 hasRag 仍为 false →
|
* 1) 底部显示「未绑定知识库」
|
* 2) 发送消息时 useRag 被算成 false,后端**根本没做检索**,
|
* 回答自然不引用知识库
|
*
|
* 根因是把「用户绑了什么」和「实际生效什么」混为一谈。
|
* 现在统一由这里推导,两处绑定方式都覆盖,不再有遗漏。
|
*/
|
const effectiveBoundCollections = computed(() => {
|
const set = new Set(boundCollections.value)
|
for (const cat of categories.value) {
|
if (!boundCategoryIds.value.includes(cat.id)) {
|
continue
|
}
|
for (const name of cat.collectionNames || []) {
|
set.add(name)
|
}
|
}
|
return [...set]
|
})
|
|
// ---------------- 图片上传与 OCR ----------------
|
|
/**
|
* 待发送的图片。
|
*
|
* 每项形如 { key, filename, previewUrl, status, progress, text, fileId, error }
|
* status: ocr(识别中)/ done / empty(没识别到字)/ failed
|
*/
|
const pendingImages = ref([])
|
const imageInputRef = ref(null)
|
|
const imageAccept = IMAGE_EXTENSIONS.map((e) => `.${e}`).join(',')
|
|
function pickImage() {
|
if (!props.chatId || chatStore.streaming) return
|
imageInputRef.value?.click()
|
}
|
|
function handleImageSelect(event) {
|
const files = Array.from(event.target.files || [])
|
// 清空 value,否则连续选同一个文件不会触发 change
|
event.target.value = ''
|
uploadImages(files)
|
}
|
|
async function uploadImages(files) {
|
if (files.length === 0) return
|
|
for (const file of files) {
|
const ext = file.name.split('.').pop()?.toLowerCase() || ''
|
if (!IMAGE_EXTENSIONS.includes(ext)) {
|
message.error(`${file.name}:不是支持的图片类型(${IMAGE_EXTENSIONS.join('/')})`)
|
continue
|
}
|
if (file.size > 20 * 1024 * 1024) {
|
message.error(`${file.name}:图片超过 20MB`)
|
continue
|
}
|
|
// 本地预览:ObjectURL 不占内存,删除时记得 revoke
|
const item = reactive({
|
key: `${Date.now()}_${Math.random().toString(36).slice(2, 8)}`,
|
filename: file.name,
|
previewUrl: URL.createObjectURL(file),
|
status: 'ocr',
|
progress: 0,
|
text: '',
|
fileId: null,
|
error: ''
|
})
|
pendingImages.value.push(item)
|
|
try {
|
const result = await recognizeImage(file, props.chatId, (percent) => {
|
item.progress = percent
|
})
|
item.fileId = result.fileId
|
item.text = result.text || ''
|
item.status = item.text.trim() ? 'done' : 'empty'
|
|
if (item.status === 'empty') {
|
// 不是错误:用户可能就是想发张图。说清楚它不会被模型"看懂"即可
|
message.info(`${file.name} 未识别到文字,图片仍会发出,但模型只能看到文件名`)
|
}
|
} catch (error) {
|
item.status = 'failed'
|
item.error = error.message || '识别失败'
|
message.error(`${file.name}:${item.error}`)
|
}
|
}
|
}
|
|
/**
|
* 从剪贴板事件中取出图片文件。
|
*
|
* 为什么要遍历 items 而不能只看 items[0]:
|
* 从网页复制内容时,clipboardData 里往往同时有 text/html、text/plain
|
* 和 image/png。只取第一项可能拿到 HTML 而不是图片,
|
* 导致「明明复制的图片却粘出了源码」。
|
*/
|
function extractImageFiles(event) {
|
const items = event.clipboardData?.items
|
if (!items) return []
|
const files = []
|
for (const item of items) {
|
if (item.kind === 'file' && item.type.startsWith('image/')) {
|
const file = item.getAsFile()
|
if (file) files.push(file)
|
}
|
}
|
return files
|
}
|
|
/**
|
* 粘贴处理。
|
*
|
* 只拦「剪贴板里确实有图片」的情况;纯文本粘贴交给浏览器默认行为,
|
* 否则会破坏正常粘贴文字、以及带格式文本的粘贴。
|
*/
|
/**
|
* 本次粘贴是否已被组件级处理。
|
*
|
* 用它而不是时间窗口去重:时间窗口会误伤「300ms 内连续粘贴两次图片」,
|
* 而这种精确标记只吃掉同一个事件的重复投递,不会影响下一次真实粘贴。
|
*/
|
let pasteConsumedByComposer = false
|
|
function handlePaste(event) {
|
const files = extractImageFiles(event)
|
if (files.length === 0) {
|
// 剪贴板里有文字也有图片时(从网页复制),文字照常插入,图片额外收下
|
return
|
}
|
|
// 阻止默认行为,避免把图片的 html/文件名当文本塞进输入框
|
event.preventDefault()
|
// 标记本次粘贴已被处理,避免 document 层的兜底监听重复收一次
|
pasteConsumedByComposer = true
|
|
if (!props.chatId) {
|
message.warning('请先选择或新建一个对话')
|
return
|
}
|
if (chatStore.streaming) {
|
message.warning('正在生成回复,请稍候再粘贴图片')
|
return
|
}
|
|
// 剪贴板里的图片往往没有文件名(截图、复制的图),给个可读的默认名,
|
// 否则「我的知识库」里会出现一堆无名的 png
|
const named = files.map((f, i) =>
|
f.name && f.name !== 'image.png'
|
? f
|
: new File([f], `粘贴图片_${timestampName()}${files.length > 1 ? `_${i + 1}` : ''}.png`, {
|
type: f.type || 'image/png'
|
})
|
)
|
|
uploadImages(named)
|
}
|
|
/** 生成用于文件名的短时间戳,如 20261001_143012 */
|
function timestampName() {
|
const d = new Date()
|
const pad = (n) => String(n).padStart(2, '0')
|
return (
|
`${d.getFullYear()}${pad(d.getMonth() + 1)}${pad(d.getDate())}` +
|
`_${pad(d.getHours())}${pad(d.getMinutes())}${pad(d.getSeconds())}`
|
)
|
}
|
|
/**
|
* 文档级粘贴兜底。
|
*
|
* 只在「粘贴发生的位置不在任何输入框里」时接管 —— 用户点了页面空白处再粘贴
|
* 也能收到图,符合直觉。若焦点已在输入框内,由上面的 handlePaste 处理,
|
* 这里直接跳过,否则会重复收图。
|
*/
|
function handleDocumentPaste(event) {
|
// 同一个事件已由组件级处理过,消费掉标记并跳过
|
if (pasteConsumedByComposer) {
|
pasteConsumedByComposer = false
|
return
|
}
|
|
// 焦点在输入类元素里时交给它们自己处理
|
const el = document.activeElement
|
const tag = el?.tagName?.toLowerCase()
|
if (tag === 'input' || tag === 'textarea' || el?.isContentEditable) return
|
|
const files = extractImageFiles(event)
|
if (files.length === 0) return
|
event.preventDefault()
|
uploadImages(files.map((f) => new File([f], `粘贴图片_${timestampName()}.png`, { type: f.type || 'image/png' })))
|
}
|
|
function removePendingImage(key) {
|
const idx = pendingImages.value.findIndex((i) => i.key === key)
|
if (idx === -1) return
|
// 释放 ObjectURL,否则长时间使用会持续占用内存
|
URL.revokeObjectURL(pendingImages.value[idx].previewUrl)
|
pendingImages.value.splice(idx, 1)
|
}
|
|
async function clearPendingImages() {
|
for (const img of pendingImages.value) {
|
URL.revokeObjectURL(img.previewUrl)
|
}
|
pendingImages.value = []
|
}
|
|
/** 是否有可用于检索的知识库(单篇或整类都算) */
|
const hasRag = computed(() => effectiveBoundCollections.value.length > 0)
|
|
/** 某篇文档(按集合名)当前是否处于已绑定/生效状态 */
|
function isCollectionActive(collectionName) {
|
return effectiveBoundCollections.value.includes(collectionName)
|
}
|
const canSend = computed(() => {
|
if (!props.chatId || streaming.value) return false
|
// 允许「只发图片不打字」:上传了图就能发
|
return draft.value.trim().length > 0 || pendingImages.value.length > 0
|
})
|
|
const modelName = computed(() => {
|
const meta = chat.value?.meta
|
return meta?.modelName || '默认模型'
|
})
|
|
const composerPlaceholder = computed(() =>
|
props.chatId ? '输入消息…' : '请先新建或选择一个对话'
|
)
|
|
const metaForm = ref({
|
modelName: '',
|
temperature: 0.7,
|
topP: 0.9,
|
numCtx: 8192,
|
systemPrompt: ''
|
})
|
|
// ---------------- 会话切换 ----------------
|
|
watch(
|
() => props.chatId,
|
async (chatId) => {
|
if (!chatId) {
|
chatStore.resetView()
|
files.value = []
|
boundCollections.value = []
|
boundCategoryIds.value = []
|
// 注意:**不能在这里 return**。
|
// 没有选中会话时(用户刚进 /c,或删掉了当前会话),
|
// 分类列表与文件列表仍然应该显示 —— 否则用户新建了分类、
|
// 打开知识库却什么都看不到,会以为分类没建成功。
|
// 只是此时没有「已绑定」状态可标记而已。
|
await refreshRagState(null)
|
return
|
}
|
|
// 切会话前先把可能还在跑的流中断掉。
|
// 这是「发送按钮卡死」的兜底恢复手段:一旦 streaming 因任何竞态
|
// 残留在 true,切一次会话即可恢复,不需要刷新页面。
|
chatStore.stopStreaming()
|
|
try {
|
// 不保留上一个会话的分支选择,避免 id 复用导致的错乱
|
await chatStore.loadMessages(chatId, false)
|
syncMetaForm()
|
await refreshRagState(chatId)
|
scrollToBottom()
|
} catch (error) {
|
message.error(error.message || '加载消息失败')
|
}
|
},
|
{ immediate: true }
|
)
|
|
// 新内容到达时自动滚到底部
|
watch(
|
() => path.value.map((item) => item.content).join('|'),
|
() => scrollToBottom()
|
)
|
|
watch(
|
() => chatStore.streaming,
|
(streaming) => {
|
if (!streaming) scrollToBottom()
|
}
|
)
|
|
function syncMetaForm() {
|
const meta = chat.value?.meta || {}
|
metaForm.value = {
|
modelName: meta.modelName || '',
|
temperature: meta.temperature ?? 0.7,
|
topP: meta.topP ?? 0.9,
|
numCtx: meta.numCtx ?? 8192,
|
systemPrompt: meta.systemPrompt || ''
|
}
|
}
|
|
/**
|
* 加载知识库相关状态。
|
*
|
* @param chatId 可为 null —— 未选中会话时,分类与文件列表仍需正常展示,
|
* 只是无法标记「已绑定」状态。
|
*/
|
async function refreshRagState(chatId) {
|
try {
|
const health = await ragHealth()
|
ragEnabled.value = health.enabled !== false
|
ragAvailable.value = health.available !== false
|
ragBaseUrl.value = health.baseUrl || ''
|
} catch {
|
// 健康检查失败不阻断页面,按「不可用」显示
|
ragAvailable.value = false
|
}
|
|
try {
|
// chatId 为空时跳过依赖会话的请求(会 400/404),但仍要拿分类与文件
|
const [fileList, bindings, categoryList, categoryBindings] = await Promise.all([
|
listFiles(null),
|
chatId != null ? listBindings(chatId) : Promise.resolve([]),
|
listCategories(chatId),
|
chatId != null ? listCategoryBindings(chatId) : Promise.resolve([])
|
])
|
files.value = fileList || []
|
boundCollections.value = bindings || []
|
categories.value = categoryList || []
|
boundCategoryIds.value = categoryBindings || []
|
// useRag 是「用户是否希望启用检索」的意图开关,
|
// 是否真的有知识库可用由 hasRag 推导,不再手工同步,避免两处状态漂移
|
if (hasRag.value) {
|
useRag.value = true
|
}
|
} catch (error) {
|
message.error(error.message || '加载知识库信息失败')
|
}
|
}
|
|
/** 该分类是否已绑定到当前会话 */
|
function isCategoryBound(categoryId) {
|
return boundCategoryIds.value.includes(categoryId)
|
}
|
|
/**
|
* 整类绑定 / 解绑。
|
*
|
* 提交的是**分类 id**,检索时由后端展开成集合 ——
|
* 因此之后往分类里新增文档会自动生效,不需要回到这里重新绑定。
|
*/
|
async function toggleCategoryBinding(category) {
|
if (props.chatId == null) {
|
message.warning('请先选择或新建一个对话,再绑定知识库分类')
|
return
|
}
|
const bind = !isCategoryBound(category.id)
|
categoryBindingId.value = category.id
|
try {
|
boundCategoryIds.value = (await bindCategory(props.chatId, category.id, bind)) || []
|
// 绑定后自动打开检索开关:用户刚绑定知识库,意图显然是「要用它」
|
if (hasRag.value) {
|
useRag.value = true
|
}
|
|
if (bind) {
|
// 提示里点明「新增文档会自动生效」,这是整类绑定相对逐个绑定的核心优势
|
message.success(
|
`已绑定分类「${category.name}」(${category.ingestedCount} 篇已入库),` +
|
'以后往该分类新增文档会自动参与检索'
|
)
|
} else {
|
message.success(`已解绑分类「${category.name}」`)
|
}
|
} catch (error) {
|
message.error(error.message || '操作失败')
|
} finally {
|
categoryBindingId.value = null
|
}
|
}
|
|
// ---------------- 发送 ----------------
|
|
function handleKeydown(event) {
|
// Enter 发送,Shift+Enter 换行;输入法组合中的 Enter 不应触发发送
|
if (event.key === 'Enter' && !event.shiftKey && !event.isComposing) {
|
event.preventDefault()
|
handleSend()
|
}
|
}
|
|
async function handleSend() {
|
const content = draft.value.trim()
|
const hasImages = pendingImages.value.length > 0
|
if ((!content && !hasImages) || !props.chatId || chatStore.streaming) return
|
|
// 先清空输入框与待发送图片,让用户能立即继续打字 / 继续选图
|
draft.value = ''
|
|
// 图片数据先取下快照:sendMessage 会立刻把消息乐观渲染进消息树,
|
// 预览区就没必要继续占着了。
|
//
|
// 注意不能等 sendMessage 返回再清 —— 那要等整段回答生成完
|
// (实测 9 秒以上),期间预览区一直挂着「待发送图片」,
|
// 用户会以为没发出去而重复发送。
|
const imageText = pendingImages.value
|
.map((i) => i.text)
|
.filter((t) => t && t.trim())
|
.join('\n\n')
|
const imageFileIds = pendingImages.value
|
.map((i) => i.fileId)
|
.filter((id) => id != null)
|
|
await clearPendingImages()
|
|
// 长文本先暂存换短 id:SSE 是 GET,参数只能走 query string,
|
// 而中文 URL 编码约 9 字节/字,2000 字就 18KB,
|
// 超过 Tomcat 默认 8KB 的请求行上限会得到 "Request header is too large"。
|
// 阈值取 1000 字(约 9KB 编码后仍偏高),超过就走暂存。
|
let imageTextId = null
|
let inlineImageText = imageText
|
if (imageText && imageText.length > 1000) {
|
try {
|
const stored = await storeAttachmentText(imageText)
|
imageTextId = stored?.id || null
|
if (imageTextId) {
|
inlineImageText = null
|
}
|
} catch (error) {
|
// 暂存失败就退回内联传递;内容不长时仍可用,
|
// 过长时后端会给出明确提示而不是静默失败
|
message.warning(`图片文字暂存失败,将尝试直接发送:${error.message || ''}`)
|
}
|
}
|
|
try {
|
await chatStore.sendMessage({
|
chatId: props.chatId,
|
content,
|
useRag: useRag.value && hasRag.value,
|
imageText: inlineImageText,
|
imageTextId,
|
imageFileIds
|
})
|
} catch (error) {
|
message.error(error.message || '发送失败')
|
// 发送失败把内容还回输入框,避免用户白打字。
|
// 图片不还原:文件已在服务端落盘,重新识别一遍代价更高,
|
// 用户重新选图即可(消息树里也没有产生垃圾消息)。
|
draft.value = content
|
} finally {
|
inputRef.value?.focus?.()
|
}
|
}
|
|
async function handleRegenerate(msg) {
|
try {
|
await chatStore.regenerate({
|
chatId: props.chatId,
|
userMessageId: msg.id,
|
useRag: useRag.value && hasRag.value
|
})
|
} catch (error) {
|
message.error(error.message || '重新生成失败')
|
}
|
}
|
|
async function handleEdit(msg, content) {
|
try {
|
await chatStore.editMessage(props.chatId, msg.id, content)
|
message.success('已保存')
|
} catch (error) {
|
message.error(error.message || '保存失败')
|
}
|
}
|
|
function handleDelete(msg) {
|
dialog.warning({
|
title: '删除消息',
|
content: '该消息及其之后的所有对话都会被删除,确定继续吗?',
|
positiveText: '删除',
|
negativeText: '取消',
|
onPositiveClick: async () => {
|
try {
|
await chatStore.removeMessage(props.chatId, msg.id)
|
message.success('已删除')
|
} catch (error) {
|
message.error(error.message || '删除失败')
|
}
|
}
|
})
|
}
|
|
// ---------------- 参数 ----------------
|
|
async function saveMeta() {
|
savingMeta.value = true
|
try {
|
await chatStore.updateChatMeta(props.chatId, {
|
modelName: metaForm.value.modelName || null,
|
temperature: metaForm.value.temperature,
|
topP: metaForm.value.topP,
|
numCtx: metaForm.value.numCtx || null,
|
systemPrompt: metaForm.value.systemPrompt || null
|
})
|
message.success('参数已保存')
|
showSettings.value = false
|
} catch (error) {
|
message.error(error.message || '保存失败')
|
} finally {
|
savingMeta.value = false
|
}
|
}
|
|
// ---------------- 知识库 ----------------
|
|
async function handleUploaded(uploaded) {
|
files.value = [...uploaded, ...files.value]
|
// 上传时若选了分类,分类的文档数变了,连同文件列表一起刷新
|
await refreshRagState(props.chatId)
|
}
|
|
/**
|
* 在上传区现场新建了分类。
|
*
|
* 必须刷新分类列表 —— 否则用户刚建的分类不会出现在上方的
|
* 「分类绑定」区里,看起来像没建成功。
|
*/
|
async function handleCategoryCreated() {
|
await refreshRagState(props.chatId)
|
}
|
|
async function handleIngest(file) {
|
ingestingId.value = file.id
|
try {
|
const updated = await ingestFile(file.id)
|
const index = files.value.findIndex((item) => item.id === file.id)
|
if (index !== -1) {
|
files.value[index] = updated
|
}
|
message.success(`向量化完成,共 ${updated.chunkCount} 个片段`)
|
} catch (error) {
|
message.error(error.message || '向量化失败')
|
// 重新拉取以显示后端的失败状态
|
try {
|
files.value = await listFiles(null)
|
} catch {
|
// 忽略
|
}
|
} finally {
|
ingestingId.value = null
|
}
|
}
|
|
async function toggleBinding(collectionName) {
|
const next = boundCollections.value.includes(collectionName)
|
? boundCollections.value.filter((name) => name !== collectionName)
|
: [...boundCollections.value, collectionName]
|
|
try {
|
// 后端是全量覆盖语义,因此提交完整列表。
|
// 返回的是**实际绑定成功**的列表 —— 已失效的集合后端会忽略,
|
// 所以这里必须用返回值覆盖本地状态,否则本地会一直残留
|
// 那个已失效的集合名,导致每次绑定都重复提交它。
|
const applied = (await bindCollections(props.chatId, next)) || []
|
boundCollections.value = applied
|
if (hasRag.value) {
|
useRag.value = true
|
}
|
|
// 告知被剔除的项,避免用户觉得「点了没反应」
|
const dropped = next.filter((name) => !applied.includes(name))
|
if (dropped.length > 0) {
|
message.warning(
|
`${dropped.length} 个知识库已失效(文档可能已被删除或被取消全局),已自动移除:` +
|
dropped.join('、')
|
)
|
// 拉一次文件列表,让失效文档从界面上消失
|
await refreshRagState(props.chatId)
|
} else {
|
message.success(applied.length ? '绑定已更新' : '已解除全部绑定')
|
}
|
} catch (error) {
|
message.error(error.message || '绑定失败')
|
}
|
}
|
|
function handleDeleteFile(file) {
|
dialog.warning({
|
title: '删除文档',
|
content: `确定删除「${file.filename}」吗?磁盘文件与已入库的向量都会一并清理。`,
|
positiveText: '删除',
|
negativeText: '取消',
|
onPositiveClick: async () => {
|
try {
|
await deleteFile(file.id)
|
files.value = files.value.filter((item) => item.id !== file.id)
|
if (file.collectionName) {
|
boundCollections.value = boundCollections.value.filter(
|
(name) => name !== file.collectionName
|
)
|
}
|
message.success('已删除')
|
} catch (error) {
|
message.error(error.message || '删除失败')
|
}
|
}
|
})
|
}
|
|
function formatSize(bytes) {
|
if (!bytes && bytes !== 0) return ''
|
if (bytes < 1024) return `${bytes} B`
|
if (bytes < 1024 * 1024) return `${(bytes / 1024).toFixed(1)} KB`
|
return `${(bytes / 1024 / 1024).toFixed(1)} MB`
|
}
|
|
// ---------------- 生命周期 ----------------
|
|
onMounted(() => {
|
document.addEventListener('paste', handleDocumentPaste)
|
})
|
|
onBeforeUnmount(() => {
|
document.removeEventListener('paste', handleDocumentPaste)
|
// 离开页面时释放未发送图片的 ObjectURL,避免泄漏
|
clearPendingImages()
|
})
|
|
function scrollToBottom() {
|
nextTick(() => {
|
const el = scrollRef.value
|
if (el) {
|
el.scrollTop = el.scrollHeight
|
}
|
})
|
}
|
|
defineExpose({ refreshRagState })
|
</script>
|
|
<style scoped>
|
.chat-view {
|
flex: 1;
|
display: flex;
|
flex-direction: column;
|
min-width: 0;
|
height: 100vh;
|
background: var(--bg-page);
|
}
|
|
.chat-header {
|
height: 54px;
|
border-bottom: 1px solid var(--border-color);
|
display: flex;
|
align-items: center;
|
justify-content: space-between;
|
padding: 0 16px;
|
flex-shrink: 0;
|
}
|
|
.chat-header-left,
|
.chat-header-right {
|
display: flex;
|
align-items: center;
|
gap: 4px;
|
}
|
|
.header-btn {
|
font-size: 15px;
|
}
|
|
.chat-title-area {
|
margin-left: 8px;
|
min-width: 0;
|
}
|
|
.chat-title {
|
font-size: 14px;
|
font-weight: 600;
|
overflow: hidden;
|
text-overflow: ellipsis;
|
white-space: nowrap;
|
max-width: 380px;
|
}
|
|
.chat-subtitle {
|
font-size: 11.5px;
|
color: var(--text-muted);
|
margin-top: 1px;
|
}
|
|
.rag-badge {
|
margin-left: 8px;
|
color: #0f766e;
|
}
|
|
.message-list {
|
flex: 1;
|
overflow-y: auto;
|
padding: 8px 24px 24px;
|
scroll-behavior: smooth;
|
}
|
|
.welcome {
|
text-align: center;
|
padding-top: 16vh;
|
}
|
|
.welcome-logo {
|
width: 56px;
|
height: 56px;
|
margin: 0 auto 18px;
|
border-radius: 15px;
|
background: #374151;
|
color: #fff;
|
font-weight: 700;
|
font-size: 20px;
|
display: flex;
|
align-items: center;
|
justify-content: center;
|
}
|
|
.welcome-title {
|
margin: 0 0 8px;
|
font-size: 21px;
|
font-weight: 600;
|
}
|
|
.welcome-sub {
|
margin: 0;
|
font-size: 13.5px;
|
color: var(--text-secondary);
|
line-height: 1.9;
|
}
|
|
.stream-error {
|
margin: 0 24px 8px;
|
padding: 9px 12px;
|
background: #fef2f2;
|
border: 1px solid #fecaca;
|
border-radius: 8px;
|
font-size: 13px;
|
color: #b91c1c;
|
display: flex;
|
align-items: center;
|
justify-content: space-between;
|
gap: 12px;
|
max-width: 780px;
|
align-self: center;
|
width: calc(100% - 48px);
|
box-sizing: border-box;
|
}
|
|
.error-close {
|
background: none;
|
border: none;
|
font-size: 17px;
|
line-height: 1;
|
cursor: pointer;
|
color: #b91c1c;
|
padding: 0 2px;
|
}
|
|
.composer {
|
padding: 8px 24px 16px;
|
flex-shrink: 0;
|
}
|
|
.composer-inner {
|
max-width: 780px;
|
margin: 0 auto;
|
border: 1px solid var(--border-color);
|
border-radius: 12px;
|
padding: 10px 12px 8px;
|
box-shadow: 0 2px 10px rgba(15, 23, 42, 0.04);
|
transition: border-color 0.15s ease;
|
}
|
|
.composer-inner:focus-within {
|
border-color: #9ca3af;
|
}
|
|
.composer-inner :deep(.n-input) {
|
--n-border: none !important;
|
--n-border-hover: none !important;
|
--n-border-focus: none !important;
|
--n-box-shadow-focus: none !important;
|
}
|
|
.hidden-image-input {
|
display: none;
|
}
|
|
.pending-images {
|
display: flex;
|
flex-wrap: wrap;
|
gap: 8px;
|
margin-bottom: 8px;
|
}
|
|
.pending-image {
|
position: relative;
|
display: flex;
|
align-items: center;
|
gap: 8px;
|
padding: 6px 26px 6px 6px;
|
border: 1px solid var(--border-color);
|
border-radius: 8px;
|
background: #fafafa;
|
max-width: 260px;
|
}
|
|
.pending-thumb {
|
width: 40px;
|
height: 40px;
|
object-fit: cover;
|
border-radius: 6px;
|
flex-shrink: 0;
|
}
|
|
.pending-info {
|
min-width: 0;
|
}
|
|
.pending-name {
|
font-size: 12px;
|
overflow: hidden;
|
text-overflow: ellipsis;
|
white-space: nowrap;
|
}
|
|
.pending-status {
|
font-size: 11px;
|
color: var(--text-muted);
|
margin-top: 2px;
|
}
|
|
.pending-status.done {
|
color: #0f766e;
|
}
|
|
.pending-status.failed {
|
color: #dc2626;
|
}
|
|
.pending-remove {
|
position: absolute;
|
top: 2px;
|
right: 4px;
|
background: none;
|
border: none;
|
cursor: pointer;
|
font-size: 15px;
|
line-height: 1;
|
color: var(--text-muted);
|
padding: 0 2px;
|
}
|
|
.pending-remove:hover {
|
color: #dc2626;
|
}
|
|
.composer-actions {
|
display: flex;
|
align-items: center;
|
justify-content: space-between;
|
margin-top: 8px;
|
}
|
|
.rag-toggle {
|
display: flex;
|
align-items: center;
|
gap: 7px;
|
cursor: pointer;
|
}
|
|
.rag-toggle-label {
|
font-size: 12.5px;
|
color: var(--text-secondary);
|
}
|
|
.rag-toggle-label.disabled {
|
color: var(--text-muted);
|
}
|
|
.composer-buttons {
|
display: flex;
|
gap: 8px;
|
}
|
|
.composer-hint {
|
text-align: center;
|
font-size: 11.5px;
|
color: var(--text-muted);
|
margin-top: 8px;
|
}
|
|
/* ---------------- 抽屉内部 ---------------- */
|
.rag-alert {
|
margin-bottom: 16px;
|
font-size: 12.5px;
|
line-height: 1.8;
|
}
|
|
.rag-section-title {
|
font-size: 13px;
|
font-weight: 600;
|
margin: 20px 0 10px;
|
}
|
|
.rag-section-title:first-of-type {
|
margin-top: 0;
|
}
|
|
.section-refresh {
|
float: right;
|
font-size: 11.5px;
|
color: var(--text-secondary);
|
margin-top: 1px;
|
}
|
|
.section-hint {
|
font-weight: 400;
|
color: var(--text-muted);
|
font-size: 11.5px;
|
margin-left: 6px;
|
}
|
|
.category-row {
|
display: flex;
|
align-items: center;
|
justify-content: space-between;
|
gap: 10px;
|
padding: 10px 12px;
|
border: 1px solid var(--border-color);
|
border-radius: 8px;
|
margin-bottom: 8px;
|
background: #fcfcfd;
|
}
|
|
.category-row-main {
|
min-width: 0;
|
flex: 1;
|
}
|
|
.category-name {
|
font-size: 13px;
|
font-weight: 500;
|
overflow: hidden;
|
text-overflow: ellipsis;
|
white-space: nowrap;
|
}
|
|
.category-meta {
|
font-size: 11.5px;
|
color: var(--text-muted);
|
margin-top: 3px;
|
}
|
|
.file-category {
|
color: #0f766e;
|
}
|
|
.file-row {
|
display: flex;
|
align-items: center;
|
justify-content: space-between;
|
gap: 10px;
|
padding: 10px 0;
|
border-bottom: 1px solid #f3f4f6;
|
}
|
|
.file-row-main {
|
min-width: 0;
|
flex: 1;
|
}
|
|
.file-name {
|
font-size: 13px;
|
overflow: hidden;
|
text-overflow: ellipsis;
|
white-space: nowrap;
|
}
|
|
/* 全局知识库标记:提示这个文档是全员共用的公共知识库 */
|
.global-badge {
|
display: inline-block;
|
margin-left: 6px;
|
padding: 0 5px;
|
font-size: 11px;
|
line-height: 16px;
|
border-radius: 4px;
|
color: #0f766e;
|
background: #ecfdf5;
|
vertical-align: middle;
|
}
|
|
.file-meta {
|
font-size: 11.5px;
|
color: var(--text-muted);
|
margin-top: 3px;
|
}
|
|
.file-status.ok {
|
color: #0f766e;
|
}
|
|
.file-status.fail {
|
color: #dc2626;
|
}
|
|
.file-status.pending {
|
color: #b45309;
|
}
|
|
.file-row-actions {
|
display: flex;
|
gap: 4px;
|
flex-shrink: 0;
|
}
|
|
.rag-footer {
|
font-size: 12.5px;
|
}
|
</style>
|