feat(chat): add session-scoped temporary attachments with async parsing

Let users upload documents in chat without ingesting them into a knowledge base: files are parsed in the background, referenced by ID on send, and expire after a configurable TTL.
This commit is contained in:
wizardchen
2026-07-16 14:48:20 +08:00
committed by lyingbug
parent 7b2c9e73bf
commit ceb4d1a310
63 changed files with 3513 additions and 248 deletions
+10
View File
@@ -79,6 +79,16 @@ export interface CustomAgentConfig {
image_storage_provider?: string; // 图片存储提供商
audio_upload_enabled?: boolean; // 是否启用音频上传/ASR转录(默认: false)
asr_model_id?: string; // ASR模型ID(音频转录用)
// 附件图片理解 / 扫描件 OCR 开关(默认: false,开启会增加解析耗时)
attachment_image_understanding?: boolean;
// 扫描件 OCR 最大页数(0 = 使用全局默认 WEKNORA_CHAT_ATTACHMENT_OCR_MAX_PAGES)
attachment_ocr_max_pages?: number;
// 单轮问答等待附件解析完成的最长时间(秒,0 = 使用全局默认 WEKNORA_CHAT_ATTACHMENT_WAIT_TIMEOUT_SEC)
attachment_parse_wait_timeout_sec?: number;
// ===== 聊天附件解析引擎策略 =====
// 按文件类型选择解析引擎;优先级:请求 parser_engine > 智能体规则 > 租户规则 > auto
chat_parser_engine_rules?: { file_types: string[]; engine: string }[];
// ===== 文件类型限制 =====
// 支持的文件类型(如 ["csv", "xlsx", "xls"])
+4 -1
View File
@@ -36,7 +36,7 @@ export function useStream() {
let renderTimer: number | null = null
// 启动流式请求
const startStream = async (params: { session_id: any; query: any; knowledge_base_ids?: string[]; knowledge_ids?: string[]; tag_ids?: string[]; agent_enabled?: boolean; agent_id?: string; web_search_enabled?: boolean; enable_memory?: boolean; summary_model_id?: string; mcp_service_ids?: string[]; skill_names?: string[]; mentioned_items?: Array<{id: string; name: string; type: string; kb_type?: string; kb_id?: string; kb_name?: string; service_id?: string; skill_name?: string}>; images?: Array<{data: string}>; attachment_uploads?: Array<{data: string; file_name: string; file_size: number}>; suggestion_attribution?: { suggestion_set_id: string; question_id: string }; method: string; url: string; embed_token?: string; embed_session_sig?: string; embed_visitor_id?: string }) => {
const startStream = async (params: { session_id: any; query: any; knowledge_base_ids?: string[]; knowledge_ids?: string[]; tag_ids?: string[]; agent_enabled?: boolean; agent_id?: string; web_search_enabled?: boolean; enable_memory?: boolean; summary_model_id?: string; mcp_service_ids?: string[]; skill_names?: string[]; mentioned_items?: Array<{id: string; name: string; type: string; kb_type?: string; kb_id?: string; kb_name?: string; service_id?: string; skill_name?: string}>; images?: Array<{data: string}>; attachment_uploads?: Array<{data: string; file_name: string; file_size: number}>; attachment_ids?: string[]; suggestion_attribution?: { suggestion_set_id: string; question_id: string }; method: string; url: string; embed_token?: string; embed_session_sig?: string; embed_visitor_id?: string }) => {
const myGeneration = ++streamGeneration
// 重置状态
output.value = '';
@@ -133,6 +133,9 @@ export function useStream() {
if (params.attachment_uploads !== undefined && params.attachment_uploads.length > 0) {
postBody.attachment_uploads = params.attachment_uploads;
}
if (params.attachment_ids !== undefined && params.attachment_ids.length > 0) {
postBody.attachment_ids = params.attachment_ids;
}
if (params.suggestion_attribution) {
postBody.suggestion_attribution = params.suggestion_attribution;
}
@@ -0,0 +1,55 @@
import { del, get, getDown, postUpload } from '@/utils/request';
export type TemporaryAttachmentStatus = 'uploaded' | 'processing' | 'ready' | 'failed';
export interface TemporaryAttachment {
id: string;
session_id: string;
file_name: string;
file_type: string;
file_size: number;
mime_type?: string;
status: TemporaryAttachmentStatus;
token_count: number;
chunk_count: number;
image_refs?: Array<{ original_ref?: string; url: string; mime_type?: string }>;
error_message?: string;
expires_at: string;
}
interface AttachmentResponse {
success: boolean;
data: TemporaryAttachment;
}
export function uploadTemporaryAttachment(
sessionId: string,
file: File,
agentId?: string,
parserEngine?: string,
onProgress?: (percent: number) => void,
): Promise<AttachmentResponse> {
const form = new FormData();
form.append('file', file);
if (agentId) form.append('agent_id', agentId);
if (parserEngine) form.append('parser_engine', parserEngine);
return postUpload(
`/api/v1/sessions/${sessionId}/attachments`,
form,
(event) => {
if (event.total) onProgress?.(Math.round((event.loaded * 100) / event.total));
},
);
}
export function getTemporaryAttachment(sessionId: string, attachmentId: string): Promise<AttachmentResponse> {
return get(`/api/v1/sessions/${sessionId}/attachments/${attachmentId}`);
}
export function previewTemporaryAttachment(sessionId: string, attachmentId: string): Promise<Blob> {
return getDown(`/api/v1/sessions/${sessionId}/attachments/${attachmentId}/preview`);
}
export function deleteTemporaryAttachment(sessionId: string, attachmentId: string): Promise<void> {
return del(`/api/v1/sessions/${sessionId}/attachments/${attachmentId}`);
}
+1
View File
@@ -73,6 +73,7 @@ export interface ParserEngineInfo {
/** 解析引擎配置(引擎相关存空间;docreader 地址由环境变量配置) */
export interface ParserEngineConfig {
chat_parser_engine_rules?: Array<{ file_types: string[]; engine: string }>
docreader_addr?: string
docreader_transport?: string
mineru_endpoint?: string
+161 -11
View File
@@ -1,7 +1,15 @@
<script setup lang="ts">
import { ref, computed } from 'vue';
import { ref, computed, onMounted, onUnmounted } from 'vue';
import { MessagePlugin } from 'tdesign-vue-next';
import { useI18n } from 'vue-i18n';
import { MAX_FILE_SIZE_MB } from '@/utils';
import { getParserEngines } from '@/api/system';
import {
deleteTemporaryAttachment,
getTemporaryAttachment,
uploadTemporaryAttachment,
type TemporaryAttachmentStatus,
} from '@/api/chat/temporary-attachments';
const { t } = useI18n();
@@ -12,12 +20,18 @@ export interface AttachmentFile {
size: number;
type: string;
preview?: string;
documentId?: string;
status: TemporaryAttachmentStatus | 'local' | 'uploading';
progress?: number;
error?: string;
}
const props = defineProps<{
maxFiles?: number;
maxSize?: number; // in MB
disabled?: boolean;
sessionId?: string;
agentId?: string;
}>();
const emit = defineEmits<{
@@ -27,19 +41,40 @@ const emit = defineEmits<{
const attachments = ref<AttachmentFile[]>([]);
const fileInputRef = ref<HTMLInputElement>();
const pollTimers = new Map<string, ReturnType<typeof setTimeout>>();
let disposed = false;
// Supported file types (matching backend)
const SUPPORTED_TYPES = [
const supportedTypes = ref([
// Documents
'.pdf', '.doc', '.docx', '.xls', '.xlsx', '.ppt', '.pptx', '.epub', '.mhtml',
// Text
'.txt', '.md', '.csv', '.json', '.xml', '.html',
'.markdown', '.yaml', '.yml', '.log',
// Images are parsed as documents here; the dedicated image button remains
// available for direct multimodal chat.
'.jpg', '.jpeg', '.png', '.gif', '.bmp', '.tiff', '.webp',
// Audio
'.mp3', '.wav', '.m4a', '.flac', '.ogg', '.aac',
];
]);
onMounted(async () => {
try {
const response = await getParserEngines();
const discovered = (response.data || [])
.filter(engine => engine.Available !== false)
.flatMap(engine => engine.FileTypes || [])
.filter(type => type && type.toLowerCase() !== 'url')
.map(type => `.${type.replace(/^\./, '').toLowerCase()}`);
supportedTypes.value = [...new Set([...supportedTypes.value, ...discovered])];
} catch {
// The static baseline remains available when engine discovery is offline.
}
});
const maxFiles = computed(() => props.maxFiles || 5);
const maxSize = computed(() => (props.maxSize || 20) * 1024 * 1024); // Convert MB to bytes
const maxSizeMB = computed(() => props.maxSize || MAX_FILE_SIZE_MB);
const maxSize = computed(() => maxSizeMB.value * 1024 * 1024); // Convert MB to bytes
const triggerFileSelect = () => {
if (props.disabled) return;
@@ -66,13 +101,13 @@ const addFiles = async (files: File[]) => {
// Check file size
if (file.size > maxSize.value) {
MessagePlugin.warning(t('chat.attachmentTooLarge', { name: file.name, max: props.maxSize || 20 }));
MessagePlugin.warning(t('chat.attachmentTooLarge', { name: file.name, max: maxSizeMB.value }));
continue;
}
// Check file type
const ext = '.' + file.name.split('.').pop()?.toLowerCase();
if (!SUPPORTED_TYPES.includes(ext)) {
if (!supportedTypes.value.includes(ext)) {
MessagePlugin.warning(t('chat.attachmentTypeNotSupported', { name: file.name }));
continue;
}
@@ -83,20 +118,88 @@ const addFiles = async (files: File[]) => {
name: file.name,
size: file.size,
type: file.type || ext,
status: props.sessionId ? 'uploading' : 'local',
progress: 0,
};
attachments.value.push(attachment);
emit('update:files', [...attachments.value]);
if (props.sessionId) {
void uploadAttachment(attachment);
}
}
emit('update:files', attachments.value);
};
const emitFiles = () => emit('update:files', [...attachments.value]);
const uploadAttachment = async (attachment: AttachmentFile) => {
if (!props.sessionId) return;
try {
const response = await uploadTemporaryAttachment(
props.sessionId,
attachment.file,
props.agentId,
'auto',
(progress) => {
attachment.progress = progress;
emitFiles();
},
);
attachment.documentId = response.data.id;
if (disposed || !attachments.value.some(item => item.id === attachment.id)) {
await deleteTemporaryAttachment(props.sessionId, response.data.id).catch(() => undefined);
return;
}
attachment.status = response.data.status;
attachment.progress = 100;
emitFiles();
if (attachment.status !== 'ready' && attachment.status !== 'failed') {
scheduleStatusPoll(attachment);
}
} catch (error: any) {
attachment.status = 'failed';
attachment.error = error?.message || t('chat.attachmentUploadFailed');
emitFiles();
}
};
const scheduleStatusPoll = (attachment: AttachmentFile) => {
clearPoll(attachment.id);
pollTimers.set(attachment.id, setTimeout(() => void pollStatus(attachment), 800));
};
const pollStatus = async (attachment: AttachmentFile) => {
if (!props.sessionId || !attachment.documentId || !attachments.value.some(item => item.id === attachment.id)) return;
try {
const response = await getTemporaryAttachment(props.sessionId, attachment.documentId);
attachment.status = response.data.status;
attachment.error = response.data.error_message;
emitFiles();
if (attachment.status !== 'ready' && attachment.status !== 'failed') scheduleStatusPoll(attachment);
} catch (error: any) {
attachment.status = 'failed';
attachment.error = error?.message || t('chat.attachmentParseFailed');
emitFiles();
}
};
const clearPoll = (id: string) => {
const timer = pollTimers.get(id);
if (timer) clearTimeout(timer);
pollTimers.delete(id);
};
const removeAttachment = (id: string) => {
const index = attachments.value.findIndex(a => a.id === id);
if (index !== -1) {
const attachment = attachments.value[index];
clearPoll(id);
attachments.value.splice(index, 1);
emit('update:files', attachments.value);
emitFiles();
emit('remove', id);
if (props.sessionId && attachment.documentId) {
void deleteTemporaryAttachment(props.sessionId, attachment.documentId).catch(() => undefined);
}
}
};
@@ -122,11 +225,27 @@ const getFileIcon = (fileName: string): string => {
return 'file';
};
const statusLabel = (attachment: AttachmentFile): string => {
if (attachment.status === 'uploading') return t('chat.attachmentUploading', { progress: attachment.progress || 0 });
if (attachment.status === 'uploaded' || attachment.status === 'processing') return t('chat.attachmentParsing');
if (attachment.status === 'ready') return t('chat.attachmentReady');
if (attachment.status === 'failed') return attachment.error || t('chat.attachmentParseFailed');
return '';
};
onUnmounted(() => {
disposed = true;
pollTimers.forEach(timer => clearTimeout(timer));
pollTimers.clear();
});
defineExpose({
attachments,
triggerFileSelect,
addFiles,
clear: () => {
pollTimers.forEach(timer => clearTimeout(timer));
pollTimers.clear();
attachments.value = [];
emit('update:files', []);
}
@@ -139,7 +258,7 @@ defineExpose({
<input
ref="fileInputRef"
type="file"
:accept="SUPPORTED_TYPES.join(',')"
:accept="supportedTypes.join(',')"
multiple
style="display: none"
@change="handleFileSelect"
@@ -165,6 +284,10 @@ defineExpose({
<div class="attachment-preview-info">
<div class="attachment-preview-name">{{ attachment.name }}</div>
<div class="attachment-preview-meta">{{ getFileExt(attachment.name) }}&nbsp;·&nbsp;{{ formatFileSize(attachment.size) }}</div>
<div v-if="attachment.status !== 'local'" class="attachment-preview-status" :class="`is-${attachment.status}`">
<span v-if="attachment.status === 'uploading' || attachment.status === 'uploaded' || attachment.status === 'processing'" class="attachment-status-spinner" />
{{ statusLabel(attachment) }}
</div>
</div>
<span class="attachment-preview-remove" @click="removeAttachment(attachment.id)" :aria-label="$t('common.remove')">×</span>
</div>
@@ -231,6 +354,29 @@ defineExpose({
white-space: nowrap;
}
.attachment-preview-status {
max-width: 170px;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
font-size: 11px;
color: var(--td-text-color-secondary, #999);
&.is-ready { color: var(--td-success-color, #2ba471); }
&.is-failed { color: var(--td-error-color, #d54941); }
}
.attachment-status-spinner {
display: inline-block;
width: 9px;
height: 9px;
margin-right: 3px;
border: 1px solid currentColor;
border-right-color: transparent;
border-radius: 50%;
animation: attachment-spin .8s linear infinite;
}
.attachment-preview-remove {
position: absolute;
top: 4px;
@@ -252,4 +398,8 @@ defineExpose({
}
}
}
@keyframes attachment-spin {
to { transform: rotate(360deg); }
}
</style>
@@ -0,0 +1,271 @@
<script setup lang="ts">
import { computed, onMounted, onUnmounted, ref } from 'vue'
import DocumentPreview from '@/components/document-preview.vue'
import { useChatAttachmentPreviewDrawer } from '@/composables/useChatAttachmentPreviewDrawer'
const drawer = useChatAttachmentPreviewDrawer()
const MAIN_DRAWER_WIDTH_KEY = 'weknora-chat-attachment-drawer-width'
const MAIN_DRAWER_DEFAULT_WIDTH = 654
const MAIN_DRAWER_MIN_WIDTH = 480
const mainDrawerWidth = ref(MAIN_DRAWER_DEFAULT_WIDTH)
const mainDrawerResizing = ref(false)
let mainResizeStartX = 0
let mainResizeStartWidth = 0
const visible = computed(() => drawer?.visible.value ?? false)
const target = computed(() => drawer?.target.value ?? null)
function mainDrawerMaxWidth() {
return Math.min(1600, Math.max(MAIN_DRAWER_MIN_WIDTH, Math.floor(window.innerWidth * 0.95)))
}
function clampMainDrawerWidth(width: number) {
return Math.max(MAIN_DRAWER_MIN_WIDTH, Math.min(mainDrawerMaxWidth(), width))
}
function loadMainDrawerWidth() {
try {
const raw = localStorage.getItem(MAIN_DRAWER_WIDTH_KEY)
const parsed = raw ? parseInt(raw, 10) : NaN
if (!Number.isNaN(parsed)) {
mainDrawerWidth.value = clampMainDrawerWidth(parsed)
}
} catch {
/* ignore */
}
}
function onMainDrawerResizeStart(e: MouseEvent) {
mainDrawerResizing.value = true
mainResizeStartX = e.clientX
mainResizeStartWidth = mainDrawerWidth.value
document.addEventListener('mousemove', onMainDrawerResizeMove)
document.addEventListener('mouseup', onMainDrawerResizeEnd)
document.body.style.cursor = 'col-resize'
document.body.style.userSelect = 'none'
}
function onMainDrawerResizeMove(e: MouseEvent) {
const delta = mainResizeStartX - e.clientX
mainDrawerWidth.value = clampMainDrawerWidth(mainResizeStartWidth + delta)
}
function onMainDrawerResizeEnd() {
document.removeEventListener('mousemove', onMainDrawerResizeMove)
document.removeEventListener('mouseup', onMainDrawerResizeEnd)
document.body.style.cursor = ''
document.body.style.userSelect = ''
mainDrawerResizing.value = false
try {
localStorage.setItem(MAIN_DRAWER_WIDTH_KEY, String(mainDrawerWidth.value))
} catch {
/* ignore */
}
}
function cleanupMainDrawerResize() {
document.removeEventListener('mousemove', onMainDrawerResizeMove)
document.removeEventListener('mouseup', onMainDrawerResizeEnd)
document.body.style.cursor = ''
document.body.style.userSelect = ''
mainDrawerResizing.value = false
}
function onWindowResize() {
mainDrawerWidth.value = clampMainDrawerWidth(mainDrawerWidth.value)
}
function close() {
drawer?.close()
}
onMounted(() => {
loadMainDrawerWidth()
window.addEventListener('resize', onWindowResize)
})
onUnmounted(() => {
window.removeEventListener('resize', onWindowResize)
cleanupMainDrawerResize()
})
</script>
<template>
<teleport to="body">
<div
v-if="mainDrawerResizing"
class="chat-attachment-drawer-resize-overlay"
aria-hidden="true"
/>
<div
v-if="visible"
class="chat-attachment-drawer-resize-handle"
:class="{ 'chat-attachment-drawer-resize-handle--active': mainDrawerResizing }"
:style="{ right: `${mainDrawerWidth}px` }"
role="separator"
aria-orientation="vertical"
@mousedown.prevent="onMainDrawerResizeStart"
>
<div class="chat-attachment-drawer-resize-line" />
</div>
</teleport>
<t-drawer
:visible="visible"
:z-index="2000"
:size="`${mainDrawerWidth}px`"
attach="body"
:close-btn="true"
:footer="false"
:class="['chat-attachment-preview-drawer', { 'chat-attachment-preview-drawer--resizing': mainDrawerResizing }]"
@close="close"
>
<template #header>
<div class="chat-attachment-drawer-header">
<div class="chat-attachment-drawer-header-icon">
<t-icon name="file" />
</div>
<div class="chat-attachment-drawer-header-text">
<div class="chat-attachment-drawer-header-title">{{ target?.fileName || '' }}</div>
</div>
</div>
</template>
<section v-if="target" class="chat-attachment-drawer-body">
<DocumentPreview
:session-id="target.sessionId"
:attachment-id="target.attachmentId"
:file-type="target.fileType"
:file-name="target.fileName"
:active="visible"
fill-height
/>
</section>
</t-drawer>
</template>
<style scoped lang="less">
:deep(.t-drawer__header) {
font-weight: normal;
}
.chat-attachment-drawer-header {
display: flex;
align-items: center;
gap: 10px;
min-width: 0;
width: 100%;
padding-right: 32px;
}
.chat-attachment-drawer-header-icon {
flex-shrink: 0;
width: 32px;
height: 32px;
border-radius: 9px;
display: flex;
align-items: center;
justify-content: center;
background: rgba(7, 192, 95, 0.1);
color: var(--td-brand-color);
font-size: 16px;
}
.chat-attachment-drawer-header-text {
flex: 1 1 auto;
min-width: 0;
}
.chat-attachment-drawer-header-title {
font-size: 15px;
font-weight: 600;
line-height: 1.4;
color: var(--td-text-color-primary);
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
.chat-attachment-drawer-body {
flex: 1;
min-height: 0;
display: flex;
flex-direction: column;
}
.chat-attachment-drawer-resize-overlay {
position: fixed;
inset: 0;
z-index: 2001;
cursor: col-resize;
}
.chat-attachment-drawer-resize-handle {
position: fixed;
top: 0;
bottom: 0;
width: 12px;
margin-left: -6px;
z-index: 2002;
cursor: col-resize;
display: flex;
align-items: center;
justify-content: center;
}
.chat-attachment-drawer-resize-line {
width: 2px;
height: 48px;
border-radius: 1px;
background: var(--td-component-border);
opacity: 0.55;
transition: opacity 0.15s ease, background 0.15s ease;
}
.chat-attachment-drawer-resize-handle:hover .chat-attachment-drawer-resize-line,
.chat-attachment-drawer-resize-handle--active .chat-attachment-drawer-resize-line {
opacity: 1;
background: var(--td-brand-color);
}
</style>
<style lang="less">
.t-drawer.chat-attachment-preview-drawer {
.t-drawer__content-wrapper,
.t-drawer__content {
height: 100%;
}
.t-drawer__header {
padding: 14px 18px;
border-bottom: 1px solid var(--td-component-stroke);
flex-shrink: 0;
}
.t-drawer__body {
flex: 1;
min-height: 0;
padding: 12px 16px 16px;
display: flex;
flex-direction: column;
overflow: hidden;
}
}
.t-drawer.chat-attachment-preview-drawer--resizing .t-drawer__content {
transition: none !important;
}
.t-drawer.chat-attachment-preview-drawer--resizing {
.chat-attachment-drawer-body,
.document-preview,
iframe,
.pdf-iframe {
pointer-events: none;
user-select: none;
}
}
</style>
+17 -1
View File
@@ -1849,6 +1849,21 @@ const createSession = async (val: string) => {
if (props.isReplying) {
return MessagePlugin.error(t('input.messages.replying'));
}
// Only block while the file is still uploading (no document ID yet). Once
// uploaded, sending is allowed even if parsing is still in progress: the
// backend shows a "parsing attachment" step on the timeline and waits.
const pendingAttachment = uploadedAttachments.value.find(item =>
item.status === 'uploading'
);
if (pendingAttachment) {
MessagePlugin.warning(t('chat.attachmentStillProcessing', { name: pendingAttachment.name }));
return;
}
const failedAttachment = uploadedAttachments.value.find(item => item.status === 'failed');
if (failedAttachment) {
MessagePlugin.error(failedAttachment.error || t('chat.attachmentParseFailed'));
return;
}
// Embed 渠道由后端绑定 agent/KB,勿走平台侧 agent 列表与就绪校验
if (props.embeddedMode) {
@@ -2446,7 +2461,8 @@ defineExpose({
</div>
<!-- 附件列表区域 (由 AttachmentUpload 组件渲染) -->
<AttachmentUpload ref="attachmentUploadRef" :max-files="5" :max-size="20"
<AttachmentUpload ref="attachmentUploadRef" :max-files="5"
:session-id="sessionId" :agent-id="selectedAgentId"
@update:files="uploadedAttachments = $event" />
<!-- 选中的知识库和文件标签(显示在输入框内顶部) -->
+83 -9
View File
@@ -2,6 +2,7 @@
<script setup lang="ts">
import { ref, shallowRef, watch, onUnmounted, nextTick, defineAsyncComponent } from 'vue';
import { previewKnowledgeFile } from '@/api/knowledge-base/index';
import { previewTemporaryAttachment } from '@/api/chat/temporary-attachments';
import { MessagePlugin } from 'tdesign-vue-next';
import hljs from 'highlight.js';
import 'highlight.js/styles/github.css';
@@ -16,10 +17,13 @@ const VueOfficePptx = defineAsyncComponent(() => import('@vue-office/pptx'));
const { t } = useI18n();
const props = defineProps<{
knowledgeId: string;
knowledgeId?: string;
sessionId?: string;
attachmentId?: string;
fileType: string;
fileName: string;
active: boolean;
fillHeight?: boolean;
}>();
const loading = ref(false);
@@ -248,11 +252,27 @@ function onImageLoad(e: Event) {
imageNaturalHeight.value = img.naturalHeight;
}
function getPreviewSourceKey(): string {
if (props.knowledgeId) return `knowledge:${props.knowledgeId}`;
if (props.sessionId && props.attachmentId) return `attachment:${props.sessionId}:${props.attachmentId}`;
return '';
}
async function fetchPreviewBlob(): Promise<Blob> {
if (props.knowledgeId) {
return previewKnowledgeFile(props.knowledgeId);
}
if (props.sessionId && props.attachmentId) {
return previewTemporaryAttachment(props.sessionId, props.attachmentId);
}
throw new Error('Missing preview source');
}
async function loadPreview() {
const id = props.knowledgeId;
const sourceKey = getPreviewSourceKey();
const ft = props.fileType;
if (!id || !ft) return;
if (loadedForId === id) return;
if (!sourceKey || !ft) return;
if (loadedForId === sourceKey) return;
cleanup();
loading.value = true;
@@ -265,9 +285,9 @@ async function loadPreview() {
}
try {
const rawBlob = await previewKnowledgeFile(id);
const rawBlob = await fetchPreviewBlob();
const blob = ensureBlobType(rawBlob, ft);
loadedForId = id;
loadedForId = sourceKey;
loading.value = false;
await nextTick();
@@ -333,9 +353,9 @@ function cleanup() {
}
watch(
() => [props.active, props.knowledgeId],
() => [props.active, props.knowledgeId, props.sessionId, props.attachmentId],
([active]) => {
if (active && props.knowledgeId) {
if (active && getPreviewSourceKey()) {
loadPreview();
}
},
@@ -349,7 +369,7 @@ onUnmounted(() => {
</script>
<template>
<div class="document-preview" :class="{ 'is-fullscreen': isFullscreen }">
<div class="document-preview" :class="{ 'is-fullscreen': isFullscreen, 'fill-height': fillHeight }">
<!-- Toolbar -->
<div class="preview-toolbar" v-if="!loading && !error && previewType !== 'unsupported'">
<t-space size="small">
@@ -474,6 +494,60 @@ onUnmounted(() => {
.document-preview {
min-height: 200px;
position: relative;
&.fill-height {
height: 100%;
min-height: 0;
display: flex;
flex-direction: column;
.preview-pdf,
.preview-pptx,
.preview-docx,
.preview-image,
.preview-excel,
.preview-markdown,
.preview-text,
.preview-audio,
.preview-loading,
.preview-error,
.preview-unsupported {
flex: 1;
min-height: 0;
max-height: none;
}
.preview-pdf {
height: auto;
min-height: 0;
}
.preview-pptx {
overflow: auto;
}
.preview-docx {
display: flex;
flex-direction: column;
.docx-container {
flex: 1;
min-height: 0;
max-height: none;
height: auto;
}
}
.preview-image .image-wrapper img {
max-height: 100%;
}
.preview-excel .excel-container,
.preview-markdown,
.preview-text .code-preview {
max-height: none;
}
}
}
.is-fullscreen {
@@ -0,0 +1,48 @@
import { inject, provide, ref, type InjectionKey, type Ref } from 'vue'
export type ChatAttachmentPreviewTarget = {
sessionId: string
attachmentId: string
fileName: string
fileType: string
}
export type ChatAttachmentPreviewDrawerContext = {
visible: Ref<boolean>
target: Ref<ChatAttachmentPreviewTarget | null>
open: (target: ChatAttachmentPreviewTarget) => void
close: () => void
}
const CHAT_ATTACHMENT_PREVIEW_DRAWER_KEY: InjectionKey<ChatAttachmentPreviewDrawerContext> = Symbol(
'chatAttachmentPreviewDrawer',
)
export function provideChatAttachmentPreviewDrawer(): ChatAttachmentPreviewDrawerContext {
const visible = ref(false)
const target = ref<ChatAttachmentPreviewTarget | null>(null)
const open = (next: ChatAttachmentPreviewTarget) => {
target.value = next
visible.value = true
}
const close = () => {
visible.value = false
target.value = null
}
const ctx: ChatAttachmentPreviewDrawerContext = {
visible,
target,
open,
close,
}
provide(CHAT_ATTACHMENT_PREVIEW_DRAWER_KEY, ctx)
return ctx
}
export function useChatAttachmentPreviewDrawer(): ChatAttachmentPreviewDrawerContext | null {
return inject(CHAT_ATTACHMENT_PREVIEW_DRAWER_KEY, null)
}
+30
View File
@@ -227,6 +227,13 @@ const messages = {
"attachmentTooMany": "最多上传 {max} 个附件",
"attachmentTooLarge": "文件 {name} 超过 {max}MB 限制",
"attachmentTypeNotSupported": "不支持的文件类型:{name}",
"attachmentUploading": "上传中 {progress}%",
"attachmentParsing": "正在解析",
"attachmentReady": "解析完成",
"attachmentUploadFailed": "附件上传失败",
"attachmentParseFailed": "附件解析失败",
"attachmentStillProcessing": "附件 {name} 仍在解析,请稍候",
"attachmentParseTimeout": "附件解析时间过长,请稍后重试",
"copySuccess": "已复制到剪贴板",
"copyFailed": "复制失败",
"emptyContentWarning": "当前回答为空",
@@ -375,6 +382,11 @@ const messages = {
"chunkRange": "已加载 {fetched} / {total} 个分块",
"page": "第 {page} 页,每页 {pageSize} 个"
},
"attachmentParsing": {
"parsedSummary": "已解析 {count} 个附件",
"parsedWithSkipped": "已解析 {parsed} 个附件,{skipped} 个未完成已跳过",
"noneReady": "没有可用的已解析附件"
},
"ragPipeline": {
"understanding": "正在理解问题...",
"understandDone": "已完成问题理解",
@@ -410,6 +422,9 @@ const messages = {
"imageAnalyzing": "正在查看图片内容...",
"imageAnalysisDone": "已查看图片内容",
"imageAnalysisFailed": "图片内容查看失败",
"attachmentParsing": "正在解析附件...",
"attachmentParsingDone": "已解析附件",
"attachmentParsingFailed": "附件解析失败",
"queryUnderstanding": "正在理解问题...",
"queryUnderstandDone": "已完成问题理解",
"called": "调用 {name}",
@@ -703,6 +718,13 @@ const messages = {
"attachmentTooMany": "Maximum {max} attachments allowed",
"attachmentTooLarge": "File {name} exceeds {max}MB limit",
"attachmentTypeNotSupported": "Unsupported file type: {name}",
"attachmentUploading": "Uploading {progress}%",
"attachmentParsing": "Parsing",
"attachmentReady": "Ready",
"attachmentUploadFailed": "Attachment upload failed",
"attachmentParseFailed": "Attachment parsing failed",
"attachmentStillProcessing": "Attachment {name} is still being parsed",
"attachmentParseTimeout": "Attachment parsing timed out. Please try again later.",
"copySuccess": "Copied to clipboard",
"copyFailed": "Copy failed",
"emptyContentWarning": "Content is empty",
@@ -851,6 +873,11 @@ const messages = {
"chunkRange": "Loaded {fetched} / {total} chunks",
"page": "Page {page}, {pageSize} per page"
},
"attachmentParsing": {
"parsedSummary": "Parsed {count} attachment(s)",
"parsedWithSkipped": "Parsed {parsed} attachment(s), {skipped} skipped (still processing)",
"noneReady": "No parsed attachments available"
},
"ragPipeline": {
"understanding": "Understanding query...",
"understandDone": "Query understood",
@@ -886,6 +913,9 @@ const messages = {
"imageAnalyzing": "Viewing image content...",
"imageAnalysisDone": "Image content viewed",
"imageAnalysisFailed": "Image viewing failed",
"attachmentParsing": "Parsing attachments...",
"attachmentParsingDone": "Attachments parsed",
"attachmentParsingFailed": "Attachment parsing failed",
"queryUnderstanding": "Understanding query...",
"queryUnderstandDone": "Query understood",
"called": "Called {name}",
+40 -9
View File
@@ -124,7 +124,7 @@ export default {
},
done: {
title: 'Then create an agent',
desc: 'After saving, close settings and click "Create agent". The wizard covers mode, knowledge bases, and multimodal options.',
desc: 'After saving, close settings and click "Create agent". The wizard covers mode, knowledge bases, and attachment upload options.',
},
},
},
@@ -231,12 +231,12 @@ export default {
desc: 'Allow the agent to call external search for up-to-date information.',
},
navMultimodal: {
title: 'Image upload (optional)',
desc: 'Lets users send images in chat; requires a VLM model in system settings.',
title: 'Attachment upload (optional)',
desc: 'Lets users send images, documents, and audio in chat; image understanding requires a VLM in system settings.',
},
multimodal: {
title: 'Enable image understanding',
desc: 'Turn on the switch and select a VLM below when enabled.',
title: 'Enable attachment upload',
desc: 'Configure image and audio upload plus attachment parse rules; select a VLM below when image upload is enabled.',
},
navTools: {
title: 'Tools & MCP (optional)',
@@ -1353,6 +1353,9 @@ export default {
docs: 'Docs',
loadFailed: 'Failed to load parser engine list',
ensureDocreaderConnected: 'Please ensure the DocReader service is configured via environment variables and connected',
chatPolicyTitle: 'Chat attachment parser policy',
chatPolicyDescription: 'Set the default parser per file type for chat attachments at the workspace level. Individual agents can override these rules.',
chatPolicySaved: 'Chat attachment parser policy saved',
checkDoneStatusUpdated: 'Checked with current parameters. Status above has been updated.',
checkSuccess: 'Test Connection Successful',
checkFailed: 'Check failed',
@@ -3297,6 +3300,13 @@ export default {
attachmentTooMany: 'Maximum {max} attachments allowed',
attachmentTooLarge: 'File {name} exceeds {max}MB limit',
attachmentTypeNotSupported: 'Unsupported file type: {name}',
attachmentUploading: 'Uploading {progress}%',
attachmentParsing: 'Parsing',
attachmentReady: 'Ready',
attachmentUploadFailed: 'Attachment upload failed',
attachmentParseFailed: 'Attachment parsing failed',
attachmentStillProcessing: 'Attachment {name} is still being parsed',
attachmentParseTimeout: 'Attachment parsing timed out. Please try again later.',
},
tenant: {
title: 'Workspace Information',
@@ -3709,6 +3719,7 @@ export default {
taskTypes: {
documentProcess: "Document parsing",
manualProcess: "Manual reprocessing",
temporaryDocumentProcess: "Chat attachment parsing",
postProcess: "Document post-processing",
summary: "Summary generation",
tableSummary: "Table summary generation",
@@ -5524,6 +5535,7 @@ export default {
todoWrite: 'Plan Management',
knowledgeGraphExtract: 'Knowledge Graph Extraction',
thinking: 'Thinking',
attachmentParsing: 'Parsing Attachment',
imageAnalysis: 'Image Analysis',
queryUnderstand: 'Understand Query',
queryKnowledgeGraph: 'Knowledge Graph Query',
@@ -5579,6 +5591,11 @@ export default {
chunkRange: 'Loaded {fetched} / {total} chunks',
page: 'Page {page}, {pageSize} per page',
},
attachmentParsing: {
parsedSummary: 'Parsed {count} attachment(s)',
parsedWithSkipped: 'Parsed {parsed} attachment(s), {skipped} skipped (still processing)',
noneReady: 'No parsed attachments available',
},
ragPipeline: {
understanding: 'Understanding query...',
understandDone: 'Query understood',
@@ -5614,6 +5631,9 @@ export default {
imageAnalyzing: 'Viewing image content...',
imageAnalysisDone: 'Image content viewed',
imageAnalysisFailed: 'Image viewing failed',
attachmentParsing: 'Parsing attachments...',
attachmentParsingDone: 'Attachments parsed',
attachmentParsingFailed: 'Attachment parsing failed',
queryUnderstanding: 'Understanding query...',
queryUnderstandDone: 'Query understood',
called: 'Called {name}',
@@ -5923,15 +5943,20 @@ export default {
placeholder: "Enter seconds, recommended range 60-1800",
},
imageUpload: {
navLabel: 'Multimodal',
sectionTitle: 'Multimodal Configuration',
sectionDesc: 'Configure image/audio upload and their VLM and ASR models',
navLabel: 'Attachment Upload',
sectionTitle: 'Attachment Upload',
sectionDesc: 'Configure image, document, and audio attachments in chat, plus parse rules and related models',
label: 'Image Upload',
desc: 'Allow users to upload images for multimodal Q&A in conversations',
desc: 'Allow users to upload images in chat for VLM understanding',
vlmModel: 'VLM Model',
vlmModelDesc: 'Vision language model for image analysis',
vlmModelPlaceholder: 'Select VLM model',
vlmModelRequired: 'VLM model is required when image upload is enabled',
imageUnderstandingLabel: 'Attachment Image Understanding / Scanned OCR',
imageUnderstandingDesc: 'For image-only PDFs/PPTs (scanned documents), run VLM OCR when no text can be extracted. Increases parse latency; off by default.',
ocrMaxPagesLabel: 'Scanned OCR Max Pages',
ocrMaxPagesDesc: 'Max pages of a scanned document sent to the VLM for OCR. More pages means better coverage but slower and costlier parsing. 0 uses the global default.',
useGlobalDefault: '0 = global default',
storageProvider: 'Image Storage',
storageProviderDesc: 'Storage engine for uploaded images. Leave empty to use system default',
storageProviderPlaceholder: 'Select storage engine',
@@ -5946,6 +5971,12 @@ export default {
asrModelDesc: 'Speech recognition model for audio transcription. If not configured, audio files will be passed as placeholders.',
asrModelPlaceholder: 'Select ASR Model',
},
chatParser: {
label: 'Chat Attachment Parsing Policy',
desc: 'Choose a parser engine per file type for this agent\'s chat attachments.',
waitTimeoutLabel: 'Attachment Parse Wait Timeout (s)',
waitTimeoutDesc: 'How long a chat turn waits for still-parsing attachments before proceeding with only the finished ones. Raise for large / scanned files. 0 uses the global default.',
},
faq: {
title: 'FAQ Priority Strategy',
tooltip: 'When the knowledge base contains FAQ (Q&A pairs), enable this strategy to prioritize FAQ answers over regular documents',
+40 -9
View File
@@ -124,7 +124,7 @@ export default {
},
done: {
title: "이후 에이전트 생성",
desc: "저장 후 설정을 닫고 「에이전트 생성」을 클릭하세요. 마법사가 모드·지식 베이스·멀티모달 옵션을 안내합니다.",
desc: "저장 후 설정을 닫고 「에이전트 생성」을 클릭하세요. 마법사가 모드·지식 베이스·첨부 업로드 옵션을 안내합니다.",
},
},
},
@@ -231,12 +231,12 @@ export default {
desc: "최신 정보를 위해 외부 검색을 호출할 수 있게 합니다.",
},
navMultimodal: {
title: "이미지 업로드(선택)",
desc: "채팅에서 이미지 전송을 허용합니다. 시스템 설정에 VLM이 필요합니다.",
title: "첨부 업로드(선택)",
desc: "채팅에서 이미지, 문서, 오디오 등 첨부를 허용합니다. 이미지 이해에는 시스템 설정의 VLM이 필요합니다.",
},
multimodal: {
title: "이미지 이해 켜기",
desc: "스위치를 켜고 아래에서 VLM을 선택하세요.",
title: "첨부 업로드 켜기",
desc: "이미지·오디오 업로드와 첨부 파싱 규칙을 설정하세요. 이미지 업로드 시 아래에서 VLM을 선택해야 합니다.",
},
navTools: {
title: "도구 및 MCP(선택)",
@@ -1057,6 +1057,13 @@ export default {
attachmentTooMany: "최대 {max}개 파일까지 업로드 가능합니다",
attachmentTooLarge: "파일 {name}이(가) {max}MB 제한을 초과합니다",
attachmentTypeNotSupported: "지원하지 않는 파일 형식: {name}",
attachmentUploading: "업로드 중 {progress}%",
attachmentParsing: "분석 중",
attachmentReady: "준비됨",
attachmentUploadFailed: "첨부 파일 업로드 실패",
attachmentParseFailed: "첨부 파일 분석 실패",
attachmentStillProcessing: "첨부 파일 {name}을(를) 아직 분석 중입니다",
attachmentParseTimeout: "첨부 파일 분석 시간이 초과되었습니다. 나중에 다시 시도하세요.",
},
settings: {
title: "설정",
@@ -1186,6 +1193,9 @@ export default {
title: '파서 엔진',
description: '문서 파서 엔진 상태 및 구성. 이 설정은 서버 환경변수보다 우선 적용됩니다. 비워두면 환경변수 기본값을 사용합니다.',
// Section / label keys for the redesigned drawer
chatPolicyTitle: '채팅 첨부 파일 파서 정책',
chatPolicyDescription: '파일 형식별 채팅 첨부 파서를 공간 기본값으로 지정합니다. 개별 에이전트에서 덮어쓸 수 있습니다.',
chatPolicySaved: '채팅 첨부 파일 파서 정책을 저장했습니다',
supportedFileTypes: '지원 형식',
statusSection: '상태',
configSection: '구성',
@@ -2704,6 +2714,7 @@ export default {
taskTypes: {
documentProcess: "문서 파싱",
manualProcess: "수동 재처리",
temporaryDocumentProcess: "채팅 첨부 파일 파싱",
postProcess: "문서 후처리",
summary: "요약 생성",
tableSummary: "표 요약 생성",
@@ -5551,6 +5562,7 @@ export default {
todoWrite: '계획 관리',
knowledgeGraphExtract: '지식 그래프 추출',
thinking: '사고',
attachmentParsing: '첨부 파일 파싱',
imageAnalysis: '이미지 내용 분석',
queryUnderstand: '질문 이해',
queryKnowledgeGraph: '지식 그래프 조회',
@@ -5604,6 +5616,11 @@ export default {
chunkRange: '{fetched} / {total} 청크 로드됨',
page: '{page}페이지, 페이지당 {pageSize}개',
},
attachmentParsing: {
parsedSummary: '첨부 파일 {count}개 파싱 완료',
parsedWithSkipped: '첨부 파일 {parsed}개 파싱 완료, {skipped}개 미완료로 건너뜀',
noneReady: '사용 가능한 파싱된 첨부 파일이 없습니다',
},
ragPipeline: {
understanding: '질문 이해 중...',
understandDone: '질문 이해 완료',
@@ -5635,6 +5652,9 @@ export default {
imageAnalyzing: '이미지 내용 분석 중...',
imageAnalysisDone: '이미지 내용 분석 완료',
imageAnalysisFailed: '이미지 내용 분석 실패',
attachmentParsing: '첨부 파일 파싱 중...',
attachmentParsingDone: '첨부 파일 파싱 완료',
attachmentParsingFailed: '첨부 파일 파싱 실패',
queryUnderstanding: '질문 이해 중...',
queryUnderstandDone: '질문 이해 완료',
called: '{name} 호출 완료',
@@ -5927,15 +5947,20 @@ export default {
placeholder: "초 단위로 입력하세요. 권장 범위 60-1800",
},
imageUpload: {
navLabel: '멀티모달',
sectionTitle: '멀티모달 설정',
sectionDesc: '이미지/오디오 업로드와 VLM·ASR 모델을 설정합니다',
navLabel: '첨부 업로드',
sectionTitle: '첨부 업로드',
sectionDesc: '채팅에서 이미지, 문서, 오디오 등 첨부 업로드·파싱 및 관련 모델을 설정합니다',
label: '이미지 업로드',
desc: '활성화하면 사용자가 대화에서 이미지를 업로드하여 멀티모달 질의응답을 할 수 있습니다',
desc: '활성화하면 사용자가 대화에서 이미지를 업로드하고 VLM으로 이해할 수 있습니다',
vlmModel: 'VLM 모델',
vlmModelDesc: '이미지 분석을 위한 비전 언어 모델',
vlmModelPlaceholder: 'VLM 모델을 선택하세요',
vlmModelRequired: '이미지 업로드 활성화 시 VLM 모델을 선택해야 합니다',
imageUnderstandingLabel: '첨부 이미지 이해 / 스캔 문서 OCR',
imageUnderstandingDesc: '이미지로만 구성된 PDF/PPT(스캔 문서)에서 텍스트를 추출할 수 없을 때 VLM OCR을 실행합니다. 파싱 시간이 늘어나며 기본값은 꺼짐입니다.',
ocrMaxPagesLabel: '스캔 문서 OCR 최대 페이지 수',
ocrMaxPagesDesc: 'VLM OCR에 전달하는 스캔 문서의 최대 페이지 수입니다. 페이지가 많을수록 범위는 넓어지지만 느리고 비용이 큽니다. 0은 전역 기본값을 사용합니다.',
useGlobalDefault: '0 = 전역 기본값',
storageProvider: '이미지 저장소',
storageProviderDesc: '업로드 이미지의 저장 엔진을 선택합니다. 비워두면 시스템 기본값을 사용합니다',
storageProviderPlaceholder: '저장 엔진 선택',
@@ -5950,6 +5975,12 @@ export default {
asrModelDesc: '음성 인식 모델입니다. 설정하지 않으면 오디오 파일이 플레이스홀더로 전달됩니다',
asrModelPlaceholder: 'ASR 모델 선택',
},
chatParser: {
label: '채팅 첨부 파싱 정책',
desc: '현재 에이전트의 채팅 첨부 파일 유형별 파서 엔진을 지정합니다.',
waitTimeoutLabel: '첨부 파싱 대기 시간(초)',
waitTimeoutDesc: '한 번의 답변에서 파싱 중인 첨부를 기다리는 최대 시간이며, 초과하면 미완료 첨부는 건너뜁니다. 대용량/스캔 파일은 늘리세요. 0은 전역 기본값을 사용합니다.',
},
faq: {
title: 'FAQ 우선 전략',
tooltip: '지식베이스에 FAQ(질문-답변 쌍)가 포함된 경우, 이 전략을 활성화하면 FAQ 답변이 일반 문서보다 우선됩니다',
+40 -9
View File
@@ -124,7 +124,7 @@ export default {
},
done: {
title: 'Затем создайте агента',
desc: 'После сохранения закройте настройки и нажмите «Создать агента». Мастер охватит режим, базы знаний и мультимодальные опции.',
desc: 'После сохранения закройте настройки и нажмите «Создать агента». Мастер охватит режим, базы знаний и загрузку вложений.',
},
},
},
@@ -231,12 +231,12 @@ export default {
desc: 'Разрешить агенту вызывать внешний поиск для актуальной информации.',
},
navMultimodal: {
title: 'Загрузка изображений (необязательно)',
desc: 'Позволяет отправлять изображения в чате; нужна VLM в настройках.',
title: 'Загрузка вложений (необязательно)',
desc: 'Позволяет отправлять изображения, документы и аудио в чате; для понимания изображений нужна VLM в настройках.',
},
multimodal: {
title: 'Включить понимание изображений',
desc: 'Включите переключатель и выберите VLM ниже.',
title: 'Включить загрузку вложений',
desc: 'Настройте загрузку изображений и аудио, а также правила разбора вложений; при загрузке изображений выберите VLM ниже.',
},
navTools: {
title: 'Инструменты и MCP (необязательно)',
@@ -1270,6 +1270,9 @@ export default {
checkFailed: 'Проверка не пройдена',
saveSuccess: 'Сохранено',
saveFailed: 'Ошибка сохранения',
chatPolicyTitle: 'Политика обработки вложений чата',
chatPolicyDescription: 'Задайте парсер по умолчанию для каждого типа вложений чата на уровне пространства. Отдельные агенты могут переопределить эти правила.',
chatPolicySaved: 'Политика обработки вложений сохранена',
mineruEndpointPlaceholder: 'напр. https://your-mineru.example.com',
defaultPipeline: 'Pipeline по умолчанию',
languagePlaceholder: 'напр. ch, en, ja (по умолчанию ch)',
@@ -2400,6 +2403,7 @@ export default {
taskTypes: {
documentProcess: "Разбор документа",
manualProcess: "Ручная повторная обработка",
temporaryDocumentProcess: "Обработка вложения чата",
postProcess: "Постобработка документа",
summary: "Создание сводки",
tableSummary: "Создание сводки таблицы",
@@ -3967,6 +3971,13 @@ export default {
attachmentTooMany: 'Максимум {max} файлов',
attachmentTooLarge: 'Файл {name} превышает лимит {max} МБ',
attachmentTypeNotSupported: 'Неподдерживаемый тип файла: {name}',
attachmentUploading: 'Загрузка {progress}%',
attachmentParsing: 'Обработка',
attachmentReady: 'Готово',
attachmentUploadFailed: 'Не удалось загрузить вложение',
attachmentParseFailed: 'Не удалось обработать вложение',
attachmentStillProcessing: 'Вложение {name} ещё обрабатывается',
attachmentParseTimeout: 'Время обработки вложения истекло. Повторите попытку позже.',
thinkingAlt: 'Обдумывание...',
deepThoughtCompleted: 'Глубокий анализ завершён',
deepThoughtAlt: 'Глубокий анализ'
@@ -5051,6 +5062,7 @@ export default {
todoWrite: 'Управление планами',
knowledgeGraphExtract: 'Извлечение графа знаний',
thinking: 'Размышление',
attachmentParsing: 'Разбор вложения',
imageAnalysis: 'Анализ изображения',
queryUnderstand: 'Понимание запроса',
queryKnowledgeGraph: 'Запрос графа знаний',
@@ -5104,6 +5116,11 @@ export default {
chunkRange: 'Загружено {fetched} / {total} фрагментов',
page: 'Стр. {page}, по {pageSize} на странице',
},
attachmentParsing: {
parsedSummary: 'Разобрано вложений: {count}',
parsedWithSkipped: 'Разобрано вложений: {parsed}, пропущено (ещё обрабатываются): {skipped}',
noneReady: 'Нет готовых разобранных вложений',
},
ragPipeline: {
understanding: 'Анализ запроса...',
understandDone: 'Запрос понят',
@@ -5135,6 +5152,9 @@ export default {
imageAnalyzing: 'Анализ изображения...',
imageAnalysisDone: 'Анализ изображения завершён',
imageAnalysisFailed: 'Ошибка анализа изображения',
attachmentParsing: 'Разбор вложений...',
attachmentParsingDone: 'Вложения разобраны',
attachmentParsingFailed: 'Ошибка разбора вложений',
queryUnderstanding: 'Анализ запроса...',
queryUnderstandDone: 'Запрос понят',
called: 'Вызван {name}',
@@ -5426,15 +5446,20 @@ export default {
placeholder: 'Введите количество секунд, рекомендуемый диапазон 60-1800',
},
imageUpload: {
navLabel: 'Мультимодальность',
sectionTitle: 'Настройка мультимодальности',
sectionDesc: 'Настройте загрузку изображений/аудио и соответствующие модели VLM и ASR',
navLabel: 'Загрузка вложений',
sectionTitle: 'Загрузка вложений',
sectionDesc: 'Настройте загрузку и разбор изображений, документов и аудио в чате, а также связанные модели',
label: 'Загрузка изображений',
desc: 'Разрешить пользователям загружать изображения для мультимодальных вопросов и ответов',
desc: 'Разрешить пользователям загружать изображения в чате для понимания через VLM',
vlmModel: 'Модель VLM',
vlmModelDesc: 'Визуально-языковая модель для анализа изображений',
vlmModelPlaceholder: 'Выберите модель VLM',
vlmModelRequired: 'Модель VLM обязательна при включённой загрузке изображений',
imageUnderstandingLabel: 'Понимание изображений / OCR сканов',
imageUnderstandingDesc: 'Для PDF/PPT, состоящих только из изображений (сканов), запускать OCR через VLM, когда текст не извлекается. Увеличивает время разбора; по умолчанию выключено.',
ocrMaxPagesLabel: 'Макс. страниц OCR для сканов',
ocrMaxPagesDesc: 'Максимум страниц скана, отправляемых в VLM для OCR. Больше страниц — полнее охват, но медленнее и дороже. 0 использует глобальное значение по умолчанию.',
useGlobalDefault: '0 = глобальное значение',
storageProvider: 'Хранилище изображений',
storageProviderDesc: 'Хранилище для загруженных изображений. Оставьте пустым для системного значения по умолчанию',
storageProviderPlaceholder: 'Выберите хранилище',
@@ -5449,6 +5474,12 @@ export default {
asrModelDesc: 'Модель распознавания речи. Если не настроена, аудиофайлы передаются как заглушки.',
asrModelPlaceholder: 'Выберите ASR-модель',
},
chatParser: {
label: 'Политика разбора вложений чата',
desc: 'Выберите движок разбора по типу файла для вложений чата этого агента.',
waitTimeoutLabel: 'Тайм-аут ожидания разбора вложений (с)',
waitTimeoutDesc: 'Сколько ход чата ждёт ещё разбираемые вложения, прежде чем продолжить только с готовыми. Увеличьте для больших/сканированных файлов. 0 использует глобальное значение по умолчанию.',
},
faq: {
title: 'Стратегия приоритета FAQ',
tooltip: 'Если база знаний содержит FAQ (пары вопрос-ответ), включите эту стратегию для приоритета ответов FAQ над обычными документами',
+40 -9
View File
@@ -124,7 +124,7 @@ export default {
},
done: {
title: "然后创建智能体",
desc: "保存并关闭设置后,点击「创建智能体」,向导会带你配置模式、知识库与多模态等选项。",
desc: "保存并关闭设置后,点击「创建智能体」,向导会带你配置模式、知识库与附件上传等选项。",
},
},
},
@@ -231,12 +231,12 @@ export default {
desc: "配置是否允许智能体调用外部搜索引擎补充实时信息。",
},
navMultimodal: {
title: "图片上传(可选)",
desc: "开启后,对话中可上传图片并由 VLM 理解;需先在系统设置中配置 VLLM 模型。",
title: "附件上传(可选)",
desc: "开启后,对话中可上传图片、文档、音频等附件;图片理解需先在系统设置中配置 VLLM 模型。",
},
multimodal: {
title: "启用图片理解",
desc: "打开开关后,记得在下方选择 VLM 模型(开启时必填)。",
title: "启用附件上传",
desc: "可分别配置图片、音频上传及附件解析策略;启用图片上传时需在下方选择 VLM 模型。",
},
navTools: {
title: "工具与 MCP(可选)",
@@ -1065,6 +1065,13 @@ export default {
attachmentTooMany: "最多上传 {max} 个附件",
attachmentTooLarge: "文件 {name} 超过 {max}MB 限制",
attachmentTypeNotSupported: "不支持的文件类型:{name}",
attachmentUploading: "上传中 {progress}%",
attachmentParsing: "正在解析",
attachmentReady: "解析完成",
attachmentUploadFailed: "附件上传失败",
attachmentParseFailed: "附件解析失败",
attachmentStillProcessing: "附件 {name} 仍在解析,请稍候",
attachmentParseTimeout: "附件解析时间过长,请稍后重试",
},
settings: {
title: "设置",
@@ -1224,6 +1231,9 @@ export default {
checkFailed: "检测失败",
saveSuccess: "保存成功",
saveFailed: "保存失败",
chatPolicyTitle: "聊天附件解析策略",
chatPolicyDescription: "为不同文件类型指定聊天附件使用的解析引擎,作为空间级默认;单个智能体可覆盖此配置。",
chatPolicySaved: "聊天附件解析策略已保存",
mineruEndpointPlaceholder: "如 https://your-mineru.example.com",
defaultPipeline: "默认 pipeline",
languagePlaceholder: "如 ch、en、ja(默认 ch)",
@@ -2705,6 +2715,7 @@ export default {
taskTypes: {
documentProcess: "文档解析",
manualProcess: "手工重新处理",
temporaryDocumentProcess: "聊天附件解析",
postProcess: "文档后处理",
summary: "摘要生成",
tableSummary: "表格摘要生成",
@@ -5549,6 +5560,7 @@ export default {
todoWrite: "计划管理",
knowledgeGraphExtract: "知识图谱抽取",
thinking: "思考",
attachmentParsing: "解析附件",
imageAnalysis: "查看图片内容",
queryUnderstand: "理解问题",
queryKnowledgeGraph: "知识图谱查询",
@@ -5604,6 +5616,11 @@ export default {
chunkRange: "已加载 {fetched} / {total} 个分块",
page: "第 {page} 页,每页 {pageSize} 个",
},
attachmentParsing: {
parsedSummary: "已解析 {count} 个附件",
parsedWithSkipped: "已解析 {parsed} 个附件,{skipped} 个未完成已跳过",
noneReady: "没有可用的已解析附件",
},
ragPipeline: {
understanding: "正在理解问题...",
understandDone: "已完成问题理解",
@@ -5639,6 +5656,9 @@ export default {
imageAnalyzing: "正在查看图片内容...",
imageAnalysisDone: "已查看图片内容",
imageAnalysisFailed: "图片内容查看失败",
attachmentParsing: "正在解析附件...",
attachmentParsingDone: "已解析附件",
attachmentParsingFailed: "附件解析失败",
queryUnderstanding: "正在理解问题...",
queryUnderstandDone: "已完成问题理解",
called: "调用 {name}",
@@ -5948,15 +5968,20 @@ export default {
placeholder: "输入秒数,建议范围 60-1800",
},
imageUpload: {
navLabel: "多模态",
sectionTitle: "多模态配置",
sectionDesc: "配置图片/音频上传及对应的 VLM、ASR 模型",
navLabel: "附件上传",
sectionTitle: "附件上传",
sectionDesc: "配置对话中图片、文档、音频等附件的上传、解析及对应模型",
label: "图片上传",
desc: "启用后用户可在对话中上传图片进行多模态问答",
desc: "启用后用户可在对话中上传图片并由 VLM 理解",
vlmModel: "VLM 模型",
vlmModelDesc: "用于图片分析的视觉语言模型",
vlmModelPlaceholder: "请选择 VLM 模型",
vlmModelRequired: "启用图片上传时必须选择 VLM 模型",
imageUnderstandingLabel: "附件图片理解 / 扫描件 OCR",
imageUnderstandingDesc: "对图片型 PDF/PPT 等扫描件,当解析不出文字时用 VLM 进行 OCR 识别。开启会增加解析耗时,默认关闭。",
ocrMaxPagesLabel: "扫描件 OCR 最大页数",
ocrMaxPagesDesc: "扫描件送入 VLM 做 OCR 的最大页数,越多覆盖越全但越慢、越贵。0 表示使用全局默认。",
useGlobalDefault: "0 = 全局默认",
storageProvider: "图片存储",
storageProviderDesc: "选择图片文件的存储引擎,留空则使用系统默认",
storageProviderPlaceholder: "选择存储引擎",
@@ -5971,6 +5996,12 @@ export default {
asrModelDesc: "用于音频转录的语音识别模型,未配置时音频文件将以占位符形式传递",
asrModelPlaceholder: "请选择 ASR 模型",
},
chatParser: {
label: "聊天附件解析策略",
desc: "为不同文件类型指定解析引擎,仅对当前智能体的聊天附件生效",
waitTimeoutLabel: "附件解析等待超时(秒)",
waitTimeoutDesc: "单轮问答等待附件解析完成的最长时间,超时后未完成的附件会被跳过。大文件 / 扫描件可调大。0 表示使用全局默认。",
},
faq: {
title: "FAQ 优先策略",
tooltip: "当知识库中包含 FAQ(问答对)时,可以启用此策略让 FAQ 答案优先于普通文档",
@@ -76,3 +76,14 @@ test('getRagPipelineStepTitle uses web labels when search_source is web', () =>
})
assert.equal(title, 'agentStream.toolStatus.webSearch')
})
test('getRagPipelineStepTitle uses attachment parsing labels', () => {
assert.equal(
getRagPipelineStepTitle(t, { tool_name: 'attachment_parsing', pending: true }),
'agentStream.toolStatus.attachmentParsing',
)
assert.equal(
getRagPipelineStepTitle(t, { tool_name: 'attachment_parsing', pending: false, success: true }),
'agentStream.toolStatus.attachmentParsingDone',
)
})
+14
View File
@@ -183,5 +183,19 @@ export function getRagPipelineStepTitle(t: ComposerTranslation, event: RagPipeli
return query ? `${baseTitle}:「${query}」` : baseTitle
}
if (toolName === 'attachment_parsing') {
if (pending) return t('agentStream.toolStatus.attachmentParsing')
return event.success === false
? t('agentStream.toolStatus.attachmentParsingFailed')
: t('agentStream.toolStatus.attachmentParsingDone')
}
if (toolName === 'image_analysis') {
if (pending) return t('agentStream.toolStatus.imageAnalyzing')
return event.success === false
? t('agentStream.toolStatus.imageAnalysisFailed')
: t('agentStream.toolStatus.imageAnalysisDone')
}
return ''
}
+3
View File
@@ -33,6 +33,9 @@ export function getAgentToolIconName(
if (toolName === 'image_analysis' || toolName === 'query_understand') {
return 'ai-search'
}
if (toolName === 'attachment_parsing') {
return 'attach'
}
if (toolName.startsWith('mcp_')) {
return 'terminal'
}
@@ -0,0 +1,54 @@
import assert from 'node:assert/strict'
import test from 'node:test'
import {
getAttachmentParsingSummaryHtml,
resolveAttachmentParsingCounts,
} from './attachmentParsingDisplay.ts'
const t = (key, params) => {
if (key === 'agentStream.attachmentParsing.parsedSummary') {
return `已解析 ${params?.count} 个附件`
}
if (key === 'agentStream.attachmentParsing.parsedWithSkipped') {
return `已解析 ${params?.parsed} 个附件,${params?.skipped} 个未完成已跳过`
}
if (key === 'agentStream.attachmentParsing.noneReady') {
return '没有可用的已解析附件'
}
return key
}
test('resolveAttachmentParsingCounts prefers structured tool_data', () => {
assert.deepEqual(
resolveAttachmentParsingCounts({
tool_data: { parsed_count: 2, skipped_count: 1 },
}),
{ parsed: 2, skipped: 1 },
)
})
test('resolveAttachmentParsingCounts falls back to legacy output text', () => {
assert.deepEqual(
resolveAttachmentParsingCounts({
output: '已解析 3 个附件,1 个未完成已跳过',
}),
{ parsed: 3, skipped: 1 },
)
})
test('getAttachmentParsingSummaryHtml renders parsed count', () => {
const html = getAttachmentParsingSummaryHtml(t, {
success: true,
tool_data: { parsed_count: 1, skipped_count: 0 },
})
assert.equal(html, '已解析 <strong>1</strong> 个附件')
})
test('getAttachmentParsingSummaryHtml renders skipped count', () => {
const html = getAttachmentParsingSummaryHtml(t, {
success: true,
tool_data: { parsed_count: 2, skipped_count: 1 },
})
assert.equal(html, '已解析 <strong>2</strong> 个附件,<strong>1</strong> 个未完成已跳过')
})
@@ -0,0 +1,63 @@
import type { ComposerTranslation } from 'vue-i18n'
type AttachmentParsingEvent = {
success?: boolean
output?: string
error?: string
tool_data?: Record<string, unknown> | null
}
export function resolveAttachmentParsingCounts(event: AttachmentParsingEvent): {
parsed: number
skipped: number
} {
const toolData = event.tool_data
if (toolData && toolData.parsed_count !== undefined) {
return {
parsed: Number(toolData.parsed_count) || 0,
skipped: Number(toolData.skipped_count) || 0,
}
}
return parseAttachmentOutput(event.output)
}
function parseAttachmentOutput(output?: string): { parsed: number; skipped: number } {
if (!output) return { parsed: 0, skipped: 0 }
const parsedMatch = output.match(/已解析\s*(\d+)\s*个附件/)
const skippedMatch = output.match(/(\d+)\s*个未完成已跳过/)
const parsedEnMatch = output.match(/Parsed\s*(\d+)\s*attachment/i)
const skippedEnMatch = output.match(/(\d+)\s*skipped/i)
return {
parsed: Number(parsedMatch?.[1] ?? parsedEnMatch?.[1] ?? 0) || 0,
skipped: Number(skippedMatch?.[1] ?? skippedEnMatch?.[1] ?? 0) || 0,
}
}
export function getAttachmentParsingSummaryHtml(
t: ComposerTranslation,
event: AttachmentParsingEvent,
): string {
if (event.success === false) {
const err = String(event.error || event.output || '').trim()
if (!err) return ''
const normalized = err.replace(/^附件解析失败:\s*/i, '').trim()
return normalized || err
}
const { parsed, skipped } = resolveAttachmentParsingCounts(event)
if (parsed === 0 && skipped === 0) {
return t('agentStream.attachmentParsing.noneReady')
}
if (skipped > 0) {
return t('agentStream.attachmentParsing.parsedWithSkipped', {
parsed: `<strong>${parsed}</strong>`,
skipped: `<strong>${skipped}</strong>`,
})
}
return t('agentStream.attachmentParsing.parsedSummary', {
count: `<strong>${parsed}</strong>`,
})
}
@@ -0,0 +1,17 @@
import test from 'node:test';
import assert from 'node:assert/strict';
import {
isPreviewableAttachment,
resolveAttachmentFileType,
} from './attachmentPreview.ts';
test('resolveAttachmentFileType prefers explicit file_type', () => {
assert.equal(resolveAttachmentFileType('report.PDF', '.pdf'), 'pdf');
assert.equal(resolveAttachmentFileType('report.PDF', ''), 'pdf');
});
test('isPreviewableAttachment requires id and supported type', () => {
assert.equal(isPreviewableAttachment({ id: 'doc-1', file_name: 'notes.md' }), true);
assert.equal(isPreviewableAttachment({ file_name: 'notes.md' }), false);
assert.equal(isPreviewableAttachment({ id: 'doc-1', file_name: 'archive.zip' }), false);
});
+36
View File
@@ -0,0 +1,36 @@
const previewSupportedExtensions = new Set([
'pdf',
'docx', 'doc',
'pptx', 'ppt',
'xlsx', 'xls', 'csv',
'md', 'markdown',
'txt', 'json', 'xml', 'html', 'css', 'js', 'ts', 'py', 'java', 'go',
'cpp', 'c', 'h', 'sh', 'yaml', 'yml', 'ini', 'conf', 'log', 'sql', 'rs', 'rb', 'php',
'swift', 'kt', 'scala', 'r', 'lua', 'pl', 'toml',
'jpg', 'jpeg', 'png', 'gif', 'bmp', 'webp', 'tiff', 'svg',
'mp3', 'wav', 'm4a', 'flac', 'ogg',
]);
export type ChatAttachmentLike = {
id?: string;
file_name?: string;
file_type?: string;
};
export function resolveAttachmentFileType(fileName?: string, fileType?: string): string {
const normalizedType = String(fileType || '')
.trim()
.replace(/^\./, '')
.toLowerCase();
if (normalizedType) return normalizedType;
return String(fileName || '')
.split('.')
.pop()
?.toLowerCase() || '';
}
export function isPreviewableAttachment(attachment: ChatAttachmentLike | null | undefined): boolean {
if (!attachment?.id) return false;
const fileType = resolveAttachmentFileType(attachment.file_name, attachment.file_type);
return previewSupportedExtensions.has(fileType);
}
@@ -3,6 +3,7 @@ import test from 'node:test'
import {
ensureRagPipelineHistoryStream,
hasRagPipelineToolEvents,
RAG_TIMELINE_TOOL_NAMES,
synthesizeRagPipelineToolEvents,
} from './rag-pipeline-history.ts'
@@ -35,6 +36,54 @@ test('synthesizeRagPipelineToolEvents marks web-only references as web search',
assert.equal(events[1].tool_data.doc_count, 0)
})
test('synthesizeRagPipelineToolEvents skips retrieval when there are no references', () => {
const events = synthesizeRagPipelineToolEvents({
knowledge_references: [],
})
assert.equal(events.length, 0)
})
test('ensureRagPipelineHistoryStream does not invent retrieval for attachment-only turns', () => {
const item = {
is_completed: true,
content: 'answer from attachment only',
knowledge_references: [],
agentEventStream: [
{
type: 'tool_call',
tool_name: 'attachment_parsing',
tool_call_id: 'attach-1',
pending: false,
success: true,
tool_data: { parsed_count: 1, skipped_count: 0 },
},
],
}
ensureRagPipelineHistoryStream(item)
assert.equal(item.isAgentMode, true)
assert.equal(item.hideContent, true)
assert.equal(hasRagPipelineToolEvents(item.agentEventStream), false)
assert.equal(
item.agentEventStream.some((event) => event.tool_name === 'knowledge_search'),
false,
)
assert.equal(
item.agentEventStream.some((event) => event.tool_name === 'query_understand'),
false,
)
assert.equal(
item.agentEventStream.some((event) => event.tool_name === 'attachment_parsing'),
true,
)
assert.equal(
item.agentEventStream.some((event) => event.type === 'answer'),
true,
)
})
test('ensureRagPipelineHistoryStream restores quick-answer history after reload', () => {
const item = {
is_completed: true,
@@ -72,3 +121,9 @@ test('ensureRagPipelineHistoryStream keeps existing pipeline events', () => {
assert.equal(item.agentEventStream.length, 1)
assert.equal(item.agentEventStream[0].tool_call_id, 'live-1')
})
test('RAG_TIMELINE_TOOL_NAMES includes attachment prep tools', () => {
assert.equal(RAG_TIMELINE_TOOL_NAMES.has('attachment_parsing'), true)
assert.equal(RAG_TIMELINE_TOOL_NAMES.has('image_analysis'), true)
assert.equal(RAG_TIMELINE_TOOL_NAMES.has('knowledge_search'), true)
})
@@ -1,5 +1,12 @@
export const RAG_PIPELINE_TOOL_NAMES = new Set(['query_understand', 'knowledge_search'])
/** Tools rendered on the quick-answer timeline (includes pre-RAG attachment prep). */
export const RAG_TIMELINE_TOOL_NAMES = new Set([
...RAG_PIPELINE_TOOL_NAMES,
'attachment_parsing',
'image_analysis',
])
type RagHistoryReference = {
chunk_type?: string
knowledge_id?: string
@@ -41,6 +48,13 @@ export function synthesizeRagPipelineToolEvents(
item: RagHistoryMessage,
): Array<Record<string, unknown>> {
const refs = item.knowledge_references ?? []
// Only rebuild retrieval steps when citations prove a search actually ran.
// Content-only turns (e.g. attachment Q&A with no KB hits) must not get a
// fake "knowledge_search" row on history reload.
if (refs.length === 0) {
return []
}
const kbCounts: Record<string, number> = {}
let docCount = 0
let webCount = 0
+99 -3
View File
@@ -693,7 +693,7 @@
</div>
</div>
<!-- 多模态配置 -->
<!-- 附件上传 -->
<div v-show="currentSection === 'multimodal'" class="section">
<div class="section-header">
<h2>{{ $t('agentEditor.imageUpload.sectionTitle') }}</h2>
@@ -701,7 +701,7 @@
</div>
<div class="settings-group">
<!-- 图片上传(多模态) -->
<!-- 图片上传 -->
<div class="setting-row" data-guide="agent-create-multimodal">
<div class="setting-info">
<label>{{ $t('agentEditor.imageUpload.label') }}</label>
@@ -727,6 +727,31 @@
</div>
</div>
<!-- 附件图片理解 / 扫描件 OCR(图片上传启用时) -->
<div v-if="formData.config.image_upload_enabled" class="setting-row">
<div class="setting-info">
<label>{{ $t('agentEditor.imageUpload.imageUnderstandingLabel') }}</label>
<p class="desc">{{ $t('agentEditor.imageUpload.imageUnderstandingDesc') }}</p>
</div>
<div class="setting-control">
<t-switch v-model="formData.config.attachment_image_understanding" />
</div>
</div>
<!-- 扫描件 OCR 最大页数(开启附件图片理解时) -->
<div v-if="formData.config.image_upload_enabled && formData.config.attachment_image_understanding"
class="setting-row">
<div class="setting-info">
<label>{{ $t('agentEditor.imageUpload.ocrMaxPagesLabel') }}</label>
<p class="desc">{{ $t('agentEditor.imageUpload.ocrMaxPagesDesc') }}</p>
</div>
<div class="setting-control">
<t-input-number v-model="formData.config.attachment_ocr_max_pages" :min="0" :max="64"
:step="1" theme="normal" style="width: 160px;"
:placeholder="$t('agentEditor.imageUpload.useGlobalDefault')" />
</div>
</div>
<!-- 图片存储 Provider(图片上传启用时) -->
<div v-if="formData.config.image_upload_enabled" class="setting-row">
<div class="setting-info">
@@ -779,6 +804,33 @@
</div>
</div>
<!-- 单轮等待附件解析超时(秒) -->
<div class="setting-row">
<div class="setting-info">
<label>{{ $t('agentEditor.chatParser.waitTimeoutLabel') }}</label>
<p class="desc">{{ $t('agentEditor.chatParser.waitTimeoutDesc') }}</p>
</div>
<div class="setting-control">
<t-input-number v-model="formData.config.attachment_parse_wait_timeout_sec" :min="0" :max="600"
:step="10" theme="normal" style="width: 160px;"
:placeholder="$t('agentEditor.imageUpload.useGlobalDefault')" />
</div>
</div>
<!-- 聊天附件解析策略 -->
<div class="parser-policy-block">
<div class="parser-policy-block__header">
<label>{{ $t('agentEditor.chatParser.label') }}</label>
<p class="desc">{{ $t('agentEditor.chatParser.desc') }}</p>
</div>
<KBParserSettings
embedded
:parser-engine-rules="formData.config.chat_parser_engine_rules"
:relevant-extensions="CHAT_PARSER_EXTENSIONS"
@update:parser-engine-rules="(val: any) => formData.config.chat_parser_engine_rules = val"
/>
</div>
</div>
</div>
@@ -1601,6 +1653,7 @@ import { useEditorResourcesStore } from '@/stores/editorResources';
import AgentAvatar from '@/components/AgentAvatar.vue';
import PromptTemplateSelector from '@/components/PromptTemplateSelector.vue';
import ModelSelector from '@/components/ModelSelector.vue';
import KBParserSettings, { type ParserEngineRule } from '@/views/knowledge/settings/KBParserSettings.vue';
import AgentShareSettings from '@/components/AgentShareSettings.vue';
import { listEmbedChannels } from '@/api/embed';
import { getRootZoom, rectToCssPx } from '@/utils/zoom';
@@ -1611,6 +1664,13 @@ import {
type ScopeCapabilities,
} from '@/utils/tool-capabilities';
// File extensions offered in the agent-level chat attachment parsing policy.
const CHAT_PARSER_EXTENSIONS = [
'pdf', 'doc', 'docx', 'xls', 'xlsx', 'ppt', 'pptx', 'epub', 'mhtml',
'txt', 'md', 'markdown', 'csv', 'json', 'xml', 'html', 'yaml', 'yml', 'log',
'jpg', 'jpeg', 'png', 'gif', 'bmp', 'tiff', 'webp',
];
const uiStore = useUIStore();
const authStore = useAuthStore();
const router = useRouter();
@@ -2200,10 +2260,18 @@ const defaultFormData = {
// 编辑既有 agent 时会被 agent 自己保存的 agent_type 覆盖。
agent_type: 'rag-qa' as AgentType,
system_prompt_id: '' as string,
// 图片上传/多模态设置
// 附件上传设置
image_upload_enabled: false,
vlm_model_id: '',
image_storage_provider: '',
// 附件图片理解 / 扫描件 OCR 开关(默认关闭,避免解析耗时增加)
attachment_image_understanding: false,
// 扫描件 OCR 最大页数(0 = 使用全局默认)
attachment_ocr_max_pages: 0,
// 单轮问答等待附件解析完成的最长时间(秒,0 = 使用全局默认)
attachment_parse_wait_timeout_sec: 0,
// 聊天附件解析引擎策略(按文件类型选引擎)
chat_parser_engine_rules: [] as ParserEngineRule[],
// 文件类型限制
supported_file_types: [] as string[],
// 数据分析阶段开关(默认关闭,避免在普通问答上多一次 LLM 调用生成 SQL)
@@ -2822,6 +2890,10 @@ watch(() => props.visible, async (val) => {
}
if (!agentData.config.selected_skills) agentData.config.selected_skills = [];
if (!agentData.config.supported_file_types) agentData.config.supported_file_types = [];
if (!agentData.config.chat_parser_engine_rules) agentData.config.chat_parser_engine_rules = [];
// 附件解析调优字段:旧数据缺省时置 0(表示使用全局默认)
if (agentData.config.attachment_ocr_max_pages == null) agentData.config.attachment_ocr_max_pages = 0;
if (agentData.config.attachment_parse_wait_timeout_sec == null) agentData.config.attachment_parse_wait_timeout_sec = 0;
// 兼容旧数据:如果没有 agent_mode 字段,根据 allowed_tools 推断
if (!agentData.config.agent_mode) {
@@ -4506,6 +4578,30 @@ const handleSave = async () => {
gap: 0;
}
.parser-policy-block {
padding: 16px 0;
border-bottom: 1px solid var(--td-component-stroke);
&__header {
margin-bottom: 12px;
label {
display: block;
font-size: 15px;
font-weight: 500;
color: var(--td-text-color-primary);
margin-bottom: 4px;
}
.desc {
margin: 0;
font-size: 13px;
color: var(--td-text-color-secondary);
line-height: 1.5;
}
}
}
.setting-row {
display: flex;
align-items: flex-start;
@@ -64,9 +64,17 @@ test('rag mode delegates pre-answer loading to pipeline and keeps dots while ans
})
test('rag mode keeps model thinking out of the answer stream component', () => {
assert.match(source, /if \(props\.ragMode\)\s*\{[\s\S]*e\.type === 'answer'/)
const displayEventsBlock = source.slice(
source.indexOf('const displayEvents = computed'),
source.indexOf('// Get unique key for event'),
)
assert.match(displayEventsBlock, /if \(props\.ragMode\)\s*\{[\s\S]*e\.type === 'answer'/)
assert.doesNotMatch(
source,
displayEventsBlock,
/attachment_parsing/,
)
assert.doesNotMatch(
displayEventsBlock,
/if \(props\.ragMode\)\s*\{[\s\S]*e\.type === 'answer' \|\| e\.type === 'thinking'/,
)
})
@@ -160,6 +160,11 @@
<div class="results-summary-text" v-html="getKnowledgeChunksSummary(event.tool_data)"></div>
</div>
<div v-if="!event.pending && event.tool_name === 'attachment_parsing'"
class="search-results-summary-fixed attachment-parsing-summary">
<div class="results-summary-text" v-html="getAttachmentParsingSummary(event)"></div>
</div>
<div v-if="isEventExpanded(event.tool_call_id) && !event.pending && hasExpandableResults(event)"
class="action-details">
<div v-if="event.display_type && event.tool_data" class="tool-result-wrapper">
@@ -379,6 +384,11 @@
<div class="results-summary-text" v-html="getKnowledgeChunksSummary(event.tool_data)"></div>
</div>
<div v-if="!event.pending && event.tool_name === 'attachment_parsing'"
class="search-results-summary-fixed attachment-parsing-summary">
<div class="results-summary-text" v-html="getAttachmentParsingSummary(event)"></div>
</div>
<div v-if="isEventExpanded(event.tool_call_id) && !event.pending && hasExpandableResults(event)"
class="action-details">
<div v-if="event.display_type && event.tool_data" class="tool-result-wrapper">
@@ -472,6 +482,7 @@ import ChatCitationFloat from '@/components/ChatCitationFloat.vue';
import picturePreview from '@/components/picture-preview.vue';
import { countGrepDocuments, groupGrepChunkResults } from '@/utils/grepResultsGroup';
import { getKnowledgeChunksSummaryHtml } from '@/utils/knowledgeChunksDisplay';
import { getAttachmentParsingSummaryHtml } from '@/utils/attachmentParsingDisplay';
import { useChatCitationPopover } from '@/composables/useChatCitationPopover';
import { useChatReferencesDrawer } from '@/composables/useChatReferencesDrawer';
import type { KnowledgeReferenceLike } from '@/utils/referenceSources';
@@ -538,6 +549,7 @@ const TOOL_NAME_KEYS: Record<string, string> = {
todo_write: 'agentStream.tools.todoWrite',
knowledge_graph_extract: 'agentStream.tools.knowledgeGraphExtract',
thinking: 'agentStream.tools.thinking',
attachment_parsing: 'agentStream.tools.attachmentParsing',
image_analysis: 'agentStream.tools.imageAnalysis',
query_understand: 'agentStream.tools.queryUnderstand',
query_knowledge_graph: 'agentStream.tools.queryKnowledgeGraph',
@@ -1629,8 +1641,8 @@ const displayEvents = computed(() => {
const result = buildFullEventList(stream);
// Quick-answer RAG: pipeline steps and model thinking live in RagPipelineProgress;
// here we only render the final answer stream.
// Quick-answer RAG: pipeline steps (including attachment prep) live in
// RagPipelineProgress; this component only renders the answer stream.
if (props.ragMode) {
return result.filter((e: any) => e.type === 'answer');
}
@@ -1785,6 +1797,11 @@ const hasResults = (event: any): boolean => {
return false;
}
// Attachment parsing and image analysis: compact inline status only
if (toolName === 'attachment_parsing' || toolName === 'image_analysis') {
return false;
}
// For other tools, always allow expansion
return true;
};
@@ -2274,12 +2291,19 @@ const getKnowledgeChunksSummary = (toolData: any): string => {
return getKnowledgeChunksSummaryHtml(t, toolData);
};
const getAttachmentParsingSummary = (event: any): string => {
return getAttachmentParsingSummaryHtml(t, event);
};
// Get tool title - prefer summary over description, add query for search tools
const getToolTitle = (event: any): string => {
if (event.pending) {
if (event.tool_name === 'image_analysis') {
return t('agentStream.toolStatus.imageAnalyzing');
}
if (event.tool_name === 'attachment_parsing') {
return t('agentStream.toolStatus.attachmentParsing');
}
if (event.tool_name === 'wiki_search' || event.tool_name === 'wiki_read_page') {
return `${getLocalizedToolName(event.tool_name)}...`;
}
@@ -2389,6 +2413,9 @@ const getToolDescription = (event: any): string => {
if (event.tool_name === 'image_analysis') {
return t('agentStream.toolStatus.imageAnalyzing');
}
if (event.tool_name === 'attachment_parsing') {
return t('agentStream.toolStatus.attachmentParsing');
}
if (event.tool_name === 'query_understand') {
return t('agentStream.toolStatus.queryUnderstanding');
}
@@ -2418,6 +2445,8 @@ const getToolDescription = (event: any): string => {
return success ? t('agentStream.toolStatus.updateTodos') : t('agentStream.toolStatus.updateTodosFailed');
} else if (toolName === 'image_analysis') {
return success ? t('agentStream.toolStatus.imageAnalysisDone') : t('agentStream.toolStatus.imageAnalysisFailed');
} else if (toolName === 'attachment_parsing') {
return success ? t('agentStream.toolStatus.attachmentParsingDone') : t('agentStream.toolStatus.attachmentParsingFailed');
} else if (toolName === 'query_understand') {
return success ? t('agentStream.toolStatus.queryUnderstandDone') : t('agentStream.toolStatus.calledFailed', { name: getLocalizedToolName(toolName) });
} else {
@@ -85,3 +85,9 @@ test('rag pipeline auto-scrolls capped thinking detail while streaming', () => {
assert.match(source, /scrollThinkingDetailToBottom/)
assert.match(source, /watch\(thinkingContent[\s\S]*scrollThinkingDetailToBottom/)
})
test('rag pipeline includes attachment prep steps on the timeline', () => {
assert.match(source, /RAG_TIMELINE_TOOL_NAMES/)
assert.match(source, /getAttachmentParsingSummaryHtml/)
assert.match(source, /isAttachmentTool/)
})
@@ -209,7 +209,8 @@ import {
getRagPipelineStepTitle,
getRetrievalSearchSource,
} from '@/utils/agent-tool-display'
import { RAG_PIPELINE_TOOL_NAMES } from '@/utils/rag-pipeline-history'
import { getAttachmentParsingSummaryHtml } from '@/utils/attachmentParsingDisplay'
import { RAG_TIMELINE_TOOL_NAMES } from '@/utils/rag-pipeline-history'
import { useChatReferencesDrawer } from '@/composables/useChatReferencesDrawer'
import { buildReferenceSections } from '@/utils/referenceSources'
@@ -275,7 +276,7 @@ const steps = computed(() => {
return (
event.type === 'tool_call' &&
typeof event.tool_name === 'string' &&
RAG_PIPELINE_TOOL_NAMES.has(event.tool_name)
RAG_TIMELINE_TOOL_NAMES.has(event.tool_name)
)
})
.map((event) => {
@@ -287,13 +288,16 @@ const steps = computed(() => {
: null
const isSearchTool = toolName === 'knowledge_search' || toolName === 'search_knowledge'
const isAttachmentTool = toolName === 'attachment_parsing' || toolName === 'image_analysis'
const searchSource = isSearchTool
? getRetrievalSearchSource(event.arguments, toolData)
: undefined
const summaryHtml =
!pending && isSearchTool && toolData
? getKnowledgeSearchSummaryHtml(t, toolData)
: ''
let summaryHtml = ''
if (!pending && isSearchTool && toolData) {
summaryHtml = getKnowledgeSearchSummaryHtml(t, toolData)
} else if (!pending && isAttachmentTool) {
summaryHtml = getAttachmentParsingSummaryHtml(t, event)
}
const canOpenReferences = !pending && isSearchTool && hasReferences.value
return {
+36 -1
View File
@@ -19,7 +19,10 @@
</div>
<!-- 显示上传的附件 -->
<div v-if="hasAttachments" class="user_attachments">
<div v-for="(att, idx) in props.attachments" :key="idx" class="user_attachment_card">
<div v-for="(att, idx) in props.attachments" :key="idx"
class="user_attachment_card"
:class="{ 'is-previewable': canPreviewAttachment(att) }"
@click="openAttachmentPreview(att)">
<div class="attachment_card_icon">
<svg viewBox="0 0 40 48" fill="none" xmlns="http://www.w3.org/2000/svg" width="36" height="44">
<rect width="40" height="48" rx="4" fill="#4A90D9" />
@@ -48,6 +51,8 @@ import { computed, ref, watch, onMounted, nextTick } from "vue";
import { hydrateProtectedFileImages } from '@/utils/security';
import picturePreview from '@/components/picture-preview.vue';
import { useI18n } from 'vue-i18n';
import { useChatAttachmentPreviewDrawer } from '@/composables/useChatAttachmentPreviewDrawer';
import { isPreviewableAttachment, resolveAttachmentFileType } from '@/utils/attachmentPreview';
const { t } = useI18n();
@@ -91,9 +96,15 @@ const props = defineProps({
embeddedMode: {
type: Boolean,
default: false
},
sessionId: {
type: String,
default: ''
}
});
const attachmentPreviewDrawer = useChatAttachmentPreviewDrawer();
const channelLabelMap = {
web: () => t('chat.channelWeb'),
api: () => t('chat.channelApi'),
@@ -134,6 +145,20 @@ const formatFileSize = (bytes) => {
return (bytes / (1024 * 1024)).toFixed(1) + ' MB';
};
const canPreviewAttachment = (attachment) => {
return Boolean(props.sessionId) && isPreviewableAttachment(attachment);
};
const openAttachmentPreview = (attachment) => {
if (!canPreviewAttachment(attachment) || !attachmentPreviewDrawer) return;
attachmentPreviewDrawer.open({
sessionId: props.sessionId,
attachmentId: attachment.id,
fileName: attachment.file_name,
fileType: resolveAttachmentFileType(attachment.file_name, attachment.file_type),
});
};
const hydrateImages = async () => {
await nextTick();
await hydrateProtectedFileImages(containerRef.value);
@@ -237,6 +262,16 @@ const closePreImg = () => {
min-width: 160px;
cursor: default;
&.is-previewable {
cursor: pointer;
transition: border-color 0.2s, box-shadow 0.2s;
&:hover {
border-color: var(--td-brand-color-2, rgba(0, 82, 217, 0.25));
box-shadow: 0 2px 8px rgba(0, 0, 0, 0.06);
}
}
.attachment_card_icon {
flex-shrink: 0;
display: flex;
+75 -16
View File
@@ -77,7 +77,8 @@
<div v-if="session.role == 'user'">
<usermsg :content="session.content" :mentioned_items="session.mentioned_items"
:images="session.images" :attachments="session.attachments" :embeddedMode="embeddedMode">
:images="session.images" :attachments="session.attachments" :embeddedMode="embeddedMode"
:session-id="session_id">
</usermsg>
</div>
<div v-if="session.role == 'assistant' && shouldRenderAssistantMessage(session)">
@@ -122,6 +123,7 @@
:kb-id="uiStore.currentKBId || undefined" :initial-type="uiStore.kbEditorType"
@update:visible="(val) => val ? null : uiStore.closeKBEditor()" @success="handleKBEditorSuccess" />
<ChatReferencesDrawer />
<ChatAttachmentPreviewDrawer />
</template>
<script setup>
import { storeToRefs } from 'pinia';
@@ -132,6 +134,7 @@ import botmsg from './components/botmsg.vue';
import usermsg from './components/usermsg.vue';
import { getMessageList, getSession } from "@/api/chat/index";
import { getSuggestedQuestions } from "@/api/agent/index";
import { deleteTemporaryAttachment, uploadTemporaryAttachment } from '@/api/chat/temporary-attachments';
import { useStream } from '../../api/chat/streame'
import { useMenuStore } from '@/stores/menu';
import { useSettingsStore } from '@/stores/settings';
@@ -144,6 +147,7 @@ import { useChatStreamHandler } from '@/composables/useChatStreamHandler';
import { useStickyBottomOnResize } from '@/composables/useStickyBottomOnResize';
import { clearCitationChunkCache } from '@/utils/citationChunkCache';
import ChatReferencesDrawer from '@/components/ChatReferencesDrawer.vue';
import ChatAttachmentPreviewDrawer from '@/components/ChatAttachmentPreviewDrawer.vue';
import FollowUpSuggestions from '@/components/chat/FollowUpSuggestions.vue';
import {
ensureMessageSuggestions,
@@ -151,8 +155,10 @@ import {
recordMessageSuggestionEvent,
} from '@/api/message-suggestion';
import { provideChatReferencesDrawer } from '@/composables/useChatReferencesDrawer';
import { provideChatAttachmentPreviewDrawer } from '@/composables/useChatAttachmentPreviewDrawer';
const referencesDrawer = provideChatReferencesDrawer();
provideChatAttachmentPreviewDrawer();
const { visible: referencesDrawerVisible } = referencesDrawer;
const props = defineProps({
@@ -647,30 +653,85 @@ const sendMsg = async (value, modelId = '', mentionedItems = [], imageFiles = []
prepareForNewOutgoingMessage();
isReplying.value = true;
loading.value = true;
const selectedAgentId = props.embeddedMode ? props.agentId : (useSettingsStoreInstance.selectedAgentId || '');
// Convert images to base64 data URIs for backend processing and local display
// Images are unified with the attachment pipeline: on the authenticated web
// client they upload as temporary documents (understood in the background by
// the VLM) and are sent as attachment_ids. The inline base64 `images`
// payload is kept only for the embedded/public API path. A base64 fallback
// is used per-image if the async upload fails.
let imageAttachments = [];
let userImages = [];
const imageAttachmentIds = [];
if (imageFiles && imageFiles.length > 0) {
try {
for (const file of imageFiles) {
const dataURI = await fileToBase64(file);
imageAttachments.push({ data: dataURI });
userImages.push({ url: dataURI });
for (const file of imageFiles) {
let dataURI;
try {
dataURI = await fileToBase64(file);
} catch (e) {
console.error('[Image] Failed to read images:', e);
loading.value = false;
isReplying.value = false;
return;
}
} catch (e) {
console.error('[Image] Failed to read images:', e);
userImages.push({ url: dataURI });
if (props.embeddedMode) {
imageAttachments.push({ data: dataURI });
continue;
}
try {
const upload = await uploadTemporaryAttachment(session_id.value, file, selectedAgentId, 'auto');
imageAttachmentIds.push(upload.data.id);
} catch (e) {
console.error('[Image] Temporary image upload failed, falling back to inline:', e);
imageAttachments.push({ data: dataURI });
}
}
}
// The create-chat page cannot upload before its session exists. Once it
// navigates here, move those local files through the same asynchronous
// upload/parse flow before starting the first stream.
const localAttachments = (attachmentFiles || []).filter(attachment => !attachment.documentId);
if (!props.embeddedMode && localAttachments.length > 0) {
try {
// Only upload to obtain a document ID; parsing continues in the
// background and is awaited by the backend (shown on the timeline).
await Promise.all(localAttachments.map(async (attachment) => {
attachment.status = 'uploading';
const upload = await uploadTemporaryAttachment(
session_id.value, attachment.file, selectedAgentId, 'auto'
);
attachment.documentId = upload.data.id;
attachment.status = upload.data.status;
}));
} catch (error) {
console.error('[Attachment] Temporary document upload failed:', error);
await Promise.all(localAttachments
.filter(attachment => attachment.documentId)
.map(attachment => deleteTemporaryAttachment(session_id.value, attachment.documentId).catch(() => undefined)));
MessagePlugin.error(error?.message || t('chat.attachmentParseFailed'));
loading.value = false;
isReplying.value = false;
return;
}
}
// Convert attachment files to base64 for backend processing
// Send any successfully uploaded attachment (parsing may still be running);
// the backend waits for readiness and reports progress on the timeline.
const attachmentIds = (attachmentFiles || [])
.filter(attachment => attachment.documentId && attachment.status !== 'failed')
.map(attachment => attachment.documentId);
attachmentIds.push(...imageAttachmentIds);
// Embedded public routes do not expose the authenticated session upload API;
// keep their existing inline payload for compatibility.
const legacyAttachmentFiles = props.embeddedMode
? (attachmentFiles || []).filter(attachment => !attachment.documentId)
: [];
let attachmentUploads = [];
if (attachmentFiles && attachmentFiles.length > 0) {
if (legacyAttachmentFiles.length > 0) {
try {
for (const attachment of attachmentFiles) {
for (const attachment of legacyAttachmentFiles) {
const reader = new FileReader();
const base64Promise = new Promise((resolve, reject) => {
reader.onload = () => {
@@ -698,7 +759,7 @@ const sendMsg = async (value, modelId = '', mentionedItems = [], imageFiles = []
}
// 将@提及的知识库和文件信息存入用户消息
messagesList.push({ content: value, role: 'user', mentioned_items: mentionedItems, images: userImages, attachments: attachmentFiles.map(a => ({ file_name: a.name, file_size: a.size, file_type: '.' + a.name.split('.').pop()?.toLowerCase() })), channel: 'web' });
messagesList.push({ content: value, role: 'user', mentioned_items: mentionedItems, images: userImages, attachments: attachmentFiles.map(a => ({ id: a.documentId, file_name: a.name, file_size: a.size, file_type: '.' + a.name.split('.').pop()?.toLowerCase() })), channel: 'web' });
userHasScrolledUp.value = false;
scrollToBottom(true);
@@ -740,9 +801,6 @@ const sendMsg = async (value, modelId = '', mentionedItems = [], imageFiles = []
const mcpServiceIds = [...new Set((mentionedItems || []).filter(item => item.type === 'mcp' && item.id).map(item => item.id))];
const skillNames = [...new Set((mentionedItems || []).filter(item => item.type === 'skill' && item.id).map(item => item.skill_name || item.id))];
// Get selected agent ID (backend resolves shared agent and its tenant from share relation)
const selectedAgentId = props.embeddedMode ? props.agentId : (useSettingsStoreInstance.selectedAgentId || '');
const endpoint = agentEnabled ? '/api/v1/agent-chat' : '/api/v1/knowledge-chat';
const requestMcpServiceIds = agentEnabled ? mcpServiceIds : [];
@@ -766,6 +824,7 @@ const sendMsg = async (value, modelId = '', mentionedItems = [], imageFiles = []
mentioned_items: mentionedItems,
images: imageAttachments.length > 0 ? imageAttachments : undefined,
attachment_uploads: attachmentUploads.length > 0 ? attachmentUploads : undefined,
attachment_ids: attachmentIds.length > 0 ? attachmentIds : undefined,
query: value,
suggestion_attribution: suggestionAttribution || undefined,
method: 'POST',
@@ -14,7 +14,7 @@
<p>{{ $t('kbSettings.parser.noEngineAvailable') }}</p>
</div>
<div v-else class="settings-group">
<div v-else class="settings-group" :class="{ 'settings-group--embedded': embedded }">
<div
v-for="group in fileTypeGroups"
:key="group.key"
@@ -22,7 +22,7 @@
>
<div class="setting-info">
<label class="group-label">
<t-icon :name="group.icon" class="group-icon" />
<t-icon v-if="!embedded" :name="group.icon" class="group-icon" />
{{ group.label }}
</label>
<div class="ext-tags">
@@ -33,46 +33,18 @@
<t-select
:value="getEngineForGroup(group.extensions) || undefined"
@change="(val: string) => handleEngineChange(group.extensions, val)"
:style="embedded ? { width: '100%' } : { width: '280px' }"
:style="embedded ? undefined : { width: '280px' }"
:class="{ 'parser-engine-select--embedded': embedded }"
:status="hasAvailableEngine(group.extensions) ? 'default' : 'warning'"
:placeholder="$t('kbSettings.parser.noEngine')"
:popup-props="{ overlayInnerStyle: { maxHeight: '240px' } }"
>
<t-option
v-for="opt in getEngineOptions(group.extensions)"
:key="opt.value"
:value="opt.value"
:label="opt.selectLabel"
:disabled="opt.disabled"
>
<t-tooltip
:content="$t('kbSettings.supportedFormats') + ': ' + opt.fileTypes.map(ft => '.' + ft).join(' ')"
placement="left"
:show-arrow="false"
>
<div class="engine-option">
<div class="engine-option-top">
<span class="engine-option-name">{{ getEngineDisplayName(opt.value) }}</span>
<t-tag
v-if="opt.isDefault"
theme="primary"
variant="light"
size="small"
>{{ $t('kbSettings.parser.default') }}</t-tag>
<t-tag
v-if="opt.disabled"
theme="danger"
variant="light"
size="small"
>{{ $t('kbSettings.parser.unavailable') }}</t-tag>
</div>
<div class="engine-option-desc">{{ getEngineDisplayDesc(opt.value, opt.desc) }}</div>
<div v-if="opt.disabled && opt.reason" class="engine-option-reason">
{{ opt.reason }}
<a class="go-settings" @click.stop.prevent="goToParserSettings">{{ $t('kbSettings.parser.goSettings') }}</a>
</div>
</div>
</t-tooltip>
</t-option>
/>
</t-select>
<div v-if="!hasAvailableEngine(group.extensions)" class="no-engine-warning">
<a class="go-settings" @click.prevent="goToParserSettings">{{ $t('kbSettings.parser.goConfig') }}</a>
@@ -100,12 +72,6 @@ function getEngineDisplayName(engineName: string): string {
return translated !== key ? translated : engineName
}
function getEngineDisplayDesc(engineName: string, fallback: string): string {
const key = `kbSettings.parser.engines.${engineName}.desc`
const translated = t(key)
return translated !== key ? translated : fallback
}
export interface ParserEngineRule {
file_types: string[]
engine: string
@@ -114,11 +80,12 @@ export interface ParserEngineRule {
interface EngineOption {
value: string
selectLabel: string
desc: string
fileTypes: string[]
disabled: boolean
isDefault: boolean
reason?: string
}
function buildOptionLabel(name: string, isDefault: boolean): string {
const label = getEngineDisplayName(name)
return isDefault ? `${label} (${t('kbSettings.parser.default')})` : label
}
interface Props {
@@ -192,6 +159,14 @@ const fileTypeGroups = computed(() => {
})
}
// Keep the UI driven by the backend registry. New parser plugins can expose
// file types without requiring another frontend release; known families get
// friendly labels above and everything else gets a compact dynamic row.
const grouped = new Set(groups.flatMap(group => group.extensions))
for (const ext of [...ft].filter(ext => !grouped.has(ext) && ext !== 'url').sort()) {
groups.push({ key: `dynamic-${ext}`, label: ext.toUpperCase(), icon: 'file-code', extensions: [ext] })
}
const rel = props.relevantExtensions
if (!rel?.length) return groups
const relSet = new Set(rel)
@@ -214,19 +189,17 @@ function getEngineOptions(extensions: string[]): EngineOption[] {
}
}
const defaultName = raw.find(e => e.available)?.name ?? ''
return raw.map(e => ({
value: e.name,
selectLabel: `${getEngineDisplayName(e.name)} — ${getEngineDisplayDesc(e.name, e.desc)}`,
desc: e.desc,
fileTypes: e.fileTypes,
disabled: !e.available,
isDefault: defaultName !== '' && e.name === defaultName,
reason: e.reason,
}))
return raw
.filter(e => e.available)
.map(e => ({
value: e.name,
selectLabel: buildOptionLabel(e.name, defaultName !== '' && e.name === defaultName),
isDefault: defaultName !== '' && e.name === defaultName,
}))
}
function hasAvailableEngine(extensions: string[]): boolean {
return getEngineOptions(extensions).some(opt => !opt.disabled)
return getEngineOptions(extensions).length > 0
}
function getDefaultEngine(extensions: string[]): string {
@@ -439,77 +412,45 @@ watch(() => props.parserEngineRules, (v) => {
}
// ---- 下拉选项样式 ----
.engine-option {
display: flex;
flex-direction: column;
gap: 3px;
padding: 3px 0;
}
.engine-option-top {
display: flex;
align-items: center;
gap: 6px;
}
.engine-option-name {
font-size: 13px;
font-weight: 600;
color: var(--td-text-color-primary);
font-family: var(--app-font-family-mono);
}
.engine-option-desc {
font-size: 12px;
color: var(--td-text-color-placeholder);
line-height: 1.4;
}
.engine-option-reason {
font-size: 12px;
color: var(--td-error-color);
line-height: 1.4;
.go-settings {
color: var(--td-brand-color);
cursor: pointer;
margin-left: 4px;
font-size: 12px;
text-decoration: none;
&:hover {
text-decoration: underline;
}
}
}
.kb-parser-settings--embedded {
.settings-group {
border: 1px solid var(--td-component-stroke);
border-radius: 8px;
background: var(--td-bg-color-secondarycontainer, #f8f9fb);
overflow: hidden;
}
.setting-row {
flex-direction: column;
align-items: stretch;
gap: 10px;
padding: 12px 0;
flex-direction: row;
align-items: center;
gap: 16px;
padding: 10px 14px;
background: var(--td-bg-color-container, #fff);
border-bottom: 1px solid var(--td-component-stroke);
&:last-child {
border-bottom: none;
}
}
.setting-info {
flex: none;
max-width: none;
flex: 0 0 168px;
max-width: 168px;
padding-right: 0;
display: flex;
flex-wrap: wrap;
align-items: center;
gap: 6px 10px;
display: block;
}
.setting-control {
flex: none;
flex: 1;
min-width: 0;
max-width: none;
align-items: stretch;
}
.group-label {
font-size: 14px;
margin-bottom: 0;
font-size: 13px;
font-weight: 500;
margin-bottom: 4px;
}
.ext-tags {
@@ -521,17 +462,9 @@ watch(() => props.parserEngineRules, (v) => {
font-size: 11px;
padding: 2px 6px;
}
}
</style>
<style lang="less">
.t-select__dropdown .t-select-option {
height: auto;
align-items: flex-start;
padding-top: 6px;
padding-bottom: 6px;
}
.t-select__dropdown .t-select-option__content {
white-space: normal;
.parser-engine-select--embedded {
width: 100%;
}
}
</style>
@@ -90,6 +90,24 @@
</div>
</button>
</div>
<section v-if="engines.length > 0 && authStore.hasRole('admin')" class="chat-parser-policy">
<div class="chat-parser-policy__header">
<div>
<h3>{{ $t('settings.parser.chatPolicyTitle') }}</h3>
<p>{{ $t('settings.parser.chatPolicyDescription') }}</p>
</div>
<t-button :loading="savingPolicy" @click="saveChatParserPolicy">
{{ $t('common.save') }}
</t-button>
</div>
<KBParserSettings
embedded
:parser-engine-rules="chatParserEngineRules"
:relevant-extensions="CHAT_PARSER_EXTENSIONS"
@update:parser-engine-rules="chatParserEngineRules = $event"
/>
</section>
</template>
<!-- 配置抽屉 — 用 SettingDrawer 包装,保持与 ModelEditorDialog 同款视觉/交互 -->
@@ -375,7 +393,9 @@ import { ref, computed, onMounted, nextTick } from 'vue'
import { useI18n } from 'vue-i18n'
import { useUIStore } from '@/stores/ui'
import { useAuthStore } from '@/stores/auth'
import { MessagePlugin } from 'tdesign-vue-next'
import SettingDrawer from '@/components/settings/SettingDrawer.vue'
import KBParserSettings, { type ParserEngineRule } from '@/views/knowledge/settings/KBParserSettings.vue'
import {
getParserEngines,
getParserEngineConfig,
@@ -391,6 +411,11 @@ const uiStore = useUIStore()
const authStore = useAuthStore()
const CONFIGURABLE_ENGINES = new Set(['mineru', 'mineru_cloud', 'paddleocr_vl', 'paddleocr_vl_cloud'])
const CHAT_PARSER_EXTENSIONS = [
'pdf', 'doc', 'docx', 'xls', 'xlsx', 'ppt', 'pptx', 'epub', 'mhtml',
'txt', 'md', 'markdown', 'csv', 'json', 'xml', 'html', 'yaml', 'yml', 'log',
'jpg', 'jpeg', 'png', 'gif', 'bmp', 'tiff', 'webp',
]
/** 各解析引擎的项目/官方文档地址 */
const ENGINE_DOC_LINKS: Record<string, string> = {
@@ -437,6 +462,8 @@ const error = ref('')
const config = ref<ParserEngineConfig>({ ...DEFAULT_PARSER_CONFIG })
const saving = ref(false)
const savingPolicy = ref(false)
const chatParserEngineRules = ref<ParserEngineRule[]>([])
const saveMessage = ref('')
const saveSuccess = ref(false)
const checking = ref(false)
@@ -563,7 +590,9 @@ async function loadConfig() {
paddleocr_vl_cloud_model: data?.paddleocr_vl_cloud_model ?? DEFAULT_PARSER_CONFIG.paddleocr_vl_cloud_model ?? 'PaddleOCR-VL-1.6',
paddleocr_vl_cloud_use_seal_recognition: data?.paddleocr_vl_cloud_use_seal_recognition ?? DEFAULT_PARSER_CONFIG.paddleocr_vl_cloud_use_seal_recognition ?? true,
paddleocr_vl_cloud_use_chart_recognition: data?.paddleocr_vl_cloud_use_chart_recognition ?? DEFAULT_PARSER_CONFIG.paddleocr_vl_cloud_use_chart_recognition ?? false,
chat_parser_engine_rules: data?.chat_parser_engine_rules ?? [],
}
chatParserEngineRules.value = [...(data?.chat_parser_engine_rules ?? [])]
} catch {
config.value = { ...DEFAULT_PARSER_CONFIG }
}
@@ -578,6 +607,7 @@ async function loadAll() {
function buildConfigPayload(): ParserEngineConfig {
return {
chat_parser_engine_rules: chatParserEngineRules.value,
docreader_addr: config.value.docreader_addr?.trim() ?? '',
docreader_transport: (config.value.docreader_transport ?? 'grpc').trim() || 'grpc',
mineru_endpoint: config.value.mineru_endpoint?.trim() ?? '',
@@ -603,6 +633,19 @@ function buildConfigPayload(): ParserEngineConfig {
}
}
async function saveChatParserPolicy() {
savingPolicy.value = true
try {
const res = await updateParserEngineConfig(buildConfigPayload())
if (res?.data) config.value = { ...config.value, ...res.data }
MessagePlugin.success(t('settings.parser.chatPolicySaved'))
} catch (e: any) {
MessagePlugin.error(e?.message || t('settings.parser.saveFailed'))
} finally {
savingPolicy.value = false
}
}
async function onCheck() {
if (!connected) {
checkMessage.value = t('settings.parser.ensureDocreaderConnected')
@@ -740,6 +783,33 @@ onMounted(loadAll)
padding: 16px 0;
}
.chat-parser-policy {
margin-top: 28px;
padding-top: 24px;
border-top: 1px solid var(--td-component-stroke);
&__header {
display: flex;
align-items: flex-start;
justify-content: space-between;
gap: 20px;
margin-bottom: 16px;
h3 {
margin: 0 0 6px;
font-size: 16px;
color: var(--td-text-color-primary);
}
p {
margin: 0;
color: var(--td-text-color-secondary);
font-size: 13px;
line-height: 1.5;
}
}
}
.empty-state {
padding: 48px 0;
text-align: center;
@@ -534,6 +534,7 @@ const taskStates: RuntimeTaskState[] = ['active', 'pending', 'scheduled', 'retry
const runtimeTaskTypeKeys: Record<string, string> = {
'document:process': 'documentProcess',
'manual:process': 'manualProcess',
'temporary_document:process': 'temporaryDocumentProcess',
'knowledge:post_process': 'postProcess',
'summary:generation': 'summary',
'datatable:summary': 'tableSummary',