Merge dev into hugo

This commit is contained in:
hugo committed 2026-06-02 10:32:17 +08:00
commit a5cc48b6aa
28 files changed
+3608 -4237

No files matched your search

File diff suppressed because it is too large. Load diff
+609 -142
View File
@@ -1,5 +1,3 @@
<script setup lang="ts">
/**
* ChatView.vue
@@ -13,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';
@@ -23,12 +21,31 @@ import DeleteConfirmDialog from '../components/DeleteConfirmDialog.vue';
import GeneralFeedbackDialog from '../components/GeneralFeedbackDialog.vue';
import { useMessage } from '../composables/useMessage';
import { useIsMobile } from '../composables/useIsMobile';
import { getVoiceUnavailableErrorKey, useSpeechRecognition } from '../composables/useSpeechRecognition';
import { useTheme } from '../composables/useTheme';
import { getAuthHeaders, getStoredAuthUser, logoutAuth } from '../utils/auth';
import { copyTextToClipboard } from '../utils/clipboard';
import { setLastChatAgentId } from '../utils/lastChatAgent';
import { openAgentChatTab, registerOpenAgentId } from '../utils/agentTabs';
import ChatShell from '../layouts/ChatShell.vue';
import { BusinessError } from '../api/client';
import {
listChatSessions,
deleteAllChatSessions,
deleteChatSession,
listChatMessages,
saveLocalChatMessage,
resolveChatSourceFile,
listOaEmployees,
uploadChatFile,
} from '../api/chat';
import {
getUserProfile,
getLeaveBalance,
submitLeaveWorkflow,
getUserAgent,
listUserAgents,
} from '../api/user';
const { t, locale } = useI18n();
const { appliedTheme, toggleLightDark } = useTheme();
@@ -97,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 = () => {
@@ -113,10 +133,6 @@ watch(locale, (newLang) => {
localStorage.setItem('hxops_lang', String(newLang));
});
const handleVoiceFeatureClick = () => {
msg.info(t('chat.devComingSoon'));
};
const stripReasoningPrelude = (text: string) => {
if (!text) return '';
let cleaned = text
@@ -556,18 +572,11 @@ const resolveSourceLink = async (file: SourceFileLink): Promise<{ name: string;
throw new Error('当前源文件暂未返回可预览链接');
}
const params = new URLSearchParams({
agent_id: String(agentId),
const data = await resolveChatSourceFile({
agent_id: agentId,
dataset_id: file.datasetId,
remote_document_id: file.remoteDocumentId,
});
const response = await fetch(`/api/chat/source-file?${params.toString()}`, {
headers: getAuthHeaders(),
});
const data = await response.json().catch(() => ({}));
if (!response.ok) {
throw new Error(data?.error || `HTTP ${response.status}`);
}
const resolvedUrl = normalizeUrl(data?.source_download_url || '');
if (!resolvedUrl) {
@@ -613,6 +622,34 @@ const copiedIndex = ref<number | null>(null);
// 从 useChat 中解构出消息列表、思考状态、会话 ID 与发送函数
const { messages, isThinking, conversationId, runs, activeRunId, activateRun, createNewChatView, sendMessage } = useChat();
const input = ref('');
const {
isListening: isVoiceListening,
toggle: toggleVoiceInput,
stop: stopVoiceInput,
} = useSpeechRecognition({
lang: locale,
onResult: (text) => {
input.value = text;
},
onError: (key) => {
msg.warning(t(key));
},
});
const handleVoiceFeatureClick = () => {
if (isThinking.value) return;
const unavailable = getVoiceUnavailableErrorKey();
if (unavailable) {
msg.warning(t(unavailable));
return;
}
toggleVoiceInput(input.value);
};
watch(isThinking, (thinking) => {
if (thinking) stopVoiceInput();
});
const currentAgent = ref<any>(null);
const userAgents = ref<Array<{ id: number; name: string; description: string; icon_url?: string; dify_app_type?: 'chatflow' | 'workflow' }>>([]);
const showGeneralFeedbackDialog = ref(false);
@@ -621,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
@@ -858,18 +1264,17 @@ const fetchLeaveAgents = async (isLoadMore = false) => {
leaveAgentLoading.value = true;
try {
const res = await fetch(`/api/chat/oa/employees?keyword=${encodeURIComponent(leaveAgentKeyword.value)}&page=${leaveAgentPage.value}&page_size=20&agent_id=${agentId}`, {
headers: getAuthHeaders()
const data = await listOaEmployees(agentId, {
keyword: leaveAgentKeyword.value,
page: leaveAgentPage.value,
page_size: 20,
});
if (res.ok) {
const data = await res.json();
if (isLoadMore) {
leaveAgentOptions.value.push(...data.items);
} else {
leaveAgentOptions.value = data.items;
}
leaveAgentHasMore.value = leaveAgentOptions.value.length < data.total;
if (isLoadMore) {
leaveAgentOptions.value.push(...data.items);
} else {
leaveAgentOptions.value = data.items;
}
leaveAgentHasMore.value = leaveAgentOptions.value.length < data.total;
} catch (e) {
console.error('Failed to load OA employees', e);
} finally {
@@ -891,14 +1296,13 @@ const loadAllAgents = async () => {
if (!leaveAgentHasMore.value || leaveAgentLoading.value) return;
leaveAgentLoading.value = true;
try {
const res = await fetch(`/api/chat/oa/employees?keyword=${encodeURIComponent(leaveAgentKeyword.value)}&page=1&page_size=100000&agent_id=${agentId}`, {
headers: getAuthHeaders()
const data = await listOaEmployees(agentId, {
keyword: leaveAgentKeyword.value,
page: 1,
page_size: 100000,
});
if (res.ok) {
const data = await res.json();
leaveAgentOptions.value = data.items;
leaveAgentHasMore.value = false;
}
leaveAgentOptions.value = data.items;
leaveAgentHasMore.value = false;
} catch (e) {
console.error('Failed to load all OA employees', e);
} finally {
@@ -1173,11 +1577,12 @@ const syncLeaveDuration = (form: LeaveRequestFormData) => {
}
};
const getLeaveIntentNormalized = (content: string) => (content || '').replace(/\s+/g, '');
const isStrongLeaveIntent = (content: string) => {
const normalized = getLeaveIntentNormalized(content);
const weakConsultationIntent = /(请假流程|请假怎么走|请假步骤|请假如何申请|请假如何走流程|请假怎么办|请假需要什么|请假规定)/;
const weakConsultationIntent = /(请假流程|请假怎么走|请假步骤|请假如何申请|请假如何走流程|请假怎么办|请假需要什么|请假规定|请假管理办法|请假制度)/;
const materialConsultationIntent = /(提交哪些|提交什么|需要哪些|需要什么|要提交哪些|要提交什么|哪些资料|哪些材料|什么资料|什么材料|申请材料|所需资料|所需材料)/;
if (weakConsultationIntent.test(normalized)) return false;
if (materialConsultationIntent.test(normalized)) return false;
@@ -1187,29 +1592,19 @@ const isStrongLeaveIntent = (content: string) => {
const saveLocalMessageToBackend = async (msg: any, userQuery: string = '') => {
try {
const res = await fetch('/api/chat/messages/local', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
...getAuthHeaders()
},
body: JSON.stringify({
conversation_id: conversationId.value,
type: msg.type,
content: msg.content,
payload: msg.payload,
query: userQuery,
agent_id: agentId
})
const data = await saveLocalChatMessage({
conversation_id: conversationId.value,
type: msg.type,
content: msg.content,
payload: msg.payload,
query: userQuery,
agent_id: agentId,
});
if (res.ok) {
const data = await res.json();
if (!conversationId.value && data.conversation_id) {
conversationId.value = data.conversation_id;
}
if (data.chat_log_id) {
msg.chat_log_id = data.chat_log_id;
}
if (!conversationId.value && data.conversation_id) {
conversationId.value = data.conversation_id;
}
if (data.chat_log_id) {
msg.chat_log_id = data.chat_log_id;
}
} catch (e) {
console.error('Failed to save local message', e);
@@ -1234,11 +1629,7 @@ const checkLeaveBalance = async (leaveTypeCode: string): Promise<{
remaining_hours: number | null;
} | null> => {
try {
const res = await fetch(`/api/user/leave-balance?leave_type=${encodeURIComponent(leaveTypeCode)}`, {
headers: getAuthHeaders(),
});
if (!res.ok) return null;
return await res.json();
return await getLeaveBalance(leaveTypeCode);
} catch (e) {
console.error('Failed to check leave balance', e);
return null;
@@ -1316,10 +1707,8 @@ const startLocalLeaveFlow = async (content: string) => {
try {
const keyword = payload.form.applicantName || payload.form.employeeId;
if (keyword) {
const res = await fetch(`/api/chat/oa/employees?keyword=${encodeURIComponent(keyword)}&page=1&page_size=1&agent_id=${agentId}`, { headers: getAuthHeaders() });
if (res.ok) {
const data = await res.json();
const match = (data.items || []).find((item: LeaveAgentOption) => item.employeeId === payload.form.employeeId);
const data = await listOaEmployees(agentId, { keyword, page: 1, page_size: 1 });
const match = (data.items || []).find((item: LeaveAgentOption) => item.employeeId === payload.form.employeeId);
if (match) {
payload.form.fillerJobTitle = match.jobtitle || '';
payload.form.fillerJobTitleName = match.jobtitleName || '';
@@ -1335,7 +1724,6 @@ const startLocalLeaveFlow = async (content: string) => {
payload.form.applicantDepartmentName = match.departmentName || '';
payload.form.applicantSubCompanyName = match.subcompanyName || '';
}
}
}
} catch (e) {
console.error('Failed to prefill OA user info', e);
@@ -1396,9 +1784,7 @@ const formatYesNoLabel = (value: 0 | 1 | null) => {
const syncCurrentUserProfile = async () => {
if (currentUser.value?.real_name?.trim()) return;
try {
const res = await fetch('/api/user/profile', { headers: getAuthHeaders() });
if (!res.ok) return;
const data = await res.json();
const data = await getUserProfile();
currentUser.value = { ...currentUser.value, ...data };
} catch (e) {
console.error('Failed to load current user profile', e);
@@ -1683,16 +2069,43 @@ const shippingCaseIdFromQuery = 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();
@@ -1824,19 +2237,7 @@ const confirmLeaveSubmission = async (chatMsg: any) => {
}
try {
const res = await fetch('/api/user/leave-workflow/submit', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
...getAuthHeaders(),
},
body: JSON.stringify(payload.form),
});
const data = await res.json().catch(() => ({}));
if (!res.ok) {
throw new Error(data?.error || t('chat.oaLeaveSubmitFailed'));
}
const data = await submitLeaveWorkflow(payload.form);
const resultMsg = {
role: 'assistant' as const,
type: 'leave-result' as const,
@@ -1921,10 +2322,7 @@ const regenerate = () => {
// 加载历史记录
const loadHistory = async () => {
try {
const res = await fetch(`/api/chat/sessions?agent_id=${agentId}`, { headers: getAuthHeaders() });
if (res.ok) {
history.value = await res.json();
}
history.value = await listChatSessions(agentId);
} catch (e) {
console.error('Failed to load history', e);
}
@@ -1933,16 +2331,11 @@ const loadHistory = async () => {
const clearAllHistory = async () => {
openDeleteConfirmDialog(t('chat.confirmClearHistory'), async () => {
try {
const res = await fetch(`/api/chat/sessions?agent_id=${agentId}`, {
method: 'DELETE',
headers: getAuthHeaders()
});
if (res.ok) {
history.value = [];
runs.value = [];
if (conversationId.value || activeRunId.value) {
startNewChat();
}
await deleteAllChatSessions(agentId);
history.value = [];
runs.value = [];
if (conversationId.value || activeRunId.value) {
startNewChat();
}
} catch (e) {
console.error('Failed to clear history', e);
@@ -1954,15 +2347,10 @@ const deleteHistoryItem = async (id: string, event: Event) => {
event.stopPropagation();
openDeleteConfirmDialog(t('chat.confirmDeleteHistoryItem'), async () => {
try {
const res = await fetch(`/api/chat/sessions/${id}?agent_id=${agentId}`, {
method: 'DELETE',
headers: getAuthHeaders()
});
if (res.ok) {
history.value = history.value.filter(h => h.conversation_id !== id);
if (conversationId.value === id) {
startNewChat();
}
await deleteChatSession(id, agentId);
history.value = history.value.filter(h => h.conversation_id !== id);
if (conversationId.value === id) {
startNewChat();
}
} catch (e) {
console.error('Failed to delete history item', e);
@@ -1976,13 +2364,8 @@ const loadConversation = async (id: string) => {
try {
activeRunId.value = null;
isThinking.value = false;
const res = await fetch(`/api/chat/messages?conversation_id=${id}&agent_id=${agentId}`, { headers: getAuthHeaders() });
if (res.ok) {
messages.value = await res.json();
conversationId.value = id;
// Reset feedback state
}
messages.value = await listChatMessages(id, agentId);
conversationId.value = id;
} catch (e) {
console.error('Failed to load conversation', e);
}
@@ -1994,33 +2377,26 @@ const startNewChat = () => {
const loadAgent = async () => {
try {
const res = await fetch(`/api/user/agents/${agentId}`, { headers: getAuthHeaders() });
if (res.ok) {
currentAgent.value = await res.json();
} else {
if (res.status === 403) {
msg.error(t('workspace.permission.denied') || 'Access denied');
router.push('/workspace?no_redirect=1');
return;
}
currentAgent.value = { name: t('workspace.unknownAgent') };
}
currentAgent.value = await getUserAgent(agentId);
} catch (e) {
if (e instanceof BusinessError && e.status === 403) {
msg.error(t('workspace.permission.denied') || 'Access denied');
router.push('/workspace?no_redirect=1');
return;
}
console.error('Failed to load agent', e);
currentAgent.value = { name: t('workspace.unknownAgent') };
}
};
const loadUserAgents = async () => {
try {
const res = await fetch('/api/agents', { headers: getAuthHeaders() });
if (res.ok) {
const agents = await res.json();
userAgents.value = Array.isArray(agents)
? agents.filter((a: any) => a.id !== agentId && (a.dify_app_type || 'chatflow') === 'chatflow')
: [];
if (userAgents.value.length === 0) {
showAgentPanel.value = false;
}
const agents = await listUserAgents();
userAgents.value = Array.isArray(agents)
? agents.filter((a: any) => a.id !== agentId && (a.dify_app_type || 'chatflow') === 'chatflow')
: [];
if (userAgents.value.length === 0) {
showAgentPanel.value = false;
}
} catch (e) {
userAgents.value = [];
@@ -2839,7 +3215,7 @@ const showChatRating = ref(false);
v-model="input"
@keydown.enter.prevent="handleSend"
rows="1"
:placeholder="$t('chat.askAnything')"
:placeholder="isVoiceListening ? $t('chat.voiceListening') : $t('chat.askAnything')"
class="w-full resize-none border-none bg-transparent px-3 py-2 text-[15px] leading-relaxed text-primary placeholder-slate-400 focus:outline-none focus:ring-0 focus:border-transparent"
style="min-height: 44px; max-height: 220px;"
:disabled="isThinking"
@@ -2847,17 +3223,107 @@ 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">
<button
@click="handleVoiceFeatureClick"
type="button"
:title="$t('chat.voiceFeature')"
class="text-muted transition-colors hover:text-brand-600"
:disabled="isThinking"
:title="isVoiceListening ? $t('chat.voiceStop') : $t('chat.voiceFeature')"
class="transition-colors disabled:cursor-not-allowed disabled:opacity-50"
:class="isVoiceListening ? 'text-red-500 animate-pulse' : 'text-muted hover:text-brand-600'"
>
<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"
@@ -2892,13 +3358,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>
+9 -22
View File
@@ -3,6 +3,7 @@ import { ref } from 'vue';
import { useRoute, useRouter } from 'vue-router';
import { Lock, AlertCircle, CheckCircle } from 'lucide-vue-next';
import MinimalShell from '../layouts/MinimalShell.vue';
import { resetPasswordConfirm } from '../api/user';
const route = useRoute();
const router = useRouter();
@@ -32,29 +33,15 @@ const handleReset = async () => {
message.value = '';
try {
const res = await fetch('/api/user/reset-password-confirm', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
token: token.value,
new_password: password.value
})
});
const data = await res.json();
if (res.ok) {
status.value = 'success';
message.value = 'Password reset successfully! Redirecting to login...';
setTimeout(() => {
router.push('/');
}, 3000);
} else {
status.value = 'error';
message.value = data.error || 'Failed to reset password';
}
} catch {
await resetPasswordConfirm(token.value, password.value);
status.value = 'success';
message.value = 'Password reset successfully! Redirecting to login...';
setTimeout(() => {
router.push('/');
}, 3000);
} catch (e) {
status.value = 'error';
message.value = 'Network error occurred';
message.value = (e as Error).message || 'Failed to reset password';
} finally {
isLoading.value = false;
}
+153 -205
View File
@@ -52,13 +52,18 @@ import {
Megaphone,
X,
ChevronDown,
ChevronUp
ChevronUp,
Clock,
Download,
Search,
RefreshCw,
Package
} from 'lucide-vue-next';
import KbWorkspaceView from './KbWorkspaceView.vue';
import ShippingNoticeView from './ShippingNoticeView.vue';
import { listWorkspaceScheduleRuns, workspaceRunExcelUrl, type ScheduleRun } from '../api/schedule';
import { Clock, Download, Search, RefreshCw, Package } from 'lucide-vue-next';
import { BusinessError, requestJson } from '../api/client';
const { t, locale } = useI18n();
const msg = useMessage();
@@ -203,23 +208,17 @@ const handleForgotPassword = async () => {
}
try {
const res = await fetch('/api/user/reset-password-by-email', {
await requestJson('/api/user/reset-password-by-email', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(forgotPasswordForm.value)
});
const data = await res.json();
if (res.ok) {
msg.success(t('login.passwordResetEmailSent'));
showForgotPasswordModal.value = false;
forgotPasswordForm.value = { email: '' };
} else {
msg.error(data.error || t('login.passwordResetRequestFailed'));
}
msg.success(t('login.passwordResetEmailSent'));
showForgotPasswordModal.value = false;
forgotPasswordForm.value = { email: '' };
} catch (e) {
console.error('Password reset error', e);
msg.error(t('common.errorOccurred'));
msg.error((e as Error)?.message || t('login.passwordResetRequestFailed'));
}
};
@@ -280,13 +279,10 @@ const getSectionTitleKey = (sectionId: string) => {
// Methods
const fetchHome = async () => {
try {
const res = await fetch('/api/user/home', { headers: getAuthHeaders() });
if (res.status === 401) {
msg.error(t('login.loginRequired'));
handleLogout();
return;
const data = await requestJson<any>('/api/user/home', { headers: getAuthHeaders() });
if (!data) {
throw new Error('Missing /api/user/home payload');
}
const data = await res.json();
currentUser.value = {
id: data.user.id,
username: data.user.username,
@@ -358,6 +354,11 @@ return;
});
}
} catch (e) {
if ((e as BusinessError)?.status === 401) {
msg.error(t('login.loginRequired'));
handleLogout();
return;
}
console.error('Failed to load user home', e);
} finally {
isLoading.value = false;
@@ -366,12 +367,7 @@ return;
const fetchPublicAgents = async () => {
try {
const res = await fetch('/api/agents/public');
if (res.ok) {
publicAgents.value = await res.json();
} else {
publicAgents.value = [];
}
publicAgents.value = await requestJson<Agent[]>('/api/agents/public');
} catch (e) {
publicAgents.value = [];
}
@@ -379,10 +375,7 @@ const fetchPublicAgents = async () => {
const fetchAnnouncements = async () => {
try {
const res = await fetch('/api/user/announcements');
if (res.ok) {
announcements.value = await res.json();
}
announcements.value = await requestJson<Announcement[]>('/api/user/announcements');
} catch (e) {
console.error('Failed to load announcements', e);
}
@@ -449,7 +442,7 @@ const handleLogin = async (event?: Event) => {
const loginApi = isCasdoorMode
? (config.auth?.casdoor?.passwordLoginApi || '/api/user/casdoor/password-login')
: '/api/user/login';
const res = await fetch(loginApi, {
const user = await requestJson<any>(loginApi, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
@@ -458,31 +451,6 @@ const handleLogin = async (event?: Event) => {
})
});
if (!res.ok) {
const err = await res.json();
// Handle specific error messages if needed, or just alert
let msg = err.error || t('login.failed');
if (isCasdoorMode) {
if (err.error_code === 'CASDOOR_USER_NOT_FOUND') {
msg = t('workspace.msg.casdoorNotMatchedContactAdmin');
} else if (err.error_code === 'ACCOUNT_DISABLED') {
msg = t('login.accountDisabled');
} else if (String(err.error || '').includes('invalid_grant')) {
msg = t('login.incorrectPassword');
}
}
if (err.error === 'User not found') msg = t('login.userNotFound');
if (err.error === 'Incorrect password') msg = t('login.incorrectPassword');
if (err.error === 'Account is disabled') msg = t('login.accountDisabled');
if (err.error === 'Database connection failed') msg = t('login.dbConnectionFailed');
if (err.error === 'Internal server error') msg = t('login.internalError');
msg.error(msg);
return;
}
const user = await res.json();
persistLoginUser(user);
await fetchHome();
@@ -490,8 +458,27 @@ const handleLogin = async (event?: Event) => {
pendingAgentId.value = null;
await router.replace(`/chat/${DEFAULT_POST_LOGIN_AGENT_ID}`);
} catch (e) {
const err = e as BusinessError;
const rawError = String(err.message || '');
const errorCode = String(err.code || '');
let errorText = rawError || t('login.failed');
const loginMode = String(config.auth?.loginMode || 'casdoor').toLowerCase();
if (loginMode === 'casdoor') {
if (errorCode === 'CASDOOR_USER_NOT_FOUND') {
errorText = t('workspace.msg.casdoorNotMatchedContactAdmin');
} else if (errorCode === 'ACCOUNT_DISABLED') {
errorText = t('login.accountDisabled');
} else if (rawError.includes('invalid_grant')) {
errorText = t('login.incorrectPassword');
}
}
if (rawError === 'User not found') errorText = t('login.userNotFound');
if (rawError === 'Incorrect password') errorText = t('login.incorrectPassword');
if (rawError === 'Account is disabled') errorText = t('login.accountDisabled');
if (rawError === 'Database connection failed') errorText = t('login.dbConnectionFailed');
if (rawError === 'Internal server error') errorText = t('login.internalError');
console.error(e);
msg.error(t('login.requestFailed'));
msg.error(errorText || t('login.requestFailed'));
}
};
@@ -520,24 +507,11 @@ const tryCasdoorCallbackLogin = async () => {
}
try {
const api = config.auth.casdoor.loginApi || '/api/user/casdoor/login';
const res = await fetch(api, {
const data = await requestJson<any>(api, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ code, state }),
});
const data = await res.json();
if (!res.ok) {
const code = String(data.error_code || '');
let msg = data.error || 'Casdoor login failed';
if (code === 'CASDOOR_USER_NOT_FOUND') {
msg = t('workspace.msg.casdoorNotMatchedNeedLocalUser');
} else if (code === 'ACCOUNT_DISABLED') {
msg = t('workspace.msg.localAccountDisabled');
}
msg.error(msg);
clearWecomCallbackQuery();
return true;
}
// Persist access+refresh tokens for API auth and silent refresh.
persistLoginUser(data);
sessionStorage.removeItem('hxops_casdoor_state');
@@ -545,8 +519,15 @@ const tryCasdoorCallbackLogin = async () => {
await fetchHome();
return true;
} catch (e) {
const err = e as BusinessError;
if (err.code === 'CASDOOR_USER_NOT_FOUND') {
msg.error(t('workspace.msg.casdoorNotMatchedNeedLocalUser'));
} else if (err.code === 'ACCOUNT_DISABLED') {
msg.error(t('workspace.msg.localAccountDisabled'));
} else {
msg.error(err.message || 'Casdoor login failed');
}
console.error(e);
msg.error('Casdoor login failed');
clearWecomCallbackQuery();
return true;
}
@@ -573,10 +554,9 @@ const handleWecomLogin = async () => {
if (hint) {
qs.set('provider_hint', hint);
}
const res = await fetch(`${api}?${qs.toString()}`);
const data = await res.json();
if (!res.ok || !data.url) {
msg.error(data.error || t('login.wecomStartFailed'));
const data = await requestJson<any>(`${api}?${qs.toString()}`);
if (!data?.url) {
msg.error(t('login.wecomStartFailed'));
return;
}
if (data.state) {
@@ -588,10 +568,9 @@ const handleWecomLogin = async () => {
const redirectUri = `${window.location.origin}${wecomCfg.callbackPath || '/workspace'}`;
const api = wecomCfg.authorizeApi || '/api/user/wecom/authorize-url';
const res = await fetch(`${api}?redirect_uri=${encodeURIComponent(redirectUri)}`);
const data = await res.json();
if (!res.ok || !data.url) {
msg.error(data.error || t('login.wecomStartFailed'));
const data = await requestJson<any>(`${api}?redirect_uri=${encodeURIComponent(redirectUri)}`);
if (!data?.url) {
msg.error(t('login.wecomStartFailed'));
return;
}
if (data.state) {
@@ -600,7 +579,7 @@ const handleWecomLogin = async () => {
window.location.href = data.url;
} catch (e) {
console.error(e);
msg.error(t('login.wecomStartFailed'));
msg.error((e as Error)?.message || t('login.wecomStartFailed'));
}
};
@@ -646,7 +625,7 @@ const submitWecomCompleteBind = async () => {
wecomBindPrompt.value.error = '';
try {
const api = config.auth.wecom.completeBindApi || '/api/user/wecom/complete-bind';
const res = await fetch(api, {
const data = await requestJson<any>(api, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
@@ -655,15 +634,6 @@ const submitWecomCompleteBind = async () => {
value: wecomBindPrompt.value.value.trim(),
}),
});
const data = await res.json();
if (!res.ok) {
wecomBindPrompt.value.error = formatWecomBindPromptError(data);
if (String(data.error_code || '') === 'WECOM_BIND_SESSION_EXPIRED') {
openWecomLoginDialog(data);
wecomBindPrompt.value = null;
}
return;
}
wecomLoginDialog.value = null;
persistLoginUser(data);
@@ -672,10 +642,19 @@ const submitWecomCompleteBind = async () => {
window.history.replaceState({}, '', '/workspace');
await fetchHome();
} catch (e) {
console.error(e);
const err = e as BusinessError;
if (wecomBindPrompt.value) {
wecomBindPrompt.value.error = t('login.wecomLoginFailed');
const errorPayload = {
error: err.message,
error_code: err.code,
};
wecomBindPrompt.value.error = formatWecomBindPromptError(errorPayload);
if (String(err.code || '') === 'WECOM_BIND_SESSION_EXPIRED') {
openWecomLoginDialog(errorPayload);
wecomBindPrompt.value = null;
}
}
console.error(e);
} finally {
if (wecomBindPrompt.value) {
wecomBindPrompt.value.submitting = false;
@@ -707,33 +686,11 @@ const tryWecomCallbackLogin = async () => {
isWecomLoggingIn.value = true;
try {
const api = config.auth.wecom.loginApi || '/api/user/wecom/login';
const res = await fetch(api, {
const data = await requestJson<any>(api, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ code, state }),
});
const data = await res.json();
if (!res.ok) {
const rawError = String(data.error || '');
let friendly = rawError || t('login.wecomLoginFailed');
if (rawError.includes('Invalid or expired WeCom state')) {
friendly = t('login.wecomStateExpired');
} else if (rawError.includes('bind WeCom account') || rawError.includes('No linked account found')) {
friendly = t('login.wecomBindRequired');
} else if (rawError.includes('Account is disabled')) {
friendly = t('login.wecomAccountDisabled');
}
msg.error(friendly);
sessionStorage.removeItem('hxops_wecom_state');
if (String(data.error_code || '') === 'WECOM_BIND_INPUT_REQUIRED') {
openWecomBindPrompt(data);
clearWecomCallbackQuery();
return true;
}
openWecomLoginDialog(data);
clearWecomCallbackQuery();
return true;
}
wecomLoginDialog.value = null;
persistLoginUser(data);
@@ -742,10 +699,25 @@ const tryWecomCallbackLogin = async () => {
await fetchHome();
return true;
} catch (e) {
const err = e as BusinessError;
const rawError = String(err.message || '');
const errorCode = String(err.code || '');
let friendly = rawError || t('login.wecomLoginFailed');
if (rawError.includes('Invalid or expired WeCom state')) {
friendly = t('login.wecomStateExpired');
} else if (rawError.includes('bind WeCom account') || rawError.includes('No linked account found')) {
friendly = t('login.wecomBindRequired');
} else if (rawError.includes('Account is disabled')) {
friendly = t('login.wecomAccountDisabled');
}
console.error(e);
msg.error(t('login.wecomLoginFailed'));
msg.error(friendly);
sessionStorage.removeItem('hxops_wecom_state');
openWecomLoginDialog({ error: t('login.wecomLoginFailed') });
if (errorCode === 'WECOM_BIND_INPUT_REQUIRED') {
openWecomBindPrompt({ error: rawError, error_code: errorCode });
} else {
openWecomLoginDialog({ error: rawError || t('login.wecomLoginFailed'), error_code: errorCode });
}
clearWecomCallbackQuery();
return true;
} finally {
@@ -760,23 +732,17 @@ const handleRegister = async () => {
}
try {
const res = await fetch('/api/user/register', {
await requestJson('/api/user/register', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(registerForm.value)
});
if (res.ok) {
msg.success(t('register.success'));
showRegisterModal.value = false;
registerForm.value = { username: '', password: '', email: '', real_name: '', employee_id: '', phone_number: '' };
} else {
const err = await res.json();
msg.error(err.error || t('register.failed'));
}
msg.success(t('register.success'));
showRegisterModal.value = false;
registerForm.value = { username: '', password: '', email: '', real_name: '', employee_id: '', phone_number: '' };
} catch (e) {
console.error('Register error:', e);
msg.error(t('register.requestFailed'));
msg.error((e as Error)?.message || t('register.requestFailed'));
}
};
@@ -873,28 +839,14 @@ const captureOriginalProfile = () => {
originalProfile.value = { ...profileUser.value };
};
const parseErrorMessage = async (res: Response) => {
try {
const data = await res.json();
return data?.error || data?.message || '';
} catch {
try {
return await res.text();
} catch {
return '';
}
}
};
const fetchProfile = async () => {
isProfileLoading.value = true;
try {
const res = await fetch('/api/user/profile', { headers: getAuthHeaders() });
if (!res.ok) {
const data = await requestJson<any>('/api/user/profile', { headers: getAuthHeaders() });
if (!data) {
msg.error(t('workspace.profile.msg.loadFailed'));
return;
}
const data = await res.json();
profileUser.value = { ...profileUser.value, ...data };
if (data.language) locale.value = data.language;
if (data.theme_preference) {
@@ -953,24 +905,17 @@ const saveProfile = async () => {
try {
isProfileSaving.value = true;
const res = await fetch('/api/user/profile', {
await requestJson('/api/user/profile', {
method: 'PUT',
headers: { 'Content-Type': 'application/json', ...getAuthHeaders() },
body: JSON.stringify(payload),
});
if (!res.ok) {
const message = await parseErrorMessage(res);
msg.error(message || t('workspace.profile.msg.saveFailed'));
return;
}
msg.success(t('workspace.profile.msg.saved'));
captureOriginalProfile();
isProfileEditing.value = false;
} catch (e) {
console.error(e);
msg.error(t('workspace.profile.msg.saveFailed'));
msg.error((e as Error)?.message || t('workspace.profile.msg.saveFailed'));
} finally {
isProfileSaving.value = false;
}
@@ -983,7 +928,7 @@ const handleChangePassword = async () => {
}
try {
const res = await fetch('/api/user/change-password', {
await requestJson('/api/user/change-password', {
method: 'POST',
headers: { 'Content-Type': 'application/json', ...getAuthHeaders() },
body: JSON.stringify({
@@ -991,19 +936,12 @@ const handleChangePassword = async () => {
new_password: passwordForm.value.new,
}),
});
const data = await res.json();
if (!res.ok) {
msg.error(data.error || t('workspace.profile.msg.changePasswordFailed'));
return;
}
msg.success(t('profile.passwordChanged') || 'Password changed successfully');
passwordForm.value = { current: '', new: '', confirm: '' };
showPasswordModal.value = false;
} catch (e) {
console.error(e);
msg.error(t('workspace.profile.msg.changePasswordFailed'));
msg.error((e as Error)?.message || t('workspace.profile.msg.changePasswordFailed'));
}
};
@@ -1152,19 +1090,14 @@ const isLoadingHistories = ref(false);
const loadChatHistories = async () => {
isLoadingHistories.value = true;
try {
const res = await fetch('/api/agents', { headers: getAuthHeaders() });
if (!res.ok) { isLoadingHistories.value = false; return; }
const agentList = await res.json();
const agentList = await requestJson<any[]>('/api/agents', { headers: getAuthHeaders() });
const allHistories: ChatHistoryItem[] = [];
await Promise.all(
(Array.isArray(agentList) ? agentList : []).map(async (agent: any) => {
try {
const hRes = await fetch(`/api/chat/sessions?agent_id=${agent.id}`, { headers: getAuthHeaders() });
if (hRes.ok) {
const sessions = await hRes.json();
for (const s of sessions) {
allHistories.push({ ...s, agent_id: agent.id, agent_name: agent.name });
}
const sessions = await requestJson<any[]>(`/api/chat/sessions?agent_id=${agent.id}`, { headers: getAuthHeaders() });
for (const s of (Array.isArray(sessions) ? sessions : [])) {
allHistories.push({ ...s, agent_id: agent.id, agent_name: agent.name });
}
} catch {}
})
@@ -1219,7 +1152,7 @@ const handleWecomDeeplinkContext = async () => {
if (traceId && isLoggedIn.value) {
try {
const api = config.auth?.wecom?.deeplinkTraceApi || '/api/user/wecom/deeplink-opened';
await fetch(api, {
await requestJson(api, {
method: 'POST',
headers: { 'Content-Type': 'application/json', ...getAuthHeaders() },
body: JSON.stringify({ trace_id: traceId }),
@@ -1247,14 +1180,18 @@ const handleWecomDeeplinkContext = async () => {
// Favorites
const toggleFavorite = async (agentId: number) => {
if (favoriteAgentIds.value.includes(agentId)) {
// Remove
await fetch(`/api/user/favorites/${agentId}`, { method: 'DELETE', headers: getAuthHeaders() });
favoriteAgentIds.value = favoriteAgentIds.value.filter(id => id !== agentId);
} else {
// Add
await fetch(`/api/user/favorites/${agentId}`, { method: 'POST', headers: getAuthHeaders() });
favoriteAgentIds.value.push(agentId);
try {
if (favoriteAgentIds.value.includes(agentId)) {
// Remove
await requestJson(`/api/user/favorites/${agentId}`, { method: 'DELETE', headers: getAuthHeaders() });
favoriteAgentIds.value = favoriteAgentIds.value.filter(id => id !== agentId);
} else {
// Add
await requestJson(`/api/user/favorites/${agentId}`, { method: 'POST', headers: getAuthHeaders() });
favoriteAgentIds.value.push(agentId);
}
} catch (e) {
msg.error((e as Error)?.message || t('common.errorOccurred'));
}
};
@@ -1298,18 +1235,17 @@ const saveQuickQuestion = async () => {
const method = editingQuestionId.value ? 'PUT' : 'POST';
const res = await fetch(url, {
method: method,
headers: { 'Content-Type': 'application/json', ...getAuthHeaders() },
body: JSON.stringify(newQuestion.value),
});
if (res.ok) {
try {
await requestJson(url, {
method: method,
headers: { 'Content-Type': 'application/json', ...getAuthHeaders() },
body: JSON.stringify(newQuestion.value),
});
await fetchHome();
isAddingQuestion.value = false;
editingQuestionId.value = null;
} else {
msg.error(t('workspace.quickQuestions.msg.saveFailed'));
} catch (e) {
msg.error((e as Error)?.message || t('workspace.quickQuestions.msg.saveFailed'));
}
};
@@ -1321,10 +1257,14 @@ const removeQuickQuestion = async (id: number) => {
const confirmRemoveQuickQuestion = async () => {
if (pendingDeleteQuickQuestionId.value === null) return;
await fetch(`/api/user/quick-questions/${pendingDeleteQuickQuestionId.value}`, { method: 'DELETE', headers: getAuthHeaders() });
await fetchHome();
pendingDeleteQuickQuestionId.value = null;
showDeleteQuickQuestionDialog.value = false;
try {
await requestJson(`/api/user/quick-questions/${pendingDeleteQuickQuestionId.value}`, { method: 'DELETE', headers: getAuthHeaders() });
await fetchHome();
pendingDeleteQuickQuestionId.value = null;
showDeleteQuickQuestionDialog.value = false;
} catch (e) {
msg.error((e as Error)?.message || t('workspace.quickQuestions.msg.saveFailed'));
}
};
const cancelRemoveQuickQuestion = () => {
@@ -1335,13 +1275,17 @@ const cancelRemoveQuickQuestion = () => {
// Drag & Drop
const toggleSectionCollapse = async (section: LayoutSection) => {
section.collapsed = !section.collapsed;
// Save layout state
await fetch('/api/user/homepage-layout', {
method: 'PUT',
headers: { 'Content-Type': 'application/json', ...getAuthHeaders() },
body: JSON.stringify({ layout: { sections: layoutSections.value } })
});
try {
await requestJson('/api/user/homepage-layout', {
method: 'PUT',
headers: { 'Content-Type': 'application/json', ...getAuthHeaders() },
body: JSON.stringify({ layout: { sections: layoutSections.value } })
});
} catch (e) {
msg.error((e as Error)?.message || t('common.errorOccurred'));
}
};
const onDragStart = (index: number) => {
@@ -1359,13 +1303,17 @@ const onDrop = async (index: number) => {
layoutSections.value.splice(draggedSectionIndex.value, 1);
layoutSections.value.splice(index, 0, draggedItem);
draggedSectionIndex.value = null;
// Save layout
await fetch('/api/user/homepage-layout', {
method: 'PUT',
headers: { 'Content-Type': 'application/json', ...getAuthHeaders() },
body: JSON.stringify({ layout: { sections: layoutSections.value } })
});
try {
await requestJson('/api/user/homepage-layout', {
method: 'PUT',
headers: { 'Content-Type': 'application/json', ...getAuthHeaders() },
body: JSON.stringify({ layout: { sections: layoutSections.value } })
});
} catch (e) {
msg.error((e as Error)?.message || t('common.errorOccurred'));
}
};
const openAnnouncement = (ann: Announcement) => {