feat: 支持输入框内选择知识库和文件,优化选择交互体验

This commit is contained in:
wizardchen
2025-12-19 22:17:56 +08:00
committed by lyingbug
parent 485d8d7252
commit de1ffa7f7c
49 changed files with 2246 additions and 521 deletions
+5 -1
View File
@@ -28,7 +28,7 @@ export function useStream() {
let renderTimer: number | null = null
// 启动流式请求
const startStream = async (params: { session_id: any; query: any; knowledge_base_ids?: string[]; agent_enabled?: boolean; web_search_enabled?: boolean; summary_model_id?: string; mcp_service_ids?: string[]; method: string; url: string }) => {
const startStream = async (params: { session_id: any; query: any; knowledge_base_ids?: string[]; knowledge_ids?: string[]; agent_enabled?: boolean; web_search_enabled?: boolean; summary_model_id?: string; mcp_service_ids?: string[]; method: string; url: string }) => {
// 重置状态
output.value = '';
error.value = null;
@@ -85,6 +85,10 @@ export function useStream() {
if (params.knowledge_base_ids !== undefined && params.knowledge_base_ids.length > 0) {
postBody.knowledge_base_ids = params.knowledge_base_ids;
}
// Include knowledge_ids if provided
if (params.knowledge_ids !== undefined && params.knowledge_ids.length > 0) {
postBody.knowledge_ids = params.knowledge_ids;
}
// Include web_search_enabled if provided
if (params.web_search_enabled !== undefined) {
postBody.web_search_enabled = params.web_search_enabled;
+5 -1
View File
@@ -230,4 +230,8 @@ export interface FAQImportProgress {
export function getFAQImportProgress(taskId: string) {
return get(`/api/v1/faq/import/progress/${taskId}`);
}
}
export function searchKnowledge(keyword: string, offset = 0, limit = 20) {
return get(`/api/v1/knowledge/search?keyword=${encodeURIComponent(keyword)}&offset=${offset}&limit=${limit}`);
}
File diff suppressed because it is too large Load Diff
+243
View File
@@ -0,0 +1,243 @@
<template>
<div v-if="visible" class="mention-menu" :style="style" ref="menuRef" @click.stop @scroll="onScroll">
<!-- Knowledge Bases Group -->
<div v-if="kbItems.length > 0" class="mention-group">
<div class="mention-group-header">{{ $t('common.knowledgeBase') }}</div>
<div
v-for="(item, index) in kbItems"
:key="item.id"
class="mention-item"
:class="{ active: index === activeIndex }"
@click="$emit('select', item)"
@mouseenter="$emit('update:activeIndex', index)"
>
<div class="icon" :class="item.kbType === 'faq' ? 'faq-icon' : 'kb-icon'">
<t-icon :name="item.kbType === 'faq' ? 'chat-bubble-help' : 'folder'" />
</div>
<span class="name">{{ item.name }}</span>
<span class="count">({{ item.count || 0 }})</span>
</div>
</div>
<!-- Files Group -->
<div v-if="fileItems.length > 0" class="mention-group">
<div class="mention-group-header">{{ $t('common.file') }}</div>
<div
v-for="(item, index) in fileItems"
:key="item.id"
class="mention-item"
:class="{ active: (kbItems.length + index) === activeIndex }"
@click="$emit('select', item)"
@mouseenter="$emit('update:activeIndex', kbItems.length + index)"
>
<div class="icon file-icon">
<t-icon name="file" />
</div>
<span class="name">{{ item.name }}</span>
<span v-if="item.kbName" class="kb-name">{{ item.kbName }}</span>
</div>
<!-- Loading indicator -->
<div v-if="loading" class="loading-more">
<t-loading size="small" />
</div>
</div>
<div v-if="items.length === 0 && !loading" class="empty">
{{ $t('common.noResult') }}
</div>
</div>
</template>
<script setup lang="ts">
import { computed, watch, ref, nextTick } from 'vue';
const props = defineProps<{
visible: boolean;
style: any;
items: Array<{ id: string; name: string; type: 'kb' | 'file'; kbType?: 'document' | 'faq'; count?: number; kbName?: string }>;
activeIndex: number;
hasMore?: boolean;
loading?: boolean;
}>();
const emit = defineEmits(['select', 'update:activeIndex', 'loadMore']);
const menuRef = ref<HTMLElement | null>(null);
const kbItems = computed(() => props.items.filter(item => item.type === 'kb'));
const fileItems = computed(() => props.items.filter(item => item.type === 'file'));
const onScroll = (e: Event) => {
const target = e.target as HTMLElement;
const { scrollTop, scrollHeight, clientHeight } = target;
// Load more when scrolled to bottom (with 50px threshold)
if (scrollHeight - scrollTop - clientHeight < 50 && props.hasMore && !props.loading) {
emit('loadMore');
}
};
watch(() => props.activeIndex, (newIndex) => {
scrollToItem(newIndex);
});
watch(() => props.visible, (newVisible) => {
if (newVisible) {
nextTick(() => {
if (menuRef.value) menuRef.value.scrollTop = 0;
scrollToItem(props.activeIndex);
});
}
});
const scrollToItem = (index: number) => {
nextTick(() => {
if (!menuRef.value) return;
const items = menuRef.value.querySelectorAll('.mention-item');
if (!items || items.length <= index) return;
const activeItem = items[index] as HTMLElement;
const menu = menuRef.value;
if (activeItem) {
const menuRect = menu.getBoundingClientRect();
const itemRect = activeItem.getBoundingClientRect();
// 检查是否在上方被遮挡
if (itemRect.top < menuRect.top) {
menu.scrollTop -= (menuRect.top - itemRect.top);
}
// 检查是否在下方被遮挡
else if (itemRect.bottom > menuRect.bottom) {
menu.scrollTop += (itemRect.bottom - menuRect.bottom);
}
}
});
};
</script>
<style scoped>
.mention-menu {
position: fixed;
z-index: 10000;
background: var(--td-bg-color-container, #fff);
border: 1px solid var(--td-component-border, #e7e9eb);
border-radius: var(--td-radius-medium, 6px);
box-shadow: var(--td-shadow-2, 0 3px 14px 2px rgba(0, 0, 0, 0.05));
width: 300px;
max-height: 360px;
overflow-y: auto;
display: flex;
flex-direction: column;
padding: 4px 0;
}
.mention-group {
padding: 4px 0;
}
.mention-group:not(:last-child) {
border-bottom: 1px solid var(--td-component-border, #f0f0f0);
}
.mention-group-header {
padding: 8px 12px 4px;
font-size: var(--td-font-size-mark-small, 12px);
font-weight: 600;
color: var(--td-text-color-secondary, #999);
}
.mention-item {
display: flex;
align-items: center;
gap: 8px;
padding: 8px 12px;
margin: 0 4px;
cursor: pointer;
border-radius: var(--td-radius-default, 3px);
color: var(--td-text-color-primary, #333);
font-size: var(--td-font-size-body-medium, 14px);
font-family: var(--td-font-family, "PingFang SC");
transition: background 0.2s cubic-bezier(0.38, 0, 0.24, 1);
}
.mention-item:hover {
background: var(--td-bg-color-container-hover, #f3f3f3);
}
.mention-item.active {
background: var(--td-brand-color-light, #e9f8ec);
color: var(--td-brand-color, #07c05f);
}
.icon {
display: flex;
align-items: center;
justify-content: center;
width: 20px;
height: 20px;
border-radius: var(--td-radius-small, 2px);
flex-shrink: 0;
/* background: var(--td-bg-color-secondarycontainer, #f3f3f3); */
}
/* Document KB - Greenish */
.kb-icon {
background: rgba(16, 185, 129, 0.1);
color: #10b981;
}
/* FAQ KB - Blueish */
.faq-icon {
background: rgba(0, 82, 217, 0.1);
color: #0052d9;
}
/* File - Orange */
.file-icon {
background: rgba(237, 123, 47, 0.1);
color: #ed7b2f;
}
.mention-item.active .icon {
/* Active state keeps the colored icon but maybe adjusts background or just inherits */
background: transparent;
color: inherit;
}
.name {
flex: 1;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
.count {
flex-shrink: 0;
font-size: var(--td-font-size-mark-small, 12px);
color: var(--td-text-color-secondary, #999);
}
.kb-name {
flex-shrink: 0;
max-width: 80px;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
font-size: var(--td-font-size-mark-small, 12px);
color: var(--td-text-color-secondary, #999);
}
.empty {
padding: 24px 12px;
text-align: center;
color: var(--td-text-color-placeholder, #999);
font-size: var(--td-font-size-body-medium, 14px);
}
.loading-more {
display: flex;
justify-content: center;
padding: 8px 12px;
}
</style>
+4
View File
@@ -638,6 +638,9 @@ export default {
confirmDelete: 'Confirm Delete',
deleteSuccess: 'Deleted successfully',
deleteFailed: 'Delete failed',
file: 'File',
knowledgeBase: 'Knowledge Base',
noResult: 'No results',
},
file: {
upload: 'Upload File',
@@ -746,6 +749,7 @@ export default {
input: {
addModel: 'Add Model',
placeholder: 'Ask questions based on the knowledge base',
placeholderWithContext: 'Enter your question, will answer based on selected knowledge bases/files above',
agentMode: 'Agent Mode',
normalMode: 'Normal Mode',
normalModeDesc: 'Knowledge base RAG Q&A',
+4
View File
@@ -639,6 +639,9 @@ export default {
confirmDelete: 'Подтвердить удаление',
deleteSuccess: 'Успешно удалено',
deleteFailed: 'Ошибка удаления',
file: 'Файл',
knowledgeBase: 'База знаний',
noResult: 'Нет результатов',
},
file: {
upload: 'Загрузить файл',
@@ -1669,6 +1672,7 @@ export default {
input: {
addModel: 'Добавить модель',
placeholder: 'Задайте вопрос на основе базы знаний',
placeholderWithContext: 'Введите вопрос, ответ будет основан на выбранных выше базах знаний/файлах',
agentMode: 'Agent режим',
normalMode: 'Обычный режим',
normalModeDesc: 'RAG-вопросы и ответы по базе знаний',
+7
View File
@@ -731,6 +731,9 @@ export default {
confirmDelete: "确认删除",
deleteSuccess: "删除成功",
deleteFailed: "删除失败",
file: "文件",
knowledgeBase: "知识库",
noResult: "无结果",
},
file: {
upload: "上传文件",
@@ -1150,6 +1153,9 @@ export default {
messages: {
deleted: "已删除",
deleteFailed: "删除失败",
file: "文件",
knowledgeBase: "知识库",
noResult: "无结果",
},
features: {
knowledgeGraph: "已启用知识图谱",
@@ -1422,6 +1428,7 @@ export default {
input: {
addModel: "添加模型",
placeholder: "基于知识库提问",
placeholderWithContext: "输入问题,将基于上方选中的知识库/文件回答",
agentMode: "Agent 模式",
normalMode: "普通模式",
normalModeDesc: "基于知识库的 RAG 问答",
+28 -1
View File
@@ -8,6 +8,7 @@ interface Settings {
isAgentEnabled: boolean;
agentConfig: AgentConfig;
selectedKnowledgeBases: string[]; // 当前选中的知识库ID列表
selectedFiles: string[]; // 当前选中的文件ID列表
modelConfig: ModelConfig; // 模型配置
ollamaConfig: OllamaConfig; // Ollama配置
webSearchEnabled: boolean; // 网络搜索是否启用
@@ -71,6 +72,7 @@ const defaultSettings: Settings = {
use_custom_system_prompt: false
},
selectedKnowledgeBases: [], // 默认为空数组
selectedFiles: [], // 默认为空数组
modelConfig: {
chatModels: [],
embeddingModels: [],
@@ -273,5 +275,30 @@ export const useSettingsStore = defineStore("settings", {
this.settings.webSearchEnabled = enabled;
localStorage.setItem("WeKnora_settings", JSON.stringify(this.settings));
},
// File selection actions
addFile(fileId: string) {
if (!this.settings.selectedFiles) this.settings.selectedFiles = [];
if (!this.settings.selectedFiles.includes(fileId)) {
this.settings.selectedFiles.push(fileId);
localStorage.setItem("WeKnora_settings", JSON.stringify(this.settings));
}
},
removeFile(fileId: string) {
if (!this.settings.selectedFiles) return;
this.settings.selectedFiles = this.settings.selectedFiles.filter((id: string) => id !== fileId);
localStorage.setItem("WeKnora_settings", JSON.stringify(this.settings));
},
clearFiles() {
this.settings.selectedFiles = [];
localStorage.setItem("WeKnora_settings", JSON.stringify(this.settings));
},
getSelectedFiles(): string[] {
return this.settings.selectedFiles || [];
},
},
});
});
+58
View File
@@ -0,0 +1,58 @@
export interface CaretCoordinates {
top: number;
left: number;
height: number;
}
export function getCaretCoordinates(element: HTMLTextAreaElement, position: number): CaretCoordinates {
const div = document.createElement('div');
const style = window.getComputedStyle(element);
// Copy styles
const properties = [
'direction', 'boxSizing', 'width', 'height', 'overflowX', 'overflowY',
'borderTopWidth', 'borderRightWidth', 'borderBottomWidth', 'borderLeftWidth', 'borderStyle',
'paddingTop', 'paddingRight', 'paddingBottom', 'paddingLeft',
'fontStyle', 'fontVariant', 'fontWeight', 'fontStretch', 'fontSize', 'fontSizeAdjust', 'lineHeight', 'fontFamily',
'textAlign', 'textTransform', 'textIndent', 'textDecoration', 'letterSpacing', 'wordSpacing',
'tabSize', 'MozTabSize'
];
properties.forEach(prop => {
// @ts-ignore
div.style[prop] = style[prop];
});
div.style.position = 'absolute';
div.style.visibility = 'hidden';
div.style.whiteSpace = 'pre-wrap';
div.style.wordWrap = 'break-word';
div.style.top = '0';
div.style.left = '0';
// We append a special character to the end of the text to handle the case where the caret is at the end
const textContent = element.value.substring(0, position);
div.textContent = textContent;
const span = document.createElement('span');
// Use a zero-width space to simulate the caret position without adding visible width,
// but if it's at the end of a line, we might need something else.
// Standard trick is using a pipe or similar and measuring it.
span.textContent = '|';
div.appendChild(span);
document.body.appendChild(div);
const spanRect = span.getBoundingClientRect();
const divRect = div.getBoundingClientRect();
const coordinates = {
top: span.offsetTop + parseInt(style.borderTopWidth),
left: span.offsetLeft + parseInt(style.borderLeftWidth),
height: parseInt(style.lineHeight) || spanRect.height
};
document.body.removeChild(div);
return coordinates;
}
@@ -1074,9 +1074,28 @@ const renderMarkdown = (content: any): string => {
if (!content) return '';
// Ensure content is a string
const contentStr = typeof content === 'string' ? content : String(content || '');
let contentStr = typeof content === 'string' ? content : String(content || '');
if (!contentStr.trim()) return '';
// Handle streaming image syntax to prevent flickering
// Check if the content ends with an incomplete image markdown syntax like `![...` or `![...](...`
// This prevents the text from being rendered as plain text first and then jumping to an image
const lastImgStart = contentStr.lastIndexOf('![');
if (lastImgStart !== -1) {
// Only check the last occurrence to see if it's incomplete
// We check if the tail (from the last ![) contains a matching closing parenthesis )
// This is a heuristic: if the last ![ doesn't have a corresponding ), it's likely incomplete
const potentialImgTag = contentStr.slice(lastImgStart);
const hasClosingParen = potentialImgTag.includes(')');
const hasClosingBracket = potentialImgTag.includes(']');
// If we have ![ but missing ] or ), it's incomplete
// Note: This is a simple check. It might false positive on `![text] (note)` but that's rare in this context
if (!hasClosingBracket || !hasClosingParen) {
contentStr = contentStr.slice(0, lastImgStart);
}
}
try {
// Preprocess custom citation tags into safe HTML the sanitizer will allow
// Supported formats:
+3 -11
View File
@@ -311,18 +311,9 @@ const sendMsg = async (value, modelId = '') => {
// Get knowledge_base_ids from settings store (selected by user via KnowledgeBaseSelector)
const kbIds = useSettingsStoreInstance.settings.selectedKnowledgeBases || [];
const knowledgeIds = useSettingsStoreInstance.settings.selectedFiles || [];
// Validate knowledge_base_ids before sending (only when agent mode is enabled)
if (agentEnabled && kbIds.length === 0) {
MessagePlugin.warning(t('chat.selectKnowledgeBaseWarning'));
isReplying.value = false;
loading.value = false;
// 清空当前 assistant message ID
currentAssistantMessageId.value = '';
// Remove the user message that was just added
messagesList.pop();
return;
}
// Use agent-chat endpoint when agent is enabled, otherwise use knowledge-chat
const endpoint = agentEnabled ? '/api/v1/agent-chat' : '/api/v1/knowledge-chat';
@@ -333,6 +324,7 @@ const sendMsg = async (value, modelId = '') => {
await startStream({
session_id: session_id.value,
knowledge_base_ids: kbIds,
knowledge_ids: knowledgeIds,
agent_enabled: agentEnabled,
web_search_enabled: webSearchEnabled,
summary_model_id: modelId,
+3 -6
View File
@@ -44,12 +44,8 @@ const sendMsg = (value: string) => {
}
async function createNewSession(value: string) {
const selectedKbs = settingsStore.settings.selectedKnowledgeBases;
if (!selectedKbs || selectedKbs.length === 0) {
MessagePlugin.warning(t('createChat.messages.selectKnowledgeBase'));
return;
}
const selectedKbs = settingsStore.settings.selectedKnowledgeBases || [];
const selectedFiles = settingsStore.settings.selectedFiles || [];
// 构建 session 数据,包含 Agent 配置
const sessionData: any = {};
@@ -60,6 +56,7 @@ async function createNewSession(value: string) {
max_iterations: settingsStore.agentConfig.maxIterations,
temperature: settingsStore.agentConfig.temperature,
knowledge_bases: selectedKbs, // 所有选中的知识库
knowledge_ids: selectedFiles, // 所有选中的普通知识/文件
allowed_tools: settingsStore.agentConfig.allowedTools
};