Files
syops/frontend/src/views/ChatView.vue
T
2026-06-03 10:43:18 +08:00

3768 lines
158 KiB
Vue
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
<script setup lang="ts">
/**
* ChatView.vue
* 文件用途:单个 Agent 的对话界面
* 引用文件:vue, vue-router, lucide-vue-next, useChat 组合函数
* 逻辑关系:
* - 使用 useChat 发送消息并接收 SSE 流
* - 支持从首页携带预设问题快速发起对话
* - 在回答结束后允许用户对本次回答进行评分与意见反馈
*/
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, Paperclip, Link2 } from 'lucide-vue-next';
import LocaleToggleButton from '../components/LocaleToggleButton.vue';
import { marked } from 'marked';
import { useRoute, useRouter } from 'vue-router';
import { config } from '../config';
import FilePreviewModal from '../components/FilePreviewModal.vue';
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 { 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();
const msg = useMessage();
const { isMobile } = useIsMobile();
const showMobileAgentPopover = ref(false);
const mobileAgentPopoverRef = ref<HTMLElement | null>(null);
const handleMobileAgentPopoverClickOutside = (e: MouseEvent | TouchEvent) => {
if (mobileAgentPopoverRef.value && !mobileAgentPopoverRef.value.contains(e.target as Node)) {
showMobileAgentPopover.value = false;
}
};
const toggleMobileAgentPopover = () => {
showMobileAgentPopover.value = !showMobileAgentPopover.value;
if (showMobileAgentPopover.value) {
loadUserAgents();
}
};
const currentUser = ref(getStoredAuthUser());
const showUserDropdown = ref(false);
const userMenuRef = ref<HTMLElement | null>(null);
const selectedKb = ref('企业知识库');
const showKbDropdown = ref(false);
const kbMenuRef = ref<HTMLElement | null>(null);
const kbOptions = ['企业知识库', 'ERP知识库'];
const getKbLabel = (kb: string) => {
if (kb === '企业知识库') return t('chat.kb.enterprise');
if (kb === 'ERP知识库') return t('chat.kb.erp');
return kb;
};
const chatScrollContainer = ref<HTMLElement | null>(null);
let scrollToBottomFrame: number | null = null;
let wasThinking = false;
marked.setOptions({
gfm: true,
breaks: true,
});
const currentUserDisplayName = computed(() => {
const realName = currentUser.value?.real_name?.trim();
if (realName) return realName;
const aliasName = (currentUser.value as any)?.name?.trim?.() || (currentUser.value as any)?.wecom_name?.trim?.();
if (aliasName) return aliasName;
const username = currentUser.value?.username?.trim();
if (username && !/^\d+$/.test(username)) return username;
return '当前用户';
});
const currentUserEmployeeId = computed(() => {
const employeeId = currentUser.value?.employee_id?.trim();
if (employeeId) return employeeId;
const username = currentUser.value?.username?.trim();
return username || '-';
});
const handleDocumentPointerDown = (event: MouseEvent | TouchEvent) => {
const target = event.target as Node | null;
if (!target) return;
if (showUserDropdown.value && userMenuRef.value && !userMenuRef.value.contains(target)) {
showUserDropdown.value = false;
}
if (showKbDropdown.value && kbMenuRef.value && !kbMenuRef.value.contains(target)) {
showKbDropdown.value = false;
}
if (showAttachmentMenu.value && attachmentMenuRef.value && !attachmentMenuRef.value.contains(target)) {
closeAttachmentMenu();
}
};
const onAuthLogout = () => {
currentUser.value = null;
};
const handleLogout = () => {
logoutAuth();
onAuthLogout();
router.push('/');
};
watch(locale, (newLang) => {
localStorage.setItem('hxops_lang', String(newLang));
});
const stripReasoningPrelude = (text: string) => {
if (!text) return '';
let cleaned = text
.replace(/<think[\s\S]*?<\/think>/gi, '')
.replace(/<analysis[\s\S]*?<\/analysis>/gi, '')
.trim();
const reasoningMarkers = [
'让我分析',
'根据应答生成规则',
'分析知识库返回的内容',
'我需要直接给出答案',
'思考过程',
'推理过程',
];
const hasReasoningMarker = reasoningMarkers.some((marker) => cleaned.includes(marker));
if (!hasReasoningMarker) return cleaned;
const headingMatch = cleaned.match(/(^|\n)\s{0,3}#{1,6}\s+/);
if (headingMatch && typeof headingMatch.index === 'number') {
const start = headingMatch.index + (headingMatch[1] ? headingMatch[1].length : 0);
cleaned = cleaned.slice(start).trim();
}
return cleaned;
};
const renderMarkdown = (text: string) => {
if (!text) return '';
const displayText = stripReasoningPrelude(text);
try {
// 把 # 标题、代码块、[链接](url) 等 Markdown 解析成 HTML
return marked.parse(displayText);
} catch (e) {
return displayText;
}
};
const getSourceTitle = (item: any) => {
return item?.document_name || item?.title || item?.source || 'Untitled Source';
};
const getSourceMeta = (item: any) => {
const parts: string[] = [];
if (item?.dataset_name) parts.push(item.dataset_name);
if (item?.segment_id) parts.push(`segment: ${item.segment_id}`);
if (typeof item?.score === 'number') parts.push(`score: ${item.score.toFixed(3)}`);
return parts.join(' | ');
};
const getSourceContent = (item: any) => {
return item?.content || item?.segment_content || item?.text || '';
};
const getSourceBrief = (item: any) => {
const raw = getSourceContent(item);
const plain = raw
.replace(/\[[^\]]+\]\(([^)]+)\)/g, '$1')
.replace(/[#>*`]/g, ' ')
.replace(/\s+/g, ' ')
.trim();
if (!plain) return '';
return plain.length > 180 ? `${plain.slice(0, 180)}...` : plain;
};
interface SourceFileLink {
name: string;
url?: string;
datasetId?: string;
remoteDocumentId?: string;
actualExt?: string;
}
// 源文件展示配置(来自 config.ts)
// const sourceFileConfig = {
// // 是否显示整个“源文件”区域
// showSourceFiles: config.workspace?.sourceFiles?.showSourceFiles !== false,
// // 是否显示 MD 源文件(.md/.markdown)
// showMdFiles: config.workspace?.sourceFiles?.showMdFiles !== false,
// // MD 源文件是否默认展开“源文档”详情
// expandMdByDefault: config.workspace?.sourceFiles?.expandMdByDefault === true,
// };
const PREFERRED_SOURCE_EXTS = new Set([
'pdf', 'doc', 'docx', 'ppt', 'pptx', 'xls', 'xlsx', 'csv',
'jpg', 'jpeg', 'png', 'gif', 'webp', 'svg', 'bmp',
'txt', 'rtf', 'md', 'markdown',
]);
const safeDecode = (value: string) => {
try {
return decodeURIComponent(value);
} catch {
return value;
}
};
const normalizeUrl = (url: string) => {
// 统一清洗 URL:去掉包裹引号、还原转义字符、剔除末尾标点。
// 目的:让后续提取逻辑面对 Dify 返回的不同转义形态时保持稳定。
let v = url
.trim()
.replace(/^['"]|['"]$/g, '')
.replace(/\\\//g, '/')
.replace(/\\u0026/gi, '&')
.replace(/\\u003d/gi, '=')
.replace(/\\u003a/gi, ':')
.replace(/\\u002f/gi, '/')
.replace(/&amp;/g, '&');
v = v.replace(/[),.;]+$/g, '');
if (!v) return '';
if (v.startsWith('//')) return `${window.location.protocol}${v}`;
if (/^https?:\/\//i.test(v) || v.startsWith('/')) return v;
if (/^(?:\d{1,3}\.){3}\d{1,3}(?::\d+)?\//.test(v)) return `http://${v}`;
if (/^[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}(?::\d+)?\//.test(v)) return `http://${v}`;
return '';
};
const getUrlExt = (url: string) => {
const clean = (url.split('?')[0] || '').toLowerCase();
const idx = clean.lastIndexOf('.');
if (idx < 0) return '';
return clean.slice(idx + 1);
};
const isChunkLikeLink = (url: string) => {
// 保留原始 Markdown 文件链接;仅过滤明显的分片/切片类链接。
return /segment|chunk|fragments?|split/i.test(url);
};
const isPreferredSourceLink = (url: string) => {
const ext = getUrlExt(url);
return PREFERRED_SOURCE_EXTS.has(ext);
};
const isNoisySourceUrl = (_url: string) => {
// 带签名参数的下载链接在 UI 中可读性差(如 download?version_id=...&token=...)。
// 暂时注释掉这段校验逻辑,保证有元数据能被展示出来
// return /(?:^|\/)download\?/i.test(url) || /[?&](token|version_id|kind)=/i.test(url);
return false;
};
const isNoisySourceName = (_name: string) => {
// 兜底过滤:名称如果本质是查询串而不是文件名,则不展示。
// 注释掉,允许带参数的链接在没有文件名时也可以显示(作为退路)
// return n.startsWith('download?') || n.includes('token=') || n.includes('version_id=');
return false;
};
const looksLikeFileName = (name: string) => {
const n = (name || '').trim();
if (!n) return false;
// 保留中英文文件名,如 员工手册.doc
return /\.[A-Za-z0-9]{2,8}$/.test(n);
};
const findFirstByKeys = (payload: any, keyCandidates: string[]): string => {
if (payload == null) return '';
if (Array.isArray(payload)) {
for (const item of payload) {
const found = findFirstByKeys(item, keyCandidates);
if (found) return found;
}
return '';
}
if (typeof payload !== 'object') return '';
for (const key of keyCandidates) {
const value = payload?.[key];
if (value != null && String(value).trim()) {
return String(value).trim();
}
}
for (const value of Object.values(payload)) {
const found = findFirstByKeys(value, keyCandidates);
if (found) return found;
}
return '';
};
const findDirectByKeys = (payloads: any[], keyCandidates: string[]): string => {
for (const payload of payloads) {
if (!payload || typeof payload !== 'object' || Array.isArray(payload)) continue;
for (const key of keyCandidates) {
const value = payload?.[key];
if (value != null && String(value).trim()) {
return String(value).trim();
}
}
}
return '';
};
const getResourceIds = (item: any) => {
const metadata = item?.metadata && typeof item.metadata === 'object' && !Array.isArray(item.metadata)
? item.metadata
: null;
const datasetId = findFirstByKeys(item, ['dataset_id', 'dify_dataset_id', 'knowledge_base_id', 'kb_id']);
const remoteDocumentId = findDirectByKeys([item, metadata], [
'remote_document_id',
'dify_document_id',
'source_document_id',
'doc_id',
]) || findFirstByKeys(item, [
'remote_document_id',
'dify_document_id',
'source_document_id',
'doc_id',
]) || findDirectByKeys([item, metadata], ['document_id']);
return { datasetId, remoteDocumentId };
};
const canPreviewSourceLink = (link: Partial<SourceFileLink> | null | undefined) => {
if (!link) return false;
return Boolean(link.url || (link.datasetId && link.remoteDocumentId));
};
const buildSourceLinkKey = (name: string, datasetId?: string, remoteDocumentId?: string, url?: string) => {
const normalizedName = String(name || '').trim();
const normalizedDatasetId = String(datasetId || '').trim();
const normalizedRemoteDocumentId = String(remoteDocumentId || '').trim();
const normalizedUrl = String(url || '').split('?')[0];
if (normalizedDatasetId && normalizedRemoteDocumentId) {
return `${normalizedName}|${normalizedDatasetId}|${normalizedRemoteDocumentId}`;
}
if (looksLikeFileName(normalizedName)) {
return normalizedUrl ? `${normalizedName}|${normalizedUrl}` : normalizedName;
}
return `${normalizedName}|${normalizedUrl}`;
};
const isMarkdownFileName = (name: string) => /\.(md|markdown)$/i.test((name || '').trim());
const isMarkdownByUrl = (url: string) => /\.(md|markdown)(?:$|\?)/i.test((url || '').toLowerCase());
const extractUrlsFromText = (text: string) => {
if (!text) return [];
const urls: string[] = [];
// 先把常见 JSON/Markdown 转义做一次反转义,避免 regex 漏抓。
const normalizedText = text
.replace(/\\\//g, '/')
.replace(/\\u0026/gi, '&')
.replace(/\\u003d/gi, '=')
.replace(/\\u003a/gi, ':')
.replace(/\\u002f/gi, '/');
// 1) Markdown 链接: [name](url)
const mdRegex = /\[[^\]]+\]\(([^)]+)\)/g;
let m;
while ((m = mdRegex.exec(normalizedText)) !== null) {
const url = normalizeUrl(m[1] || '');
if (url) urls.push(url);
}
// 2) HTML 链接: href/src 属性
const htmlAttrRegex = /\b(?:href|src)\s*=\s*["']([^"']+)["']/gi;
while ((m = htmlAttrRegex.exec(normalizedText)) !== null) {
const url = normalizeUrl(m[1] || '');
if (url) urls.push(url);
}
// 3) 尖括号 URL: <http://...>
const angleRegex = /<\s*((?:https?:\/\/|\/\/)[^>\s]+)\s*>/gi;
while ((m = angleRegex.exec(normalizedText)) !== null) {
const url = normalizeUrl(m[1] || '');
if (url) urls.push(url);
}
// 4) 原始 URL:支持带/不带协议、内网 IP、相对路径文件等
const rawRegex =
/((?:https?:\/\/|\/\/)[^\s"'<>]+|(?:\d{1,3}\.){3}\d{1,3}(?::\d+)?\/[^\s"'<>]+|[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}(?::\d+)?\/[^\s"'<>]+|\/[^\s"'<>]+\.(?:md|markdown|txt|pdf|doc|docx|ppt|pptx|xls|xlsx|jpg|jpeg|png|gif|webp|svg|bmp))/gi;
while ((m = rawRegex.exec(normalizedText)) !== null) {
const url = normalizeUrl(m[1] || '');
if (url) urls.push(url);
}
return urls;
};
const getSourceLinks = (resources: any[] = []): SourceFileLink[] => {
const map = new Map<string, SourceFileLink>();
const mergeSourceLink = (key: string, nextLink: SourceFileLink) => {
const existing = map.get(key);
if (!existing) {
map.set(key, nextLink);
return;
}
map.set(key, {
...existing,
...(nextLink.url ? { url: nextLink.url } : {}),
...(nextLink.datasetId ? { datasetId: nextLink.datasetId } : {}),
...(nextLink.remoteDocumentId ? { remoteDocumentId: nextLink.remoteDocumentId } : {}),
});
};
for (const item of resources) {
const { datasetId, remoteDocumentId } = getResourceIds(item);
const directCandidates = [
item?.source_download_url,
item?.url,
item?.file_url,
item?.document_url,
item?.source_url,
item?.download_url,
item?.metadata?.source_download_url,
item?.metadata?.url,
item?.metadata?.file_url,
item?.metadata?.document_url,
].filter(Boolean) as string[];
const content = getSourceContent(item);
// 直接强制从对象的顶层属性里获取文件名和链接
const forceName = item?.source_filename || item?.document_name || item?.title;
const forceUrl = normalizeUrl(item?.source_download_url || item?.url || '');
if (forceName && (forceUrl || (datasetId && remoteDocumentId))) {
const key = buildSourceLinkKey(forceName, datasetId, remoteDocumentId, forceUrl);
mergeSourceLink(key, {
name: forceName,
...(forceUrl ? { url: forceUrl } : {}),
...(datasetId ? { datasetId } : {}),
...(remoteDocumentId ? { remoteDocumentId } : {}),
});
}
const serialized = JSON.stringify(item || {});
const discovered = [
...directCandidates.map(normalizeUrl).filter(Boolean),
...extractUrlsFromText(content),
...extractUrlsFromText(serialized),
];
// 若 Dify 返回了 files 数组,额外补充其显式文件链接。
const files = Array.isArray(item?.files) ? item.files : [];
for (const f of files) {
const fu = normalizeUrl(f?.url || f?.download_url || f?.file_url || '');
if (fu) {
discovered.push(fu);
}
}
for (const url of discovered) {
if (isChunkLikeLink(url)) continue;
// URL 若为噪声签名链接,且没有可用文件名元数据,则跳过。
// 这里去掉 isNoisySourceUrl 判断的直接 continue,让有名的链接能过
// if (isNoisySourceUrl(url) && !item?.source_filename && !item?.document_name) continue;
const name = item?.source_filename || item?.document_name || item?.title || safeDecode(url.split('/').pop() || 'source-file');
// Skip links whose display name itself is noisy.
if (isNoisySourceName(name)) continue;
// 根据配置决定是否显示 MD 文件
if (isMarkdownFileName(name) || isMarkdownByUrl(url)) continue;
const key = buildSourceLinkKey(name, datasetId, remoteDocumentId, url);
mergeSourceLink(key, {
name,
url,
...(datasetId ? { datasetId } : {}),
...(remoteDocumentId ? { remoteDocumentId } : {}),
});
}
}
const links = Array.from(map.values()).filter((link) => canPreviewSourceLink(link));
// 暂时注释掉 isPreferredSourceLink 的过滤,让所有解析出来的气泡都能显示
// const preferred = links.filter((l) => isPreferredSourceLink(l.url));
// return preferred.length > 0 ? preferred : links;
return links;
};
const getMessageLinks = (msg: any): SourceFileLink[] => {
// if (!sourceFileConfig.showSourceFiles) {
// console.info('showSourceFiles is false');
// return [];
// }
const map = new Map<string, SourceFileLink>();
const merge = (links: SourceFileLink[]) => {
const mergeMessageLink = (key: string, nextLink: SourceFileLink) => {
const existing = map.get(key);
if (!existing) {
map.set(key, nextLink);
return;
}
map.set(key, {
...existing,
...(nextLink.url ? { url: nextLink.url } : {}),
...(nextLink.datasetId ? { datasetId: nextLink.datasetId } : {}),
...(nextLink.remoteDocumentId ? { remoteDocumentId: nextLink.remoteDocumentId } : {}),
});
};
for (const link of links) {
if (!canPreviewSourceLink(link)) continue;
const linkUrl = link.url || '';
if (linkUrl && isChunkLikeLink(linkUrl)) continue;
// 文件名有效时,保留文件按钮(即便 URL 是临时签名地址)。
if (isNoisySourceName(link.name)) continue;
if (isMarkdownFileName(link.name) || isMarkdownByUrl(linkUrl)) continue;
if (isMarkdownFileName(link.name)) {
const key = buildSourceLinkKey(link.name, link.datasetId, link.remoteDocumentId, linkUrl);
mergeMessageLink(key, link);
continue;
}
if (linkUrl && isNoisySourceUrl(linkUrl) && !looksLikeFileName(link.name)) continue;
const key = buildSourceLinkKey(link.name, link.datasetId, link.remoteDocumentId, linkUrl);
mergeMessageLink(key, link);
}
};
if (msg?.retriever_resources) {
// 仅使用结构化 retriever_resources 生成源文件按钮,
// 避免把回答正文里的普通 URL 误显示为“源文件”。
merge(getSourceLinks(msg.retriever_resources));
}
const links = Array.from(map.values());
const preferred = links.filter((l) => l.url && isPreferredSourceLink(l.url));
return preferred.length > 0 ? preferred : links;
};
const getDisplayRetrieverResources = (msg: any): any[] => {
// if (!sourceFileConfig.showSourceFiles) return [];
const list = Array.isArray(msg?.retriever_resources) ? msg.retriever_resources : [];
// if (sourceFileConfig.showMdFiles) return list;
return list.filter((doc: any) => {
const name = doc?.source_filename || doc?.document_name || doc?.title || '';
const url = doc?.source_download_url || doc?.url || doc?.file_url || doc?.document_url || '';
return !(isMarkdownFileName(String(name)) || isMarkdownByUrl(String(url)));
});
};
const shouldExpandSourceDetails = (msg: any): boolean => {
// if (!sourceFileConfig.showSourceFiles) {
// console.info('showSourceFiles is false');
// return false;
// }
// if (!sourceFileConfig.showMdFiles || !sourceFileConfig.expandMdByDefault) return false;
return getMessageLinks(msg).some((link) => isMarkdownFileName(link.name) || isMarkdownByUrl(link.url || ''));
};
const shouldRenderMessage = (msg: any): boolean => {
if (msg?.role === 'user') return true;
if (msg?.type === 'leave-form' || msg?.type === 'leave-confirmation' || msg?.type === 'leave-result') return true;
const content = (msg?.content || '').trim();
if (content) return true;
if (getMessageLinks(msg).length > 0) return true;
if (getDisplayRetrieverResources(msg).length > 0) return true;
return Array.isArray(msg?.attribution_parts) && msg.attribution_parts.length > 0;
};
// “正在生成回答...” 仅在当前轮次还没有任何可显示的 assistant 内容时显示。
// 一旦最后一条用户消息之后出现了可渲染的 assistant 内容(思考或答案文本等),
// 该 loading 气泡就会隐藏,避免与正文同时出现。
const shouldShowThinkingBubble = computed(() => {
if (!isThinking.value) return false;
let lastUserIndex = -1;
for (let i = messages.value.length - 1; i >= 0; i--) {
if (messages.value[i]?.role === 'user') {
lastUserIndex = i;
break;
}
}
if (lastUserIndex < 0) return true;
return !messages.value
.slice(lastUserIndex + 1)
.some((msg) => msg?.role === 'assistant' && shouldRenderMessage(msg));
});
const filePreviewVisible = ref(false);
const previewFile = ref<{ name: string; url: string; actualExt?: string } | null>(null);
const resolveSourceLink = async (file: SourceFileLink): Promise<{ name: string; url: string; actualExt?: string }> => {
if (file.datasetId && file.remoteDocumentId) {
const data = await resolveChatSourceFile({
agent_id: currentAgentId.value,
dataset_id: file.datasetId,
remote_document_id: file.remoteDocumentId,
});
const resolvedUrl = normalizeUrl(data?.source_download_url || '');
if (resolvedUrl) {
return {
...file,
url: resolvedUrl,
name: data?.source_filename || file.name,
actualExt: String(data?.source_ext || '').trim().toLowerCase() || undefined,
};
}
}
if (!file.url) {
throw new Error('当前源文件暂未返回可预览链接');
}
return {
name: file.name,
url: file.url,
actualExt: file.actualExt,
};
};
const openPreview = async (file: SourceFileLink) => {
try {
const resolvedFile = await resolveSourceLink(file);
previewFile.value = resolvedFile;
filePreviewVisible.value = true;
} catch (error: any) {
msg.warning(error?.message || t('chat.previewUnavailable'));
}
};
const parsePlmPreviewLink = (href: string): SourceFileLink | null => {
const rawHref = (href || '').trim();
if (!rawHref.startsWith('#plm-preview?')) return null;
const params = new URLSearchParams(rawHref.slice('#plm-preview?'.length));
const name = (params.get('name') || '').trim();
const url = (params.get('url') || '').trim();
if (!name || !url) return null;
return { name, url };
};
const route = useRoute();
const router = useRouter();
const currentAgentId = computed(() => {
const id = Number(route.params.agentId);
return Number.isFinite(id) && id > 0 ? id : 0;
});
// Sidebar state for mobile
const isSidebarOpen = ref(false);
const isSidebarCollapsed = ref(false);
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);
const showDeleteConfirmDialog = ref(false);
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(currentAgentId.value, 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
) => {
deleteConfirmMessage.value = message;
pendingDeleteAction = onConfirm;
showDeleteConfirmDialog.value = true;
};
const closeDeleteConfirmDialog = () => {
showDeleteConfirmDialog.value = false;
deleteConfirmMessage.value = '';
pendingDeleteAction = null;
};
const handleDeleteConfirm = async () => {
if (!pendingDeleteAction) return;
await pendingDeleteAction();
closeDeleteConfirmDialog();
};
const OA_BASE_URL = 'http://192.168.100.221:8888';
const OA_VERIFY_LOGIN_URL = `${OA_BASE_URL}/login/VerifyLogin.jsp`;
const OA_LEAVE_APPLY_PATH = '/workflow/request/AddRequest.jsp?workflowid=652&isagent=0&beagenter=0&f_weaver_belongto_userid=';
const OA_REQUEST_VIEW_PATH = '/workflow/request/ViewRequest.jsp?requestid=';
const OA_AUTO_LOGIN_TARGET = 'hxops-oa-leave-request';
// OA 登录对话框状态
const OA_PASSWORD_STORAGE_KEY = 'hxops_oa_login_password';
const showOALoginDialog = ref(false);
const oaLoginEmployeeId = ref('');
const oaLoginPassword = ref(localStorage.getItem(OA_PASSWORD_STORAGE_KEY) || '');
const oaLoginGopage = ref('');
const oaLoginTarget = ref(OA_AUTO_LOGIN_TARGET);
const openOAAutoLoginPage = (gopage: string, username: string, password: string, target = OA_AUTO_LOGIN_TARGET) => {
// 直接在弹出窗口内写入自动提交表单,避免跨窗口时序问题
const popup = window.open('about:blank', target);
if (!popup) {
msg.warning(t('chat.oaPopupBlocked'));
return;
}
const formHtml = `
<!DOCTYPE html>
<html>
<head><meta charset="utf-8"><title>${t('chat.oaLoggingTitle')}</title></head>
<body>
<p style="text-align:center;margin-top:100px;font-family:sans-serif;color:#666;">${t('chat.oaLoggingBody')}</p>
<form id="oaLoginForm" action="${OA_VERIFY_LOGIN_URL}" method="POST">
<input type="hidden" name="loginid" value="${username}" />
<input type="hidden" name="userpassword" value="${password.replace(/"/g, '&quot;')}" />
<input type="hidden" name="gopage" value="${gopage}" />
<input type="hidden" name="logintype" value="1" />
</form>
<script>document.getElementById('oaLoginForm').submit();<\/script>
</body>
</html>
`;
popup.document.open();
popup.document.write(formHtml);
popup.document.close();
};
const openOALeaveRequestDirectly = () => {
const employeeId = currentUserEmployeeId.value;
if (!employeeId || employeeId === '-') {
msg.warning(t('chat.noEmployeeId'));
return;
}
oaLoginEmployeeId.value = employeeId;
oaLoginPassword.value = localStorage.getItem(OA_PASSWORD_STORAGE_KEY) || '';
oaLoginGopage.value = OA_LEAVE_APPLY_PATH;
oaLoginTarget.value = OA_AUTO_LOGIN_TARGET;
showOALoginDialog.value = true;
};
const confirmOALogin = () => {
if (!oaLoginPassword.value.trim()) {
msg.warning(t('chat.oaPasswordRequired'));
return;
}
// 记住密码到 localStorage
localStorage.setItem(OA_PASSWORD_STORAGE_KEY, oaLoginPassword.value.trim());
showOALoginDialog.value = false;
openOAAutoLoginPage(oaLoginGopage.value, oaLoginEmployeeId.value, oaLoginPassword.value.trim(), oaLoginTarget.value);
};
const cancelOALogin = () => {
showOALoginDialog.value = false;
};
const openOARequestDirectly = (requestId: string) => {
const normalizedRequestId = String(requestId || '').trim();
if (!normalizedRequestId || normalizedRequestId === '-') {
msg.warning(t('chat.oaRequestMissing'));
return;
}
const employeeId = currentUserEmployeeId.value;
if (!employeeId || employeeId === '-') {
msg.warning(t('chat.noEmployeeId'));
return;
}
oaLoginEmployeeId.value = employeeId;
oaLoginPassword.value = localStorage.getItem(OA_PASSWORD_STORAGE_KEY) || '';
oaLoginGopage.value = `${OA_REQUEST_VIEW_PATH}${encodeURIComponent(normalizedRequestId)}`;
oaLoginTarget.value = `hxops-oa-request-${normalizedRequestId}`;
showOALoginDialog.value = true;
};
const activeFeedbackMessageIndex = ref<number | null>(null);
const browserPanelOpen = ref(false);
const browserDraftUrl = ref('');
const browserCurrentUrl = ref('');
const browserFrameKey = ref(0);
const browserPanelWidth = ref(420);
const isBrowserResizing = ref(false);
const viewportWidth = ref(typeof window === 'undefined' ? 1440 : window.innerWidth);
const MIN_BROWSER_PANEL_WIDTH = 320;
const MAX_BROWSER_PANEL_WIDTH = 960;
const LEAVE_TYPES = [
{ label: '事假(小时)', value: '005' },
{ label: '病假(小时)', value: '006' },
{ label: '丧假(天)', value: '007' },
{ label: '年假(天)', value: '010' },
{ label: '因公出差(小时)', value: '021' },
{ label: '调休假(小时)', value: '025' },
{ label: '产假(天)', value: '401' },
{ label: '陪产假(天)', value: '402' },
{ label: '婚假(天)', value: '403' },
{ label: '住院病假(小时)', value: '405' },
{ label: '工伤假(天)', value: '406' },
{ label: '返乡假(小时)', value: 'ZZ01' },
{ label: '事假(经理专用小时)', value: 'ZZ04' },
{ label: '病假(经理专用小时)', value: 'ZZ05' },
{ label: '丧假(经理专用天)', value: 'ZZ07' },
{ label: '产假(经理专用天)', value: 'ZZ08' },
{ label: '陪产假(经理专用天)', value: 'ZZ09' },
{ label: '婚假(经理专用天)', value: 'ZZ10' },
{ label: '其他假(小时)', value: '035' },
{ label: '育儿假(小时)', value: '408' }
];
const getLeaveTypeLabel = (val: string) => {
const t = LEAVE_TYPES.find(x => x.value === val);
return t ? t.label : val;
};
interface LeaveRequestFormData {
applicantName: string;
employeeId: string;
applicantUid: string;
applicantJobTitle?: string;
applicantJobTitleName?: string;
applicantDepartmentId?: string;
applicantSubCompanyId1?: string;
applicantDepartmentName?: string;
applicantSubCompanyName?: string;
applyTime: string;
fillerName: string;
fillerJobTitle?: string;
fillerJobTitleName?: string;
fillerDepartmentId?: string;
fillerSubCompanyId1?: string;
fillerDepartmentName?: string;
fillerSubCompanyName?: string;
agentUid: string;
agentEmployeeId: string;
agentName: string;
agentJobTitle?: string;
agentJobTitleName?: string;
agentDepartmentId?: string;
agentSubCompanyId1?: string;
agentDepartmentName?: string;
agentSubCompanyName?: string;
leaveType: string;
startTime: string;
endTime: string;
durationHours: number;
isOutOfOffice: 0 | 1 | null;
isWorkInjury: 0 | 1 | null;
}
interface LeaveFormPayload {
formId: string;
form: LeaveRequestFormData;
submitting: boolean;
confirmationGenerated: boolean;
}
interface LeaveConfirmationPayload {
formId: string;
form: LeaveRequestFormData;
submitting: boolean;
confirmed?: boolean;
}
interface LeaveResultPayload {
formId: string;
success: boolean;
referenceNo: string;
submittedAt: string;
requestName?: string;
errorMessage?: string;
}
interface LeaveAgentOption {
uid: string;
employeeId: string;
name: string;
jobtitle?: string;
jobtitleName?: string;
departmentid?: string;
subcompanyid1?: string;
departmentName?: string;
subcompanyName?: string;
}
let leaveFlowCounter = 0;
const leaveAgentOptions = ref<LeaveAgentOption[]>([]);
const leaveAgentLoading = ref(false);
const leaveAgentKeyword = ref('');
const leaveAgentPage = ref(1);
const leaveAgentHasMore = ref(true);
const fetchLeaveAgents = async (isLoadMore = false) => {
if (leaveAgentLoading.value) return;
if (!isLoadMore) {
leaveAgentPage.value = 1;
leaveAgentOptions.value = [];
}
leaveAgentLoading.value = true;
try {
const data = await listOaEmployees(currentAgentId.value, {
keyword: leaveAgentKeyword.value,
page: leaveAgentPage.value,
page_size: 20,
});
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 {
leaveAgentLoading.value = false;
}
};
const handleAgentSearch = () => {
fetchLeaveAgents(false);
};
const loadMoreAgents = () => {
if (!leaveAgentHasMore.value) return;
leaveAgentPage.value += 1;
fetchLeaveAgents(true);
};
const loadAllAgents = async () => {
if (!leaveAgentHasMore.value || leaveAgentLoading.value) return;
leaveAgentLoading.value = true;
try {
const data = await listOaEmployees(currentAgentId.value, {
keyword: leaveAgentKeyword.value,
page: 1,
page_size: 100000,
});
leaveAgentOptions.value = data.items;
leaveAgentHasMore.value = false;
} catch (e) {
console.error('Failed to load all OA employees', e);
} finally {
leaveAgentLoading.value = false;
}
};
const showLeaveAgentDialog = ref(false);
const leaveUserSelectRole = ref<'agent' | 'applicant'>('agent');
const activeLeaveAgentFormId = ref<string | null>(null);
const formatDateTime = (date: Date) => {
const year = date.getFullYear();
const month = String(date.getMonth() + 1).padStart(2, '0');
const day = String(date.getDate()).padStart(2, '0');
const hours = String(date.getHours()).padStart(2, '0');
const minutes = String(date.getMinutes()).padStart(2, '0');
return `${year}-${month}-${day}T${hours}:${minutes}`;
};
const parseDateTime = (value: string) => {
const normalized = (value || '').trim().replace('T', ' ');
const match = normalized.match(/^(\d{4})-(\d{2})-(\d{2})\s+(\d{2}):(\d{2})$/);
if (!match) return null;
const [, year, month, day, hour, minute] = match;
const date = new Date(Number(year), Number(month) - 1, Number(day), Number(hour), Number(minute));
return Number.isNaN(date.getTime()) ? null : date;
};
const LEAVE_TYPE_BY_DAY = new Set(['010', '007', '401', '402', '403', '406', 'ZZ07', 'ZZ08', 'ZZ09', 'ZZ10']);
const isLeaveTypeByDay = (leaveType: string) => LEAVE_TYPE_BY_DAY.has(leaveType);
const calculateDurationHours = (startTime: string, endTime: string) => {
const start = parseDateTime(startTime);
const end = parseDateTime(endTime);
if (!start || !end || end.getTime() <= start.getTime()) return 0;
return Number((((end.getTime() - start.getTime()) / 1000 / 60 / 60)).toFixed(2));
};
const formatDurationLabel = (hours: number, leaveType?: string) => {
if (!hours) return `0 ${isLeaveTypeByDay(leaveType || '') ? t('chat.dayUnit') : t('chat.hourUnit')}`;
if (isLeaveTypeByDay(leaveType || '')) {
const days = Math.round(hours / 8);
return `${days} ${t('chat.dayUnit')}`;
}
return `${hours} ${t('chat.hourUnit')}`;
};
const LEAVE_TYPE_MAP: Record<string, string> = {
'事假': '005',
'病假': '006',
'丧假': '007',
'年假': '010',
'因公出差': '021',
'出差': '021',
'调休': '025',
'产假': '401',
'陪产假': '402',
'婚假': '403',
'住院': '405',
'工伤': '406',
'育儿假': '408',
'返乡': 'ZZ01',
};
const extractLeaveTypeFromIntent = (content: string) => {
if (!content) return '';
for (const [key, val] of Object.entries(LEAVE_TYPE_MAP)) {
if (content.includes(key)) return val;
}
return '';
};
interface ExtractedLeaveInfo {
leaveType: string;
startTime: string;
endTime: string;
durationHours: number;
}
const extractLeaveInfoFromIntent = (content: string): ExtractedLeaveInfo | null => {
const normalized = content.replace(/\s+/g, ' ').trim();
let leaveType = extractLeaveTypeFromIntent(normalized);
let startTime = '';
let endTime = '';
let durationHours = 0;
const today = new Date();
const thisYear = today.getFullYear();
const parseDateStr = (m: RegExpMatchArray | null, groupOffset: number): Date | null => {
if (!m) return null;
const rawMo = m[groupOffset];
const rawDa = m[groupOffset + 1];
if (!rawMo || !rawDa) return null;
const mo = parseInt(rawMo, 10);
const da = parseInt(rawDa, 10);
if (Number.isNaN(mo) || Number.isNaN(da) || mo < 1 || mo > 12 || da < 1 || da > 31) return null;
return new Date(thisYear, mo - 1, da, 9, 0);
};
const fmtDt = (d: Date, hour: number, minute: number) => {
const y = d.getFullYear();
const mo = String(d.getMonth() + 1).padStart(2, '0');
const da = String(d.getDate()).padStart(2, '0');
const h = String(hour).padStart(2, '0');
const mi = String(minute).padStart(2, '0');
return `${y}-${mo}-${da}T${h}:${mi}`;
};
let startDay: Date | null = null;
let endDay: Date | null = null;
let startHM = { h: 9, m: 0 };
let endHM = { h: 18, m: 0 };
const rangeM = normalized.match(/从?(\d{1,2})[月./-](\d{1,2})[日号]?[到至—\-–](\d{1,2})[月./-]?(\d{1,2})[日号]?/);
if (rangeM) {
const s = parseDateStr(rangeM, 1);
if (rangeM[3] && rangeM[3].length <= 2 && rangeM[4] && rangeM[4].length <= 2) {
const eMo = parseInt(rangeM[3]!, 10);
const eDa = parseInt(rangeM[4]!, 10);
if (!Number.isNaN(eMo) && eMo >= 1 && eMo <= 12 && !Number.isNaN(eDa) && eDa >= 1 && eDa <= 31) {
endDay = new Date(thisYear, eMo - 1, eDa, 18, 0);
} else if (!Number.isNaN(eDa) && eDa >= 1 && eDa <= 31 && s) {
endDay = new Date(thisYear, s.getMonth(), eDa, 18, 0);
}
}
if (s) startDay = s;
}
if (!startDay) {
const singleM = normalized.match(/(\d{1,2})[月./-](\d{1,2})[日号]?/);
if (singleM) {
const s = parseDateStr(singleM, 1);
if (s) {
startDay = s;
const dayUnitM = normalized.match(/(\d+\.?\d*)\s*[天日]/);
if (dayUnitM?.[1]) {
const days = parseFloat(dayUnitM[1]);
if (days > 1) endDay = new Date(s.getFullYear(), s.getMonth(), s.getDate() + Math.ceil(days) - 1, 18, 0);
else endDay = new Date(s.getFullYear(), s.getMonth(), s.getDate(), 18, 0);
} else {
endDay = new Date(s.getFullYear(), s.getMonth(), s.getDate(), 18, 0);
}
}
}
}
const hourM = normalized.match(/(\d+\.?\d*)\s*小时/);
if (hourM?.[1]) {
durationHours = parseFloat(hourM[1]);
if (startDay && !endDay) {
endDay = new Date(startDay.getTime() + durationHours * 3600000);
}
}
const dayM = normalized.match(/(\d+\.?\d*)\s*[天日]/);
if (dayM?.[1] && !hourM) {
const days = parseFloat(dayM[1]);
durationHours = days * 8;
if (startDay && !endDay) {
endDay = new Date(startDay.getFullYear(), startDay.getMonth(), startDay.getDate() + Math.ceil(days) - 1, 18, 0);
}
}
if (startDay) {
if (durationHours > 0 && durationHours <= 8 && !endDay) {
endDay = new Date(startDay.getTime() + durationHours * 3600000);
}
startTime = fmtDt(startDay, startHM.h, startHM.m);
}
if (endDay) {
if (hourM && durationHours <= 8) {
endHM = { h: 9 + Math.floor(durationHours), m: (durationHours % 1) * 60 };
} else if (!hourM && durationHours > 0 && durationHours <= 8) {
endHM = { h: 9 + Math.floor(durationHours), m: 0 };
}
endTime = fmtDt(endDay, endHM.h, endHM.m);
}
if (startTime && endTime) {
if (isLeaveTypeByDay(leaveType)) {
const s = parseDateTime(startTime);
const e = parseDateTime(endTime);
if (s && e && e.getTime() > s.getTime()) {
const sd = new Date(s.getFullYear(), s.getMonth(), s.getDate());
const ed = new Date(e.getFullYear(), e.getMonth(), e.getDate());
const days = Math.max(1, Math.round((ed.getTime() - sd.getTime()) / (24 * 3600 * 1000)) + 1);
durationHours = days * 8;
}
} else {
durationHours = durationHours || calculateDurationHours(startTime, endTime);
}
}
if (!leaveType && !startTime) return null;
return {
leaveType,
startTime,
endTime,
durationHours,
};
};
const createLeaveFormData = (content?: string, extractedInfo?: ExtractedLeaveInfo | null): LeaveRequestFormData => {
const now = new Date();
const initialLeaveType = extractedInfo?.leaveType || extractLeaveTypeFromIntent(content || '');
const isByDay = isLeaveTypeByDay(initialLeaveType);
const sameDayEnd = new Date(now.getFullYear(), now.getMonth(), now.getDate(), 18, 0);
const oneHourLater = new Date(now.getTime() + 60 * 60 * 1000);
const defaultStart = formatDateTime(now);
const defaultEnd = isByDay ? formatDateTime(sameDayEnd) : formatDateTime(oneHourLater);
const startTime = extractedInfo?.startTime || defaultStart;
const endTime = extractedInfo?.endTime || defaultEnd;
let durationHours: number;
if (isByDay) {
const start = parseDateTime(startTime);
const end = parseDateTime(endTime);
if (start && end && end.getTime() > start.getTime()) {
const startDate = new Date(start.getFullYear(), start.getMonth(), start.getDate());
const endDate = new Date(end.getFullYear(), end.getMonth(), end.getDate());
const days = Math.max(1, Math.round((endDate.getTime() - startDate.getTime()) / (24 * 3600 * 1000)) + 1);
durationHours = days * 8;
} else {
durationHours = 8;
}
} else if (extractedInfo?.durationHours) {
durationHours = extractedInfo.durationHours;
} else {
durationHours = calculateDurationHours(startTime, endTime);
}
return {
applicantName: currentUserDisplayName.value,
employeeId: currentUserEmployeeId.value,
applicantUid: '',
applyTime: formatDateTime(now),
fillerName: currentUserDisplayName.value,
agentUid: '',
agentEmployeeId: '',
agentName: '',
leaveType: initialLeaveType,
startTime,
endTime,
durationHours,
isOutOfOffice: 1,
isWorkInjury: 1,
};
};
const newLocalMessageId = (prefix: string) => {
leaveFlowCounter += 1;
return `${prefix}-${Date.now()}-${leaveFlowCounter}`;
};
const syncLeaveDuration = (form: LeaveRequestFormData) => {
if (isLeaveTypeByDay(form.leaveType)) {
const start = parseDateTime(form.startTime);
const end = parseDateTime(form.endTime);
if (!start || !end || end.getTime() <= start.getTime()) {
form.durationHours = 0;
return;
}
const startDate = new Date(start.getFullYear(), start.getMonth(), start.getDate());
const endDate = new Date(end.getFullYear(), end.getMonth(), end.getDate());
const days = Math.max(1, Math.round((endDate.getTime() - startDate.getTime()) / (24 * 3600 * 1000)) + 1);
form.durationHours = days * 8;
} else {
form.durationHours = calculateDurationHours(form.startTime, form.endTime);
}
};
const getLeaveIntentNormalized = (content: string) => (content || '').replace(/\s+/g, '');
const isStrongLeaveIntent = (content: string) => {
const normalized = getLeaveIntentNormalized(content);
const weakConsultationIntent = /(请假流程|请假怎么走|请假步骤|请假如何申请|请假如何走流程|请假怎么办|请假需要什么|请假规定|请假管理办法|请假制度)/;
const materialConsultationIntent = /(提交哪些|提交什么|需要哪些|需要什么|要提交哪些|要提交什么|哪些资料|哪些材料|什么资料|什么材料|申请材料|所需资料|所需材料)/;
if (weakConsultationIntent.test(normalized)) return false;
if (materialConsultationIntent.test(normalized)) return false;
if (/^(请假|休假|年假|事假|病假|调休|休年假|请事假|请病假|请年假)$/.test(normalized)) return true;
return /(我要请|申请请|发起请|请假申请|我要休|申请休|想请|帮我请|代我请|提交请|帮我申请|我要申请|想申请|申请.*假|请.*假|休.*假)/.test(normalized);
};
const saveLocalMessageToBackend = async (msg: any, userQuery: string = '') => {
try {
const data = await saveLocalChatMessage({
conversation_id: conversationId.value,
type: msg.type,
content: msg.content,
payload: msg.payload,
query: userQuery,
agent_id: currentAgentId.value,
});
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);
}
};
const NEED_BALANCE_CHECK_TYPES = new Set(['010', '408']);
const formatLeaveBalanceNumber = (value: any) => {
if (value === null || value === undefined) return t('chat.noData');
const num = Number(value);
if (Number.isNaN(num)) return String(value);
return Number.isInteger(num) ? String(num) : num.toFixed(2);
};
const checkLeaveBalance = async (leaveTypeCode: string): Promise<{
has_balance: boolean;
leave_type_label: string;
year: number;
total_hours: number | null;
used_hours: number | null;
remaining_hours: number | null;
} | null> => {
try {
return await getLeaveBalance(leaveTypeCode);
} catch (e) {
console.error('Failed to check leave balance', e);
return null;
}
};
const startLocalLeaveFlow = async (content: string) => {
const extractedInfo = extractLeaveInfoFromIntent(content);
const initialLeaveType = extractedInfo?.leaveType || extractLeaveTypeFromIntent(content);
if (initialLeaveType && NEED_BALANCE_CHECK_TYPES.has(initialLeaveType)) {
messages.value.push({ role: 'user', content, type: 'text' });
const thinkingMsg = {
role: 'assistant' as const,
type: 'text' as const,
content: t('chat.queryLeaveBalance'),
};
messages.value.push(thinkingMsg);
const balance = await checkLeaveBalance(initialLeaveType);
const thinkingIndex = messages.value.indexOf(thinkingMsg);
if (thinkingIndex >= 0) {
messages.value.splice(thinkingIndex, 1);
}
if (balance && !balance.has_balance) {
const unit = initialLeaveType === '010' ? t('chat.dayUnit') : t('chat.hourUnit');
const detailLines = [
t('chat.leaveBalanceInsufficient', { label: balance.leave_type_label }),
'',
`| ${t('chat.leaveBalanceTableLeaveType')} | ${t('chat.leaveBalanceTableYear')} | ${t('chat.leaveBalanceTableAvailable')} | ${t('chat.leaveBalanceTableUsed')} | ${t('chat.leaveBalanceTableRemaining')} |`,
`| :---: | :---: | :---: | :---: | :---: |`,
`| ${balance.leave_type_label} | ${balance.year} | ${formatLeaveBalanceNumber(balance.total_hours)}${unit} | ${formatLeaveBalanceNumber(balance.used_hours)}${unit} | ${formatLeaveBalanceNumber(balance.remaining_hours)}${unit} |`,
'',
t('chat.leaveBalanceContactHr'),
];
const noBalanceMsg = {
role: 'assistant' as const,
type: 'text' as const,
content: detailLines.join('\n'),
};
messages.value.push(noBalanceMsg);
await saveLocalMessageToBackend(noBalanceMsg, content);
if (history.value.length === 0 || !history.value.some(h => h.conversation_id === conversationId.value)) {
await loadHistory();
}
return;
}
}
const formId = newLocalMessageId('leave-form');
const payload: LeaveFormPayload = {
formId,
form: createLeaveFormData(content, extractedInfo),
submitting: false,
confirmationGenerated: false,
};
if (!initialLeaveType || !NEED_BALANCE_CHECK_TYPES.has(initialLeaveType)) {
messages.value.push({ role: 'user', content, type: 'text' });
}
const formMsg = {
role: 'assistant' as const,
type: 'leave-form' as const,
content: t('chat.leaveFormIntro'),
payload,
local_id: formId,
local_only: true,
};
messages.value.push(formMsg);
try {
const keyword = payload.form.applicantName || payload.form.employeeId;
if (keyword) {
const data = await listOaEmployees(currentAgentId.value, { 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 || '';
payload.form.fillerDepartmentId = match.departmentid || '';
payload.form.fillerSubCompanyId1 = match.subcompanyid1 || '';
payload.form.fillerDepartmentName = match.departmentName || '';
payload.form.fillerSubCompanyName = match.subcompanyName || '';
payload.form.applicantUid = match.uid || '';
payload.form.applicantJobTitle = match.jobtitle || '';
payload.form.applicantJobTitleName = match.jobtitleName || '';
payload.form.applicantDepartmentId = match.departmentid || '';
payload.form.applicantSubCompanyId1 = match.subcompanyid1 || '';
payload.form.applicantDepartmentName = match.departmentName || '';
payload.form.applicantSubCompanyName = match.subcompanyName || '';
}
}
} catch (e) {
console.error('Failed to prefill OA user info', e);
}
await saveLocalMessageToBackend(formMsg, content);
// 发送完成后刷新历史记录,确保新会话出现
if (history.value.length === 0 || !history.value.some(h => h.conversation_id === conversationId.value)) {
await loadHistory();
}
};
const handleChatMarkdownClick = (event: MouseEvent) => {
const target = event.target as HTMLElement | null;
const anchor = target?.closest?.('a') as HTMLAnchorElement | null;
const previewFile = parsePlmPreviewLink(anchor?.getAttribute('href') || '');
if (previewFile) {
event.preventDefault();
openPreview(previewFile);
return;
}
const actionElement = target?.closest?.('[data-leave-action]') as HTMLElement | null;
if (!actionElement) return;
const action = actionElement.getAttribute('data-leave-action');
if (action !== 'start-leave-flow' || isThinking.value) return;
event.preventDefault();
startLocalLeaveFlow('我要请假');
};
const getLeaveFormPayload = (msg: any): LeaveFormPayload | null => (
msg?.type === 'leave-form' && msg?.payload ? msg.payload as LeaveFormPayload : null
);
const getLeaveConfirmationPayload = (msg: any): LeaveConfirmationPayload | null => (
msg?.type === 'leave-confirmation' && msg?.payload ? msg.payload as LeaveConfirmationPayload : null
);
const getLeaveResultPayload = (msg: any): LeaveResultPayload | null => (
msg?.type === 'leave-result' && msg?.payload ? msg.payload as LeaveResultPayload : null
);
const findMessageIndexByLocalId = (localId: string) => messages.value.findIndex((msg: any) => msg?.local_id === localId || msg?.payload?.formId === localId);
const getLeaveAgentDisplayValue = (form: LeaveRequestFormData) => {
if (!form.agentName) return '';
const parts = [form.agentName];
if (form.agentEmployeeId) parts.push(form.agentEmployeeId);
return parts.join(' / ');
};
const formatYesNoLabel = (value: 0 | 1 | null) => {
if (value === 0) return '是';
if (value === 1) return '否';
return '未选择';
};
const syncCurrentUserProfile = async () => {
if (currentUser.value?.real_name?.trim()) return;
try {
const data = await getUserProfile();
currentUser.value = { ...currentUser.value, ...data };
} catch (e) {
console.error('Failed to load current user profile', e);
}
};
const openLeaveAgentDialog = (msg: any, role: 'agent' | 'applicant' = 'agent') => {
const payload = getLeaveFormPayload(msg);
if (!payload || payload.submitting || payload.confirmationGenerated) return;
activeLeaveAgentFormId.value = payload.formId;
leaveUserSelectRole.value = role;
showLeaveAgentDialog.value = true;
leaveAgentKeyword.value = '';
fetchLeaveAgents(false);
};
const closeLeaveAgentDialog = () => {
showLeaveAgentDialog.value = false;
activeLeaveAgentFormId.value = null;
};
const selectLeaveAgent = (option: LeaveAgentOption) => {
if (!activeLeaveAgentFormId.value) return;
const sourceIndex = findMessageIndexByLocalId(activeLeaveAgentFormId.value);
if (sourceIndex < 0) {
closeLeaveAgentDialog();
return;
}
const payload = getLeaveFormPayload(messages.value[sourceIndex]);
if (!payload) {
closeLeaveAgentDialog();
return;
}
if (leaveUserSelectRole.value === 'agent') {
payload.form.agentUid = option.uid;
payload.form.agentEmployeeId = option.employeeId;
payload.form.agentName = option.name;
payload.form.agentJobTitle = option.jobtitle;
payload.form.agentJobTitleName = option.jobtitleName;
payload.form.agentDepartmentId = option.departmentid;
payload.form.agentSubCompanyId1 = option.subcompanyid1;
payload.form.agentDepartmentName = option.departmentName;
payload.form.agentSubCompanyName = option.subcompanyName;
} else {
payload.form.applicantUid = option.uid;
payload.form.employeeId = option.employeeId;
payload.form.applicantName = option.name;
payload.form.applicantJobTitle = option.jobtitle;
payload.form.applicantJobTitleName = option.jobtitleName;
payload.form.applicantDepartmentId = option.departmentid;
payload.form.applicantSubCompanyId1 = option.subcompanyid1;
payload.form.applicantDepartmentName = option.departmentName;
payload.form.applicantSubCompanyName = option.subcompanyName;
}
closeLeaveAgentDialog();
saveLocalMessageToBackend(messages.value[sourceIndex]);
};
const browserPanelStyle = computed(() => {
if (viewportWidth.value < 1024) return undefined;
return { width: `${browserPanelWidth.value}px` };
});
const scrollChatToBottom = async () => {
await nextTick();
const container = chatScrollContainer.value;
if (!container) return;
container.scrollTo({
top: container.scrollHeight,
behavior: 'auto',
});
};
const scrollToUserQuestion = async () => {
if (scrollToBottomFrame !== null) {
window.cancelAnimationFrame(scrollToBottomFrame);
scrollToBottomFrame = null;
}
await nextTick();
await nextTick();
const container = chatScrollContainer.value;
if (!container) return;
let lastUserIndex = -1;
for (let i = messages.value.length - 1; i >= 0; i--) {
if (messages.value[i]?.role === 'user') {
lastUserIndex = i;
break;
}
}
if (lastUserIndex < 0) return;
const el = container.querySelector(`[data-msg-index="${lastUserIndex}"]`) as HTMLElement | null;
if (el) {
el.scrollIntoView({ behavior: 'smooth', block: 'start' });
}
};
const scheduleScrollChatToBottom = () => {
if (scrollToBottomFrame !== null) {
window.cancelAnimationFrame(scrollToBottomFrame);
}
scrollToBottomFrame = window.requestAnimationFrame(() => {
scrollToBottomFrame = null;
void scrollChatToBottom();
});
};
const normalizeBrowserInput = (value: string) => {
const raw = (value || '').trim();
if (!raw) return '';
if (/^https?:\/\//i.test(raw)) return raw;
if (/^localhost(?::\d+)?(\/.*)?$/i.test(raw)) return `http://${raw}`;
if (/^(?:\d{1,3}\.){3}\d{1,3}(?::\d+)?(\/.*)?$/.test(raw)) return `http://${raw}`;
if (/^[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}(\/.*)?$/.test(raw)) return `https://${raw}`;
return '';
};
const toggleBrowserPanel = () => {
browserPanelOpen.value = !browserPanelOpen.value;
};
const loadBrowserPage = () => {
const normalized = normalizeBrowserInput(browserDraftUrl.value);
if (!normalized) {
msg.warning(t('chat.invalidBrowserUrl'));
return;
}
browserCurrentUrl.value = normalized;
browserDraftUrl.value = normalized;
browserFrameKey.value += 1;
browserPanelOpen.value = true;
};
const refreshBrowserPage = () => {
if (!browserCurrentUrl.value) {
loadBrowserPage();
return;
}
browserFrameKey.value += 1;
};
const openBrowserInNewTab = () => {
const normalized = browserCurrentUrl.value || normalizeBrowserInput(browserDraftUrl.value);
if (!normalized) {
msg.warning(t('chat.enterBrowserUrl'));
return;
}
window.open(normalized, '_blank', 'noopener,noreferrer');
};
const handleBrowserUrlEnter = (event: KeyboardEvent) => {
if (event.key !== 'Enter') return;
event.preventDefault();
loadBrowserPage();
};
const clampBrowserPanelWidth = (width: number) => {
const maxAllowed = Math.min(MAX_BROWSER_PANEL_WIDTH, Math.max(MIN_BROWSER_PANEL_WIDTH, Math.floor(window.innerWidth * 0.7)));
return Math.min(Math.max(width, MIN_BROWSER_PANEL_WIDTH), maxAllowed);
};
const handleBrowserResizeMove = (event: MouseEvent) => {
if (!isBrowserResizing.value) return;
browserPanelWidth.value = clampBrowserPanelWidth(window.innerWidth - event.clientX);
};
const stopBrowserResize = () => {
if (!isBrowserResizing.value) return;
isBrowserResizing.value = false;
document.body.style.cursor = '';
document.body.style.userSelect = '';
window.removeEventListener('mousemove', handleBrowserResizeMove);
window.removeEventListener('mouseup', stopBrowserResize);
};
const startBrowserResize = (event: MouseEvent) => {
if (viewportWidth.value < 1024) return;
event.preventDefault();
isBrowserResizing.value = true;
document.body.style.cursor = 'col-resize';
document.body.style.userSelect = 'none';
window.addEventListener('mousemove', handleBrowserResizeMove);
window.addEventListener('mouseup', stopBrowserResize);
};
const syncViewportWidth = () => {
viewportWidth.value = window.innerWidth;
if (viewportWidth.value >= 1024) {
browserPanelWidth.value = clampBrowserPanelWidth(browserPanelWidth.value);
}
};
const handleOpenFeedback = (index: number) => {
activeFeedbackMessageIndex.value = index;
showGeneralFeedbackDialog.value = true;
};
const currentGeneralFeedbackChatLogId = computed(() => {
if (activeFeedbackMessageIndex.value !== null) {
const msg = messages.value[activeFeedbackMessageIndex.value];
const id = Number(msg?.chat_log_id);
if (Number.isInteger(id) && id > 0) return id;
}
for (let i = messages.value.length - 1; i >= 0; i--) {
const msg: any = messages.value[i];
if (msg?.role === 'assistant') {
const id = Number(msg?.chat_log_id);
if (Number.isInteger(id) && id > 0) return id;
}
}
return null;
});
interface ChatHistoryItem {
id: number;
conversation_id: string;
title: string;
created_at: string;
}
const history = ref<ChatHistoryItem[]>([]);
type DisplayHistoryItem = ChatHistoryItem & { __runId?: number; __status?: string };
const activeHistoryKey = computed(() => {
if (conversationId.value) return conversationId.value;
if (activeRunId.value) return `pending:${activeRunId.value}`;
return '';
});
const displayHistory = computed<DisplayHistoryItem[]>(() => {
const server = history.value || [];
const serverIds = new Set(server.map((h) => h.conversation_id));
const pending: DisplayHistoryItem[] = (runs.value || [])
.filter((r) => r.agentId === currentAgentId.value)
.filter((r) => r.runId !== activeRunId.value)
.map((r) => ({
id: 0,
conversation_id: r.conversationId || `pending:${r.runId}`,
title: (r.query || '').trim(),
created_at: r.createdAt,
__runId: r.runId,
__status: r.status,
}))
.filter((item) => item.conversation_id.startsWith('pending:') || !serverIds.has(item.conversation_id));
const merged = [...pending, ...server] as DisplayHistoryItem[];
merged.sort((a, b) => String(b.created_at || '').localeCompare(String(a.created_at || '')));
return merged;
});
const handleHistorySelect = (item: DisplayHistoryItem) => {
if (item.__runId) {
activateRun(item.__runId);
} else {
const run = runs.value.find((r) => r.agentId === currentAgentId.value && r.conversationId === item.conversation_id);
if (run && run.status === 'running') {
activateRun(run.runId);
} else {
loadConversation(item.conversation_id);
}
}
isSidebarOpen.value = false;
};
// 预设问题:从路由 query.preset 中读取(如果有)
const presetQuestion = computed(() => {
const q = route.query.preset;
return typeof q === 'string' ? q : '';
});
/**
* handleSend
* 用途:将输入框内容发送给当前 Agent
*/
const handleSend = async (textOrEvent?: string | Event) => {
const content = (typeof textOrEvent === 'string' ? textOrEvent : null) || input.value;
if (!content.trim() || isThinking.value || isUploadingAttachments.value) return;
if (isStrongLeaveIntent(content)) {
startLocalLeaveFlow(content);
return;
}
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, currentAgentId.value, selectedKb.value, files);
if (!conversationId.value && history.value.length === 0) {
await loadHistory();
} else if (conversationId.value) {
const exists = history.value.some(h => h.conversation_id === conversationId.value);
if (!exists) await loadHistory();
}
};
const validateLeaveForm = (form: LeaveRequestFormData) => {
if (!form.applicantName.trim()) return t('chat.leaveApplicantRequired');
if (!form.employeeId.trim()) return t('chat.employeeIdRequired');
if (!form.leaveType.trim()) return t('chat.leaveTypeRequired');
if (!form.agentUid.trim()) return t('chat.leaveAgentRequired');
if (!parseDateTime(form.startTime)) return t('chat.startTimeRequired');
if (!parseDateTime(form.endTime)) return t('chat.endTimeRequired');
syncLeaveDuration(form);
if (form.durationHours <= 0) return t('chat.durationInvalid');
return '';
};
const submitLeaveForm = async (chatMsg: any) => {
const payload = getLeaveFormPayload(chatMsg);
if (!payload) return;
syncLeaveDuration(payload.form);
const error = validateLeaveForm(payload.form);
if (error) {
msg.warning(error);
return;
}
if (NEED_BALANCE_CHECK_TYPES.has(payload.form.leaveType)) {
const balance = await checkLeaveBalance(payload.form.leaveType);
if (balance && balance.remaining_hours !== null && balance.remaining_hours !== undefined) {
const requestedHours = payload.form.durationHours;
if (requestedHours > balance.remaining_hours) {
const isByDay = isLeaveTypeByDay(payload.form.leaveType);
const unit = isByDay ? t('chat.dayUnit') : t('chat.hourUnit');
const requestedDisplay = isByDay ? Math.round(requestedHours / 8) : requestedHours;
const remainingDisplay = isByDay ? Math.round(balance.remaining_hours / 8) : balance.remaining_hours;
const label = getLeaveTypeLabel(payload.form.leaveType);
msg.warning(t('chat.durationExceedsBalance', {
label,
requested: `${requestedDisplay}${unit}`,
remaining: `${remainingDisplay}${unit}`,
}));
return;
}
}
}
const existingConfirmIndex = messages.value.findIndex((item: any) => item?.type === 'leave-confirmation' && item?.payload?.formId === payload.formId);
if (existingConfirmIndex >= 0) {
messages.value.splice(existingConfirmIndex, 1);
}
payload.confirmationGenerated = true;
const summary = JSON.parse(JSON.stringify(payload.form)) as LeaveRequestFormData;
const confirmMsg = {
role: 'assistant' as const,
type: 'leave-confirmation' as const,
content: t('chat.leaveConfirmPrompt'),
payload: {
formId: payload.formId,
form: summary,
submitting: false,
},
local_id: newLocalMessageId('leave-confirm'),
local_only: true,
};
messages.value.push(confirmMsg);
saveLocalMessageToBackend(chatMsg);
saveLocalMessageToBackend(confirmMsg);
};
const editLeaveConfirmation = (chatMsg: any, index: number) => {
const payload = getLeaveConfirmationPayload(chatMsg);
if (!payload) return;
const sourceIndex = findMessageIndexByLocalId(payload.formId);
if (sourceIndex >= 0) {
const sourcePayload = getLeaveFormPayload(messages.value[sourceIndex]);
if (sourcePayload) {
sourcePayload.confirmationGenerated = false;
saveLocalMessageToBackend(messages.value[sourceIndex]);
}
}
// 从后端删除对应的确认消息,或者不删除直接隐藏?
// 暂时在前端移除,后端不需要立刻删除(如果没有删除接口),它在会话记录里可能残留。
// 但是我们之前有 /api/chat/messages/local 吗?如果需要,也可以调一个删除接口。
// 为了简单,我们只在前端切除。
messages.value.splice(index, 1);
};
const confirmLeaveSubmission = async (chatMsg: any) => {
const payload = getLeaveConfirmationPayload(chatMsg);
if (!payload || payload.submitting) return;
if (NEED_BALANCE_CHECK_TYPES.has(payload.form.leaveType)) {
const balance = await checkLeaveBalance(payload.form.leaveType);
if (balance && balance.remaining_hours !== null && balance.remaining_hours !== undefined) {
const requestedHours = payload.form.durationHours;
if (requestedHours > balance.remaining_hours) {
const isByDay = isLeaveTypeByDay(payload.form.leaveType);
const unit = isByDay ? t('chat.dayUnit') : t('chat.hourUnit');
const requestedDisplay = isByDay ? Math.round(requestedHours / 8) : requestedHours;
const remainingDisplay = isByDay ? Math.round(balance.remaining_hours / 8) : balance.remaining_hours;
const label = getLeaveTypeLabel(payload.form.leaveType);
msg.warning(t('chat.durationExceedsBalance', {
label,
requested: `${requestedDisplay}${unit}`,
remaining: `${remainingDisplay}${unit}`,
}));
return;
}
}
}
payload.submitting = true;
const sourceIndex = findMessageIndexByLocalId(payload.formId);
if (sourceIndex >= 0) {
const sourcePayload = getLeaveFormPayload(messages.value[sourceIndex]);
if (sourcePayload) {
sourcePayload.submitting = true;
sourcePayload.confirmationGenerated = true;
}
}
try {
const data = await submitLeaveWorkflow(payload.form);
const resultMsg = {
role: 'assistant' as const,
type: 'leave-result' as const,
content: t('chat.leaveResultSubmitted'),
payload: {
formId: payload.formId,
success: true,
referenceNo: data.request_id || '-',
submittedAt: data.submitted_at || formatDateTime(new Date()),
requestName: data.request_name || '',
},
local_id: newLocalMessageId('leave-result'),
local_only: true,
};
messages.value.push(resultMsg);
payload.confirmed = true;
payload.submitting = false;
saveLocalMessageToBackend(chatMsg);
saveLocalMessageToBackend(resultMsg);
} catch (error: any) {
const errorMessage = error?.message || t('chat.oaLeaveSubmitFailed');
msg.error(errorMessage);
const resultMsg = {
role: 'assistant' as const,
type: 'leave-result' as const,
content: t('chat.leaveSubmitFailedPrefix', { error: errorMessage }),
payload: {
formId: payload.formId,
success: false,
referenceNo: '-',
submittedAt: formatDateTime(new Date()),
errorMessage,
},
local_id: newLocalMessageId('leave-result'),
local_only: true,
};
messages.value.push(resultMsg);
saveLocalMessageToBackend(resultMsg);
} finally {
payload.submitting = false;
if (sourceIndex >= 0) {
const sourcePayload = getLeaveFormPayload(messages.value[sourceIndex]);
if (sourcePayload) {
sourcePayload.submitting = false;
}
}
}
};
const getMessageCopyText = (message: { role?: string; content?: string; type?: string }) => {
const content = String(message?.content ?? '').trim();
if (content) return content;
return '';
};
const copyToClipboard = async (message: { role?: string; content?: string; type?: string }, index: number) => {
const text = getMessageCopyText(message);
if (!text) {
msg.warning(t('chat.actions.copyEmpty'));
return;
}
const ok = await copyTextToClipboard(text);
if (ok) {
copiedIndex.value = index;
setTimeout(() => {
copiedIndex.value = null;
}, 2000);
return;
}
msg.warning(t('chat.actions.copyFailed'));
};
const regenerate = () => {
const lastUserMsg = [...messages.value].reverse().find(m => m.role === 'user');
if (lastUserMsg) {
handleSend(lastUserMsg.content);
}
};
// 加载历史记录
const loadHistory = async () => {
try {
history.value = await listChatSessions(currentAgentId.value);
} catch (e) {
console.error('Failed to load history', e);
}
};
const clearAllHistory = async () => {
openDeleteConfirmDialog(t('chat.confirmClearHistory'), async () => {
try {
await deleteAllChatSessions(currentAgentId.value);
history.value = [];
runs.value = [];
if (conversationId.value || activeRunId.value) {
startNewChat();
}
} catch (e) {
console.error('Failed to clear history', e);
}
});
};
const deleteHistoryItem = async (id: string, event: Event) => {
event.stopPropagation();
openDeleteConfirmDialog(t('chat.confirmDeleteHistoryItem'), async () => {
try {
await deleteChatSession(id, currentAgentId.value);
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);
}
});
};
const loadConversation = async (id: string) => {
if (conversationId.value === id && !activeRunId.value) return;
try {
activeRunId.value = null;
isThinking.value = false;
messages.value = await listChatMessages(id, currentAgentId.value);
conversationId.value = id;
} catch (e) {
console.error('Failed to load conversation', e);
}
};
const startNewChat = () => {
createNewChatView();
};
const loadAgent = async () => {
try {
currentAgent.value = await getUserAgent(currentAgentId.value);
} 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 agents = await listUserAgents();
userAgents.value = Array.isArray(agents)
? agents.filter((a: any) => a.id !== currentAgentId.value && (a.dify_app_type || 'chatflow') === 'chatflow')
: [];
if (userAgents.value.length === 0) {
showAgentPanel.value = false;
}
} catch (e) {
userAgents.value = [];
showAgentPanel.value = false;
}
};
const switchToAgent = (agent: { id: number; name: string }) => {
if (agent.id === currentAgentId.value) return;
setLastChatAgentId(agent.id);
router.push(`/chat/${agent.id}`);
};
const syncOpenAgentRegistration = () => {
const id = Number(route.params.agentId);
registerOpenAgentId(Number.isFinite(id) && id > 0 ? id : null);
};
const onPageHide = () => {
registerOpenAgentId(null);
};
const goToWorkspace = (view?: string) => {
setLastChatAgentId(currentAgentId.value);
registerOpenAgentId(null);
const query: Record<string, string> = { no_redirect: '1' };
if (view) query.view = view;
router.push({ path: '/workspace', query });
};
const resetChatStateForAgentChange = () => {
createNewChatView();
history.value = [];
attachments.value = [];
input.value = '';
currentAgent.value = null;
copiedIndex.value = null;
showAttachmentMenu.value = false;
filePreviewVisible.value = false;
previewFile.value = null;
};
let routeSyncToken = 0;
const syncChatStateForRoute = async () => {
const agentId = currentAgentId.value;
if (!agentId) return;
const syncToken = ++routeSyncToken;
resetChatStateForAgentChange();
stopVoiceInput();
setLastChatAgentId(agentId);
syncOpenAgentRegistration();
await syncCurrentUserProfile();
if (syncToken !== routeSyncToken) return;
await loadAgent();
if (syncToken !== routeSyncToken) return;
await loadUserAgents();
if (syncToken !== routeSyncToken) return;
await loadHistory();
if (syncToken !== routeSyncToken) return;
const convId = route.query.conversation_id as string;
if (convId) {
await loadConversation(convId);
if (syncToken !== routeSyncToken) return;
}
if (presetQuestion.value) {
input.value = presetQuestion.value;
await handleSend();
}
};
// 组件挂载时,如果存在预设问题,则自动触发一次发送
onMounted(async () => {
window.addEventListener('pagehide', onPageHide);
window.addEventListener('hxops:logout', onAuthLogout);
document.addEventListener('mousedown', handleDocumentPointerDown);
document.addEventListener('touchstart', handleDocumentPointerDown, { passive: true });
document.addEventListener('mousedown', handleMobileAgentPopoverClickOutside);
document.addEventListener('touchstart', handleMobileAgentPopoverClickOutside, { passive: true });
window.addEventListener('resize', syncViewportWidth);
await syncChatStateForRoute();
// Use config from config.ts instead of API
showChatRating.value = config.workspace?.showChatRating ?? true;
scheduleScrollChatToBottom();
});
watch(
() => [route.params.agentId, route.query.conversation_id, route.query.preset],
async ([nextAgentId, nextConversationId, nextPreset], [prevAgentId, prevConversationId, prevPreset]) => {
if (
nextAgentId === prevAgentId
&& nextConversationId === prevConversationId
&& nextPreset === prevPreset
) {
return;
}
await syncChatStateForRoute();
}
);
watch(
() => conversationId.value,
async (id, prev) => {
if (!id || id === prev) return;
const exists = history.value.some((item) => item.conversation_id === id);
if (!exists) {
await loadHistory();
}
}
);
onBeforeUnmount(() => {
window.removeEventListener('pagehide', onPageHide);
window.removeEventListener('hxops:logout', onAuthLogout);
document.removeEventListener('mousedown', handleDocumentPointerDown);
document.removeEventListener('touchstart', handleDocumentPointerDown);
document.removeEventListener('mousedown', handleMobileAgentPopoverClickOutside);
document.removeEventListener('touchstart', handleMobileAgentPopoverClickOutside);
window.removeEventListener('resize', syncViewportWidth);
stopBrowserResize();
if (scrollToBottomFrame !== null) {
window.cancelAnimationFrame(scrollToBottomFrame);
scrollToBottomFrame = null;
}
});
watch(
() => ({
messageCount: messages.value.length,
lastMessageContent: messages.value[messages.value.length - 1]?.content || '',
lastMessageRole: messages.value[messages.value.length - 1]?.role || '',
isThinking: isThinking.value,
conversationId: conversationId.value || '',
}),
() => {
if (wasThinking && !isThinking.value) {
wasThinking = false;
scrollToUserQuestion();
} else {
if (isThinking.value) wasThinking = true;
scheduleScrollChatToBottom();
}
},
{ deep: false },
);
/**
* 反馈相关状态
* showChatRating:是否启用评分功能(后续可接入配置)
*/
const showChatRating = ref(false);
</script>
<template>
<ChatShell>
<template #overlay>
<div
v-if="isSidebarOpen && !isMobile"
class="fixed inset-0 z-40 bg-overlay backdrop-blur-sm transition-opacity md:hidden"
@click="isSidebarOpen = false"
></div>
</template>
<template #sidebar>
<aside
v-if="!isMobile"
class="glass-panel fixed inset-y-0 left-0 z-50 flex h-full flex-col border-r border-default bg-surface transition-all duration-300 ease-in-out md:relative md:translate-x-0"
:class="[
isSidebarOpen ? 'translate-x-0 w-[86vw] max-w-[300px]' : '-translate-x-full w-[86vw] max-w-[300px]',
isSidebarCollapsed ? 'md:w-[72px]' : 'md:w-80'
]"
>
<template v-if="isSidebarCollapsed">
<div class="flex h-full w-full flex-col items-center py-4">
<button @click="isSidebarCollapsed = false" class="mb-6 text-muted transition-colors hover:text-secondary">
<PanelLeftOpen class="h-5 w-5" />
</button>
<div class="mb-4 flex h-10 w-10 shrink-0 items-center justify-center rounded-full bg-gradient-to-br from-brand-500 via-brand-600 to-sky-600 text-white shadow-sm shadow-brand-500/25">
<Sparkles class="h-5 w-5" />
</div>
<button @click="startNewChat(); isSidebarOpen = false;" class="chat-sidebar-btn-icon" :title="$t('chat.createNewChat')">
<Plus class="h-5 w-5" />
</button>
<div class="mt-auto flex flex-col items-center gap-6 pb-2 text-muted">
<button class="transition-colors hover:text-secondary"><Sparkles class="h-5 w-5" /></button>
<div class="flex h-8 w-8 items-center justify-center rounded-full bg-brand-600 text-sm font-bold text-white shadow-sm shadow-brand-500/20">
{{ (currentUser?.username || 'I').charAt(0).toUpperCase() }}
</div>
<LocaleToggleButton variant="sidebar" icon-size="md" />
<button @click="showGeneralFeedbackDialog = true" class="transition-colors hover:text-secondary" :title="$t('chat.generalFeedback')"><MessageSquareText class="h-5 w-5" /></button>
<button @click="goToWorkspace()" class="transition-colors hover:text-secondary" :title="$t('workspace.title')"><Briefcase class="h-5 w-5" /></button>
</div>
</div>
</template>
<template v-else>
<div class="flex items-center justify-between p-4">
<div class="flex items-center gap-3 w-full min-w-0">
<div class="flex h-8 w-8 shrink-0 items-center justify-center rounded-xl bg-gradient-to-br from-brand-500 via-brand-600 to-sky-600 text-sm font-bold text-white shadow-sm shadow-brand-500/25">
{{ currentAgent?.name === '人事规章' ? 'HR' : 'AI' }}
</div>
<div class="flex flex-col justify-center min-w-0 flex-1 relative group">
<span class="font-bold text-primary truncate">{{ currentAgent?.name || 'AI' }}</span>
<span v-if="currentAgent?.name === '人事规章'" class="block text-[11px] text-muted mt-1 truncate cursor-help">
我是你的7x24小时专属HR政策助手。无需手动检索文档,只需用日常说话的方式提问,我能从公司最新、最全的规章制度中,为你精准提取并总结答案。
</span>
<span v-else-if="currentAgent?.name === '通用入口'" class="block text-[11px] text-muted mt-1 truncate cursor-help">
我是你的7x24小时专属AI数字人。无需手动检索文档,只需用日常说话的方式提问,我能从公司最新、最全的人事规章制度中,为你精准提取并总结答案。
</span>
<!-- 气泡提示 -->
<div v-if="currentAgent?.name === '人事规章' || currentAgent?.name === '通用入口'" class="absolute left-0 top-[calc(100%+0.25rem)] w-[20rem] p-3 bg-surface border border-default rounded-xl opacity-0 invisible group-hover:opacity-100 group-hover:visible transition-all duration-200 z-[100] shadow-xl pointer-events-none">
<div class="leading-relaxed text-[11px] text-secondary">
{{ currentAgent?.name === '人事规章' ? '我是你的7x24小时专属HR政策助手。无需手动检索文档,只需用日常说话的方式提问,我能从公司最新、最全的规章制度中,为你精准提取并总结答案。' : '我是你的7x24小时专属AI数字人。无需手动检索文档,只需用日常说话的方式提问,我能从公司最新、最全的人事规章制度中,为你精准提取并总结答案。' }}
</div>
</div>
</div>
</div>
<button @click="isSidebarCollapsed = true" class="text-muted transition-colors hover:text-secondary shrink-0 ml-2">
<PanelLeftClose class="h-5 w-5" />
</button>
</div>
<div class="px-4 pb-4">
<button @click="startNewChat(); isSidebarOpen = false;" class="chat-sidebar-btn">
<Plus class="h-4 w-4" /> {{ $t('chat.createNewChat') }}
</button>
</div>
<div class="flex items-center justify-between px-4 py-2">
<span class="text-xs font-semibold text-slate-500 dark:text-slate-400">{{ $t('chat.history') }}</span>
<button v-if="displayHistory.length > 0" @click="clearAllHistory" class="text-xs text-slate-400 transition-colors hover:text-slate-600 dark:hover:text-slate-200">
{{ $t('chat.clearAll') }}
</button>
</div>
<div class="flex-1 overflow-y-auto px-2 scrollbar-thin">
<div v-if="displayHistory.length === 0" class="py-8 text-center text-sm italic text-slate-400">{{ $t('chat.noHistory') }}</div>
<div v-else class="space-y-0.5">
<div
v-for="item in displayHistory"
:key="item.conversation_id"
class="group relative flex w-full items-center justify-between rounded-lg transition-colors"
:class="activeHistoryKey === item.conversation_id ? 'bg-brand-50 dark:bg-brand-900/20' : 'hover:bg-slate-50 dark:hover:bg-slate-800/50'"
>
<button
class="flex-1 truncate px-3 py-2.5 text-left text-sm pr-8"
:class="activeHistoryKey === item.conversation_id
? 'font-medium text-brand-700 dark:text-brand-300'
: 'text-slate-600 dark:text-slate-300'"
@click="handleHistorySelect(item)"
>
{{ item.title || $t('chat.newChat') }}
</button>
<button
v-if="!(item as any).__runId"
@click="deleteHistoryItem(item.conversation_id, $event)"
class="absolute right-2 p-1.5 text-muted opacity-0 transition-opacity hover:text-red-500 group-hover:opacity-100"
:title="$t('chat.clearOneRecord')"
>
<X class="h-4 w-4" />
</button>
</div>
</div>
</div>
<div class="mt-auto flex flex-col p-4">
<div v-if="userAgents.length > 0 && showAgentPanel" class="chat-agent-panel">
<div class="mb-2 flex items-center gap-1.5 text-xs font-semibold text-muted">
<LayoutGrid class="h-3.5 w-3.5" /> {{ $t('chat.agents') }}
</div>
<div class="grid grid-cols-2 gap-x-2 gap-y-1.5">
<button
v-for="agent in userAgents"
:key="agent.id"
@click="switchToAgent(agent)"
class="grid w-full min-w-0 grid-cols-[1rem_1fr] items-center gap-1.5 rounded-xl px-2 py-2 text-left text-xs font-medium text-secondary transition-colors hover-surface-soft hover:shadow-sm"
>
<div v-if="agent.icon_url" class="h-4 w-4 shrink-0 rounded bg-contain bg-center bg-no-repeat" :style="{ backgroundImage: `url(${agent.icon_url})` }"></div>
<div v-else class="flex h-4 w-4 shrink-0 items-center justify-center rounded bg-brand-100 text-[9px] font-bold text-brand-600">{{ agent.name.charAt(0) }}</div>
<span class="min-w-0 truncate">{{ agent.name }}</span>
</button>
</div>
</div>
<!-- Bottom Icons -->
<div class="flex items-center justify-between text-muted relative" ref="userMenuRef">
<button @click="showUserDropdown = !showUserDropdown" class="flex h-8 w-8 items-center justify-center rounded-full bg-brand-600 text-sm font-bold text-white shadow-sm shadow-brand-500/20 hover:bg-brand-700 transition-colors">
{{ (currentUser?.username || 'I').charAt(0).toUpperCase() }}
</button>
<!-- User Dropdown Menu -->
<div v-if="showUserDropdown" class="absolute bottom-full left-0 mb-2 w-56 bg-surface rounded-xl shadow-xl border border-subtle py-1 z-50 animate-fade-in">
<div class="px-4 py-3 border-b border-subtle flex items-center gap-3">
<div class="w-10 h-10 bg-brand-600 rounded-full flex items-center justify-center text-white font-bold text-lg shrink-0 shadow-sm shadow-brand-500/20">
{{ (currentUser?.username || 'U').charAt(0).toUpperCase() }}
</div>
<div class="overflow-hidden">
<div class="text-sm font-bold text-primary truncate">{{ currentUser?.username || 'User' }}</div>
<div v-if="(currentUser as any)?.employee_id" class="text-xs text-muted truncate">{{ $t('chat.employeeId') }}: {{ (currentUser as any).employee_id }}</div>
<div v-else class="text-xs text-muted truncate">{{ currentUser?.role }}</div>
</div>
</div>
<button @click="handleLogout" class="flex w-full items-center gap-2 border-t border-subtle px-4 py-2 text-left text-sm text-red-600 transition-colors hover:bg-red-50">
<LogOut class="w-4 h-4" />
{{ $t('chat.logout') }}
</button>
</div>
<div class="flex gap-3">
<button @click="userAgents.length === 0 ? undefined : (showAgentPanel = !showAgentPanel)" :class="showAgentPanel && userAgents.length > 0 ? 'text-brand-600' : ''" class="transition-colors hover:text-secondary" :title="userAgents.length === 0 ? $t('chat.noAvailableAgents') : (showAgentPanel ? $t('chat.collapseAgents') : $t('chat.expandAgents'))"><LayoutGrid class="h-4 w-4" /></button>
<!-- <button class="transition-colors hover:text-secondary"><Heart class="h-4 w-4" /></button> -->
<!-- <button class="transition-colors hover:text-secondary"><Bell class="h-4 w-4" /></button> -->
<button @click="toggleLightDark" class="transition-colors hover:text-secondary" :title="appliedTheme === 'dark' ? ($t('theme.switchToLight') || 'Switch to light mode') : ($t('theme.switchToDark') || 'Switch to dark mode')">
<Sun v-if="appliedTheme === 'dark'" class="h-4 w-4" />
<Moon v-else class="h-4 w-4" />
</button>
<LocaleToggleButton variant="sidebar" />
<button @click="showGeneralFeedbackDialog = true" class="transition-colors hover:text-secondary" :title="$t('chat.generalFeedback')"><MessageSquareText class="h-4 w-4" /></button>
<button @click="goToWorkspace()" class="transition-colors hover:text-secondary" :title="$t('workspace.title')"><Briefcase class="h-4 w-4" /></button>
</div>
</div>
</div>
</template>
</aside>
</template>
<header v-if="isMobile && currentAgent" class="flex items-center justify-between border-b border-default bg-surface px-4 py-2.5">
<div class="flex items-center gap-2">
<div class="flex h-7 w-7 items-center justify-center rounded-lg bg-gradient-to-br from-brand-500 via-brand-600 to-sky-600 text-xs font-bold text-white shadow-sm shadow-brand-500/20">AI</div>
<span class="text-sm font-semibold text-primary">{{ currentAgent?.name || 'AI' }}</span>
</div>
<div class="flex items-center gap-1">
<button @click="toggleMobileAgentPopover" class="flex h-9 w-9 items-center justify-center rounded-full text-muted transition-colors hover-surface-soft" :title="$t('chat.agents')">
<LayoutGrid class="h-5 w-5" />
</button>
<button @click="goToWorkspace('history')" class="flex h-9 w-9 items-center justify-center rounded-full text-muted transition-colors hover-surface-soft" :title="$t('chat.history')">
<History class="h-5 w-5" />
</button>
</div>
<div v-if="showMobileAgentPopover" ref="mobileAgentPopoverRef" class="absolute right-4 top-12 z-50 w-72 rounded-2xl border border-default bg-surface p-3 shadow-xl">
<div class="mb-2 text-xs font-medium text-muted">{{ $t('chat.agents') }}</div>
<div class="grid grid-cols-2 gap-2">
<button
v-for="agent in userAgents"
:key="agent.id"
@click="switchToAgent(agent); showMobileAgentPopover = false"
class="flex flex-col items-center gap-1.5 rounded-xl px-2 py-3 text-center transition-colors hover-surface-soft"
>
<div class="flex h-9 w-9 items-center justify-center rounded-lg bg-brand-50 text-sm font-bold text-brand-600">
{{ agent.name.charAt(0) }}
</div>
<span class="w-full truncate text-xs font-medium text-secondary">{{ agent.name }}</span>
</button>
</div>
<div v-if="userAgents.length === 0" class="py-3 text-center text-xs text-muted">{{ $t('chat.noOtherAgents') }}</div>
</div>
</header>
<div v-if="!currentAgent" class="flex flex-1 flex-col items-center justify-center space-y-4">
<Loader2 class="h-10 w-10 animate-spin text-brand-500" />
<p class="text-sm animate-pulse text-muted">{{ $t('chat.loadingAgent') }}</p>
</div>
<div v-else-if="currentAgent.type === 'iframe'" class="relative h-full w-full flex-1">
<iframe
:src="currentAgent.extra_config?.iframe_url"
class="h-full w-full border-0 bg-surface"
allow="microphone; camera; clipboard-read; clipboard-write"
></iframe>
</div>
<template v-else>
<div class="flex min-h-0 flex-1">
<div class="flex min-h-0 flex-1 flex-col">
<main
ref="chatScrollContainer"
class="flex-1 p-3 md:p-8"
:class="messages.length === 0 ? 'overflow-hidden md:overflow-y-auto' : 'overflow-y-auto scrollbar-thin'"
>
<div
:class="messages.length === 0 ? 'h-full' : 'flex min-h-full flex-col justify-end'"
>
<div v-if="messages.length === 0" class="flex h-full flex-col items-center justify-center py-2 md:pb-16 w-full px-4">
<template v-if="currentAgent?.name === '人事规章'">
<div class="mb-6 flex h-16 w-16 items-center justify-center rounded-2xl bg-gradient-to-br from-brand-500 via-brand-600 to-sky-600 text-2xl font-bold text-white shadow-lg shadow-brand-500/20">
HR
</div>
<h2 class="text-center text-xl font-bold text-primary md:text-2xl mb-8">你好,我是人事规章 AI 助手</h2>
<div class="grid grid-cols-1 md:grid-cols-2 gap-4 w-full max-w-4xl mx-auto">
<!-- 考勤与休假 -->
<div class="bg-surface border border-default rounded-2xl p-5 hover:border-brand-300 transition-colors shadow-sm">
<div class="flex items-center gap-2 mb-3">
<div class="p-1.5 bg-brand-50 rounded-lg text-brand-600">
<CalendarDays class="h-4 w-4" />
</div>
<h3 class="font-semibold text-secondary">考勤与休假</h3>
</div>
<div class="space-y-2">
<button @click="handleSend('查询我有多少假期?')" class="w-full text-left text-xs md:text-sm text-secondary hover:text-brand-600 bg-surface-soft hover:bg-brand-50 px-3 py-2 rounded-lg transition-colors truncate">"查询我有多少假期?"</button>
<button @click="handleSend('如何进行请假?')" class="w-full text-left text-xs md:text-sm text-secondary hover:text-brand-600 bg-surface-soft hover:bg-brand-50 px-3 py-2 rounded-lg transition-colors truncate">"如何进行请假?"</button>
<button @click="handleSend('查公司法定节假日?')" class="w-full text-left text-xs md:text-sm text-secondary hover:text-brand-600 bg-surface-soft hover:bg-brand-50 px-3 py-2 rounded-lg transition-colors truncate">"查公司法定节假日?"</button>
</div>
</div>
<!-- 规章与日常 -->
<div class="bg-surface border border-default rounded-2xl p-5 hover:border-brand-300 transition-colors shadow-sm">
<div class="flex items-center gap-2 mb-3">
<div class="p-1.5 bg-brand-50 rounded-lg text-brand-600">
<Building class="h-4 w-4" />
</div>
<h3 class="font-semibold text-secondary">规章与日常</h3>
</div>
<div class="space-y-2">
<button @click="handleSend('新员工入职须知')" class="w-full text-left text-xs md:text-sm text-secondary hover:text-brand-600 bg-surface-soft hover:bg-brand-50 px-3 py-2 rounded-lg transition-colors truncate">"新员工入职须知"</button>
<button @click="handleSend('怎么开具在职证明?')" class="w-full text-left text-xs md:text-sm text-secondary hover:text-brand-600 bg-surface-soft hover:bg-brand-50 px-3 py-2 rounded-lg transition-colors truncate">"怎么开具在职证明?"</button>
<button @click="handleSend('查公司薪酬及福利待遇怎么样?')" class="w-full text-left text-xs md:text-sm text-secondary hover:text-brand-600 bg-surface-soft hover:bg-brand-50 px-3 py-2 rounded-lg transition-colors truncate">"查公司薪酬及福利待遇怎么样?"</button>
</div>
</div>
</div>
</template>
<template v-else-if="currentAgent?.name === '通用入口'">
<div class="mb-6 flex h-16 w-16 items-center justify-center rounded-2xl bg-gradient-to-br from-brand-500 via-brand-600 to-sky-600 text-2xl font-bold text-white shadow-lg shadow-brand-500/20">
AI
</div>
<h2 class="text-center text-xl font-medium text-primary md:text-2xl mb-8">{{ $t('chat.welcomeTitle') }}</h2>
<div class="flex flex-wrap justify-center gap-3 w-full max-w-3xl mx-auto mt-2">
<button @click="handleSend('新员工入职须知')" class="px-4 py-2 text-sm text-secondary bg-surface border border-default rounded-full hover:border-brand-300 hover:text-brand-600 hover:bg-brand-50 transition-all shadow-sm">"新员工入职须知"</button>
<button @click="handleSend('查询我有多少假期?')" class="px-4 py-2 text-sm text-secondary bg-surface border border-default rounded-full hover:border-brand-300 hover:text-brand-600 hover:bg-brand-50 transition-all shadow-sm">"查询我有多少假期?"</button>
<button @click="handleSend('如何进行请假?')" class="px-4 py-2 text-sm text-secondary bg-surface border border-default rounded-full hover:border-brand-300 hover:text-brand-600 hover:bg-brand-50 transition-all shadow-sm">"如何进行请假?"</button>
<button @click="handleSend('查公司法定节假日?')" class="px-4 py-2 text-sm text-secondary bg-surface border border-default rounded-full hover:border-brand-300 hover:text-brand-600 hover:bg-brand-50 transition-all shadow-sm">"查公司法定节假日?"</button>
<button @click="handleSend('查公司薪酬及福利待遇怎么样?')" class="px-4 py-2 text-sm text-secondary bg-surface border border-default rounded-full hover:border-brand-300 hover:text-brand-600 hover:bg-brand-50 transition-all shadow-sm">"查公司薪酬及福利待遇怎么样?"</button>
</div>
</template>
<template v-else>
<div class="mb-6 flex h-16 w-16 items-center justify-center rounded-2xl bg-gradient-to-br from-brand-500 via-brand-600 to-sky-600 text-2xl font-bold text-white shadow-lg shadow-brand-500/20">
AI
</div>
<h2 class="text-center text-xl font-medium text-primary md:text-2xl">{{ $t('chat.welcomeTitle') }}</h2>
</template>
</div>
<template v-for="(msg, index) in messages" :key="index">
<div
v-if="shouldRenderMessage(msg)"
:data-msg-index="index"
class="group mx-auto mb-6 flex w-full max-w-4xl animate-slide-up"
:class="msg.role === 'user' ? 'justify-end' : 'justify-start'"
>
<div
class="flex flex-col"
:class="msg.role === 'user' ? 'max-w-[88%] md:max-w-[74%] items-end' : 'w-full'"
>
<div
class="text-[15px] leading-relaxed"
:class="msg.role === 'user'
? 'rounded-2xl rounded-tr-sm bg-brand-600 px-5 py-2.5 text-white shadow-sm shadow-brand-500/15'
: 'chat-msg-assistant'"
>
<div
v-if="msg.role === 'user'"
class="whitespace-pre-wrap"
>{{ msg.content }}</div>
<div v-else>
<div v-if="msg.type === 'leave-form'" class="space-y-4">
<div class="text-sm font-medium text-secondary">
{{ $t('chat.leaveFormIntro') }} <a href="#" @click.prevent="openOALeaveRequestDirectly" class="text-brand-600 font-bold hover:underline">{{ $t('chat.oaLeaveDirectLink') }}</a>
</div>
<div v-if="getLeaveFormPayload(msg)" class="grid gap-4 md:grid-cols-2">
<label class="space-y-1.5">
<span class="text-xs font-semibold text-muted">{{ $t('chat.leaveFiller') }}</span>
<input
v-model="getLeaveFormPayload(msg)!.form.fillerName"
type="text"
class="w-full rounded-xl border border-default bg-surface-soft px-3 py-2 text-sm text-muted outline-none"
disabled
/>
</label>
<label class="space-y-1.5">
<span class="text-xs font-semibold text-muted">{{ $t('chat.employeeId') }}</span>
<input
v-model="getLeaveFormPayload(msg)!.form.employeeId"
type="text"
class="w-full rounded-xl border border-default bg-surface-soft px-3 py-2 text-sm text-muted outline-none"
disabled
/>
</label>
<label class="space-y-1.5">
<span class="text-xs font-semibold text-muted">{{ $t('chat.createdAt') }}</span>
<input
:value="getLeaveFormPayload(msg)!.form.applyTime.replace('T', ' ')"
type="text"
class="w-full rounded-xl border border-default bg-surface-soft px-3 py-2 text-sm text-muted outline-none"
disabled
/>
</label>
<label class="space-y-1.5">
<span class="text-xs font-semibold text-muted">{{ $t('chat.leaveType') }}</span>
<select
v-model="getLeaveFormPayload(msg)!.form.leaveType"
class="w-full rounded-xl border border-default px-3 py-2 text-sm text-secondary outline-none transition focus:border-blue-400"
:disabled="getLeaveFormPayload(msg)!.submitting || getLeaveFormPayload(msg)!.confirmationGenerated"
@change="syncLeaveDuration(getLeaveFormPayload(msg)!.form)"
>
<option value="" disabled>{{ $t('chat.selectLeaveType') }}</option>
<option v-for="leaveType in LEAVE_TYPES" :key="leaveType.value" :value="leaveType.value">{{ leaveType.label }}</option>
</select>
</label>
<label class="space-y-1.5">
<span class="text-xs font-semibold text-muted">{{ $t('chat.leaveApplicant') }}</span>
<div class="relative">
<input
:value="getLeaveFormPayload(msg)!.form.applicantName ? `${getLeaveFormPayload(msg)!.form.applicantName} / ${getLeaveFormPayload(msg)!.form.employeeId}` : ''"
type="text"
:placeholder="$t('chat.selectLeaveApplicant')"
readonly
class="w-full rounded-xl border border-default bg-surface px-3 py-2 pr-11 text-sm text-secondary outline-none transition focus:border-blue-400"
:disabled="getLeaveFormPayload(msg)!.submitting || getLeaveFormPayload(msg)!.confirmationGenerated"
@click="openLeaveAgentDialog(msg, 'applicant')"
/>
<button
type="button"
class="absolute inset-y-0 right-0 flex w-11 items-center justify-center text-muted transition hover:text-brand-600 disabled:cursor-not-allowed disabled:opacity-50"
:disabled="getLeaveFormPayload(msg)!.submitting || getLeaveFormPayload(msg)!.confirmationGenerated"
@click="openLeaveAgentDialog(msg, 'applicant')"
:title="$t('chat.pickLeaveApplicant')"
>
<Search class="h-4 w-4" />
</button>
</div>
</label>
<label class="space-y-1.5">
<span class="text-xs font-semibold text-muted">{{ $t('chat.leaveAgent') }}</span>
<div class="relative">
<input
:value="getLeaveAgentDisplayValue(getLeaveFormPayload(msg)!.form)"
type="text"
:placeholder="$t('chat.selectLeaveAgent')"
readonly
class="w-full rounded-xl border border-default bg-surface px-3 py-2 pr-11 text-sm text-secondary outline-none transition focus:border-blue-400"
:disabled="getLeaveFormPayload(msg)!.submitting || getLeaveFormPayload(msg)!.confirmationGenerated"
@click="openLeaveAgentDialog(msg)"
/>
<button
type="button"
class="absolute inset-y-0 right-0 flex w-11 items-center justify-center text-muted transition hover:text-brand-600 disabled:cursor-not-allowed disabled:opacity-50"
:disabled="getLeaveFormPayload(msg)!.submitting || getLeaveFormPayload(msg)!.confirmationGenerated"
@click="openLeaveAgentDialog(msg)"
:title="$t('chat.pickLeaveAgent')"
>
<Search class="h-4 w-4" />
</button>
</div>
</label>
<label class="space-y-1.5">
<span class="text-xs font-semibold text-muted">{{ $t('chat.startTime') }}</span>
<input
v-model="getLeaveFormPayload(msg)!.form.startTime"
type="datetime-local"
class="w-full rounded-xl border border-default px-3 py-2 text-sm text-secondary outline-none transition focus:border-blue-400"
:disabled="getLeaveFormPayload(msg)!.submitting || getLeaveFormPayload(msg)!.confirmationGenerated"
@input="syncLeaveDuration(getLeaveFormPayload(msg)!.form)"
/>
</label>
<label class="space-y-1.5">
<span class="text-xs font-semibold text-muted">{{ $t('chat.endTime') }}</span>
<input
v-model="getLeaveFormPayload(msg)!.form.endTime"
type="datetime-local"
class="w-full rounded-xl border border-default px-3 py-2 text-sm text-secondary outline-none transition focus:border-blue-400"
:disabled="getLeaveFormPayload(msg)!.submitting || getLeaveFormPayload(msg)!.confirmationGenerated"
@input="syncLeaveDuration(getLeaveFormPayload(msg)!.form)"
/>
</label>
<label class="space-y-1.5">
<span class="text-xs font-semibold text-muted">{{ $t('chat.duration') }}</span>
<input
:value="formatDurationLabel(getLeaveFormPayload(msg)!.form.durationHours, getLeaveFormPayload(msg)!.form.leaveType)"
type="text"
class="w-full rounded-xl border border-default bg-surface-soft px-3 py-2 text-sm text-muted outline-none"
disabled
/>
</label>
<label class="space-y-1.5">
<span class="text-xs font-semibold text-muted">{{ $t('chat.isOutOfOffice') }}</span>
<select
v-model="getLeaveFormPayload(msg)!.form.isOutOfOffice"
class="w-full rounded-xl border border-default px-3 py-2 text-sm text-secondary outline-none transition focus:border-blue-400"
:disabled="getLeaveFormPayload(msg)!.submitting || getLeaveFormPayload(msg)!.confirmationGenerated"
>
<option :value="1">{{ $t('chat.no') }}</option>
<option :value="0">{{ $t('chat.yes') }}</option>
</select>
</label>
<label class="space-y-1.5 md:col-span-2">
<span class="text-xs font-semibold text-muted">{{ $t('chat.isWorkInjury') }}</span>
<select
v-model="getLeaveFormPayload(msg)!.form.isWorkInjury"
class="w-full rounded-xl border border-default px-3 py-2 text-sm text-secondary outline-none transition focus:border-blue-400"
:disabled="getLeaveFormPayload(msg)!.submitting || getLeaveFormPayload(msg)!.confirmationGenerated"
>
<option :value="1">{{ $t('chat.no') }}</option>
<option :value="0">{{ $t('chat.yes') }}</option>
</select>
</label>
</div>
<div v-if="getLeaveFormPayload(msg)?.confirmationGenerated" class="rounded-xl border border-amber-200 bg-amber-50 px-4 py-3 text-xs text-amber-700">
{{ $t('chat.leaveConfirmGenerated') }}
</div>
<div class="flex justify-end">
<button
@click="submitLeaveForm(msg)"
:disabled="getLeaveFormPayload(msg)?.submitting || getLeaveFormPayload(msg)?.confirmationGenerated"
class="btn-primary btn-sm disabled:cursor-not-allowed disabled:opacity-60"
>
{{ getLeaveFormPayload(msg)?.submitting ? $t('chat.submitting') : $t('chat.submit') }}
</button>
</div>
</div>
<div v-else-if="msg.type === 'leave-confirmation' && getLeaveConfirmationPayload(msg)" class="space-y-4">
<div class="text-sm font-medium text-secondary">{{ msg.content }}</div>
<div class="rounded-2xl border border-default bg-surface-soft/90 p-4">
<div class="mb-3 text-xs font-bold uppercase tracking-wider text-muted">{{ $t('chat.leaveFillerInfo') }}</div>
<div class="grid gap-3 text-sm md:grid-cols-2">
<div><span class="text-muted">{{ $t('chat.leaveFiller') }}:</span>{{ getLeaveConfirmationPayload(msg)!.form.fillerName || $t('chat.noData') }}</div>
<div><span class="text-muted">{{ $t('chat.createdAt') }}:</span>{{ getLeaveConfirmationPayload(msg)!.form.applyTime.replace('T', ' ') }}</div>
<div v-if="getLeaveConfirmationPayload(msg)!.form.fillerJobTitleName || getLeaveConfirmationPayload(msg)!.form.fillerJobTitle"><span class="text-muted">{{ $t('chat.leaveFillerTitle') }}:</span>{{ getLeaveConfirmationPayload(msg)!.form.fillerJobTitleName || getLeaveConfirmationPayload(msg)!.form.fillerJobTitle }}</div>
<div v-if="getLeaveConfirmationPayload(msg)!.form.fillerDepartmentName || getLeaveConfirmationPayload(msg)!.form.fillerDepartmentId"><span class="text-muted">{{ $t('chat.leaveFillerDept') }}:</span>{{ getLeaveConfirmationPayload(msg)!.form.fillerDepartmentName || getLeaveConfirmationPayload(msg)!.form.fillerDepartmentId }}</div>
<div v-if="getLeaveConfirmationPayload(msg)!.form.fillerSubCompanyName || getLeaveConfirmationPayload(msg)!.form.fillerSubCompanyId1"><span class="text-muted">{{ $t('chat.leaveFillerCompany') }}:</span>{{ getLeaveConfirmationPayload(msg)!.form.fillerSubCompanyName || getLeaveConfirmationPayload(msg)!.form.fillerSubCompanyId1 }}</div>
</div>
<div class="my-3 border-t border-default"></div>
<div class="mb-3 text-xs font-bold uppercase tracking-wider text-muted">{{ $t('chat.leaveApplicantInfo') }}</div>
<div class="grid gap-3 text-sm md:grid-cols-2">
<div><span class="text-muted">{{ $t('chat.leaveApplicant') }}:</span>{{ getLeaveConfirmationPayload(msg)!.form.applicantName }}({{ getLeaveConfirmationPayload(msg)!.form.employeeId }})</div>
<div v-if="getLeaveConfirmationPayload(msg)!.form.applicantJobTitleName || getLeaveConfirmationPayload(msg)!.form.applicantJobTitle"><span class="text-muted">{{ $t('chat.leaveApplicantTitle') }}:</span>{{ getLeaveConfirmationPayload(msg)!.form.applicantJobTitleName || getLeaveConfirmationPayload(msg)!.form.applicantJobTitle }}</div>
<div v-if="getLeaveConfirmationPayload(msg)!.form.applicantDepartmentName || getLeaveConfirmationPayload(msg)!.form.applicantDepartmentId"><span class="text-muted">{{ $t('chat.leaveApplicantDept') }}:</span>{{ getLeaveConfirmationPayload(msg)!.form.applicantDepartmentName || getLeaveConfirmationPayload(msg)!.form.applicantDepartmentId }}</div>
<div v-if="getLeaveConfirmationPayload(msg)!.form.applicantSubCompanyName || getLeaveConfirmationPayload(msg)!.form.applicantSubCompanyId1"><span class="text-muted">{{ $t('chat.leaveApplicantCompany') }}:</span>{{ getLeaveConfirmationPayload(msg)!.form.applicantSubCompanyName || getLeaveConfirmationPayload(msg)!.form.applicantSubCompanyId1 }}</div>
</div>
<div class="my-3 border-t border-default"></div>
<div class="mb-3 text-xs font-bold uppercase tracking-wider text-muted">{{ $t('chat.leaveInfo') }}</div>
<div class="grid gap-3 text-sm md:grid-cols-2">
<div><span class="text-muted">{{ $t('chat.leaveAgent') }}:</span>{{ getLeaveAgentDisplayValue(getLeaveConfirmationPayload(msg)!.form) || $t('chat.notSelected') }}</div>
<div v-if="getLeaveConfirmationPayload(msg)!.form.agentJobTitleName || getLeaveConfirmationPayload(msg)!.form.agentJobTitle"><span class="text-muted">{{ $t('chat.leaveAgentTitle') }}:</span>{{ getLeaveConfirmationPayload(msg)!.form.agentJobTitleName || getLeaveConfirmationPayload(msg)!.form.agentJobTitle }}</div>
<div v-if="getLeaveConfirmationPayload(msg)!.form.agentDepartmentName || getLeaveConfirmationPayload(msg)!.form.agentDepartmentId"><span class="text-muted">{{ $t('chat.leaveAgentDept') }}:</span>{{ getLeaveConfirmationPayload(msg)!.form.agentDepartmentName || getLeaveConfirmationPayload(msg)!.form.agentDepartmentId }}</div>
<div v-if="getLeaveConfirmationPayload(msg)!.form.agentSubCompanyName || getLeaveConfirmationPayload(msg)!.form.agentSubCompanyId1"><span class="text-muted">{{ $t('chat.leaveAgentCompany') }}:</span>{{ getLeaveConfirmationPayload(msg)!.form.agentSubCompanyName || getLeaveConfirmationPayload(msg)!.form.agentSubCompanyId1 }}</div>
<div><span class="text-muted">{{ $t('chat.leaveType') }}:</span>{{ getLeaveTypeLabel(getLeaveConfirmationPayload(msg)!.form.leaveType) }}</div>
<div><span class="text-muted">{{ $t('chat.duration') }}:</span>{{ formatDurationLabel(getLeaveConfirmationPayload(msg)!.form.durationHours, getLeaveConfirmationPayload(msg)!.form.leaveType) }}</div>
<div><span class="text-muted">{{ $t('chat.startTime') }}:</span>{{ getLeaveConfirmationPayload(msg)!.form.startTime.replace('T', ' ') }}</div>
<div><span class="text-muted">{{ $t('chat.endTime') }}:</span>{{ getLeaveConfirmationPayload(msg)!.form.endTime.replace('T', ' ') }}</div>
<div><span class="text-muted">{{ $t('chat.isOutOfOffice') }}:</span>{{ formatYesNoLabel(getLeaveConfirmationPayload(msg)!.form.isOutOfOffice) }}</div>
<div><span class="text-muted">{{ $t('chat.isWorkInjury') }}:</span>{{ formatYesNoLabel(getLeaveConfirmationPayload(msg)!.form.isWorkInjury) }}</div>
</div>
</div>
<div class="flex justify-end gap-3">
<button
v-if="!getLeaveConfirmationPayload(msg)?.submitting && !getLeaveConfirmationPayload(msg)?.confirmed"
@click="editLeaveConfirmation(msg, index)"
class="rounded-xl border border-default px-4 py-2 text-sm font-medium text-secondary transition hover:bg-surface-soft disabled:cursor-not-allowed disabled:opacity-60"
>
{{ $t('chat.backToEdit') }}
</button>
<button
@click="confirmLeaveSubmission(msg)"
:disabled="getLeaveConfirmationPayload(msg)?.submitting || getLeaveConfirmationPayload(msg)?.confirmed"
class="rounded-xl bg-emerald-600 px-4 py-2 text-sm font-medium text-white transition hover:bg-emerald-700 disabled:cursor-not-allowed disabled:opacity-60"
>
{{ getLeaveConfirmationPayload(msg)?.submitting ? $t('chat.confirming') : (getLeaveConfirmationPayload(msg)?.confirmed ? $t('chat.confirmed') : $t('chat.confirm')) }}
</button>
</div>
</div>
<div v-else-if="msg.type === 'leave-result' && getLeaveResultPayload(msg)" class="space-y-3">
<div
class="rounded-2xl border px-4 py-4"
:class="getLeaveResultPayload(msg)!.success
? 'border-emerald-200 bg-emerald-50 text-emerald-800'
: 'border-rose-200 bg-rose-50 text-rose-800'"
>
<div class="text-sm font-semibold">{{ getLeaveResultPayload(msg)!.success ? $t('chat.oaSubmitResult') : $t('chat.oaSubmitFailed') }}</div>
<div v-if="getLeaveResultPayload(msg)!.success" class="mt-2 whitespace-pre-wrap text-sm leading-7">
{{ $t('chat.leaveResultPrefix') }}
<a
href="#"
@click.prevent="openOARequestDirectly(getLeaveResultPayload(msg)!.referenceNo)"
class="ml-1 inline-flex items-center rounded-full border border-brand-200 bg-brand-50 px-3 py-0.5 font-bold text-brand-700 transition hover:bg-brand-100 hover:underline"
>
{{ $t('chat.leaveResultLinkText') }}
</a>
</div>
<div v-else class="mt-2 whitespace-pre-wrap text-sm leading-7">{{ msg.content }}</div>
<div class="mt-3 text-xs opacity-80">{{ $t('chat.requestNo') }}:{{ getLeaveResultPayload(msg)!.referenceNo }}</div>
<div class="mt-1 text-xs opacity-80">{{ $t('chat.submitTime') }}:{{ getLeaveResultPayload(msg)!.submittedAt }}</div>
</div>
</div>
<div
v-else
class="chat-markdown prose prose-sm max-w-none leading-7 text-primary prose-a:text-blue-600 prose-p:my-1 prose-li:my-0.5 prose-ol:my-2 prose-ul:my-2 prose-headings:my-2 prose-hr:my-3 prose-code:rounded prose-code:bg-slate-100 prose-code:px-1 prose-code:text-blue-700 prose-pre:my-3 prose-pre:border prose-pre:border-slate-700 prose-pre:bg-slate-900 prose-pre:text-slate-100"
@click="handleChatMarkdownClick"
v-html="renderMarkdown(msg.content)"
></div>
</div>
</div>
<div
v-if=" msg.role === 'assistant' && msg.type !== 'leave-form' && msg.type !== 'leave-confirmation' && msg.type !== 'leave-result' && ((getDisplayRetrieverResources(msg).length > 0) || (msg.attribution_parts && msg.attribution_parts.length > 0) || getSourceLinks(getDisplayRetrieverResources(msg)).length > 0)"
class="mt-2 space-y-2"
>
<!-- 带有URL链接的源文件名称,支持预览 -->
<div v-if="getSourceLinks(getDisplayRetrieverResources(msg)).length > 0" class="flex flex-wrap gap-2">
<button
v-for="(file, linkIndex) in getSourceLinks(getDisplayRetrieverResources(msg))"
:key="`src-link-top-${linkIndex}-${file.url}`"
@click="openPreview(file)"
class="break-all rounded-lg border border-brand-200 bg-brand-50 px-2.5 py-1.5 text-xs text-brand-700 transition-colors hover:bg-brand-100"
>
{{ file.name }}
</button>
</div>
<details
v-if="getDisplayRetrieverResources(msg).length > 0"
class="rounded-xl border border-default bg-surface-soft/90 px-4 py-3"
:open="shouldExpandSourceDetails(msg)"
>
<summary class="cursor-pointer text-xs font-semibold uppercase tracking-wide text-secondary">
{{ $t('chat.sourceDocs') }} ({{ getDisplayRetrieverResources(msg).length }})
</summary>
<div class="mt-3 space-y-2">
<div
v-for="(doc, docIndex) in getDisplayRetrieverResources(msg)"
:key="`${doc.document_name || 'doc'}-${doc.segment_id || docIndex}`"
class="rounded-lg border border-default bg-surface p-3"
>
<div class="break-all text-sm font-semibold text-primary">{{ getSourceTitle(doc) }}</div>
<div v-if="getSourceMeta(doc)" class="mt-1 text-xs text-muted">{{ getSourceMeta(doc) }}</div>
<div v-if="getSourceBrief(doc)" class="mt-2 whitespace-pre-wrap break-all text-xs text-secondary">{{ getSourceBrief(doc) }}</div>
</div>
</div>
</details>
<details
v-if="msg.attribution_parts && msg.attribution_parts.length > 0"
class="rounded-xl border border-default bg-surface-soft/90 px-4 py-3"
open
>
<summary class="cursor-pointer text-xs font-semibold uppercase tracking-wide text-secondary">
{{ $t('chat.attributionParts') }}
</summary>
<ul class="mt-3 space-y-2">
<li
v-for="(part, partIndex) in msg.attribution_parts"
:key="`attr-${partIndex}`"
class="rounded-lg border border-default bg-surface p-3 text-xs text-secondary"
>
{{ part }}
</li>
</ul>
</details>
</div>
<div
v-if="msg.type !== 'leave-form'"
class="mt-1 flex items-center gap-1 opacity-0 transition-opacity group-hover:opacity-100"
:class="msg.role === 'user' ? 'justify-end text-muted' : 'justify-start text-muted'"
>
<button
type="button"
@click.stop="copyToClipboard(msg, index)"
class="rounded-md p-1.5 text-xs transition-colors hover-surface-soft"
:title="$t('chat.actions.copy')"
>
<Check v-if="copiedIndex === index" class="h-3.5 w-3.5 text-emerald-500" />
<Copy v-else class="h-3.5 w-3.5" />
</button>
<template v-if="msg.role === 'user'">
<button
type="button"
@click.stop="input = msg.content"
class="rounded-md p-1.5 text-xs transition-colors hover-surface-soft"
:title="$t('chat.actions.edit')"
>
<Edit2 class="h-3.5 w-3.5" />
</button>
<button
type="button"
@click.stop="handleSend(msg.content)"
class="rounded-md p-1.5 text-xs transition-colors hover-surface-soft"
:title="$t('chat.actions.resend')"
>
<RotateCw class="h-3.5 w-3.5" />
</button>
</template>
<template v-else>
<button
v-if="index === messages.length - 1 && !isThinking"
@click="regenerate"
class="rounded-md p-1.5 text-xs transition-colors hover-surface-soft"
:title="$t('chat.actions.regenerate')"
>
<RotateCw class="h-3.5 w-3.5" />
</button>
<button
v-if="showChatRating && !isThinking && !(msg as any).rated"
@click="handleOpenFeedback(index)"
class="rounded-md p-1.5 text-xs transition-colors hover-surface-soft"
:title="$t('chat.rate')"
>
<MessageSquareText class="h-3.5 w-3.5" />
</button>
</template>
</div>
</div>
</div>
</template>
<div v-if="shouldShowThinkingBubble" class="mx-auto flex w-full max-w-4xl justify-start">
<div class="flex items-center gap-3 rounded-2xl rounded-tl-md border border-default bg-surface/95 px-5 py-3 shadow-md">
<div class="flex gap-1">
<span class="h-2 w-2 animate-bounce rounded-full bg-brand-400"></span>
<span class="h-2 w-2 animate-bounce rounded-full bg-brand-400 delay-75"></span>
<span class="h-2 w-2 animate-bounce rounded-full bg-brand-400 delay-150"></span>
</div>
<span class="text-sm font-medium text-muted">{{ $t('chat.thinking') }}</span>
</div>
</div>
<div v-if="messages.length > 0" class="h-2 md:h-3"></div>
</div>
</main>
<footer class="safe-bottom sticky bottom-0 z-20 bg-transparent p-3 md:p-6">
<div class="relative mx-auto max-w-4xl">
<div class="flex flex-col rounded-2xl bg-surface p-2 shadow-[0_0_15px_rgba(0,0,0,0.05)] transition-all">
<textarea
v-model="input"
@keydown.enter.prevent="handleSend"
rows="1"
: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"
spellcheck="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"
: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"
class="flex items-center gap-1 rounded-lg border border-default px-3 py-1.5 text-xs font-medium text-secondary transition-colors hover:bg-surface-soft"
>
<Database class="h-3.5 w-3.5 text-brand-500" />
{{ getKbLabel(selectedKb) }} <ChevronDown class="h-3 w-3" />
</button>
<div
v-if="showKbDropdown"
class="absolute bottom-full left-0 mb-2 w-36 overflow-hidden rounded-xl border border-subtle bg-surface py-1 shadow-xl animate-fade-in"
>
<button
v-for="option in kbOptions"
:key="option"
@click="selectedKb = option; showKbDropdown = false"
class="flex w-full items-center justify-between px-3 py-2 text-xs text-secondary transition-colors hover:bg-surface-soft"
:class="{ 'font-bold text-brand-700': selectedKb === option }"
>
{{ getKbLabel(option) }}
<Check v-if="selectedKb === option" class="h-3.5 w-3.5" />
</button>
</div>
</div>
<button
@click="toggleBrowserPanel"
class="flex items-center gap-1 rounded-lg border border-default px-3 py-1.5 text-xs font-medium text-secondary transition-colors hover:bg-surface-soft"
>
<Globe class="h-3.5 w-3.5 text-brand-500" />
{{ browserPanelOpen ? $t('chat.collapseBrowser') : $t('chat.openBrowser') }}
</button>
</div>
<button
@click="handleSend"
: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 || 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'"
>
<Loader2 v-if="isUploadingAttachments" class="h-4 w-4 animate-spin" />
<Send v-else class="h-4 w-4" />
</button>
</div>
</div>
<div class="mt-3 text-center text-[11px] text-muted">
{{ $t('chat.disclaimer') }}
</div>
</div>
</footer>
</div>
<div
v-if="browserPanelOpen"
class="fixed inset-0 z-40 bg-overlay backdrop-blur-sm lg:hidden"
@click="browserPanelOpen = false"
></div>
<div
v-if="browserPanelOpen"
class="relative z-10 hidden w-2 shrink-0 cursor-col-resize bg-transparent lg:block"
@mousedown="startBrowserResize"
>
<div
class="absolute inset-y-0 left-1/2 w-px -translate-x-1/2 transition-colors"
:class="isBrowserResizing ? 'bg-brand-500' : 'bg-slate-200'"
></div>
</div>
<aside
v-if="browserPanelOpen"
class="fixed inset-y-0 right-0 z-50 flex w-full max-w-[100vw] flex-col border-l border-default bg-surface shadow-2xl sm:w-[420px] lg:static lg:z-0 lg:w-[420px] lg:shadow-none"
:style="browserPanelStyle"
>
<div class="flex items-center justify-between border-b border-default px-4 py-3">
<div class="flex items-center gap-2 text-sm font-semibold text-secondary">
<Globe class="h-4 w-4 text-brand-500" />
{{ $t('chat.browser') }}
</div>
<button
@click="browserPanelOpen = false"
class="rounded-md p-1.5 text-muted transition-colors hover-surface-soft hover:text-secondary"
:title="$t('chat.closeBrowser')"
>
<X class="h-4 w-4" />
</button>
</div>
<div class="flex items-center gap-2 border-b border-default px-3 py-3">
<input
v-model="browserDraftUrl"
type="text"
:placeholder="$t('chat.browserInputPlaceholder')"
class="flex-1 rounded-xl border border-default bg-surface-soft px-3 py-2 text-sm text-primary outline-none transition focus:border-brand-400 focus:bg-surface"
@keydown="handleBrowserUrlEnter"
/>
<button
@click="loadBrowserPage"
class="rounded-xl bg-brand-600 px-3 py-2 text-xs font-medium text-white transition-colors hover:bg-brand-500"
>
{{ $t('chat.open') }}
</button>
<button
@click="refreshBrowserPage"
class="rounded-xl border border-default p-2 text-muted transition-colors hover:bg-surface-soft hover:text-secondary"
:title="$t('chat.refresh')"
>
<RotateCw class="h-4 w-4" />
</button>
<button
@click="openBrowserInNewTab"
class="rounded-xl border border-default p-2 text-muted transition-colors hover:bg-surface-soft hover:text-secondary"
:title="$t('chat.openInNewTab')"
>
<ExternalLink class="h-4 w-4" />
</button>
</div>
<div class="min-h-0 flex-1 bg-slate-100">
<div
v-if="!browserCurrentUrl"
class="flex h-full flex-col items-center justify-center gap-3 px-8 text-center text-sm text-muted"
>
<Globe class="h-8 w-8 text-brand-500" />
<div>{{ $t('chat.browserHint1') }}</div>
<div class="text-xs">{{ $t('chat.browserHint2') }}</div>
</div>
<iframe
v-else
:key="browserFrameKey"
:src="browserCurrentUrl"
class="h-full w-full border-0 bg-surface"
allow="clipboard-read; clipboard-write"
></iframe>
</div>
</aside>
</div>
</template>
</ChatShell>
<FilePreviewModal
v-model="filePreviewVisible"
:file="previewFile"
:agent-id="currentAgentId"
:auth-headers="getAuthHeaders()"
/>
<GeneralFeedbackDialog
v-model="showGeneralFeedbackDialog"
:auth-headers="getAuthHeaders()"
source-page="chat"
:chat-log-id="currentGeneralFeedbackChatLogId"
@submitted="() => {
if (activeFeedbackMessageIndex !== null && messages[activeFeedbackMessageIndex]) {
(messages[activeFeedbackMessageIndex] as any).rated = true;
}
msg.success(t('chat.feedbackSubmitSuccess'));
showGeneralFeedbackDialog = false;
}"
/>
<div
v-if="showLeaveAgentDialog"
class="dialog-overlay z-[100] items-center"
@click.self="closeLeaveAgentDialog"
>
<div class="dialog-panel flex max-h-[80vh] max-w-2xl flex-col">
<div class="dialog-header">
<div>
<h3 class="section-title">{{ $t('chat.selectWho', { role: leaveUserSelectRole === 'agent' ? $t('chat.leaveAgent') : $t('chat.leaveApplicant') }) }}</h3>
<p class="section-desc mt-1">{{ $t('chat.oaDataConnected') }}</p>
</div>
<button type="button" class="btn-icon-ds" :aria-label="$t('admin.close')" @click="closeLeaveAgentDialog">
<X class="h-5 w-5" />
</button>
</div>
<div class="dialog-body space-y-4 border-t-0 pt-4">
<div class="relative shrink-0">
<input
v-model="leaveAgentKeyword"
@keydown.enter="handleAgentSearch"
type="text"
:placeholder="$t('chat.searchByNameOrEmployeeId')"
class="input-field pr-10"
/>
<button type="button" @click="handleAgentSearch" class="absolute inset-y-0 right-0 flex w-10 items-center justify-center text-muted hover:text-brand-600">
<Search class="h-4 w-4" />
</button>
</div>
<div class="max-h-[50vh] flex-1 space-y-3 overflow-y-auto pr-2 scrollbar-thin">
<div v-if="leaveAgentLoading && leaveAgentPage === 1" class="flex justify-center py-8">
<Loader2 class="h-6 w-6 animate-spin text-brand-500" />
</div>
<div v-else-if="leaveAgentOptions.length === 0" class="py-8 text-center text-sm text-muted">
{{ $t('chat.noData') }}
</div>
<template v-else>
<button
v-for="option in leaveAgentOptions"
:key="option.uid"
type="button"
class="flex w-full items-center justify-between rounded-2xl border border-default px-4 py-4 text-left transition hover:border-brand-300 hover:bg-brand-50/50"
@click="selectLeaveAgent(option)"
>
<div class="space-y-1">
<div class="text-sm font-semibold text-primary">{{ option.name }}</div>
<div class="text-xs text-muted">UID:{{ option.uid }}</div>
</div>
<div class="text-right text-xs text-muted">
<div>{{ $t('chat.employeeId') }}:{{ option.employeeId }}</div>
<div>{{ $t('chat.name') }}:{{ option.name }}</div>
</div>
</button>
<div v-if="leaveAgentHasMore" class="flex items-center justify-center space-x-6 py-4">
<button
@click="loadAllAgents"
:disabled="leaveAgentLoading"
class="text-xs text-muted hover:text-secondary disabled:opacity-50"
>
{{ $t('chat.loadAll') }}
</button>
<button
@click="loadMoreAgents"
:disabled="leaveAgentLoading"
class="text-xs text-brand-600 hover:text-brand-700 disabled:opacity-50"
>
{{ leaveAgentLoading ? $t('chat.loading') : $t('chat.loadMore') }}
</button>
</div>
<div v-else class="py-4 text-center text-xs text-muted">{{ $t('chat.noMoreData') }}</div>
</template>
</div>
</div>
</div>
</div>
<!-- OA 登录对话框 -->
<Teleport to="body">
<div
v-if="showOALoginDialog"
class="dialog-overlay z-[9999] items-center"
@click.self="cancelOALogin"
>
<div class="dialog-panel max-w-sm">
<div class="dialog-header dialog-header--compact justify-center border-0 pb-2">
<h3 class="section-title text-center">{{ $t('chat.loginOaSystem') }}</h3>
</div>
<div class="dialog-body space-y-4 border-t-0 pt-0">
<label class="block space-y-1.5">
<span class="label-field">{{ $t('chat.employeeId') }}</span>
<input
v-model="oaLoginEmployeeId"
type="text"
disabled
class="input-field bg-surface-soft"
/>
</label>
<label class="block space-y-1.5">
<span class="label-field">{{ $t('login.password') }}</span>
<input
v-model="oaLoginPassword"
type="password"
:placeholder="$t('chat.enterOaPassword')"
class="input-field"
@keyup.enter="confirmOALogin"
/>
</label>
</div>
<div class="dialog-footer">
<button type="button" @click="cancelOALogin" class="btn-secondary">
{{ $t('profile.cancel') }}
</button>
<button type="button" @click="confirmOALogin" class="btn-primary btn-sm">
{{ $t('chat.confirmLogin') }}
</button>
</div>
</div>
</div>
</Teleport>
<DeleteConfirmDialog
v-model="showDeleteConfirmDialog"
:message="deleteConfirmMessage"
@confirm="handleDeleteConfirm"
@cancel="closeDeleteConfirmDialog"
/>
</template>
<style scoped>
:deep(.chat-markdown details) {
margin-top: 1rem;
border: 1px solid rgb(226 232 240);
border-radius: 0.75rem;
background: rgb(248 250 252 / 0.9);
padding: 0.75rem 1rem;
}
:deep(.dark .chat-markdown details) {
border-color: rgb(51 65 85);
background: rgb(30 41 59 / 0.65);
}
:deep(.chat-markdown details summary) {
cursor: pointer;
font-size: 0.75rem;
font-weight: 600;
letter-spacing: 0.08em;
color: rgb(71 85 105);
list-style-position: inside;
}
:deep(.dark .chat-markdown details summary) {
color: rgb(203 213 225);
}
:deep(.chat-markdown details[open] summary) {
margin-bottom: 0.75rem;
}
:deep(.chat-markdown details pre) {
margin-bottom: 0;
}
:deep(.chat-markdown .leave-action-trigger) {
display: inline-flex;
align-items: center;
justify-content: center;
margin: 0 0.2rem;
padding: 0.1rem 0.6rem;
border-radius: 9999px;
border: 1px solid rgb(59 130 246 / 0.28);
background: rgb(239 246 255);
color: rgb(29 78 216);
font-weight: 600;
text-decoration: none;
cursor: pointer;
transition: all 0.2s ease;
}
:deep(.chat-markdown .leave-action-trigger:hover) {
background: rgb(219 234 254);
border-color: rgb(59 130 246 / 0.4);
}
:deep(.chat-markdown .leave-intent-highlight) {
display: inline-block;
margin: 0 0.2rem;
padding: 0.05rem 0.4rem;
border-radius: 0.5rem;
background: rgb(254 249 195);
color: rgb(161 98 7);
font-weight: 600;
}
:deep(.dark .chat-markdown .leave-action-trigger) {
border-color: rgb(96 165 250 / 0.35);
background: rgb(30 41 59);
color: rgb(147 197 253);
}
:deep(.dark .chat-markdown .leave-action-trigger:hover) {
background: rgb(30 64 175 / 0.25);
}
:deep(.dark .chat-markdown .leave-intent-highlight) {
background: rgb(113 63 18 / 0.45);
color: rgb(253 224 71);
}
</style>