Files
syops/frontend/src/views/ChatView.vue
T
hugo ee90b66ff7 Merge branch 'dev' into hugo
# Conflicts:
#	.env.dev
#	.env.shared
#	backend/app/api/chat.py
2026-06-08 16:11:42 +08:00

5571 lines
226 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, BookOpen, FileText, Play, Image as ImageIcon } 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, useAudioTranscription } from '../composables/useAudioTranscription';
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,
listAgentGuides,
} from '../api/user';
import {
createWorkspaceShippingTask,
createWorkspaceShippingTaskFromNotice,
listWorkspaceShippingTasks,
getWorkspaceShippingTask,
applyWorkspaceShippingInventoryMapping,
getShippingChatActions,
autoProgressWorkspaceShippingTask,
generateWorkspaceShippingExcel,
markWorkspaceShippingManualUploaded,
matchWorkspaceShippingInventory,
SHIPPING_NOTICE_AGENT_NAME,
submitWorkspaceShippingDecision,
uploadWorkspaceShippingInventory,
workspaceShippingExportUrl,
} from '../api/shippingNotice';
import { SHIPPING_INTERNAL_STATUS_TOKENS, SHIPPING_KNOWN_ACTION_ID_SET, SHIPPING_TERMINAL_CHECKPOINTS } from '../constants/shippingNoticeActions';
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 DEFAULT_KB = '企业知识库';
const ERP_KB = 'ERP知识库';
const ERP_KB_ENABLED_AGENT_NAMES = new Set(['固资管理']);
const selectedKb = ref(DEFAULT_KB);
const showKbDropdown = ref(false);
const kbMenuRef = ref<HTMLElement | null>(null);
const kbOptions = [DEFAULT_KB, ERP_KB];
const getKbLabel = (kb: string) => {
if (kb === DEFAULT_KB) return t('chat.kb.enterprise');
if (kb === ERP_KB) 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 sanitizeShippingConversationText = (text: string) => {
if (!isShippingNoticeAgent.value) return text;
let result = String(text || '')
.replace(/\btask_id\s*[::]/gi, '任务编号:')
.replace(/\btask_id\b/gi, '任务编号');
// Agent 有时会复述「(显示 "rpa_pending")」类后台标记
result = result.replace(/[((]\s*显示\s*[「"'`][^"'`]+[」"'`]\s*[))]/g, '');
result = result.replace(
/\b(process_status|pending_human_reason|review_status|checkpoint|match_status|human_options)\s*[::=]\s*[「"'`]?[\w.-]+[「"'`]?/gi,
'',
);
for (const token of SHIPPING_INTERNAL_STATUS_TOKENS) {
const quoted = new RegExp(`[「"'“”‘’]\\s*${token}\\s*[」"'“”‘’]`, 'gi');
result = result.replace(quoted, '');
result = result.replace(new RegExp(`\`${token}\``, 'gi'), '');
}
return result.replace(/\n{3,}/g, '\n\n').trim();
};
type ShippingActionVariant = 'primary' | 'secondary' | 'danger';
const extractShippingActionsDirective = (rawText: string): {
cleanedText: string;
buttons: Array<{ id: string; label: string; message: string; variant?: ShippingActionVariant }>;
} => {
const text = String(rawText || '');
const re = /<!--\s*HXOPS_SHIPPING_ACTIONS\s*:\s*([\s\S]*?)\s*-->/gi;
let cleaned = text;
const buttons: Array<{ id: string; label: string; message: string; variant?: ShippingActionVariant }> = [];
for (;;) {
const m = re.exec(text);
if (!m) break;
const body = String(m[1] || '').trim();
if (!body) continue;
try {
const parsed = JSON.parse(body);
if (Array.isArray(parsed)) {
for (const item of parsed) {
if (!item || typeof item !== 'object') continue;
const id = String((item as any).id || '').trim();
const label = String((item as any).label || '').trim();
const message = String((item as any).message || '').trim();
const variantRaw = String((item as any).variant || '').trim();
const variant: ShippingActionVariant | undefined = (variantRaw === 'primary' || variantRaw === 'secondary' || variantRaw === 'danger')
? (variantRaw as ShippingActionVariant)
: undefined;
if (!id || !label || !message) continue;
if (!SHIPPING_KNOWN_ACTION_ID_SET.has(id)) {
console.warn(`[shipping] unknown action id in HXOPS_SHIPPING_ACTIONS: ${id}`);
}
buttons.push({ id, label, message, variant });
}
}
} catch {
// ignore
}
}
cleaned = cleaned.replace(re, '').trim();
return { cleanedText: cleaned, buttons };
};
const renderMarkdown = (text: string) => {
if (!text) return '';
const stripped = isShippingNoticeAgent.value ? extractShippingActionsDirective(text).cleanedText : text;
const displayText = sanitizeShippingConversationText(stripReasoningPrelude(stripped));
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 getSourcePreviewExt = (file: { name?: string; url?: string; actualExt?: string }) => {
const actual = String(file?.actualExt || '').trim().toLowerCase();
if (actual) return actual;
const byName = getUrlExt(file?.name || '');
if (byName) return byName;
return getUrlExt(file?.url || '');
};
const isWeComMobileWebView = () => {
if (typeof navigator === 'undefined') return false;
const ua = navigator.userAgent || '';
return /wxwork/i.test(ua) && /mobile/i.test(ua);
};
const shouldBypassEmbeddedPreview = (file: { name?: string; url?: string; actualExt?: string }) => {
const ext = getSourcePreviewExt(file);
if (!isMobile.value || !isWeComMobileWebView()) return false;
if (!/^https?:\/\//i.test(file?.url || '')) return false;
return ['pdf', 'xls', 'xlsx'].includes(ext);
};
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);
if (shouldBypassEmbeddedPreview(resolvedFile)) {
window.location.href = resolvedFile.url;
return;
}
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, loadConversationState, sendMessage } = useChat();
const input = ref('');
const {
isRecording: isVoiceRecording,
isTranscribing: isVoiceTranscribing,
toggle: toggleVoiceInput,
cancel: cancelVoiceInput,
} = useAudioTranscription({
onResult: (text) => {
input.value = text;
},
onError: (key) => {
msg.warning(t(key));
},
});
// HTTPS 全站就绪后改为 true,恢复硅基 ASR 录音识别(useAudioTranscription)
const VOICE_INPUT_ENABLED = false;
const handleVoiceFeatureClick = () => {
if (!VOICE_INPUT_ENABLED) {
msg.info(t('chat.devComingSoon'));
return;
}
if (isThinking.value || isVoiceTranscribing.value) return;
const unavailable = getVoiceUnavailableErrorKey();
if (unavailable) {
msg.warning(t(unavailable));
return;
}
toggleVoiceInput(input.value);
};
watch(isThinking, (thinking) => {
if (thinking) cancelVoiceInput();
});
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 LEAVE_FEATURE_AGENT_NAMES = new Set(['通用入口', '人事规章']);
const canUseLeaveFeature = computed(() => LEAVE_FEATURE_AGENT_NAMES.has(String(currentAgent.value?.name || '').trim()));
type AgentSuggestedQuestionItem = {
question: string;
group: string;
};
const DEFAULT_AGENT_DESCRIPTIONS: Record<string, string> = {
人事规章: '我是你的7x24小时专属HR政策助手。无需手动检索文档,只需用日常说话的方式提问,我能从公司最新、最全的规章制度中,为你精准提取并总结答案。',
通用入口: '我是你的7x24小时专属AI数字人。无需手动检索文档,只需用日常说话的方式提问,我能从公司最新、最全的人事规章制度中,为你精准提取并总结答案。',
};
const DEFAULT_AGENT_SUGGESTED_QUESTIONS: Record<string, { style: 'plain' | 'styled'; questions: AgentSuggestedQuestionItem[] }> = {
人事规章: {
style: 'styled',
questions: [
{ question: '查询我有多少假期?', group: '考勤与休假' },
{ question: '如何进行请假?', group: '考勤与休假' },
{ question: '查公司法定节假日?', group: '考勤与休假' },
{ question: '新员工入职须知', group: '规章与日常' },
{ question: '怎么开具在职证明?', group: '规章与日常' },
{ question: '查公司薪酬及福利待遇怎么样?', group: '规章与日常' },
],
},
通用入口: {
style: 'plain',
questions: [
{ question: '新员工入职须知', group: '' },
{ question: '查询我有多少假期?', group: '' },
{ question: '如何进行请假?', group: '' },
{ question: '查公司法定节假日?', group: '' },
{ question: '查公司薪酬及福利待遇怎么样?', group: '' },
],
},
};
const normalizeAgentSuggestedQuestions = (value: unknown): AgentSuggestedQuestionItem[] => {
if (!Array.isArray(value)) return [];
return value
.map((item) => {
if (typeof item === 'string') {
const question = item.trim();
return question ? { question, group: '' } : null;
}
if (!item || typeof item !== 'object') return null;
const record = item as Record<string, unknown>;
const question = String(record.question || record.text || '').trim();
const group = String(record.group || '').trim();
return question ? { question, group } : null;
})
.filter((item): item is AgentSuggestedQuestionItem => !!item);
};
const currentAgentName = computed(() => String(currentAgent.value?.name || '').trim());
const canSelectErpKnowledgeBase = computed(() => ERP_KB_ENABLED_AGENT_NAMES.has(currentAgentName.value));
const availableKbOptions = computed(() => (
canSelectErpKnowledgeBase.value
? kbOptions
: kbOptions.filter((option) => option !== ERP_KB)
));
const kbDropdownDisabled = computed(() => availableKbOptions.value.length <= 1);
const toggleKbDropdown = () => {
if (kbDropdownDisabled.value) {
showKbDropdown.value = false;
return;
}
showKbDropdown.value = !showKbDropdown.value;
};
const selectKb = (option: string) => {
if (!availableKbOptions.value.includes(option)) return;
selectedKb.value = option;
showKbDropdown.value = false;
};
watch(canSelectErpKnowledgeBase, (allowed) => {
if (!allowed && selectedKb.value === ERP_KB) {
selectedKb.value = DEFAULT_KB;
}
if (!allowed) {
showKbDropdown.value = false;
}
}, { immediate: true });
const agentDescription = computed(() => {
const text = String(currentAgent.value?.description || '').trim();
return text || DEFAULT_AGENT_DESCRIPTIONS[currentAgentName.value] || '';
});
const suggestedQuestionsStyle = computed<'plain' | 'styled'>(() => {
const style = String(currentAgent.value?.extra_config?.suggested_questions_style || '').trim().toLowerCase();
if (style === 'styled') return 'styled';
if (style === 'plain') return 'plain';
return DEFAULT_AGENT_SUGGESTED_QUESTIONS[currentAgentName.value]?.style || 'plain';
});
const agentSuggestedQuestions = computed<AgentSuggestedQuestionItem[]>(() => {
const configured = normalizeAgentSuggestedQuestions(
currentAgent.value?.suggested_questions ?? currentAgent.value?.extra_config?.suggested_questions,
);
if (configured.length > 0) return configured;
return DEFAULT_AGENT_SUGGESTED_QUESTIONS[currentAgentName.value]?.questions || [];
});
const styledSuggestedQuestionSections = computed(() => {
const groups = new Map<string, AgentSuggestedQuestionItem[]>();
for (const item of agentSuggestedQuestions.value) {
const groupName = String(item.group || '').trim() || '常见问题';
if (!groups.has(groupName)) {
groups.set(groupName, []);
}
groups.get(groupName)?.push(item);
}
const iconTypes: Array<'calendar' | 'building'> = ['calendar', 'building'];
return Array.from(groups.entries()).map(([title, questions], index) => ({
title,
questions,
iconType: iconTypes[index % iconTypes.length],
}));
});
const agentGuides = ref<any[]>([]);
const showGuideModal = ref(false);
const activeGuideId = ref<number | null>(null);
const activeGuide = computed(() => agentGuides.value.find(g => g.id === activeGuideId.value));
const loadAgentGuides = async () => {
try {
const res = await listAgentGuides(currentAgentId.value || 0);
agentGuides.value = res || [];
} catch (error) {
console.error('Failed to load agent guides:', error);
agentGuides.value = [];
}
};
const showGuideSidebar = ref(true);
const openGuideModal = () => {
if (agentGuides.value.length > 0) {
activeGuideId.value = agentGuides.value[0].id;
showGuideModal.value = true;
showGuideSidebar.value = true; // 默认展开
}
};
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 shippingAutoFlowRequested = ref(false);
const filePickerRef = ref<HTMLInputElement | null>(null);
const shippingInventoryPickerRef = ref<HTMLInputElement | null>(null);
const pendingShippingUploadTaskId = ref('');
const shippingInventorySchemaPreviewCache = ref<Record<string, any>>({});
const attachmentMenuRef = ref<HTMLElement | null>(null);
const attachmentUrlInputRef = ref<HTMLInputElement | null>(null);
const showAttachmentMenu = ref(false);
const showAttachmentUrlPanel = ref(false);
const canSendMessage = computed(() => {
if (isThinking.value || isUploadingAttachments.value) return false;
if (input.value.trim()) return true;
if (isShippingNoticeAgent.value && attachments.value.length > 0) return true;
return 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();
if (!canUseLeaveFeature.value) {
msg.warning('请在“通用入口”或“人事规章”入口使用请假功能');
return;
}
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.status === 'running')
.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 = async (item: DisplayHistoryItem) => {
if (item.__runId) {
activateRun(item.__runId);
isSidebarOpen.value = false;
return;
}
const run = runs.value.find((r) => r.agentId === currentAgentId.value && r.conversationId === item.conversation_id);
if (run && run.status === 'running') {
activateRun(run.runId);
isSidebarOpen.value = false;
return;
}
await loadConversation(item.conversation_id, { force: true });
isSidebarOpen.value = false;
if (item.conversation_id.startsWith('pending:')) return;
const currentConvId = typeof route.query.conversation_id === 'string' ? route.query.conversation_id : '';
if (currentConvId === item.conversation_id) return;
const nextQuery: Record<string, any> = { ...route.query, conversation_id: item.conversation_id };
delete nextQuery.task_id;
delete nextQuery.preset;
await router.replace({ path: route.path, query: nextQuery });
};
// 预设问题:从路由 query.preset 中读取(如果有)
const presetQuestion = computed(() => {
const q = route.query.preset;
return typeof q === 'string' ? q : '';
});
const shippingTaskIdFromQuery = computed(() => {
const value = route.query.task_id;
return typeof value === 'string' ? value.trim() : '';
});
const findHistorySessionForShippingTask = (taskId: string) => {
const needle = taskId.trim().toUpperCase();
if (!needle) return null;
return history.value.find((item) => String(item.title || '').toUpperCase().includes(needle)) || null;
};
const resumeShippingTaskFromQuery = async () => {
const taskId = shippingTaskIdFromQuery.value;
if (!taskId || !isShippingNoticeAgent.value) return;
if (route.query.conversation_id) return;
if (presetQuestion.value) return;
const existing = findHistorySessionForShippingTask(taskId);
if (existing) {
await loadConversation(existing.conversation_id, { force: true });
return;
}
input.value = t('chat.shippingNoticeContinue', { taskId });
await handleSend();
};
const SHIPPING_TASK_ID_RE = /SN-\d{8}-[A-F0-9]{8}/i;
const isShippingNoticeAgent = computed(() => currentAgent.value?.name === SHIPPING_NOTICE_AGENT_NAME);
const resolvedShippingTaskId = ref('');
const shippingConversationTaskIdCache = ref<Record<string, string>>({});
const getActiveShippingTaskId = () =>
findLatestShippingTaskId(messages.value)
|| resolvedShippingTaskId.value
|| shippingTaskIdFromQuery.value
|| '';
type ShippingInventoryMappingFormPayload = {
taskId: string;
schema_preview: any;
order: { line_count: number; skus: string[] };
form: { sku: string; available_qty: string; reservation_id: string };
applying?: boolean;
};
const getShippingInventoryMappingPayload = (msg: any): ShippingInventoryMappingFormPayload | null => {
if (!msg || msg.type !== 'shipping-inventory-mapping') return null;
const payload = msg.payload;
if (!payload || typeof payload !== 'object') return null;
const taskId = String((payload as any).taskId || '').trim();
const schemaPreview = (payload as any).schema_preview;
const form = (payload as any).form;
if (!taskId || !schemaPreview || !form) return null;
return payload as ShippingInventoryMappingFormPayload;
};
const scrollToLastShippingInventoryMapping = async (): Promise<boolean> => {
const container = chatScrollContainer.value;
if (!container) return false;
let idx = -1;
for (let i = messages.value.length - 1; i >= 0; i -= 1) {
if ((messages.value[i] as any)?.type === 'shipping-inventory-mapping') {
idx = i;
break;
}
}
if (idx < 0) return false;
await nextTick();
await nextTick();
const el = container.querySelector(`[data-msg-index="${idx}"]`) as HTMLElement | null;
if (!el) return false;
el.scrollIntoView({ behavior: 'smooth', block: 'start' });
return true;
};
const openShippingInventoryMappingFormForTask = async (taskId: string): Promise<boolean> => {
const id = String(taskId || '').trim().toUpperCase();
if (!id) return false;
const existingIdx = (() => {
for (let i = messages.value.length - 1; i >= 0; i -= 1) {
const msg = messages.value[i] as any;
if (msg?.type !== 'shipping-inventory-mapping') continue;
const payload = getShippingInventoryMappingPayload(msg);
if (payload?.taskId?.trim().toUpperCase() === id) return i;
}
return -1;
})();
if (existingIdx >= 0) {
return scrollToLastShippingInventoryMapping();
}
const schemaPreview = shippingInventorySchemaPreviewCache.value[id];
if (!schemaPreview || typeof schemaPreview !== 'object') {
msg.warning('未找到表头预览,请重新上传库存文件后再点击“修改映射”');
return false;
}
const detail = await getWorkspaceShippingTask(id).catch(() => null);
const rawLines = Array.isArray((detail as any)?.lines) ? (detail as any).lines : [];
const pickSku = (line: any) =>
String(line?.sku || line?.SKU || line?.['AWS Sku'] || line?.['AWS SKU'] || '').trim();
const skus = [...new Set(rawLines.map(pickSku).filter(Boolean))].slice(0, 40);
const suggested = (schemaPreview as any)?.suggested_mapping || {};
const mappingMsg = {
role: 'assistant' as const,
type: 'shipping-inventory-mapping' as const,
content: [
'请用下拉框选择库存列映射(必须从表头中选择)。',
`任务编号:${id}`,
].filter(Boolean).join('\n'),
payload: {
taskId: id,
schema_preview: schemaPreview,
order: { line_count: rawLines.length, skus },
form: {
sku: String(suggested?.sku || '').trim(),
available_qty: String(suggested?.available_qty || '').trim(),
reservation_id: String(suggested?.reservation_id || '').trim(),
},
applying: false,
} as ShippingInventoryMappingFormPayload,
local_id: newLocalMessageId('shipping-assistant'),
local_only: true,
};
messages.value.push(mappingMsg);
await saveLocalMessageToBackend(mappingMsg);
await scrollToLastShippingInventoryMapping();
return true;
};
const findLatestShippingTaskId = (msgs: Array<{ content?: string }>) => {
for (let i = msgs.length - 1; i >= 0; i -= 1) {
const match = String(msgs[i]?.content || '').match(SHIPPING_TASK_ID_RE);
if (match?.[0]) return match[0].toUpperCase();
}
return '';
};
const shippingActionButtonClass = (variant?: string) => {
if (variant === 'primary') {
return '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';
}
if (variant === 'danger') {
return 'rounded-xl border border-rose-200 bg-rose-50 px-4 py-2 text-sm font-medium text-rose-700 transition hover:bg-rose-100 disabled:cursor-not-allowed disabled:opacity-60';
}
return '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';
};
type ShippingMenuAction = 'upload' | 'paste' | 'retry_rpa' | 'confirm' | 'reparse' | 'reject';
const SHIPPING_MENU_ACTION_SPECS: Record<
ShippingMenuAction,
{ id: string; label: string; message: string; variant: 'primary' | 'secondary' | 'danger' }
> = {
upload: { id: 'upload_inventory_file', label: '选择库存文件', message: '我要上传库存 Excel', variant: 'primary' },
paste: { id: 'paste_inventory_json', label: '粘贴库存', message: '我粘贴库存小表', variant: 'secondary' },
retry_rpa: { id: 'retry_rpa', label: '重试 RPA', message: '重试 RPA 导出库存', variant: 'secondary' },
confirm: { id: 'confirm', label: '确认', message: '确认', variant: 'primary' },
reparse: { id: 'reparse', label: '重新解析', message: '重新解析', variant: 'secondary' },
reject: { id: 'reject', label: '驳回', message: '驳回', variant: 'danger' },
};
const lastAssistantMessageContent = () => {
for (let i = messages.value.length - 1; i >= 0; i -= 1) {
const item = messages.value[i];
if (item?.role === 'assistant') return String(item.content || '');
}
return '';
};
const normalizeMenuDigit = (ch: string) => {
const full = '0123456789';
const idx = full.indexOf(ch);
return idx >= 0 ? idx : Number(ch);
};
const classifyShippingMenuLine = (desc: string): ShippingMenuAction | null => {
const normalized = String(desc || '').trim();
if (!normalized) return null;
if (/已确认/.test(normalized)) return null;
if (/(?:选择|上传).*(?:库存|excel|xlsx|xls|csv)/i.test(normalized)) return 'upload';
if (/粘贴|文本|小量|直接发/i.test(desc)) return 'paste';
if (/(?:重试|重新)\s*RPA|重试.*(?:导出|获取|拉取)|RPA.*(?:导出|获取|拉取).*重试/i.test(desc)) return 'retry_rpa';
if (/重新解析|重解析|reparse/i.test(desc)) return 'reparse';
if (/驳回|取消|reject/i.test(desc)) return 'reject';
if (/^(?:确认|confirm)\b/i.test(normalized)) return 'confirm';
return null;
};
const parseShippingMenuFromContext = (
ctx: string,
): Map<number, { action: ShippingMenuAction; desc: string }> => {
const map = new Map<number, { action: ShippingMenuAction; desc: string }>();
for (const line of String(ctx || '').split('\n')) {
const m = line.match(/^\s*([1-91-9])[\.、\)::]?\s*(.+)$/);
if (!m?.[1] || !m[2]) continue;
const num = normalizeMenuDigit(m[1]);
if (!Number.isFinite(num) || num < 1) continue;
const desc = String(m[2] || '').trim();
const action = classifyShippingMenuLine(desc);
if (action) map.set(num, { action, desc });
}
return map;
};
const resolveShippingNumericChoice = (text: string): ShippingMenuAction | null => {
const normalized = text.trim();
if (!/^[1-91-9](?:[\.\、\)::]?)$/.test(normalized)) return null;
const num = normalizeMenuDigit(normalized.charAt(0));
return parseShippingMenuFromContext(lastAssistantMessageContent()).get(num)?.action || null;
};
const resolveShippingActionButtons = (
content: string,
apiButtons: Array<{ id: string; label: string; message: string; variant?: string }> | null,
options?: { apiResolved?: boolean },
) => {
const directive = extractShippingActionsDirective(String(content || ''));
if (options?.apiResolved) {
return {
buttons: apiButtons || [],
cleanedText: directive.cleanedText,
fromDirective: false,
};
}
if (directive.buttons.length) {
return { buttons: directive.buttons, cleanedText: directive.cleanedText, fromDirective: true };
}
if (apiButtons?.length) {
return { buttons: apiButtons, cleanedText: directive.cleanedText, fromDirective: false };
}
return { buttons: [], cleanedText: directive.cleanedText, fromDirective: false };
};
const SHIPPING_DECISION_ACTIONS = new Set([
'confirm',
'confirm_inventory_mapping',
'correct_inventory_mapping',
'reparse_inventory',
'reject',
'reparse',
'rematch',
]);
const resolveShippingDecisionFromText = (text: string): string | null => {
const normalized = text.trim();
const direct: Record<string, string> = {
更正映射: 'correct_inventory_mapping',
更正列映射: 'correct_inventory_mapping',
重新上传库存: 'reparse_inventory',
重新上传: 'reparse_inventory',
驳回: 'reject',
取消: 'reject',
重新解析: 'reparse',
重新匹配: 'rematch',
};
if (direct[normalized]) return direct[normalized];
if (normalized === '确认') {
const ctx = lastAssistantMessageContent();
if (ctx.includes('字段对齐') || ctx.includes('field_alignment') || ctx.includes('库存字段对齐')) {
return 'confirm_inventory_mapping';
}
return 'confirm';
}
return null;
};
const executeShippingDecision = async (decision: string, displayText?: string) => {
const taskId = getActiveShippingTaskId();
if (!taskId) {
msg.warning(t('chat.shippingNoticeMissingTaskId'));
return false;
}
try {
const result =
decision === 'confirm_inventory_mapping'
? await autoProgressWorkspaceShippingTask(taskId)
: await submitWorkspaceShippingDecision(taskId, decision);
if (decision === 'correct_inventory_mapping') {
const preview = result?.data?.schema_preview;
const key = String(taskId || '').trim().toUpperCase();
if (key && preview && typeof preview === 'object') {
shippingInventorySchemaPreviewCache.value = { ...shippingInventorySchemaPreviewCache.value, [key]: preview };
}
}
const userText = (displayText || decision).trim();
const assistantContent = formatShippingDecisionAssistantMessage(decision, result, taskId);
const userMsg = {
role: 'user' as const,
type: 'text' as const,
content: `${userText}\n任务编号:${taskId}`,
local_id: newLocalMessageId('shipping-user'),
local_only: true,
};
const assistantMsg = {
role: 'assistant' as const,
type: 'text' as const,
content: assistantContent,
local_id: newLocalMessageId('shipping-assistant'),
local_only: true,
};
messages.value.push(userMsg, assistantMsg);
await saveLocalMessageToBackend(userMsg, userText);
await saveLocalMessageToBackend(assistantMsg, userText);
if (result.message && !isShippingNoticeAgent.value) {
msg.success(result.message);
}
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();
}
void refreshShippingActions();
if (decision === 'correct_inventory_mapping') {
await openShippingInventoryMappingFormForTask(taskId);
}
return true;
} catch (e: any) {
msg.warning(e?.message || t('chat.shippingNoticeUploadFailed'));
return false;
}
};
const formatShippingDecisionAssistantMessage = (
decision: string,
result: { message?: string; data?: Record<string, unknown>; checkpoint?: string },
taskId: string,
) => {
const lines: string[] = [result.message || t('chat.shippingNoticeDecisionDone')];
if (decision === 'correct_inventory_mapping') {
const preview = (result.data?.schema_preview || {}) as Record<string, any>;
const headers = Array.isArray(preview.headers) ? preview.headers.filter(Boolean) : [];
const suggested = (preview.suggested_mapping || {}) as Record<string, string>;
if (preview.header_row_index) {
lines.push('', `表头在第 ${preview.header_row_index} 行:${headers.join(' | ')}`);
} else if (headers.length) {
lines.push('', `当前表头:${headers.join(' | ')}`);
}
const mappingLines = [
suggested.sku ? `- sku → ${suggested.sku}` : null,
suggested.reservation_id ? `- reservation_id → ${suggested.reservation_id}` : null,
suggested.available_qty ? `- available_qty → ${suggested.available_qty}` : null,
].filter((line): line is string => Boolean(line));
if (mappingLines.length) {
lines.push('', '建议列映射:', ...mappingLines);
}
lines.push(
'',
'如需调整,请说明要改的列(例如:available_qty 改用 Qty Available)。',
'也可点击「选择库存文件」重新上传。',
);
} else if (decision === 'confirm_inventory_mapping') {
if (String(result.checkpoint || '').trim() === 'map_ok') {
lines.push('', '下一步:匹配库存与发货需求(match_inventory)。');
}
} else if (decision === 'reparse_inventory') {
lines.push('', '请重新上传或粘贴库存 Excel。');
}
lines.push('', `任务编号:${taskId}`);
return lines.join('\n');
};
const classifyShippingUploadFile = (file: File): 'inventory' | 'notice' => {
const ext = extractExt(file.name || '').toLowerCase();
if (['xlsx', 'xls', 'csv'].includes(ext)) return 'inventory';
return 'notice';
};
const pushShippingLocalUserMessage = async (text: string) => {
const content = String(text || '').trim();
if (!content) return;
const userMsg = {
role: 'user' as const,
type: 'text' as const,
content,
local_id: newLocalMessageId('shipping-user'),
local_only: true,
};
messages.value.push(userMsg);
await saveLocalMessageToBackend(userMsg, content);
};
const pushShippingLocalAssistantMessage = async (text: string) => {
const content = String(text || '').trim();
if (!content) return;
const assistantMsg = {
role: 'assistant' as const,
type: 'text' as const,
content,
local_id: newLocalMessageId('shipping-assistant'),
local_only: true,
};
messages.value.push(assistantMsg);
await saveLocalMessageToBackend(assistantMsg);
};
const buildShippingInventoryUploadPrompt = (
result: Record<string, any> | null | undefined,
fileName?: string,
) => {
const checkpoint = String(result?.checkpoint || '').trim();
const hasAlignment = Boolean(result?.data?.field_alignment && typeof result?.data?.field_alignment === 'object');
const suggestOk = Boolean(result?.data?.suggest_ok);
const prefix = fileName ? `我已上传库存文件《${fileName}》` : '我已上传库存文件';
if (checkpoint === 'map_infer') {
if (suggestOk) {
return `${prefix}。请继续处理库存列映射;如果系统已识别出完整映射,请直接应用映射,并展示字段对齐结果给我确认。`;
}
return `${prefix}。请继续解析库存列映射,并在拿到可用映射后展示字段对齐结果给我确认。`;
}
if (checkpoint === 'align_review' || hasAlignment) {
return `${prefix}。请展示库存字段对齐结果,并引导我确认或更正映射。`;
}
return `${prefix}。请继续处理库存导入,并告诉我下一步。`;
};
const continueShippingInventoryUploadWithDify = async (
taskId: string,
result: Record<string, any> | null | undefined,
fileName?: string,
) => {
const key = String(taskId || '').trim().toUpperCase();
const schemaPreview = result?.data?.schema_preview;
if (key && schemaPreview && typeof schemaPreview === 'object') {
shippingInventorySchemaPreviewCache.value = { ...shippingInventorySchemaPreviewCache.value, [key]: schemaPreview };
}
resolvedShippingTaskId.value = taskId;
await sendShippingMenuMessage(buildShippingInventoryUploadPrompt(result, fileName));
};
const normalizeShippingHeaderForDisplay = (raw: any): string => {
const text = String(raw ?? '').replace(/\s+/g, ' ').trim();
return text.replace(/ /g, '\u00A0');
};
const buildShippingFieldAlignmentText = (payload: any): string => {
const alignment = payload?.data?.field_alignment;
if (!alignment || typeof alignment !== 'object') return '';
const invCols = alignment.inventory_columns || {};
const mapping = invCols.mapping || {};
const rows: Array<[string, string]> = [
['sku', normalizeShippingHeaderForDisplay(mapping?.sku?.source_column) || '(未识别)'],
['reservation_id', normalizeShippingHeaderForDisplay(mapping?.reservation_id?.source_column) || '(未识别/可选)'],
['available_qty', normalizeShippingHeaderForDisplay(mapping?.available_qty?.source_column) || '(未识别)'],
];
const lines: string[] = [];
const matchRule = String(alignment.match_rule || '').trim();
if (matchRule) lines.push(`匹配规则:${matchRule}`);
lines.push('', '字段对齐表:', '', '|系统字段|库存列|', '|---|---|');
for (const [k, v] of rows) {
lines.push(`|${k}|${v}|`);
}
const warnings = Array.isArray(alignment.warnings) ? alignment.warnings.filter(Boolean) : [];
if (warnings.length) {
lines.push('', '提示:', ...warnings.map((w: any) => `- ${String(w)}`));
}
return lines.join('\n').trim();
};
const parseShippingColumnMappingFromText = (content: string): Record<string, string> | null => {
const raw = String(content || '').trim();
if (!raw) return null;
if (!/[→>=-]/.test(raw)) return null;
const lines = raw.split(/\r?\n/).map((s) => s.trim()).filter(Boolean);
const mapping: Record<string, string> = {};
const normalizeRight = (s: string) => String(s || '')
.replace(/[::]/g, '')
.replace(/列$/g, '')
.replace(/字段$/g, '')
.replace(/^\[|\]$/g, '')
.trim();
const toKey = (left: string) => {
const s = left.toLowerCase();
if (s.includes('reservation') || left.includes('预留') || left.includes('预定')) return 'reservation_id';
if (s.includes('qty') || s.includes('available') || left.includes('可用') || left.includes('数量')) return 'available_qty';
if (s.includes('sku') || left.includes('料号') || left.includes('物料')) return 'sku';
return '';
};
for (const line of lines) {
const m = line.match(/^\s*(.+?)\s*(?:→|->|=>|=|:|:)\s*(.+?)\s*$/);
if (!m) continue;
const left = m[1];
const right = m[2];
if (!left || !right) continue;
const key = toKey(left.trim());
if (!key) continue;
const col = normalizeRight(right);
if (!col) continue;
mapping[key] = col;
}
if (!mapping.sku || !mapping.available_qty) return null;
return mapping;
};
const handleShippingAutoUploadFile = async (file: File) => {
const kind = classifyShippingUploadFile(file);
if (kind === 'inventory') {
let taskId = getActiveShippingTaskId();
if (!taskId) {
const created = await createWorkspaceShippingTask({ source_type: 'manual' });
taskId = String(created.task_id || '').trim();
if (!taskId) {
msg.warning('自动创建发货任务失败');
return;
}
}
resolvedShippingTaskId.value = taskId;
const result = await uploadWorkspaceShippingInventory(taskId, file);
await continueShippingInventoryUploadWithDify(taskId, result as Record<string, any>, file.name);
return;
}
const result = await createWorkspaceShippingTaskFromNotice(file);
const taskId = String(result.task_id || '').trim();
if (taskId) resolvedShippingTaskId.value = taskId;
const hint = String(result.message || '').trim();
const status = String((result as any).status || '').trim();
const tail = status === 'needs_human' ? '请根据提示进行确认/驳回。' : '';
await pushShippingLocalAssistantMessage(
[
hint || `已处理发货通知附件:${file.name}`,
taskId ? `任务编号:${taskId}` : '',
tail,
].filter(Boolean).join('\n'),
);
void refreshShippingActions();
};
const shippingSuggestedPrompt = computed(() => {
const first = attachments.value.find((a) => a.kind === 'local') as
| Extract<PendingAttachment, { kind: 'local' }>
| undefined;
if (!first) return '';
const kind = classifyShippingUploadFile(first.file);
if (kind === 'inventory') return '上传库存并进入字段对齐';
return '解析发货通知并创建任务';
});
const useShippingSuggestedPrompt = () => {
const prompt = shippingSuggestedPrompt.value;
if (!prompt) return;
input.value = prompt;
shippingAutoFlowRequested.value = true;
};
const openShippingInventoryPicker = (): boolean => {
const taskId = getActiveShippingTaskId();
if (!taskId) {
msg.warning(t('chat.shippingNoticeMissingTaskId'));
return false;
}
pendingShippingUploadTaskId.value = taskId;
shippingInventoryPickerRef.value?.click();
return true;
};
const isShippingInventoryUploadIntent = (text: string) => {
const normalized = text.trim();
if (!normalized) return false;
const choice = resolveShippingNumericChoice(normalized);
if (choice === 'upload') return true;
return [
/^上传库存$/,
/上传库存文件/,
/手工上传/,
/选择库存/,
/upload.*inventory/i,
].some((pattern) => pattern.test(normalized));
};
const isShippingManualUploadIntent = (text: string) => {
const normalized = text.trim();
if (!normalized) return false;
return [
/已在货代系统手工上传/,
/已手工上传/,
/手工上传完成/,
/手动上传完成/,
/货代.*上传完成/,
].some((pattern) => pattern.test(normalized));
};
const executeShippingManualUpload = async (taskId: string, displayText?: string) => {
try {
const result = await markWorkspaceShippingManualUploaded(taskId);
const userText = (displayText || '已在货代系统手工上传完成').trim();
const assistantContent = [
String(result.message || '已标记为手工上传货代系统完成。').trim(),
`任务编号:${taskId}`,
].join('\n');
const userMsg = {
role: 'user' as const,
type: 'text' as const,
content: `${userText}\n任务编号:${taskId}`,
local_id: newLocalMessageId('shipping-user'),
local_only: true,
};
const assistantMsg = {
role: 'assistant' as const,
type: 'text' as const,
content: assistantContent,
local_id: newLocalMessageId('shipping-assistant'),
local_only: true,
shipping_actions_used: true,
};
messages.value.push(userMsg, assistantMsg);
messages.value.forEach((rawMsg) => {
const m = rawMsg as any;
if (m.role === 'assistant') {
m.shipping_actions = undefined;
}
});
await saveLocalMessageToBackend(userMsg, userText);
await saveLocalMessageToBackend(assistantMsg, userText);
void refreshShippingActions();
return true;
} catch (e: any) {
msg.warning(e?.message || '标记手工上传失败');
return false;
}
};
const isShippingGenerateExcelIntent = (text: string) => {
const normalized = text.trim();
if (!normalized) return false;
return [
/^生成发货excel$/i,
/^生成发货\s*excel$/i,
/生成发货.*excel/i,
/生成.*发货.*excel/i,
].some((pattern) => pattern.test(normalized));
};
const isShippingDownloadExcelIntent = (text: string) => {
const normalized = text.trim();
if (!normalized) return false;
return [
/^下载excel$/i,
/^下载发货excel$/i,
/下载.*excel/i,
].some((pattern) => pattern.test(normalized));
};
const downloadWorkspaceShippingExcelFile = async (taskId: string) => {
const url = workspaceShippingExportUrl(taskId);
const res = await fetch(url, { headers: getAuthHeaders() });
if (!res.ok) {
const body = await res.json().catch(() => ({}));
throw new Error((body as any)?.error || (body as any)?.message || res.statusText);
}
const disposition = res.headers.get('content-disposition');
const blob = await res.blob();
const objectUrl = URL.createObjectURL(blob);
const a = document.createElement('a');
a.href = objectUrl;
const rawName = disposition?.match(/filename\*?=(?:UTF-8'')?["']?([^;"'\n]+)/)?.[1] || `${taskId}.xlsx`;
try {
a.download = decodeURIComponent(rawName);
} catch {
a.download = rawName;
}
document.body.appendChild(a);
a.click();
document.body.removeChild(a);
URL.revokeObjectURL(objectUrl);
};
const sendShippingMenuMessage = async (message: string) => {
const taskId = getActiveShippingTaskId();
const text = taskId ? `${message}\n任务编号:${taskId}` : message;
await sendMessage(text, currentAgentId.value, selectedKb.value, []);
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 handleShippingMenuAction = async (action: { id?: string; message: string }, msg?: any) => {
if (isThinking.value) return;
if (action.id === 'refresh') {
await sendShippingMenuMessage(action.message || '刷新');
return;
}
if (action.id === 'download_excel') {
const taskId = getActiveShippingTaskId();
if (!taskId) {
msg.warning(t('chat.shippingNoticeMissingTaskId'));
return;
}
try {
await downloadWorkspaceShippingExcelFile(taskId);
} catch (e: any) {
msg.warning(e?.message || '下载 Excel 失败');
}
return;
}
if (action.id === 'generate_excel') {
if (msg?.shipping_actions_used) return;
if (msg) msg.shipping_actions_used = true;
const taskId = getActiveShippingTaskId();
if (!taskId) {
msg.warning(t('chat.shippingNoticeMissingTaskId'));
return;
}
try {
const result = await generateWorkspaceShippingExcel(taskId);
const userMsg = {
role: 'user' as const,
type: 'text' as const,
content: `${action.message || '生成发货 Excel'}(任务编号:${taskId})`,
local_id: newLocalMessageId('shipping-user'),
local_only: true,
};
const assistantMsg = {
role: 'assistant' as const,
type: 'text' as const,
content: [
String(result.message || '').trim(),
`任务编号:${taskId}`,
].filter(Boolean).join('\n'),
local_id: newLocalMessageId('shipping-assistant'),
local_only: true,
};
messages.value.push(userMsg, assistantMsg);
await saveLocalMessageToBackend(userMsg, action.message || '生成发货 Excel');
await saveLocalMessageToBackend(assistantMsg, action.message || '生成发货 Excel');
void refreshShippingActions();
} catch (e: any) {
msg.warning(e?.message || '生成发货 Excel 失败');
}
return;
}
if (action.id === 'edit_inventory_mapping') {
const taskId = getActiveShippingTaskId();
if (!taskId) {
msg.warning(t('chat.shippingNoticeMissingTaskId'));
return;
}
await openShippingInventoryMappingFormForTask(taskId);
return;
}
if (action.id === 'upload_inventory_file') {
openShippingInventoryPicker();
return;
}
if (action.id === 'match_inventory') {
if (msg?.shipping_actions_used) return;
if (msg) msg.shipping_actions_used = true;
const taskId = getActiveShippingTaskId();
if (!taskId) {
msg.warning(t('chat.shippingNoticeMissingTaskId'));
return;
}
try {
const result = await matchWorkspaceShippingInventory(taskId);
const userMsg = {
role: 'user' as const,
type: 'text' as const,
content: `${action.message || '匹配库存'}(任务编号:${taskId})`,
local_id: newLocalMessageId('shipping-user'),
local_only: true,
};
const assistantMsg = {
role: 'assistant' as const,
type: 'text' as const,
content: [
String(result.message || '').trim(),
`任务编号:${taskId}`,
].filter(Boolean).join('\n'),
local_id: newLocalMessageId('shipping-assistant'),
local_only: true,
};
messages.value.push(userMsg, assistantMsg);
await saveLocalMessageToBackend(userMsg, action.message || '匹配库存');
await saveLocalMessageToBackend(assistantMsg, action.message || '匹配库存');
void refreshShippingActions();
} catch (e: any) {
msg.warning(e?.message || '匹配库存失败');
}
return;
}
if (action.id === 'mark_manual_uploaded') {
if (msg?.shipping_actions_used) return;
if (msg) msg.shipping_actions_used = true;
const taskId = getActiveShippingTaskId();
if (!taskId) {
msg.warning(t('chat.shippingNoticeMissingTaskId'));
return;
}
await executeShippingManualUpload(taskId, action.message || '已在货代系统手工上传完成');
return;
}
if (action.id === 'paste_inventory_json') {
msg.info(t('chat.shippingNoticePasteHint'));
return;
}
if (action.id && SHIPPING_DECISION_ACTIONS.has(action.id)) {
if (msg?.shipping_actions_used) return;
if (msg) msg.shipping_actions_used = true;
await executeShippingDecision(action.id, action.message);
return;
}
if (msg?.shipping_actions_used) return;
if (msg) msg.shipping_actions_used = true;
await sendShippingMenuMessage(action.message);
};
let shippingActionsRequestSeq = 0;
const assistantMessageHasLaterUserReply = (msgs: Array<{ role?: string }>, index: number) =>
msgs.slice(index + 1).some((item) => item.role === 'user');
const refreshShippingActions = async () => {
if (!isShippingNoticeAgent.value) return;
const msgs = messages.value;
if (!msgs.length) return;
const cid = String(conversationId.value || '').trim();
const historyTaskId = (() => {
if (!cid) return '';
const session = history.value.find((item) => String(item.conversation_id || '') === cid);
const title = String((session as any)?.title || '');
const match = title.match(SHIPPING_TASK_ID_RE);
return match?.[0] ? match[0].toUpperCase() : '';
})();
let taskId = findLatestShippingTaskId(msgs)
|| resolvedShippingTaskId.value
|| shippingTaskIdFromQuery.value
|| historyTaskId;
if (!taskId && cid && !isThinking.value) {
const cached = shippingConversationTaskIdCache.value[cid];
if (cached) {
taskId = cached;
} else {
try {
const rows = await listWorkspaceShippingTasks({ limit: 500 });
const hit = rows.find((t) => String(t.conversation_id || '') === cid);
const taskNo = hit?.task_no ? String(hit.task_no).trim().toUpperCase() : '';
if (taskNo) {
shippingConversationTaskIdCache.value = { ...shippingConversationTaskIdCache.value, [cid]: taskNo };
taskId = taskNo;
}
} catch {
// fall back to content-based buttons
}
}
}
if (taskId) resolvedShippingTaskId.value = taskId;
let apiButtons: Array<{ id: string; label: string; message: string; variant?: string }> | null = null;
let apiCheckpoint: string | null = null;
let apiResolved = false;
if (taskId && !isThinking.value) {
const seq = ++shippingActionsRequestSeq;
try {
const data = await getShippingChatActions(taskId);
if (seq === shippingActionsRequestSeq) {
apiResolved = true;
apiCheckpoint = data.checkpoint ? String(data.checkpoint) : null;
apiButtons = data.action_buttons?.length ? data.action_buttons : null;
}
} catch {
// fall back to content-based buttons
}
}
if (apiResolved && apiCheckpoint && SHIPPING_TERMINAL_CHECKPOINTS.has(apiCheckpoint)) {
msgs.forEach((rawMsg) => {
const m = rawMsg as any;
if (m.role === 'assistant') {
m.shipping_actions = undefined;
}
});
return;
}
let lastOpenAssistantIndex = -1;
for (let i = msgs.length - 1; i >= 0; i -= 1) {
const item = msgs[i];
if (item?.role !== 'assistant') continue;
if (assistantMessageHasLaterUserReply(msgs, i)) continue;
lastOpenAssistantIndex = i;
break;
}
let lastAssistantIndex = -1;
for (let i = msgs.length - 1; i >= 0; i -= 1) {
const item = msgs[i];
if (item?.role === 'assistant') {
lastAssistantIndex = i;
break;
}
}
const targetAssistantIndex = lastOpenAssistantIndex >= 0 ? lastOpenAssistantIndex : lastAssistantIndex;
msgs.forEach((rawMsg, index) => {
const msg = rawMsg as any;
if (msg.role !== 'assistant' || msg.shipping_actions_used) {
return;
}
if (msg.type && !['text', undefined].includes(msg.type)) {
msg.shipping_actions = undefined;
return;
}
if (assistantMessageHasLaterUserReply(msgs, index) && index !== targetAssistantIndex) {
msg.shipping_actions = undefined;
return;
}
let buttons: Array<{ id: string; label: string; message: string; variant?: string }> = [];
if (index === targetAssistantIndex) {
const resolved = resolveShippingActionButtons(
String(msg.content || ''),
apiResolved ? (apiButtons ?? []) : null,
{ apiResolved },
);
if (resolved.fromDirective) {
msg.content = resolved.cleanedText;
}
buttons = resolved.buttons;
} else if (!apiResolved) {
const resolved = resolveShippingActionButtons(String(msg.content || ''), null);
if (resolved.fromDirective) {
msg.content = resolved.cleanedText;
}
buttons = resolved.buttons;
}
msg.shipping_actions = buttons.length ? buttons : undefined;
});
};
const shippingActionsWatchKey = computed(() => {
const msgs = messages.value;
const last = msgs.length ? (msgs[msgs.length - 1] as any) : null;
return [
String(conversationId.value || ''),
String(msgs.length),
String(last?.role || ''),
String(last?.content || '').slice(-120),
].join('|');
});
watch([shippingActionsWatchKey, isThinking, isShippingNoticeAgent, () => currentAgent.value?.name], () => {
void refreshShippingActions();
});
const handleShippingActionClick = async (msg: any, action: { id?: string; message: string }) => {
await handleShippingMenuAction(action, msg);
};
const handleShippingInventorySelected = async (event: Event) => {
const input = event.target as HTMLInputElement;
const file = input.files?.[0];
input.value = '';
const taskId = pendingShippingUploadTaskId.value;
pendingShippingUploadTaskId.value = '';
if (!file || !taskId) return;
try {
const result = await uploadWorkspaceShippingInventory(taskId, file);
await continueShippingInventoryUploadWithDify(taskId, result as Record<string, any>, file.name);
} catch (e: any) {
msg.warning(e?.message || t('chat.shippingNoticeUploadFailed'));
}
};
const applyShippingInventoryMappingForm = async (msgObj: any) => {
const payload = getShippingInventoryMappingPayload(msgObj);
if (!payload) return;
if (payload.applying) return;
const taskId = String(payload.taskId || '').trim();
if (!taskId) {
msg.warning('未找到任务编号');
return;
}
const mapping = {
sku: String(payload.form?.sku || '').trim(),
available_qty: String(payload.form?.available_qty || '').trim(),
reservation_id: String(payload.form?.reservation_id || '').trim(),
};
if (!mapping.sku || !mapping.available_qty) {
msg.warning('请先选择 SKU 列 与 可用数量列');
return;
}
if (!mapping.reservation_id) {
delete (mapping as any).reservation_id;
}
payload.applying = true;
try {
const result = await applyWorkspaceShippingInventoryMapping(taskId, mapping);
const alignmentText = buildShippingFieldAlignmentText(result);
const hint = alignmentText || String(result.message || '').trim();
await pushShippingLocalAssistantMessage(
[
'映射已应用并解析库存。',
`任务编号:${taskId}`,
hint,
].filter(Boolean).join('\n'),
);
resolvedShippingTaskId.value = taskId;
void refreshShippingActions();
} catch (e: any) {
msg.warning(e?.message || '应用映射失败');
} finally {
payload.applying = false;
await saveLocalMessageToBackend(msgObj);
}
};
const reuploadShippingInventoryFromMappingForm = (msgObj: any) => {
const payload = getShippingInventoryMappingPayload(msgObj);
if (!payload) return;
const taskId = String(payload.taskId || '').trim();
if (!taskId) return;
pendingShippingUploadTaskId.value = taskId;
shippingInventoryPickerRef.value?.click();
};
/**
* handleSend
* 用途:将输入框内容发送给当前 Agent
*/
const handleSend = async (textOrEvent?: string | Event) => {
const content = (typeof textOrEvent === 'string' ? textOrEvent : null) || input.value;
const trimmed = content.trim();
if ((shippingAutoFlowRequested.value || !trimmed) && isShippingNoticeAgent.value && attachments.value.length > 0 && !isThinking.value && !isUploadingAttachments.value) {
shippingAutoFlowRequested.value = false;
const localFiles = attachments.value.filter((a) => a.kind === 'local') as Array<Extract<PendingAttachment, { kind: 'local' }>>;
const first = localFiles[0];
if (!first) {
msg.warning('当前仅支持本地附件触发自动流程');
return;
}
const kind = classifyShippingUploadFile(first.file);
if (kind === 'inventory') {
attachments.value = [];
if (typeof textOrEvent !== 'string') input.value = '';
if (localFiles.length > 1) {
msg.warning('一次仅支持处理一个文件,将自动处理第一个');
}
try {
const prompt = trimmed || shippingSuggestedPrompt.value || '上传库存并进入字段对齐';
await pushShippingLocalUserMessage(prompt);
await handleShippingAutoUploadFile(first.file);
} catch (e: any) {
msg.warning(e?.message || '文件处理失败');
}
return;
}
if (!trimmed) {
const prompt = shippingSuggestedPrompt.value || '解析发货通知并创建任务';
let files: ChatUploadFileSpec[] = [];
if (attachmentPolicy.value.anyEnabled && attachments.value.length > 0) {
try {
files = await buildFileSpecsForSend();
} catch (e: any) {
msg.warning(`附件处理失败:${e?.message || 'unknown error'}`);
return;
}
}
if (typeof textOrEvent !== 'string') input.value = '';
attachments.value = [];
await sendMessage(prompt, 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();
}
return;
}
}
if (!trimmed || isThinking.value || isUploadingAttachments.value) return;
if (canUseLeaveFeature.value && isStrongLeaveIntent(content)) {
startLocalLeaveFlow(content);
return;
}
if (isShippingNoticeAgent.value) {
const menuChoice = resolveShippingNumericChoice(content);
if (menuChoice) {
if (typeof textOrEvent !== 'string') input.value = '';
if (menuChoice === 'upload') {
if (openShippingInventoryPicker()) return;
} else if (menuChoice === 'paste') {
msg.info(t('chat.shippingNoticePasteHint'));
return;
} else {
await sendShippingMenuMessage(SHIPPING_MENU_ACTION_SPECS[menuChoice].message);
return;
}
}
const shippingDecision = resolveShippingDecisionFromText(content);
if (shippingDecision) {
if (typeof textOrEvent !== 'string') input.value = '';
if (await executeShippingDecision(shippingDecision, content.trim())) return;
}
const lastAssistant = lastAssistantMessageContent();
if (lastAssistant.includes('schema_preview') || lastAssistant.includes('列映射') || lastAssistant.includes('字段对齐')) {
const mapping = parseShippingColumnMappingFromText(content);
if (mapping) {
const taskId = getActiveShippingTaskId();
if (!taskId) {
msg.warning('未找到任务编号,请先上传库存文件');
return;
}
resolvedShippingTaskId.value = taskId;
if (typeof textOrEvent !== 'string') input.value = '';
attachments.value = [];
await pushShippingLocalUserMessage(content.trim());
try {
const result = await applyWorkspaceShippingInventoryMapping(taskId, mapping);
const alignmentText = buildShippingFieldAlignmentText(result);
const hint = alignmentText || String(result.message || '').trim();
await pushShippingLocalAssistantMessage(
[
`映射已应用:${Object.entries(mapping).map(([k, v]) => `${k}=${v}`).join(',')}`,
`任务编号:${taskId}`,
hint,
].filter(Boolean).join('\n'),
);
void refreshShippingActions();
} catch (e: any) {
msg.warning(e?.message || '应用映射失败');
}
return;
}
}
if (isShippingManualUploadIntent(content)) {
const taskId = getActiveShippingTaskId();
if (!taskId) {
msg.warning('未找到任务编号,请先完成前面的步骤');
return;
}
resolvedShippingTaskId.value = taskId;
if (typeof textOrEvent !== 'string') input.value = '';
attachments.value = [];
await executeShippingManualUpload(taskId, content.trim());
return;
}
if (isShippingInventoryUploadIntent(content)) {
if (typeof textOrEvent !== 'string') input.value = '';
if (openShippingInventoryPicker()) return;
}
if (isShippingGenerateExcelIntent(content)) {
const taskId = getActiveShippingTaskId();
if (!taskId) {
msg.warning('未找到任务编号,请先完成解析与库存匹配');
return;
}
resolvedShippingTaskId.value = taskId;
if (typeof textOrEvent !== 'string') input.value = '';
attachments.value = [];
await pushShippingLocalUserMessage(content.trim());
try {
const result = await generateWorkspaceShippingExcel(taskId);
await pushShippingLocalAssistantMessage(
[
String(result.message || '').trim() || '已生成发货 Excel',
`任务编号:${taskId}`,
].filter(Boolean).join('\n'),
);
void refreshShippingActions();
} catch (e: any) {
msg.warning(e?.message || '生成发货 Excel 失败');
}
return;
}
if (isShippingDownloadExcelIntent(content)) {
const taskId = getActiveShippingTaskId();
if (!taskId) {
msg.warning('未找到任务编号,请先完成解析与库存匹配');
return;
}
resolvedShippingTaskId.value = taskId;
if (typeof textOrEvent !== 'string') input.value = '';
attachments.value = [];
await pushShippingLocalUserMessage(content.trim());
try {
await downloadWorkspaceShippingExcelFile(taskId);
} catch (e: any) {
msg.warning(e?.message || '下载 Excel 失败');
}
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);
runs.value = runs.value.filter((r) => !(r.agentId === currentAgentId.value && r.conversationId === id));
if (conversationId.value === id) {
startNewChat();
}
} catch (e) {
console.error('Failed to delete history item', e);
}
});
};
const loadConversation = async (id: string, options?: { force?: boolean }) => {
const force = options?.force ?? false;
if (!force && conversationId.value === id && !activeRunId.value && messages.value.length > 0) {
return;
}
try {
if (conversationId.value !== id) {
resolvedShippingTaskId.value = '';
}
const loaded = await listChatMessages(id, currentAgentId.value);
loadConversationState(id, Array.isArray(loaded) ? loaded : []);
if (!loaded?.length) {
msg.warning(t('chat.historyEmpty'));
}
void refreshShippingActions();
} catch (e) {
console.error('Failed to load conversation', e);
if (isShippingNoticeAgent.value && shippingTaskIdFromQuery.value && !isThinking.value) {
createNewChatView();
void router.replace({ path: route.path, query: { task_id: shippingTaskIdFromQuery.value } });
input.value = t('chat.shippingNoticeContinue', { taskId: shippingTaskIdFromQuery.value });
await handleSend();
return;
}
msg.warning(t('chat.historyLoadFailed'));
}
};
const startNewChat = () => {
createNewChatView();
void router.replace({ path: route.path, query: {} });
};
const loadAgent = async () => {
try {
currentAgent.value = await getUserAgent(currentAgentId.value);
await loadAgentGuides();
} 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') };
agentGuides.value = [];
}
};
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();
cancelVoiceInput();
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, { force: true });
if (syncToken !== routeSyncToken) return;
} else if (shippingTaskIdFromQuery.value) {
await resumeShippingTaskFromQuery();
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, route.query.task_id],
async ([nextAgentId, nextConversationId, nextPreset, nextTaskId], [prevAgentId, prevConversationId, prevPreset, prevTaskId]) => {
if (
nextAgentId === prevAgentId
&& nextConversationId === prevConversationId
&& nextPreset === prevPreset
&& nextTaskId === prevTaskId
) {
return;
}
if (
nextAgentId === prevAgentId
&& nextPreset === prevPreset
&& nextTaskId === prevTaskId
&& nextConversationId !== prevConversationId
) {
if (typeof nextConversationId === 'string' && nextConversationId) {
await loadConversation(nextConversationId, { force: true });
} else {
createNewChatView();
}
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">
<div class="flex items-center gap-2">
<span class="font-bold text-primary truncate">{{ currentAgent?.name || 'AI' }}</span>
<button
v-if="agentGuides.length > 0"
@click="openGuideModal"
class="flex items-center gap-1.5 px-3 py-1.5 text-xs font-bold text-brand-700 bg-brand-100 border border-brand-300 rounded-lg hover:bg-brand-200 hover:border-brand-400 transition-all shadow-sm"
>
<BookOpen class="w-4 h-4" />
学习之窗
</button>
</div>
<span v-if="agentDescription" class="block text-[11px] text-muted mt-1 truncate cursor-help">
{{ agentDescription }}
</span>
<!-- 气泡提示 -->
<div v-if="agentDescription" 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">
{{ agentDescription }}
</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-10 min-w-[2.5rem] items-center justify-center rounded-full bg-brand-600 px-3 text-sm font-bold text-white shadow-sm shadow-brand-500/20 transition-colors hover:bg-brand-700">
退出
</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>
<button
v-if="agentGuides.length > 0"
@click="openGuideModal"
class="flex items-center gap-1.5 px-3 py-1.5 text-xs font-bold text-brand-700 bg-brand-100 border border-brand-300 rounded-lg hover:bg-brand-200 hover:border-brand-400 transition-all shadow-sm ml-1"
>
<BookOpen class="w-4 h-4" />
学习之窗
</button>
</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 min-h-0 w-full flex-col items-center px-4 pt-2 pb-2 md:pb-3">
<template v-if="suggestedQuestionsStyle === 'styled' && styledSuggestedQuestionSections.length > 0">
<div class="mb-6 mt-2 flex h-16 w-16 shrink-0 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">
{{ currentAgent?.name === '人事规章' ? 'HR' : 'AI' }}
</div>
<h2 class="mb-6 shrink-0 text-center text-xl font-bold text-primary md:text-2xl">
{{ currentAgent?.name === '人事规章' ? '你好,我是人事规章 AI 助手' : t('chat.welcomeTitle') }}
</h2>
<div class="w-full flex-1 min-h-0 overflow-y-auto pb-2">
<div class="mx-auto grid w-full max-w-4xl grid-cols-1 gap-4 md:grid-cols-2">
<div
v-for="(section, sectionIndex) in styledSuggestedQuestionSections"
:key="`${section.title}-${sectionIndex}`"
class="w-full 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 v-if="section.iconType === 'calendar'" class="h-4 w-4" />
<Building v-else class="h-4 w-4" />
</div>
<h3 class="font-semibold text-secondary">{{ section.title }}</h3>
</div>
<div class="space-y-2">
<button
v-for="(item, questionIndex) in section.questions"
:key="`${section.title}-${questionIndex}`"
@click="handleSend(item.question)"
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"
>
"{{ item.question }}"
</button>
</div>
</div>
</div>
</div>
</template>
<template v-else-if="agentSuggestedQuestions.length > 0">
<div class="mb-6 mt-2 flex h-16 w-16 shrink-0 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="mb-6 shrink-0 text-center text-xl font-medium text-primary md:text-2xl">{{ $t('chat.welcomeTitle') }}</h2>
<div class="w-full flex-1 min-h-0 overflow-y-auto pb-2">
<div class="flex flex-wrap justify-center gap-3 w-full max-w-3xl mx-auto mt-2">
<button
v-for="(item, index) in agentSuggestedQuestions"
:key="`${item.question}-${index}`"
@click="handleSend(item.question)"
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"
>
"{{ item.question }}"
</button>
</div>
</div>
</template>
<template v-else>
<div class="mb-6 mt-2 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-if="msg.type === 'shipping-inventory-mapping' && getShippingInventoryMappingPayload(msg)" class="space-y-4">
<div class="text-sm font-medium text-secondary whitespace-pre-wrap">{{ msg.content }}</div>
<div class="rounded-2xl border border-default bg-surface-soft/90 p-4 space-y-4">
<div class="space-y-2">
<div class="text-xs font-bold uppercase tracking-wider text-muted">{{ $t('chat.shippingNoticeMapping.inventoryHeaders') }}</div>
<div class="text-xs text-muted">
{{ $t('chat.shippingNoticeMapping.headerRow', { row: getShippingInventoryMappingPayload(msg)!.schema_preview.header_row_index || 1 }) }}
</div>
<div class="flex flex-wrap gap-2">
<span
v-for="h in (getShippingInventoryMappingPayload(msg)!.schema_preview.headers || [])"
:key="`inv-h-${h}`"
class="rounded-full border border-default bg-surface px-3 py-1 text-xs text-secondary"
>{{ normalizeShippingHeaderForDisplay(h) || $t('chat.shippingNoticeMapping.empty') }}</span>
</div>
<div
v-if="Array.isArray(getShippingInventoryMappingPayload(msg)!.schema_preview.sample_rows) && getShippingInventoryMappingPayload(msg)!.schema_preview.sample_rows.length"
class="text-xs text-muted whitespace-pre-wrap"
>
{{ $t('chat.shippingNoticeMapping.sample') }}:{{ (getShippingInventoryMappingPayload(msg)!.schema_preview.sample_rows[0] || []).join(' | ') }}
</div>
</div>
<div class="space-y-2">
<div class="text-xs font-bold uppercase tracking-wider text-muted">{{ $t('chat.shippingNoticeMapping.orderDetails') }}</div>
<div class="text-xs text-muted">
{{ $t('chat.shippingNoticeMapping.orderRowCount', { count: getShippingInventoryMappingPayload(msg)!.order.line_count }) }};{{ $t('chat.shippingNoticeMapping.orderSkuPreview', { count: getShippingInventoryMappingPayload(msg)!.order.skus.length, skus: getShippingInventoryMappingPayload(msg)!.order.skus.join(',') || $t('chat.shippingNoticeMapping.unrecognized') }) }}
</div>
</div>
<div class="grid gap-4 md:grid-cols-2">
<label class="space-y-1.5">
<span class="text-xs font-semibold text-muted">{{ $t('chat.shippingNoticeMapping.skuColumnRequired') }}</span>
<select
v-model="getShippingInventoryMappingPayload(msg)!.form.sku"
class="w-full rounded-xl border border-default px-3 py-2 text-sm text-secondary outline-none transition focus:border-blue-400"
:disabled="getShippingInventoryMappingPayload(msg)!.applying"
>
<option value="" disabled>{{ $t('chat.shippingNoticeMapping.selectHeader') }}</option>
<option v-for="h in (getShippingInventoryMappingPayload(msg)!.schema_preview.headers || [])" :key="`sku-${h}`" :value="h">{{ normalizeShippingHeaderForDisplay(h) }}</option>
</select>
</label>
<label class="space-y-1.5">
<span class="text-xs font-semibold text-muted">{{ $t('chat.shippingNoticeMapping.availableQtyColumnRequired') }}</span>
<select
v-model="getShippingInventoryMappingPayload(msg)!.form.available_qty"
class="w-full rounded-xl border border-default px-3 py-2 text-sm text-secondary outline-none transition focus:border-blue-400"
:disabled="getShippingInventoryMappingPayload(msg)!.applying"
>
<option value="" disabled>{{ $t('chat.shippingNoticeMapping.selectHeader') }}</option>
<option v-for="h in (getShippingInventoryMappingPayload(msg)!.schema_preview.headers || [])" :key="`qty-${h}`" :value="h">{{ normalizeShippingHeaderForDisplay(h) }}</option>
</select>
</label>
<label class="space-y-1.5 md:col-span-2">
<span class="text-xs font-semibold text-muted">{{ $t('chat.shippingNoticeMapping.reservationIdColumnOptional') }}</span>
<select
v-model="getShippingInventoryMappingPayload(msg)!.form.reservation_id"
class="w-full rounded-xl border border-default px-3 py-2 text-sm text-secondary outline-none transition focus:border-blue-400"
:disabled="getShippingInventoryMappingPayload(msg)!.applying"
>
<option value="">{{ $t('chat.shippingNoticeMapping.reservationIdNotUsed') }}</option>
<option v-for="h in (getShippingInventoryMappingPayload(msg)!.schema_preview.headers || [])" :key="`rid-${h}`" :value="h">{{ normalizeShippingHeaderForDisplay(h) }}</option>
</select>
</label>
</div>
<div class="flex justify-end gap-3">
<button
type="button"
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"
:disabled="getShippingInventoryMappingPayload(msg)!.applying"
@click="reuploadShippingInventoryFromMappingForm(msg)"
>
{{ $t('chat.shippingNoticeMapping.reupload') }}
</button>
<button
type="button"
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"
:disabled="getShippingInventoryMappingPayload(msg)!.applying"
@click="applyShippingInventoryMappingForm(msg)"
>
{{ getShippingInventoryMappingPayload(msg)!.applying ? $t('chat.shippingNoticeMapping.applying') : $t('chat.shippingNoticeMapping.applyAndParse') }}
</button>
</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 prose-table:w-full prose-table:border-collapse prose-th:border prose-th:border-slate-200 prose-th:bg-slate-50 prose-th:px-3 prose-th:py-2 prose-th:text-left prose-td:border prose-td:border-slate-200 prose-td:px-3 prose-td:py-2"
@click="handleChatMarkdownClick"
v-html="renderMarkdown(msg.content)"
></div>
<div
v-if="isShippingNoticeAgent && msg.shipping_actions?.length"
class="mt-4 space-y-2 border-t border-default pt-4"
>
<div class="text-xs font-medium text-muted">{{ $t('chat.shippingNoticeActionsHint') }}</div>
<div class="flex flex-wrap gap-2">
<button
v-for="(action, actionIndex) in msg.shipping_actions"
:key="`${msg.local_id || index}-shipping-action-${action.id}-${actionIndex}`"
type="button"
:class="shippingActionButtonClass(action.variant)"
:disabled="isThinking || msg.shipping_actions_used"
@click="handleShippingActionClick(msg, action)"
>
{{ action.label }}
</button>
</div>
</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="isVoiceTranscribing ? $t('chat.voiceTranscribing') : isVoiceRecording ? $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 || isVoiceTranscribing"
spellcheck="false"
autocorrect="off"
autocapitalize="off"
></textarea>
<input
ref="shippingInventoryPickerRef"
type="file"
class="hidden"
accept=".xlsx,.xls,.csv,application/vnd.openxmlformats-officedocument.spreadsheetml.sheet,application/vnd.ms-excel,text/csv"
@change="handleShippingInventorySelected"
/>
<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
v-if="isShippingNoticeAgent && attachments.length > 0"
class="flex flex-wrap items-center gap-2 px-3 pb-1 text-xs text-muted"
>
<button
type="button"
class="rounded-full border border-default bg-surface-soft px-3 py-1 font-medium text-secondary transition-colors hover:bg-surface-soft/70"
@click="useShippingSuggestedPrompt"
>
{{ shippingSuggestedPrompt || '推荐问题' }}
</button>
<span>点发送开始处理</span>
</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 || isVoiceTranscribing"
:title="isVoiceRecording ? $t('chat.voiceStop') : isVoiceTranscribing ? $t('chat.voiceTranscribing') : $t('chat.voiceFeature')"
class="transition-colors disabled:cursor-not-allowed disabled:opacity-50"
:class="isVoiceRecording ? 'text-red-500 animate-pulse' : isVoiceTranscribing ? 'text-brand-500' : 'text-muted hover:text-brand-600'"
>
<Loader2 v-if="isVoiceTranscribing" class="h-5 w-5 animate-spin" />
<Mic v-else 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="flex h-9 w-9 items-center justify-center rounded-lg 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="toggleKbDropdown"
:disabled="kbDropdownDisabled"
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 disabled:cursor-not-allowed disabled:opacity-60"
>
<Database class="h-3.5 w-3.5 text-brand-500" />
{{ getKbLabel(selectedKb) }} <ChevronDown class="h-3 w-3" />
</button>
<div
v-if="showKbDropdown && !kbDropdownDisabled"
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 availableKbOptions"
:key="option"
@click="selectKb(option)"
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="!canSendMessage"
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="!canSendMessage
? '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"
/>
<Teleport to="body">
<!-- 学习之窗 Modal -->
<div v-if="showGuideModal" class="fixed inset-0 z-[9999] flex items-center justify-center p-4 bg-black/50 backdrop-blur-sm">
<div class="bg-surface rounded-2xl shadow-xl w-full max-w-4xl overflow-hidden flex flex-col h-[85vh]">
<div class="px-6 py-4 border-b border-default flex justify-between items-center bg-surface shrink-0">
<h3 class="text-lg font-bold text-primary flex items-center gap-2">
<BookOpen class="w-5 h-5 text-brand-600" />
{{ currentAgent?.name }} - 学习之窗
</h3>
<div class="flex items-center gap-3">
<button @click="showGuideSidebar = !showGuideSidebar" class="flex items-center gap-1.5 px-3 py-1.5 text-sm font-medium text-brand-600 hover:text-brand-700 hover:bg-brand-50 rounded-lg transition-colors border border-transparent hover:border-brand-100">
<component :is="showGuideSidebar ? PanelLeftClose : PanelLeftOpen" class="w-4 h-4" />
{{ showGuideSidebar ? '收起目录' : '展开目录' }}
</button>
<div class="w-px h-5 bg-default"></div>
<button @click="showGuideModal = false" class="text-muted hover:text-primary transition-colors p-1 rounded-lg hover:bg-surface-soft">
<X class="w-6 h-6" />
</button>
</div>
</div>
<div class="flex-1 overflow-hidden flex min-h-0 relative">
<div
class="absolute md:relative z-10 h-full w-64 border-r border-default overflow-y-auto bg-surface-soft p-4 space-y-2 shrink-0 transition-transform duration-300 shadow-xl md:shadow-none"
:class="showGuideSidebar ? 'translate-x-0' : '-translate-x-full absolute'"
v-show="showGuideSidebar"
>
<button
v-for="guide in agentGuides"
:key="guide.id"
@click="activeGuideId = guide.id"
class="w-full text-left px-4 py-3 rounded-xl transition-all border"
:class="activeGuideId === guide.id ? 'bg-brand-50 border-brand-200 text-brand-700 shadow-sm' : 'bg-surface border-transparent hover:border-default hover:shadow-sm'"
>
<div class="flex items-center gap-2 mb-1">
<component :is="guide.file_type === 'video' ? Play : (guide.file_type === 'pdf' ? FileText : ImageIcon)" class="w-4 h-4 shrink-0" />
<span class="font-medium text-sm truncate">{{ guide.file_name }}</span>
</div>
<p v-if="guide.remark" class="text-xs opacity-70 truncate" :class="activeGuideId === guide.id ? 'text-brand-600' : 'text-muted'">{{ guide.remark }}</p>
</button>
</div>
<div class="flex-1 bg-[#ebedf0] dark:bg-gray-900 flex items-center justify-center relative overflow-hidden">
<template v-if="activeGuide">
<video
v-if="activeGuide.file_type === 'video'"
:key="'video-' + activeGuide.id"
:src="activeGuide.file_url || activeGuide.file_path"
controls
class="w-full h-full object-contain bg-black"
></video>
<iframe
v-else-if="activeGuide.file_type === 'pdf'"
:key="'pdf-' + activeGuide.id"
:src="activeGuide.file_url || activeGuide.file_path"
class="w-full h-full border-none bg-white"
></iframe>
<img
v-else
:key="'img-' + activeGuide.id"
:src="activeGuide.file_url || activeGuide.file_path"
class="max-w-full max-h-full object-contain"
/>
</template>
<div v-else class="text-muted flex flex-col items-center gap-3">
<BookOpen class="w-12 h-12 opacity-20" />
<p class="text-sm">请选择左侧指南进行查阅</p>
</div>
</div>
</div>
</div>
</div>
</Teleport>
</template>
<style scoped>
:deep(.chat-markdown table) {
width: 100%;
border-collapse: collapse;
margin: 0.75rem 0;
font-size: 0.875rem;
}
:deep(.chat-markdown th),
:deep(.chat-markdown td) {
border: 1px solid rgb(226 232 240);
padding: 0.5rem 0.75rem;
text-align: left;
vertical-align: top;
}
:deep(.chat-markdown th) {
background: rgb(248 250 252);
font-weight: 600;
}
:deep(.dark .chat-markdown th),
:deep(.dark .chat-markdown td) {
border-color: rgb(51 65 85);
}
:deep(.dark .chat-markdown th) {
background: rgb(30 41 59);
}
: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>