feat(chat): 为聊天功能添加上传本地文件和远程URL附件的支持
This commit is contained in:
1 parent
2a036764e3
commit
a1e0fa9404
7 files changed
+1024
-17
No files matched your search
@@ -34,6 +34,15 @@ export interface ChatSourceFileResult {
|
||||
source_ext?: string;
|
||||
}
|
||||
|
||||
export interface ChatUploadResult {
|
||||
id: string;
|
||||
name?: string;
|
||||
size?: number;
|
||||
extension?: string;
|
||||
mime_type?: string;
|
||||
type?: 'image' | 'document' | 'audio' | 'video' | 'custom';
|
||||
}
|
||||
|
||||
export const listChatSessions = (agentId: number) =>
|
||||
requestJson<ChatSessionItem[]>(`/api/chat/sessions?agent_id=${agentId}`, auth());
|
||||
|
||||
@@ -78,3 +87,14 @@ export const listOaEmployees = (
|
||||
});
|
||||
return requestJson<OaEmployeesResponse>(`/api/chat/oa/employees?${qs.toString()}`, auth());
|
||||
};
|
||||
|
||||
export const uploadChatFile = (agentId: number, file: File) => {
|
||||
const qs = new URLSearchParams({ agent_id: String(agentId) });
|
||||
const fd = new FormData();
|
||||
fd.append('file', file);
|
||||
return requestJson<ChatUploadResult>(`/api/chat/files/upload?${qs.toString()}`, {
|
||||
method: 'POST',
|
||||
body: fd,
|
||||
headers: getAuthHeaders(),
|
||||
});
|
||||
};
|
||||
@@ -1,4 +1,4 @@
|
||||
/**
|
||||
/**
|
||||
* frontend/src/api/client.ts
|
||||
* 用途:封装前端统一 API 访问与响应解析逻辑。
|
||||
* 说明:
|
||||
@@ -50,10 +50,23 @@ export class BusinessError extends Error {
|
||||
function resolveLocalizedErrorMessage(code?: string, fallbackMessage?: string): string {
|
||||
const normalizedCode = code ? code.replace(/\./g, '_') : '';
|
||||
const key = normalizedCode ? `errors.codes.${normalizedCode}` : '';
|
||||
const fallback = String(fallbackMessage || '').trim();
|
||||
const isGenericFallback = (msg: string) => {
|
||||
const v = msg.trim().toLowerCase();
|
||||
if (!v) return true;
|
||||
if (v === 'invalid request parameters' || v === 'invalid request parameters.') return true;
|
||||
if (v === 'request failed' || v === 'request failed.') return true;
|
||||
if (v.startsWith('http ')) return true;
|
||||
return false;
|
||||
};
|
||||
if (key && i18n.global.te(key)) {
|
||||
return String(i18n.global.t(key));
|
||||
const localized = String(i18n.global.t(key));
|
||||
if (normalizedCode === 'VALIDATION_INVALID_PARAM' && fallback && !isGenericFallback(fallback) && fallback !== localized) {
|
||||
return `${localized} ${fallback}`;
|
||||
}
|
||||
return localized;
|
||||
}
|
||||
if (fallbackMessage) return fallbackMessage;
|
||||
if (fallback) return fallback;
|
||||
if (i18n.global.te('errors.generic')) {
|
||||
return String(i18n.global.t('errors.generic'));
|
||||
}
|
||||
|
||||
@@ -179,7 +179,15 @@ export function useChat() {
|
||||
* query: 用户输入文本
|
||||
* agentId: 目标 Agent ID
|
||||
*/
|
||||
const sendMessage = async (query: string, agentId: number, kbType: string = '企业知识库') => {
|
||||
const sendMessage = async (
|
||||
query: string,
|
||||
agentId: number,
|
||||
kbType: string = '企业知识库',
|
||||
files?: Array<
|
||||
| { type: 'image' | 'document' | 'audio' | 'video' | 'custom'; transfer_method: 'local_file'; upload_file_id: string }
|
||||
| { type: 'image' | 'document' | 'audio' | 'video' | 'custom'; transfer_method: 'remote_url'; url: string }
|
||||
>,
|
||||
) => {
|
||||
const runViewId = viewId.value;
|
||||
const runMessages = messages.value;
|
||||
const run: ChatRun = {
|
||||
@@ -227,7 +235,8 @@ export function useChat() {
|
||||
query,
|
||||
agent_id: agentId,
|
||||
conversation_id: conversationId.value,
|
||||
kb_type: kbType
|
||||
kb_type: kbType,
|
||||
files: files && files.length > 0 ? files : undefined,
|
||||
})
|
||||
});
|
||||
|
||||
|
||||
@@ -11,7 +11,7 @@
|
||||
import { ref, onMounted, onBeforeUnmount, computed, watch, nextTick } from 'vue';
|
||||
import { useI18n } from 'vue-i18n';
|
||||
import { useChat } from '../composables/useChat';
|
||||
import { Send, Loader2, Plus, Copy, Edit2, RotateCw, Check, X, PanelLeftClose, PanelLeftOpen, ChevronDown, Sparkles, Database, Mic, LogOut, MessageSquareText, Globe, ExternalLink, Search, LayoutGrid, Briefcase, History, Sun, Moon, CalendarDays, Building } from 'lucide-vue-next';
|
||||
import { Send, Loader2, Plus, Copy, Edit2, RotateCw, Check, X, PanelLeftClose, PanelLeftOpen, ChevronDown, Sparkles, Database, Mic, LogOut, MessageSquareText, Globe, ExternalLink, Search, LayoutGrid, Briefcase, History, Sun, Moon, CalendarDays, Building, Paperclip, Link2 } from 'lucide-vue-next';
|
||||
import LocaleToggleButton from '../components/LocaleToggleButton.vue';
|
||||
import { marked } from 'marked';
|
||||
import { useRoute, useRouter } from 'vue-router';
|
||||
@@ -37,6 +37,7 @@ import {
|
||||
saveLocalChatMessage,
|
||||
resolveChatSourceFile,
|
||||
listOaEmployees,
|
||||
uploadChatFile,
|
||||
} from '../api/chat';
|
||||
import {
|
||||
getUserProfile,
|
||||
@@ -113,6 +114,9 @@ const handleDocumentPointerDown = (event: MouseEvent | TouchEvent) => {
|
||||
if (showKbDropdown.value && kbMenuRef.value && !kbMenuRef.value.contains(target)) {
|
||||
showKbDropdown.value = false;
|
||||
}
|
||||
if (showAttachmentMenu.value && attachmentMenuRef.value && !attachmentMenuRef.value.contains(target)) {
|
||||
closeAttachmentMenu();
|
||||
}
|
||||
};
|
||||
|
||||
const onAuthLogout = () => {
|
||||
@@ -654,6 +658,375 @@ const deleteConfirmMessage = ref('');
|
||||
let pendingDeleteAction: (() => Promise<void> | void) | null = null;
|
||||
const showAgentPanel = ref(true);
|
||||
|
||||
type ChatUploadFileType = 'image' | 'document' | 'audio' | 'video' | 'custom';
|
||||
|
||||
type ChatUploadFileSpec =
|
||||
| { type: ChatUploadFileType; transfer_method: 'local_file'; upload_file_id: string }
|
||||
| { type: ChatUploadFileType; transfer_method: 'remote_url'; url: string };
|
||||
|
||||
const DIFY_SUPPORTED_EXTS: Record<Exclude<ChatUploadFileType, 'custom'>, Set<string>> = {
|
||||
document: new Set([
|
||||
'txt', 'md', 'markdown', 'mdx', 'pdf', 'html', 'htm', 'xlsx', 'xls', 'vtt', 'properties',
|
||||
'doc', 'docx', 'csv', 'eml', 'msg', 'pptx', 'ppt', 'xml', 'epub',
|
||||
]),
|
||||
image: new Set(['jpg', 'jpeg', 'png', 'gif', 'webp', 'svg']),
|
||||
audio: new Set(['mp3', 'm4a', 'wav', 'webm', 'mpga']),
|
||||
video: new Set(['mp4', 'mov', 'mpeg', 'webm']),
|
||||
};
|
||||
|
||||
const extractExt = (value: string) => {
|
||||
const text = (value || '').trim().toLowerCase();
|
||||
const withoutQuery = (text.split('?')[0] || '').split('#')[0] || '';
|
||||
const idx = withoutQuery.lastIndexOf('.');
|
||||
if (idx < 0) return '';
|
||||
return withoutQuery.slice(idx + 1).trim();
|
||||
};
|
||||
|
||||
const isKnownDifyExt = (ext: string) => {
|
||||
if (!ext) return false;
|
||||
return (
|
||||
DIFY_SUPPORTED_EXTS.image.has(ext)
|
||||
|| DIFY_SUPPORTED_EXTS.document.has(ext)
|
||||
|| DIFY_SUPPORTED_EXTS.audio.has(ext)
|
||||
|| DIFY_SUPPORTED_EXTS.video.has(ext)
|
||||
);
|
||||
};
|
||||
|
||||
const resolveDifyType = (ext: string, mime?: string): Exclude<ChatUploadFileType, 'custom'> | null => {
|
||||
const m = (mime || '').toLowerCase();
|
||||
if (m.startsWith('image/')) return 'image';
|
||||
if (m.startsWith('audio/')) return 'audio';
|
||||
if (m.startsWith('video/')) return 'video';
|
||||
if (DIFY_SUPPORTED_EXTS.image.has(ext)) return 'image';
|
||||
if (DIFY_SUPPORTED_EXTS.document.has(ext)) return 'document';
|
||||
const inAudio = DIFY_SUPPORTED_EXTS.audio.has(ext);
|
||||
const inVideo = DIFY_SUPPORTED_EXTS.video.has(ext);
|
||||
if (inAudio && !inVideo) return 'audio';
|
||||
if (inVideo) return 'video';
|
||||
return null;
|
||||
};
|
||||
|
||||
type PendingAttachment =
|
||||
| { id: string; kind: 'local'; file: File; type: ChatUploadFileType }
|
||||
| { id: string; kind: 'remote'; url: string; type: ChatUploadFileType };
|
||||
|
||||
const attachments = ref<PendingAttachment[]>([]);
|
||||
const attachmentUrlInput = ref('');
|
||||
const isUploadingAttachments = ref(false);
|
||||
const filePickerRef = ref<HTMLInputElement | null>(null);
|
||||
const attachmentMenuRef = ref<HTMLElement | null>(null);
|
||||
const attachmentUrlInputRef = ref<HTMLInputElement | null>(null);
|
||||
const showAttachmentMenu = ref(false);
|
||||
const showAttachmentUrlPanel = ref(false);
|
||||
|
||||
const closeAttachmentMenu = () => {
|
||||
showAttachmentMenu.value = false;
|
||||
showAttachmentUrlPanel.value = false;
|
||||
attachmentUrlInput.value = '';
|
||||
};
|
||||
|
||||
const toggleAttachmentMenu = async () => {
|
||||
if (isThinking.value || isUploadingAttachments.value) return;
|
||||
showAttachmentMenu.value = !showAttachmentMenu.value;
|
||||
if (!showAttachmentMenu.value) {
|
||||
showAttachmentUrlPanel.value = false;
|
||||
attachmentUrlInput.value = '';
|
||||
}
|
||||
};
|
||||
|
||||
const selectAttachmentLocal = () => {
|
||||
if (!attachmentPolicy.value.canLocal) return;
|
||||
closeAttachmentMenu();
|
||||
filePickerRef.value?.click();
|
||||
};
|
||||
|
||||
const selectAttachmentUrl = async () => {
|
||||
if (!attachmentPolicy.value.canRemote) return;
|
||||
showAttachmentMenu.value = true;
|
||||
showAttachmentUrlPanel.value = true;
|
||||
await nextTick();
|
||||
attachmentUrlInputRef.value?.focus();
|
||||
};
|
||||
|
||||
const difyFileUploadConfig = computed<Record<string, any>>(() => {
|
||||
return (currentAgent.value?.dify_parameters?.file_upload as any) || {};
|
||||
});
|
||||
|
||||
const difySystemParameters = computed<Record<string, any>>(() => {
|
||||
return (currentAgent.value?.dify_parameters?.system_parameters as any) || {};
|
||||
});
|
||||
|
||||
const attachmentPolicy = computed(() => {
|
||||
const types: ChatUploadFileType[] = ['image', 'document', 'audio', 'video', 'custom'];
|
||||
const enabled: Record<ChatUploadFileType, { local: boolean; remote: boolean; limit?: number }> = {
|
||||
image: { local: false, remote: false },
|
||||
document: { local: false, remote: false },
|
||||
audio: { local: false, remote: false },
|
||||
video: { local: false, remote: false },
|
||||
custom: { local: false, remote: false },
|
||||
};
|
||||
const raw = difyFileUploadConfig.value as any;
|
||||
const normalizedAllowedExts = Array.isArray(raw?.allowed_file_extensions)
|
||||
? raw.allowed_file_extensions
|
||||
.map((v: any) => String(v || '').trim())
|
||||
.filter(Boolean)
|
||||
.map((v: string) => (v.startsWith('.') ? v.slice(1) : v).toLowerCase())
|
||||
.filter(Boolean)
|
||||
: [];
|
||||
const allowedExts: Set<string> | null = normalizedAllowedExts.length > 0 ? new Set<string>(normalizedAllowedExts) : null;
|
||||
|
||||
const allowedTypes = Array.isArray(raw?.allowed_file_types)
|
||||
? raw.allowed_file_types
|
||||
.map((v: any) => String(v || '').trim().toLowerCase())
|
||||
.filter(Boolean)
|
||||
: [];
|
||||
const allowedTypeSet = allowedTypes.length > 0 ? new Set(allowedTypes) : null;
|
||||
|
||||
const allowedMethods = Array.isArray(raw?.allowed_file_upload_methods)
|
||||
? raw.allowed_file_upload_methods
|
||||
.map((v: any) => String(v || '').trim().toLowerCase())
|
||||
.filter(Boolean)
|
||||
: [];
|
||||
const allowedMethodSet = allowedMethods.length > 0 ? new Set(allowedMethods) : null;
|
||||
|
||||
const isNewSchema = Boolean(raw && raw.enabled === true && allowedTypeSet && allowedMethodSet);
|
||||
if (isNewSchema && allowedTypeSet && allowedMethodSet) {
|
||||
for (const t of types) {
|
||||
const cfg = raw?.[t];
|
||||
const cfgEnabled = typeof cfg?.enabled === 'boolean' ? Boolean(cfg.enabled) : null;
|
||||
const typeAllowed = allowedTypeSet.has(t);
|
||||
if (cfgEnabled === false) continue;
|
||||
if (cfgEnabled !== true && !typeAllowed) continue;
|
||||
|
||||
const transferMethods = Array.isArray(cfg?.transfer_methods)
|
||||
? cfg.transfer_methods
|
||||
.map((v: any) => String(v || '').trim().toLowerCase())
|
||||
.filter(Boolean)
|
||||
: [];
|
||||
const methodSet = transferMethods.length > 0 ? new Set(transferMethods) : allowedMethodSet;
|
||||
|
||||
enabled[t] = {
|
||||
local: methodSet.has('local_file'),
|
||||
remote: methodSet.has('remote_url'),
|
||||
limit: Number.isFinite(Number(cfg?.number_limits))
|
||||
? Number(cfg.number_limits)
|
||||
: (Number.isFinite(Number(raw?.number_limits)) ? Number(raw.number_limits) : undefined),
|
||||
};
|
||||
}
|
||||
} else {
|
||||
for (const t of types) {
|
||||
const cfg = raw?.[t];
|
||||
if (!cfg || !cfg.enabled) continue;
|
||||
const transferMethods = Array.isArray(cfg.transfer_methods) ? cfg.transfer_methods : [];
|
||||
enabled[t] = {
|
||||
local: transferMethods.includes('local_file'),
|
||||
remote: transferMethods.includes('remote_url'),
|
||||
limit: Number.isFinite(Number(cfg.number_limits)) ? Number(cfg.number_limits) : undefined,
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
const mergedLimits = {
|
||||
...(difySystemParameters.value || {}),
|
||||
...(raw?.fileUploadConfig || {}),
|
||||
} as any;
|
||||
const system = mergedLimits || {};
|
||||
const sizeLimitMb: Record<ChatUploadFileType, number | null> = {
|
||||
image: Number.isFinite(Number(system.image_file_size_limit)) ? Number(system.image_file_size_limit) : (Number.isFinite(Number(system.file_size_limit)) ? Number(system.file_size_limit) : null),
|
||||
audio: Number.isFinite(Number(system.audio_file_size_limit)) ? Number(system.audio_file_size_limit) : (Number.isFinite(Number(system.file_size_limit)) ? Number(system.file_size_limit) : null),
|
||||
video: Number.isFinite(Number(system.video_file_size_limit)) ? Number(system.video_file_size_limit) : (Number.isFinite(Number(system.file_size_limit)) ? Number(system.file_size_limit) : null),
|
||||
document: Number.isFinite(Number(system.file_size_limit)) ? Number(system.file_size_limit) : null,
|
||||
custom: Number.isFinite(Number(system.file_size_limit)) ? Number(system.file_size_limit) : null,
|
||||
};
|
||||
|
||||
const anyEnabled = Object.values(enabled).some((v) => v.local || v.remote);
|
||||
const canLocal = Object.values(enabled).some((v) => v.local);
|
||||
const canRemote = Object.values(enabled).some((v) => v.remote);
|
||||
const totalLimit = (() => {
|
||||
const v1 = raw?.fileUploadConfig?.file_upload_limit;
|
||||
if (Number.isFinite(Number(v1))) return Number(v1);
|
||||
const v2 = raw?.number_limits;
|
||||
if (Number.isFinite(Number(v2))) return Number(v2);
|
||||
return null;
|
||||
})();
|
||||
|
||||
const effectiveAllowedExts: Set<string> | null = (() => {
|
||||
if (!allowedExts) return null;
|
||||
const filtered = new Set<string>();
|
||||
for (const ext of allowedExts) {
|
||||
const t = resolveDifyType(ext);
|
||||
if (!t) {
|
||||
if (enabled.custom.local || enabled.custom.remote) filtered.add(ext);
|
||||
continue;
|
||||
}
|
||||
if (enabled[t]?.local || enabled[t]?.remote) filtered.add(ext);
|
||||
}
|
||||
return filtered.size > 0 ? filtered : null;
|
||||
})();
|
||||
|
||||
const accept = (() => {
|
||||
if (enabled.custom.local) return '';
|
||||
if (effectiveAllowedExts) {
|
||||
return Array.from(effectiveAllowedExts).map((e) => `.${e}`).join(',');
|
||||
}
|
||||
const parts = new Set<string>();
|
||||
const pushExts = (exts: Set<string>) => {
|
||||
for (const e of exts) parts.add(`.${e}`);
|
||||
};
|
||||
if (enabled.image.local) pushExts(DIFY_SUPPORTED_EXTS.image);
|
||||
if (enabled.audio.local) pushExts(DIFY_SUPPORTED_EXTS.audio);
|
||||
if (enabled.video.local) pushExts(DIFY_SUPPORTED_EXTS.video);
|
||||
if (enabled.document.local) pushExts(DIFY_SUPPORTED_EXTS.document);
|
||||
return Array.from(parts).join(',');
|
||||
})();
|
||||
|
||||
return {
|
||||
anyEnabled,
|
||||
enabled,
|
||||
sizeLimitMb,
|
||||
canLocal,
|
||||
canRemote,
|
||||
accept,
|
||||
allowedExts: effectiveAllowedExts,
|
||||
totalLimit,
|
||||
};
|
||||
});
|
||||
|
||||
const inferFileTypeFromUrl = (url: string): ChatUploadFileType | null => {
|
||||
const ext = extractExt(url);
|
||||
const resolved = resolveDifyType(ext);
|
||||
return resolved;
|
||||
};
|
||||
|
||||
const inferFileTypeFromFile = (file: File): ChatUploadFileType | null => {
|
||||
const ext = extractExt(file.name || '');
|
||||
const resolved = resolveDifyType(ext, file.type || '');
|
||||
return resolved;
|
||||
};
|
||||
|
||||
const removeAttachment = (id: string) => {
|
||||
attachments.value = attachments.value.filter((a) => a.id !== id);
|
||||
};
|
||||
|
||||
const handleLocalFilesSelected = (event: Event) => {
|
||||
const inputEl = event.target as HTMLInputElement | null;
|
||||
const fileList = inputEl?.files;
|
||||
if (!fileList) return;
|
||||
const files = Array.from(fileList);
|
||||
for (const f of files) {
|
||||
if (attachmentPolicy.value.totalLimit && attachments.value.length >= attachmentPolicy.value.totalLimit) {
|
||||
msg.warning(`附件数量已达上限(${attachmentPolicy.value.totalLimit})`);
|
||||
break;
|
||||
}
|
||||
const ext = extractExt(f.name || '');
|
||||
if (attachmentPolicy.value.allowedExts && (!ext || !attachmentPolicy.value.allowedExts.has(ext))) {
|
||||
msg.warning(`不支持的附件类型:${f.name}`);
|
||||
continue;
|
||||
}
|
||||
let type = inferFileTypeFromFile(f);
|
||||
if (!type) {
|
||||
if (attachmentPolicy.value.enabled.custom.local && !isKnownDifyExt(ext)) {
|
||||
type = 'custom';
|
||||
} else {
|
||||
msg.warning(`不支持的附件类型:${f.name}`);
|
||||
continue;
|
||||
}
|
||||
}
|
||||
const caps = attachmentPolicy.value.enabled[type];
|
||||
if (!caps?.local) {
|
||||
msg.warning(`当前应用不支持上传此类型附件:${type}`);
|
||||
continue;
|
||||
}
|
||||
const limit = attachmentPolicy.value.sizeLimitMb[type];
|
||||
if (limit && f.size > limit * 1024 * 1024) {
|
||||
msg.warning(`附件过大(上限 ${limit}MB):${f.name}`);
|
||||
continue;
|
||||
}
|
||||
const countSameType = attachments.value.filter((a) => a.type === type).length;
|
||||
if (caps.limit && countSameType >= caps.limit) {
|
||||
msg.warning(`该类型附件数量已达上限(${caps.limit})`);
|
||||
continue;
|
||||
}
|
||||
attachments.value.push({ id: `${Date.now()}_${Math.random()}`, kind: 'local', file: f, type });
|
||||
}
|
||||
if (inputEl) inputEl.value = '';
|
||||
};
|
||||
|
||||
const addRemoteUrlAttachment = () => {
|
||||
const raw = attachmentUrlInput.value.trim();
|
||||
if (!raw) return;
|
||||
const url = raw.startsWith('//') ? `${window.location.protocol}${raw}` : raw;
|
||||
if (!/^https?:\/\//i.test(url)) {
|
||||
msg.warning('仅支持 http/https URL');
|
||||
return;
|
||||
}
|
||||
if (!attachmentPolicy.value.canRemote) {
|
||||
msg.warning('当前应用不支持 URL 附件');
|
||||
return;
|
||||
}
|
||||
if (attachmentPolicy.value.totalLimit && attachments.value.length >= attachmentPolicy.value.totalLimit) {
|
||||
msg.warning(`附件数量已达上限(${attachmentPolicy.value.totalLimit})`);
|
||||
return;
|
||||
}
|
||||
const ext = extractExt(url);
|
||||
if (attachmentPolicy.value.allowedExts && (!ext || !attachmentPolicy.value.allowedExts.has(ext))) {
|
||||
msg.warning('不支持的 URL 附件类型');
|
||||
return;
|
||||
}
|
||||
let type = inferFileTypeFromUrl(url);
|
||||
if (!type) {
|
||||
if (attachmentPolicy.value.enabled.custom.remote && !isKnownDifyExt(ext)) {
|
||||
type = 'custom';
|
||||
} else {
|
||||
msg.warning('不支持的 URL 附件类型');
|
||||
return;
|
||||
}
|
||||
}
|
||||
const caps = attachmentPolicy.value.enabled[type];
|
||||
if (!caps?.remote) {
|
||||
msg.warning(`当前应用不支持该类型 URL 附件:${type}`);
|
||||
return;
|
||||
}
|
||||
const countSameType = attachments.value.filter((a) => a.type === type).length;
|
||||
if (caps.limit && countSameType >= caps.limit) {
|
||||
msg.warning(`该类型附件数量已达上限(${caps.limit})`);
|
||||
return;
|
||||
}
|
||||
attachments.value.push({ id: `${Date.now()}_${Math.random()}`, kind: 'remote', url, type });
|
||||
attachmentUrlInput.value = '';
|
||||
closeAttachmentMenu();
|
||||
};
|
||||
|
||||
const buildFileSpecsForSend = async (): Promise<ChatUploadFileSpec[]> => {
|
||||
if (!attachmentPolicy.value.anyEnabled) return [];
|
||||
if (attachments.value.length === 0) return [];
|
||||
|
||||
const specs: ChatUploadFileSpec[] = [];
|
||||
const locals = attachments.value.filter((a) => a.kind === 'local') as Array<Extract<PendingAttachment, { kind: 'local' }>>;
|
||||
const remotes = attachments.value.filter((a) => a.kind === 'remote') as Array<Extract<PendingAttachment, { kind: 'remote' }>>;
|
||||
|
||||
if (locals.length > 0) {
|
||||
isUploadingAttachments.value = true;
|
||||
try {
|
||||
for (const item of locals) {
|
||||
const uploaded = await uploadChatFile(agentId, item.file);
|
||||
if (!uploaded?.id) {
|
||||
throw new Error('Missing upload id');
|
||||
}
|
||||
specs.push({ type: item.type, transfer_method: 'local_file', upload_file_id: uploaded.id });
|
||||
}
|
||||
} finally {
|
||||
isUploadingAttachments.value = false;
|
||||
}
|
||||
}
|
||||
|
||||
for (const item of remotes) {
|
||||
specs.push({ type: item.type, transfer_method: 'remote_url', url: item.url });
|
||||
}
|
||||
|
||||
return specs;
|
||||
};
|
||||
|
||||
const openDeleteConfirmDialog = (
|
||||
message: string,
|
||||
onConfirm: () => Promise<void> | void
|
||||
@@ -1690,16 +2063,43 @@ const presetQuestion = computed(() => {
|
||||
|
||||
const handleSend = async (textOrEvent?: string | Event) => {
|
||||
const content = (typeof textOrEvent === 'string' ? textOrEvent : null) || input.value;
|
||||
if (!content.trim() || isThinking.value) return;
|
||||
|
||||
if (typeof textOrEvent !== 'string') input.value = '';
|
||||
if (!content.trim() || isThinking.value || isUploadingAttachments.value) return;
|
||||
|
||||
if (isStrongLeaveIntent(content)) {
|
||||
startLocalLeaveFlow(content);
|
||||
return;
|
||||
}
|
||||
|
||||
await sendMessage(content, agentId, selectedKb.value);
|
||||
let files: ChatUploadFileSpec[] = [];
|
||||
if (attachmentPolicy.value.anyEnabled && attachments.value.length > 0) {
|
||||
try {
|
||||
files = await buildFileSpecsForSend();
|
||||
} catch (e: any) {
|
||||
let suffix = '';
|
||||
if (e instanceof BusinessError) {
|
||||
const headers = e.details?.headers;
|
||||
const requestId = headers?.['x-request-id']
|
||||
|| headers?.['x-requestid']
|
||||
|| headers?.['request-id']
|
||||
|| headers?.['trace-id']
|
||||
|| headers?.['cf-ray'];
|
||||
if (requestId) {
|
||||
suffix = `(rid=${requestId})`;
|
||||
}
|
||||
try {
|
||||
console.warn('[chat] attachment upload failed', { message: e.message, code: e.code, requestId, details: e.details });
|
||||
} catch {
|
||||
}
|
||||
}
|
||||
msg.warning(`附件处理失败:${e?.message || 'unknown error'}${suffix}`);
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
if (typeof textOrEvent !== 'string') input.value = '';
|
||||
attachments.value = [];
|
||||
|
||||
await sendMessage(content, agentId, selectedKb.value, files);
|
||||
|
||||
if (!conversationId.value && history.value.length === 0) {
|
||||
await loadHistory();
|
||||
@@ -2814,6 +3214,30 @@ const showChatRating = ref(false);
|
||||
autocorrect="off"
|
||||
autocapitalize="off"
|
||||
></textarea>
|
||||
|
||||
<input
|
||||
ref="filePickerRef"
|
||||
type="file"
|
||||
multiple
|
||||
class="hidden"
|
||||
:accept="attachmentPolicy.accept || undefined"
|
||||
@change="handleLocalFilesSelected"
|
||||
/>
|
||||
|
||||
<div v-if="attachments.length > 0" class="flex flex-wrap gap-2 px-3 pb-1">
|
||||
<div
|
||||
v-for="a in attachments"
|
||||
:key="a.id"
|
||||
class="flex items-center gap-2 rounded-lg border border-default bg-surface-soft px-2 py-1 text-xs text-secondary"
|
||||
>
|
||||
<span class="max-w-[220px] truncate">
|
||||
{{ a.kind === 'local' ? a.file.name : a.url }}
|
||||
</span>
|
||||
<button type="button" class="text-muted hover:text-red-500" @click="removeAttachment(a.id)">
|
||||
<X class="h-3.5 w-3.5" />
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="mt-2 flex items-center justify-between px-2 pb-1">
|
||||
<div class="flex items-center gap-3">
|
||||
@@ -2827,6 +3251,70 @@ const showChatRating = ref(false);
|
||||
>
|
||||
<Mic class="h-5 w-5" />
|
||||
</button>
|
||||
<div v-if="attachmentPolicy.anyEnabled" ref="attachmentMenuRef" class="relative">
|
||||
<button
|
||||
@click="toggleAttachmentMenu"
|
||||
type="button"
|
||||
:disabled="isThinking || isUploadingAttachments"
|
||||
title="附件"
|
||||
class="text-muted transition-colors hover:text-brand-600 disabled:cursor-not-allowed disabled:opacity-50"
|
||||
>
|
||||
<Paperclip class="h-5 w-5" />
|
||||
</button>
|
||||
<div
|
||||
v-if="showAttachmentMenu"
|
||||
class="absolute bottom-full left-0 mb-2 w-72 overflow-hidden rounded-xl border border-subtle bg-surface py-1 shadow-xl animate-fade-in"
|
||||
>
|
||||
<button
|
||||
v-if="attachmentPolicy.canLocal"
|
||||
type="button"
|
||||
class="flex w-full items-center gap-2 px-3 py-2 text-xs text-secondary transition-colors hover:bg-surface-soft"
|
||||
@click="selectAttachmentLocal"
|
||||
>
|
||||
<Paperclip class="h-4 w-4 text-brand-500" />
|
||||
上传本地文件
|
||||
</button>
|
||||
<button
|
||||
v-if="attachmentPolicy.canRemote"
|
||||
type="button"
|
||||
class="flex w-full items-center gap-2 px-3 py-2 text-xs text-secondary transition-colors hover:bg-surface-soft"
|
||||
@click="selectAttachmentUrl"
|
||||
>
|
||||
<Link2 class="h-4 w-4 text-brand-500" />
|
||||
粘贴 URL
|
||||
</button>
|
||||
<div v-if="showAttachmentUrlPanel" class="px-3 py-2">
|
||||
<div class="flex items-center gap-2">
|
||||
<input
|
||||
ref="attachmentUrlInputRef"
|
||||
v-model="attachmentUrlInput"
|
||||
:disabled="isThinking || isUploadingAttachments"
|
||||
placeholder="粘贴附件 URL(http/https)"
|
||||
class="flex-1 rounded-lg border border-default bg-surface-soft px-3 py-2 text-xs text-secondary placeholder-slate-400 focus:outline-none focus:ring-0"
|
||||
@keydown.enter.prevent="addRemoteUrlAttachment"
|
||||
/>
|
||||
<button
|
||||
type="button"
|
||||
:disabled="isThinking || isUploadingAttachments"
|
||||
@click="addRemoteUrlAttachment"
|
||||
class="flex h-9 w-9 items-center justify-center rounded-lg border border-default text-muted transition-colors hover:bg-surface-soft disabled:cursor-not-allowed disabled:opacity-50"
|
||||
title="添加"
|
||||
>
|
||||
<Check class="h-4 w-4" />
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
:disabled="isThinking || isUploadingAttachments"
|
||||
@click="closeAttachmentMenu"
|
||||
class="flex h-9 w-9 items-center justify-center rounded-lg border border-default text-muted transition-colors hover:bg-surface-soft disabled:cursor-not-allowed disabled:opacity-50"
|
||||
title="取消"
|
||||
>
|
||||
<X class="h-4 w-4" />
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<div class="relative" ref="kbMenuRef">
|
||||
<button
|
||||
@click="showKbDropdown = !showKbDropdown"
|
||||
@@ -2861,13 +3349,14 @@ const showChatRating = ref(false);
|
||||
</div>
|
||||
<button
|
||||
@click="handleSend"
|
||||
:disabled="!input.trim() || isThinking"
|
||||
:disabled="!input.trim() || isThinking || isUploadingAttachments"
|
||||
class="flex h-10 w-10 items-center justify-center rounded-full border shadow-sm transition-all duration-200 disabled:cursor-not-allowed disabled:opacity-50"
|
||||
:class="!input.trim() || isThinking
|
||||
:class="!input.trim() || isThinking || isUploadingAttachments
|
||||
? 'border-default bg-slate-100 text-muted'
|
||||
: 'border-brand-500 bg-brand-500 text-white shadow-[0_0_0_4px_rgba(59,130,246,0.18)] hover:scale-105 hover:bg-brand-600 hover:shadow-[0_0_0_6px_rgba(59,130,246,0.24)] active:scale-95'"
|
||||
>
|
||||
<Send class="h-4 w-4" />
|
||||
<Loader2 v-if="isUploadingAttachments" class="h-4 w-4 animate-spin" />
|
||||
<Send v-else class="h-4 w-4" />
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
Reference in new issue
Block a user