| 12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976 |
- <template>
- <a-modal
- :visible="props.visible"
- @cancel="emit('close')"
- :width="isFullscreen ? '100vw' : 1400"
- :footer="null"
- destroyOnClose
- :class="['ai-assistant-modal', { fullscreen: isFullscreen }]"
- >
- <template #title>
- <div :class="['draggable-title', { 'no-drag': isFullscreen }]" @mousedown="onDragStart">"通安智风"大模型</div>
- </template>
- <!-- 最大化/还原按钮 -->
- <div class="maximize-btn" @click="toggleFullscreen">
- <div :class="['maximize-icon', { minimized: isFullscreen }]"></div>
- </div>
- <!-- 收起/展开按钮 -->
- <div class="collapse-btn" @click="togglePanel">
- <div :class="['collapse-icon', { collapsed: panelCollapsed }]"></div>
- </div>
- <div class="ai-container">
- <!-- 左侧任务列表 -->
- <div :class="['task-panel-wrapper', { collapsed: panelCollapsed }]">
- <TaskListPanel
- :taskList="taskList"
- :currentTaskId="currentTaskId"
- @switch-task="switchTask"
- @create-task="createNewTask"
- @delete-task="handleDeleteTask"
- @pin-task="handlePinTask"
- />
- </div>
- <!-- 中间聊天区域 -->
- <div class="chat-panel">
- <!-- 顶部任务选择器 -->
- <div class="chat-header">
- <template v-if="panelCollapsed">
- <div :class="['nav-btn', { disabled: !canGoPrev }]" @click="goToPrev">
- <div class="nav-icon prev-icon"></div>
- </div>
- <div :class="['nav-btn', { disabled: !canGoNext }]" @click="goToNext">
- <div class="nav-icon next-icon"></div>
- </div>
- <div class="nav-btn" @click="createNewTask">
- <div class="nav-icon add-icon"></div>
- </div>
- </template>
- <div v-if="currentTask?.sessionId" class="chat-header-title-wrapper">
- <template v-if="editingTitle">
- <input v-model="editTitleValue" class="title-edit-input" @keyup.enter="saveTitle" @keyup.escape="cancelEditTitle" @blur="saveTitle" />
- </template>
- <template v-else>
- <div class="title-edit-btn" @click="startEditTitle" title="编辑标题"></div>
- <span class="chat-header-title">{{ currentTask.name }}</span>
- </template>
- </div>
- <div v-if="currentWordUrl" class="upload-bg" @click="downloadWordReport">
- <div class="download-icon"></div>
- </div>
- </div>
- <!-- 附件列表面板 -->
- <FileListPanel :visible="showFileList" :files="getCurrentTaskFiles()" @close="showFileList = false" @file-click="openFilePreview" />
- <!-- 消息列表 -->
- <ChatMessages
- ref="chatMessagesRef"
- :messages="messages"
- @file-preview="openFilePreview"
- @download-word="downloadWordFile"
- @approve="handleApprove"
- @reject="handleReject"
- />
- <!-- 下载确认条 -->
- <div v-if="downloadConfirm && downloadConfirmTaskId === currentTaskId" class="download-confirm-bar">
- <span class="download-confirm-text">是否下载 {{ downloadConfirm.filename }} 到本地?</span>
- <div class="download-confirm-actions">
- <button class="download-confirm-btn download-btn" @click="doDownload">下载</button>
- <button class="download-confirm-btn cancel-btn" @click="clearDownloadConfirm">取消</button>
- </div>
- </div>
- <!-- 任务进度条 -->
- <TodoListBar v-if="showTodoBar" :todos="currentTodos" />
- <!-- 输入区域 -->
- <ChatInputArea
- ref="chatInputRef"
- v-model="inputMessage"
- :pendingFile="pendingFile"
- :loading="loading || !!pendingApprovalSessionId"
- :contextUsed="contextUsed"
- :contextMax="contextMax"
- :contextPercent="contextPercent"
- :contextBreakdown="contextBreakdown"
- :initialThinkLevel="thinkLevel"
- :initialEditMode="editMode"
- :taskList="taskList"
- :currentTaskId="currentTaskId"
- @send="handleSendMessage"
- @file-upload="triggerFileUpload"
- @file-change="handleFileUpload"
- @remove-pending-file="removePendingFile"
- @think-level-change="handleThinkLevelChange"
- @edit-mode-change="handleEditModeChange"
- @update:selected-sessions="handleUpdateSelectedSessions"
- />
- </div>
- <!-- 右侧文件预览面板 -->
- <div v-if="previewFile" class="right-panel">
- <FilePreviewPanel :file="previewFile" @close="removePreviewFile" />
- </div>
- </div>
- </a-modal>
- </template>
- <script setup lang="ts">
- import { ref, nextTick, watch, computed, onMounted, onBeforeUnmount } from 'vue';
- import dayjs from 'dayjs';
- import {
- unifiedStream,
- reviewPdfStream,
- chatResumeStream,
- getHistoryList,
- getDetail,
- deleteSession,
- pinSession,
- editSessionTitle,
- getContext,
- switchThinking,
- getModelMsg,
- getSessionMode,
- putSessionMode,
- } from '../api';
- import { message, Modal } from 'ant-design-vue';
- import TaskListPanel from './chatModal/TaskListPanel.vue';
- import FileListPanel from './chatModal/FileListPanel.vue';
- import ChatMessages from './chatModal/ChatMessages.vue';
- import ChatInputArea from './chatModal/ChatInputArea.vue';
- import FilePreviewPanel from './chatModal/FilePreviewPanel.vue';
- import TodoListBar from './chatModal/TodoListBar.vue';
- import type { AttachedFile, Message, Task } from './chatModal/types';
- interface Props {
- visible: boolean;
- }
- interface Emits {
- (e: 'close'): void;
- }
- const props = defineProps<Props>();
- const emit = defineEmits<Emits>();
- const taskList = ref<Task[]>([]);
- // 从接口获取会话列表
- const fetchSessionList = async () => {
- try {
- const res = await getHistoryList({});
- const sessions = res?.sessions || res?.data || [];
- if (Array.isArray(sessions)) {
- const apiTasks: Task[] = sessions.map((item: { session_id: string; title: string; updated_at: string; sort_order?: number }) => ({
- id: item.session_id,
- name: item.title || '未命名会话',
- sessionId: item.session_id,
- messages: [],
- attachedFiles: [],
- updatedAt: item.updated_at,
- sortOrder: item.sort_order,
- }));
- const mergedTasks = apiTasks.map((apiTask) => {
- const existing = taskList.value.find((t) => t.id === apiTask.id);
- if (existing) {
- return {
- ...apiTask,
- messages: existing.messages,
- attachedFiles: existing.attachedFiles,
- wordUrl: existing.wordUrl,
- };
- }
- return apiTask;
- });
- const localOnlyTasks = taskList.value.filter((t) => !t.sessionId && !apiTasks.find((a) => a.id === t.id));
- taskList.value = [...localOnlyTasks, ...mergedTasks];
- return mergedTasks;
- }
- } catch (error) {
- console.error('获取会话列表失败:', error);
- }
- return [];
- };
- const currentTaskId = ref('');
- const chatInputRef = ref<InstanceType<typeof ChatInputArea>>();
- const chatMessagesRef = ref<InstanceType<typeof ChatMessages>>();
- const previewFile = ref<AttachedFile | null>(null);
- const showFileList = ref(false);
- const pendingFile = ref<AttachedFile | null>(null);
- const messages = ref<Message[]>([]);
- const contextUsed = ref(0);
- const contextMax = ref(1000000);
- const contextPercent = ref(0);
- const thinkLevel = ref('off');
- const editMode = ref('full');
- const pendingApprovalSessionId = ref('');
- const pendingApprovalThreadId = ref('');
- const downloadConfirm = ref<{ url: string; filename: string } | null>(null);
- const downloadConfirmTaskId = ref('');
- let downloadConfirmTimer: ReturnType<typeof setTimeout> | null = null;
- const clearDownloadConfirm = () => {
- downloadConfirm.value = null;
- downloadConfirmTaskId.value = '';
- if (downloadConfirmTimer) {
- clearTimeout(downloadConfirmTimer);
- downloadConfirmTimer = null;
- }
- };
- const startDownloadConfirmTimer = () => {
- if (downloadConfirmTimer) clearTimeout(downloadConfirmTimer);
- downloadConfirmTimer = setTimeout(() => {
- clearDownloadConfirm();
- }, 10000);
- };
- const contextBreakdown = ref({ messages: 0, mcp: 0, skills: 0, system_prompt: 0, other: 0 });
- const currentTodos = ref<Array<{ content: string; status: string }>>([]);
- const showTodoBar = ref(false);
- const syncTodoBarFromMessages = () => {
- for (let i = messages.value.length - 1; i >= 0; i--) {
- const msg = messages.value[i];
- if (msg.type === 'ai' && msg.thinkingSteps) {
- for (let j = msg.thinkingSteps.length - 1; j >= 0; j--) {
- const step = msg.thinkingSteps[j];
- if (step.type === 'updated_todo_list' && step.todos) {
- currentTodos.value = [...step.todos];
- showTodoBar.value = true;
- return;
- }
- }
- }
- }
- showTodoBar.value = false;
- currentTodos.value = [];
- };
- const panelCollapsed = ref(false);
- const togglePanel = () => {
- panelCollapsed.value = !panelCollapsed.value;
- };
- const editingTitle = ref(false);
- const editTitleValue = ref('');
- const startEditTitle = () => {
- if (!currentTask.value?.sessionId) return;
- editTitleValue.value = currentTask.value.name;
- editingTitle.value = true;
- nextTick(() => {
- const input = document.querySelector('.title-edit-input') as HTMLInputElement;
- input?.focus();
- input?.select();
- });
- };
- const saveTitle = async () => {
- const newTitle = editTitleValue.value.trim();
- if (!currentTask.value?.sessionId || !newTitle || newTitle === currentTask.value.name) {
- editingTitle.value = false;
- return;
- }
- try {
- await editSessionTitle(currentTask.value.sessionId, newTitle);
- currentTask.value.name = newTitle;
- message.success('标题修改成功');
- } catch {
- message.error('标题修改失败');
- }
- editingTitle.value = false;
- };
- const cancelEditTitle = () => {
- editingTitle.value = false;
- };
- const isFullscreen = ref(false);
- const toggleFullscreen = () => {
- isFullscreen.value = !isFullscreen.value;
- nextTick(() => {
- const wraps = document.querySelectorAll<HTMLElement>('.zxm-modal-wrap, .ant-modal-wrap, [class*="modal-wrap"]');
- wraps.forEach((wrap) => {
- if (isFullscreen.value) {
- wrap.style.position = '';
- wrap.style.left = '';
- wrap.style.top = '0';
- wrap.style.right = '';
- wrap.style.bottom = '';
- wrap.style.width = '';
- wrap.style.height = '';
- wrap.style.margin = '0';
- wrap.style.padding = '0';
- wrap.style.transform = '';
- } else {
- wrap.style.position = '';
- wrap.style.left = '';
- wrap.style.top = '';
- wrap.style.right = '';
- wrap.style.bottom = '';
- wrap.style.width = '';
- wrap.style.height = '';
- wrap.style.margin = '';
- wrap.style.padding = '';
- wrap.style.transform = '';
- }
- });
- draggedEl = null;
- if (!isFullscreen.value) {
- centerModal();
- }
- });
- };
- const inputMessage = ref('');
- const loading = ref(false);
- const selectedSessions = ref<Array<{ id: string; name: string }>>([]);
- const getCurrentSessionId = (): string => {
- const currentTask = taskList.value.find((t) => t.id === currentTaskId.value);
- return currentTask?.sessionId || '';
- };
- const historyLoadedTasks = ref<Set<string>>(new Set());
- const setCurrentSessionId = (sessionId: string) => {
- const currentTask = taskList.value.find((t) => t.id === currentTaskId.value);
- if (currentTask && currentTask.id !== sessionId) {
- taskList.value = taskList.value.filter((t) => t.id !== sessionId);
- currentTask.id = sessionId;
- currentTask.sessionId = sessionId;
- currentTaskId.value = sessionId;
- historyLoadedTasks.value.add(sessionId);
- }
- };
- const switchTask = async (taskId: string) => {
- const currentTask = taskList.value.find((t) => t.id === currentTaskId.value);
- if (currentTask) {
- currentTask.messages = [...messages.value];
- }
- currentTaskId.value = taskId;
- const newTask = taskList.value.find((t) => t.id === taskId);
- if (!newTask) return;
- inputMessage.value = '';
- pendingFile.value = null;
- previewFile.value = null;
- showFileList.value = false;
- if (newTask.sessionId && !historyLoadedTasks.value.has(taskId)) {
- loading.value = true;
- try {
- const res = await getDetail(newTask.sessionId);
- const messages = res?.messages || (Array.isArray(res) ? res : res?.data);
- if (Array.isArray(messages)) {
- newTask.messages = transformHistoryToMessages(messages);
- }
- historyLoadedTasks.value.add(taskId);
- } catch (error) {
- console.error('加载历史会话失败:', error);
- } finally {
- loading.value = false;
- }
- }
- if (newTask.sessionId) {
- fetchContext(newTask.sessionId);
- fetchSessionMode(newTask.sessionId);
- } else {
- contextUsed.value = 0;
- contextPercent.value = 0;
- contextBreakdown.value = { messages: 0, mcp: 0, skills: 0, system_prompt: 0, other: 0 };
- editMode.value = 'full';
- }
- messages.value = newTask.messages && newTask.messages.length > 0 ? [...newTask.messages] : getDefaultMessages();
- syncTodoBarFromMessages();
- await nextTick();
- chatMessagesRef.value?.forceScrollToBottom();
- };
- const createNewTask = () => {
- const existingBlank = taskList.value.find((t) => !t.sessionId);
- if (existingBlank) {
- switchTask(existingBlank.id);
- return;
- }
- const newTask: Task = {
- id: `task-${Date.now()}`,
- name: '新任务',
- sessionId: '',
- messages: getDefaultMessages(),
- attachedFiles: [],
- };
- contextUsed.value = 0;
- contextPercent.value = 0;
- contextBreakdown.value = { messages: 0, mcp: 0, skills: 0, system_prompt: 0, other: 0 };
- editMode.value = 'full';
- taskList.value.unshift(newTask);
- switchTask(newTask.id);
- };
- const handlePinTask = async (task: Task) => {
- if (!task.sessionId) {
- message.warning('请先发送消息后再置顶');
- return;
- }
- try {
- await pinSession(task.sessionId);
- await fetchSessionList();
- } catch {
- message.error('置顶操作失败');
- }
- };
- const handleThinkLevelChange = async (levelKey: string) => {
- try {
- await switchThinking(levelKey);
- } catch {
- message.error('切换思考级别失败');
- }
- };
- const handleUpdateSelectedSessions = (sessions: Array<{ id: string; name: string }>) => {
- selectedSessions.value = sessions;
- };
- const getSessionRefIconUrl = () => {
- const val = getComputedStyle(document.documentElement).getPropertyValue('--img-chat-popup-session-icon').trim();
- return val.replace(/^url\(["']?/, '').replace(/["']?\)$/, '');
- };
- const handleEditModeChange = async (modeKey: string) => {
- editMode.value = modeKey;
- const sessionId = getCurrentSessionId();
- if (!sessionId) return;
- try {
- await putSessionMode(sessionId, modeKey);
- } catch {
- message.error('切换模式失败');
- }
- };
- const handleApprove = async () => {
- const sessionId = pendingApprovalSessionId.value || getCurrentSessionId();
- if (!sessionId) return;
- const approveTask = taskList.value.find((t) => t.sessionId === sessionId);
- if (!approveTask) return;
- const taskMessages = approveTask.messages;
- const lastMsg = taskMessages[taskMessages.length - 1];
- if (!lastMsg || !lastMsg.isPendingApproval) return;
- // 复用同一条消息继续渲染:清除审批状态,恢复 loading,重置前端计时起点
- lastMsg.isPendingApproval = false;
- lastMsg.pendingApprovalData = undefined;
- lastMsg.isLoading = true;
- lastMsg.generateStartTime = Date.now();
- // thinkingSteps、thinkingContent、baseDurationMs 保持不变,后续继续累积
- const aiMsgIndex = taskMessages.length - 1;
- approveTask.messages = [...taskMessages];
- if (currentTaskId.value === approveTask.id) {
- messages.value = approveTask.messages;
- await scrollToBottom();
- }
- loading.value = true;
- approveTask.isStreaming = true;
- showTodoBar.value = false;
- currentTodos.value = [];
- try {
- const result = await chatResumeStream(
- {
- session_id: sessionId,
- thread_id: pendingApprovalThreadId.value || undefined,
- action: 'approve',
- },
- (chunk: string) => {
- parseSSEData(chunk, aiMsgIndex, approveTask.id);
- if (currentTaskId.value === approveTask.id) scrollToBottom();
- }
- );
- if (result.session_id) {
- setCurrentSessionId(result.session_id);
- }
- } catch (error) {
- console.error('审批继续执行失败:', error);
- message.error('审批失败,请重试');
- lastMsg.isLoading = false;
- if (!lastMsg.content) {
- lastMsg.content = '抱歉,审批请求失败,请稍后重试。';
- }
- } finally {
- loading.value = false;
- approveTask.isStreaming = false;
- pendingApprovalSessionId.value = '';
- pendingApprovalThreadId.value = '';
- if (currentTaskId.value === approveTask.id) {
- await scrollToBottom();
- }
- }
- };
- const handleReject = async () => {
- const sessionId = pendingApprovalSessionId.value || getCurrentSessionId();
- if (!sessionId) return;
- const rejectTask = taskList.value.find((t) => t.sessionId === sessionId);
- if (!rejectTask) return;
- const taskMessages = rejectTask.messages;
- const lastMsg = taskMessages[taskMessages.length - 1];
- if (!lastMsg || !lastMsg.isPendingApproval) return;
- // 复用同一条消息:清除审批状态,标记为已拒绝
- lastMsg.isPendingApproval = false;
- lastMsg.pendingApprovalData = undefined;
- lastMsg.isLoading = false;
- lastMsg.content = (lastMsg.content ? lastMsg.content + '\n\n' : '') + '已拒绝执行计划。';
- rejectTask.messages = [...taskMessages];
- pendingApprovalSessionId.value = '';
- pendingApprovalThreadId.value = '';
- try {
- await chatResumeStream(
- {
- session_id: sessionId,
- thread_id: pendingApprovalThreadId.value || undefined,
- action: 'reject',
- },
- () => {}
- );
- } catch (error) {
- console.error('拒绝操作失败:', error);
- }
- if (currentTaskId.value === rejectTask.id) {
- messages.value = rejectTask.messages;
- await scrollToBottom();
- }
- };
- const handleDeleteTask = (task: Task, _index: number) => {
- Modal.confirm({
- title: '提示',
- content: '是否删除该对话?',
- okText: '确认',
- cancelText: '取消',
- wrapClassName: 'delete-task-confirm-modal',
- onOk: async () => {
- try {
- if (task.sessionId) {
- await deleteSession(task.sessionId);
- }
- const realIndex = taskList.value.findIndex((t) => t.id === task.id);
- if (realIndex !== -1) {
- taskList.value.splice(realIndex, 1);
- }
- if (currentTaskId.value === task.id) {
- if (taskList.value.length > 0) {
- switchTask(taskList.value[0].id);
- } else {
- messages.value = [];
- currentTaskId.value = '';
- }
- }
- message.success('删除成功');
- } catch {
- message.error('删除失败');
- }
- },
- });
- };
- const getDefaultMessages = (): Message[] => {
- return [];
- };
- const normalizeLineBreaks = (str: string): string => {
- if (!str) return '';
- return str.replace(/\\n/g, '\n').replace(/\r\n/g, '\n');
- };
- const transformHistoryToMessages = (data: Array<{ role?: string; type?: string; content: string; created_at?: string }>): Message[] => {
- const messages: Message[] = [];
- for (const item of data) {
- const normalizedContent = normalizeLineBreaks(item.content);
- const time = item.created_at ? dayjs(item.created_at).format('HH:mm') : '';
- const createdAt = item.created_at || '';
- // 新格式:role 字段 (user/assistant)
- if (item.role === 'user') {
- messages.push({ type: 'user', content: normalizedContent, time, createdAt });
- } else if (item.role === 'assistant') {
- messages.push({ type: 'ai', content: normalizedContent, time, createdAt });
- }
- // 兼容旧格式:type 字段
- else if (item.type === 'user_message') {
- messages.push({ type: 'user', content: normalizedContent, time, createdAt });
- } else if (item.type === 'model_thinking') {
- const lastAiMsg = messages[messages.length - 1];
- if (lastAiMsg && lastAiMsg.type === 'ai') {
- lastAiMsg.content += normalizedContent;
- lastAiMsg.content = lastAiMsg.content.replace(/\|\|\|SPLIT_CONTENT\|\|\|/g, '');
- } else {
- messages.push({ type: 'ai', content: normalizedContent, time, createdAt });
- }
- }
- }
- return messages;
- };
- const triggerFileUpload = () => {
- chatInputRef.value?.fileInputRef?.click();
- };
- const handleFileUpload = async (event: Event) => {
- const target = event.target as HTMLInputElement;
- const file = target.files?.[0];
- if (!file) return;
- try {
- const newFile: AttachedFile = {
- id: `file-${Date.now()}`,
- name: file.name,
- size: file.size,
- type: file.type,
- uploadTime: dayjs().format('YYYY-MM-DD HH:mm'),
- originalFile: file,
- };
- const reader = new FileReader();
- reader.onload = (e) => {
- newFile.preview = e.target?.result as string;
- };
- reader.readAsDataURL(file);
- pendingFile.value = newFile;
- message.success(`文件 "${file.name}" 已添加,点击发送按钮提交`);
- } catch (error) {
- console.error('文件处理失败:', error);
- message.error('文件处理失败,请重试');
- }
- target.value = '';
- };
- const removePendingFile = () => {
- pendingFile.value = null;
- };
- const removePreviewFile = () => {
- previewFile.value = null;
- };
- const openFilePreview = (file: AttachedFile) => {
- previewFile.value = file;
- const msgIndex = messages.value.findIndex((m) => m.attachedFile?.id === file.id);
- if (msgIndex !== -1) {
- nextTick(() => {
- const messageElements = chatMessagesRef.value?.messagesRef?.querySelectorAll('.message-wrapper');
- if (messageElements && messageElements[msgIndex]) {
- (messageElements[msgIndex] as HTMLElement).scrollIntoView({
- behavior: 'smooth',
- block: 'center',
- });
- }
- });
- }
- };
- const getCurrentTaskFiles = (): AttachedFile[] => {
- const currentTask = taskList.value.find((t) => t.id === currentTaskId.value);
- return currentTask?.attachedFiles || [];
- };
- const currentTask = computed(() => taskList.value.find((t) => t.id === currentTaskId.value));
- const currentWordUrl = computed(() => {
- return currentTask.value?.wordUrl || '';
- });
- const currentTaskIndex = computed(() => taskList.value.findIndex((t) => t.id === currentTaskId.value));
- const canGoPrev = computed(() => currentTaskIndex.value > 0);
- const canGoNext = computed(() => currentTaskIndex.value >= 0 && currentTaskIndex.value < taskList.value.length - 1);
- const goToPrev = () => {
- if (!canGoPrev.value) return;
- const prevTask = taskList.value[currentTaskIndex.value - 1];
- if (prevTask) switchTask(prevTask.id);
- };
- const goToNext = () => {
- if (!canGoNext.value) return;
- const nextTask = taskList.value[currentTaskIndex.value + 1];
- if (nextTask) switchTask(nextTask.id);
- };
- const downloadWordReport = () => {
- const url = currentWordUrl.value;
- if (!url) return;
- const a = document.createElement('a');
- a.href = url;
- a.download = '';
- a.target = '_blank';
- document.body.appendChild(a);
- a.click();
- document.body.removeChild(a);
- };
- const doDownload = () => {
- if (!downloadConfirm.value) return;
- const a = document.createElement('a');
- a.href = downloadConfirm.value.url;
- a.download = downloadConfirm.value.filename;
- document.body.appendChild(a);
- a.click();
- document.body.removeChild(a);
- clearDownloadConfirm();
- };
- const downloadWordFile = (url: string) => {
- if (!url) return;
- const a = document.createElement('a');
- a.href = url;
- a.download = '';
- a.target = '_blank';
- document.body.appendChild(a);
- a.click();
- document.body.removeChild(a);
- };
- const handleSendMessage = async () => {
- const hasText = inputMessage.value.trim();
- const hasFile = pendingFile.value;
- if (!hasText) {
- message.warning('请输入消息内容');
- return;
- }
- if (loading.value) return;
- if (pendingApprovalSessionId.value) {
- message.warning('请先审批执行计划');
- return;
- }
- const sessionPrefix = selectedSessions.value.length > 0 ? selectedSessions.value.map((s) => `#session:${s.id}`).join(' ') + ' ' : '';
- const userInput = sessionPrefix + inputMessage.value.trim();
- let displayContent = inputMessage.value.trim();
- if (selectedSessions.value.length > 0) {
- const names = selectedSessions.value.map((s) => s.name).join('、');
- const iconUrl = getSessionRefIconUrl();
- displayContent = `[<img src="${iconUrl}" class="session-ref-icon" /> 引用 ${selectedSessions.value.length} 个会话:${names}] ${displayContent}`;
- }
- const fileToSend = pendingFile.value;
- inputMessage.value = '';
- pendingFile.value = null;
- selectedSessions.value = [];
- try {
- loading.value = true;
- await nextTick();
- chatMessagesRef.value?.forceScrollToBottom();
- if (hasFile) {
- await sendWithAttachment(fileToSend!, userInput, displayContent);
- } else {
- await sendTextOnly(userInput, displayContent);
- }
- } catch (error) {
- console.error('发送消息失败:', error);
- message.error('发送失败,请重试');
- const lastMsg = messages.value[messages.value.length - 1];
- if (lastMsg && lastMsg.type === 'ai' && lastMsg.isLoading) {
- messages.value.pop();
- }
- const errorMsg: Message = {
- type: 'ai',
- content: '抱歉,请求失败,请稍后重试。',
- time: dayjs().format('HH:mm'),
- };
- messages.value.push(errorMsg);
- const currentTask = taskList.value.find((t) => t.id === currentTaskId.value);
- if (currentTask) {
- currentTask.messages = [...messages.value];
- }
- } finally {
- loading.value = false;
- await scrollToBottom();
- }
- };
- const extractAgentName = (toolName: string): string => {
- const nameMap: Record<string, string> = {
- form_review: '形式审查',
- verify_coal_face_ventilation: '采煤工作面需风量计算核验',
- verify_tunneling_face_ventilation: '掘进工作面需风量计算核验',
- verify_chamber_ventilation: '硐室需风量计算核验',
- verify_other_points_ventilation: '其他地点需风量计算核验',
- check_data_by_gas_report: '瓦斯数据一致性审查',
- check_data_by_face_design: '设计规程一致性审查',
- check_data_by_vent_report: '测风报表一致性审查',
- check_current_month_plan: '日期有效性审查',
- get_key_translate: '计算参数对照',
- calculate_ventilation: '需风量计算',
- get_ventilation_data: '需风量查询',
- recalculate_ventilation: '需风量重计算',
- get_plan_required_wind: '需风量提取',
- get_model_calculated_wind: '三维模型解算风量提取',
- get_sensor_wind: '巷道监测风量提取',
- merge_wind_by_location: '地点风量智能合并',
- check_wind_compliance: '风量检查',
- };
- return nameMap[toolName] || nameMap[toolName.toLowerCase()] || '智能分析助手';
- };
- // 累积所有步骤,保留完整历史
- const upsertStep = (steps: any[], step: any) => {
- steps.push(step);
- };
- const fetchModelMsg = async () => {
- try {
- const res = await getModelMsg();
- if (res?.thinking_level) {
- thinkLevel.value = res.thinking_level;
- }
- } catch (e) {
- console.error('获取模型信息失败:', e);
- }
- };
- const fetchSessionMode = async (sessionId: string) => {
- try {
- const res = await getSessionMode(sessionId);
- if (res?.mode) {
- editMode.value = res.mode;
- }
- } catch (e) {
- console.error('获取会话模式失败:', e);
- }
- };
- const fetchContext = async (sessionId: string) => {
- try {
- const res = await getContext(sessionId);
- if (res?.current_usage != null) {
- contextUsed.value = res.current_usage;
- }
- if (res?.total_limit != null) {
- contextMax.value = res.total_limit;
- }
- if (res?.usage_pct != null) {
- contextPercent.value = res.usage_pct;
- }
- if (res?.breakdown) {
- contextBreakdown.value = res.breakdown;
- }
- } catch (e) {
- console.error('获取上下文容量失败:', e);
- }
- };
- const handleSSEMessage = (data: any, aiMsgIndex: number, taskId: string) => {
- const streamingTask = taskList.value.find((t) => t.id === taskId);
- if (!streamingTask) return;
- // 当前正在查看流式任务时,新消息被 push 到 messages.value 而非 task.messages
- // 所以需要从 messages.value 读取;否则从任务存储的 messages 读取
- const isViewingTask = currentTaskId.value === taskId;
- const sourceArr = isViewingTask ? messages.value : streamingTask.messages;
- const aiMsg = sourceArr[aiMsgIndex];
- if (!aiMsg) return;
- const normalizedContent = normalizeLineBreaks(data.content || '');
- // 初始化 thinkingSteps 数组
- if (!aiMsg.thinkingSteps) {
- aiMsg.thinkingSteps = [];
- }
- switch (data.type) {
- // token 流式内容 - 直接拼接到消息内容
- case 'token':
- if (normalizedContent) {
- aiMsg.content += normalizedContent;
- }
- break;
- // thinking_token - 模型思考过程内容
- case 'thinking_token':
- if (normalizedContent) {
- aiMsg.thinkingContent = (aiMsg.thinkingContent || '') + normalizedContent;
- }
- break;
- // 系统进度消息 - 仅当 agent 不是 system 时才作为 thinking step
- case 'progress': {
- if (data.agent && data.agent !== 'system') {
- upsertStep(aiMsg.thinkingSteps!, {
- type: 'executing',
- agent: data.agent,
- message: data.message || '',
- timestamp: Date.now(),
- });
- }
- break;
- }
- // agent 开始处理
- case 'agent_start': {
- upsertStep(aiMsg.thinkingSteps!, {
- type: 'agent_start',
- agent: data.cn_agent || data.agent || '智能助手',
- message: data.message || '开始处理...',
- timestamp: Date.now(),
- });
- break;
- }
- // agent 任务列表更新(同一 agent 的 todos 更新已有条目,不重复添加)
- case 'agent_todos':
- case 'updated_todo_list': {
- const agentName = data.cn_agent || data.agent || '智能助手';
- const existingIdx = aiMsg.thinkingSteps!.findIndex((s) => s.type === 'updated_todo_list' && s.agent === agentName);
- if (existingIdx !== -1) {
- aiMsg.thinkingSteps![existingIdx].todos = data.todos || [];
- aiMsg.thinkingSteps![existingIdx].timestamp = Date.now();
- } else {
- aiMsg.thinkingSteps!.push({
- type: 'updated_todo_list',
- agent: agentName,
- todos: data.todos || [],
- message: data.message || '任务进度已更新',
- timestamp: Date.now(),
- });
- }
- currentTodos.value = [...(data.todos || [])];
- showTodoBar.value = true;
- break;
- }
- // agent 执行中(工具调用)
- case 'agent_executing':
- case 'executing': {
- upsertStep(aiMsg.thinkingSteps!, {
- type: 'executing',
- agent: data.cn_agent || data.agent || '智能助手',
- tool: (data.cn_tools || data.tools || []).join('、'),
- message: data.message || '',
- timestamp: Date.now(),
- });
- break;
- }
- // 工具结果
- case 'agent_tool_result':
- case 'tool_result': {
- upsertStep(aiMsg.thinkingSteps!, {
- type: 'tool_result',
- agent: data.cn_agent || data.agent || '智能助手',
- tool: data.cn_tool || data.tool || '',
- message: data.message || '执行完成',
- timestamp: Date.now(),
- });
- if (data.download_url) {
- downloadConfirm.value = { url: data.download_url, filename: data.filename || '文件' };
- downloadConfirmTaskId.value = taskId;
- startDownloadConfirmTimer();
- }
- break;
- }
- // agent 完成
- case 'agent_done': {
- upsertStep(aiMsg.thinkingSteps!, {
- type: 'agent_done',
- agent: data.cn_agent || data.agent || '智能助手',
- message: `${(data.message || '审查完成').replace(/(\d+ms)/g, '')}${data.duration_ms ? `(${(data.duration_ms / 1000).toFixed(0)}s)` : ''}${data.progress ? ` [${data.progress}]` : ''}`,
- timestamp: Date.now(),
- });
- // 累加后端返回的各段耗时,并重置前端计时起点,避免重复计算已验证的时间段
- if (data.duration_ms) {
- aiMsg.baseDurationMs = (aiMsg.baseDurationMs || 0) + data.duration_ms;
- aiMsg.generateStartTime = Date.now();
- }
- if (data.preview) {
- aiMsg.content += data.preview;
- }
- break;
- }
- // 旧格式兼容
- case 'model_thinking':
- if (normalizedContent) {
- aiMsg.content += normalizedContent;
- aiMsg.content = aiMsg.content.replace(/\|\|\|SPLIT_CONTENT\|\|\|/g, '');
- }
- break;
- case 'tool_select': {
- upsertStep(aiMsg.thinkingSteps!, {
- type: 'tool_call',
- agent: extractAgentName(normalizedContent),
- tool: normalizedContent,
- message: `选择工具:${normalizedContent}`,
- timestamp: Date.now(),
- });
- break;
- }
- case 'error':
- upsertStep(aiMsg.thinkingSteps!, {
- type: 'tool_result',
- agent: '系统',
- message: `❌ 执行失败:${normalizedContent}`,
- timestamp: Date.now(),
- });
- aiMsg.isLoading = false;
- break;
- case 'word_download':
- if (normalizedContent) {
- aiMsg.wordDownloadUrl = normalizedContent;
- streamingTask.wordUrl = normalizedContent;
- }
- break;
- case 'done':
- if (data.session_id) {
- aiMsg.sessionId = data.session_id;
- fetchContext(data.session_id);
- }
- if (data.duration_ms) {
- aiMsg.durationMs = (aiMsg.baseDurationMs || 0) + data.duration_ms;
- }
- aiMsg.isLoading = false;
- break;
- case 'system':
- if (normalizedContent) {
- aiMsg.content += normalizedContent.replace(/\n/g, ' \n');
- }
- break;
- case 'interrupt': {
- // 优先使用 agent_done 已设置的后端时间,否则用前端计时
- const elapsedMs = aiMsg.baseDurationMs || (aiMsg.generateStartTime ? Date.now() - aiMsg.generateStartTime : 0);
- aiMsg.isLoading = false;
- aiMsg.isPendingApproval = true;
- const interruptSessionId = data.session_id || streamingTask.sessionId;
- aiMsg.pendingApprovalData = {
- message: data.message || '智能体制定了执行计划,等待您的审批...',
- sessionId: interruptSessionId,
- threadId: data.thread_id,
- interrupts: data.interrupts,
- elapsedMs,
- prevThinkingContent: aiMsg.thinkingContent,
- };
- pendingApprovalSessionId.value = interruptSessionId;
- pendingApprovalThreadId.value = data.thread_id || '';
- break;
- }
- }
- // 保存到流式任务的 messages,并同步 UI
- if (isViewingTask) {
- streamingTask.messages = [...messages.value];
- } else {
- streamingTask.messages = [...streamingTask.messages];
- }
- };
- const parseSSEData = (chunk: string, aiMsgIndex: number, taskId: string) => {
- const lines = chunk.split('\n');
- for (const lineRaw of lines) {
- const line = lineRaw.trim();
- if (!line) continue;
- if (line.startsWith('data:')) {
- try {
- const jsonStr = line.substring(5).trim();
- const data = JSON.parse(jsonStr);
- handleSSEMessage(data, aiMsgIndex, taskId);
- } catch (error) {
- console.error('解析 SSE data 行失败:', error, line);
- }
- continue;
- }
- try {
- const data = JSON.parse(line);
- handleSSEMessage(data, aiMsgIndex, taskId);
- continue;
- } catch {
- // not json
- }
- handleSSEMessage({ type: 'model_thinking', content: line }, aiMsgIndex, taskId);
- }
- };
- const sendTextOnly = async (userInput: string, displayContent?: string) => {
- const originTaskId = currentTaskId.value;
- const now = dayjs();
- const userMsg: Message = {
- type: 'user',
- content: displayContent || userInput,
- time: now.format('HH:mm'),
- createdAt: now.toISOString(),
- };
- messages.value.push(userMsg);
- await scrollToBottom();
- const aiMsgIndex = messages.value.length;
- const aiMsg: Message = {
- type: 'ai',
- content: '',
- time: now.format('HH:mm'),
- createdAt: now.toISOString(),
- isLoading: true,
- thinkingSteps: [],
- generateStartTime: Date.now(),
- };
- messages.value.push(aiMsg);
- await scrollToBottom();
- showTodoBar.value = false;
- currentTodos.value = [];
- const originTask = taskList.value.find((t) => t.id === originTaskId);
- if (originTask) originTask.isStreaming = true;
- try {
- const result = await unifiedStream(
- {
- message: userInput,
- session_id: getCurrentSessionId() || undefined,
- mode: editMode.value,
- },
- (chunk: string) => {
- parseSSEData(chunk, aiMsgIndex, originTaskId);
- if (currentTaskId.value === originTaskId) scrollToBottom();
- }
- );
- if (result.session_id) {
- const originTask = taskList.value.find((t) => t.id === originTaskId);
- if (originTask && !originTask.sessionId) {
- originTask.sessionId = result.session_id;
- originTask.name = userInput.substring(0, 20) + (userInput.length > 20 ? '...' : '');
- if (originTask.id !== result.session_id) {
- taskList.value = taskList.value.filter((t) => t.id !== result.session_id);
- originTask.id = result.session_id;
- historyLoadedTasks.value.add(result.session_id);
- }
- if (currentTaskId.value === originTaskId) {
- currentTaskId.value = result.session_id;
- }
- }
- }
- } finally {
- const originTask = taskList.value.find((t) => t.id === originTaskId);
- if (originTask) originTask.isStreaming = false;
- }
- };
- const sendWithAttachment = async (file: AttachedFile, userInput: string, displayContent?: string) => {
- const originTaskId = currentTaskId.value;
- let currentTask = taskList.value.find((t) => t.id === originTaskId);
- if (currentTask) {
- currentTask.attachedFiles.push(file);
- } else {
- throw new Error('未找到当前任务');
- }
- const now = dayjs();
- const userMsg: Message = {
- type: 'user',
- content: displayContent || userInput || `上传了文件:${file.name}`,
- time: now.format('HH:mm'),
- createdAt: now.toISOString(),
- attachedFile: file,
- };
- messages.value.push(userMsg);
- await scrollToBottom();
- const aiMsgIndex = messages.value.length;
- const aiMsg: Message = {
- type: 'ai',
- content: '',
- time: now.format('HH:mm'),
- createdAt: now.toISOString(),
- isLoading: true,
- thinkingSteps: [],
- generateStartTime: Date.now(),
- };
- messages.value.push(aiMsg);
- await scrollToBottom();
- showTodoBar.value = false;
- currentTodos.value = [];
- if (!file.originalFile) {
- throw new Error('缺少原始文件对象');
- }
- const originTask = taskList.value.find((t) => t.id === originTaskId);
- if (originTask) originTask.isStreaming = true;
- try {
- const result = await reviewPdfStream(
- {
- file: file.originalFile!,
- session_id: getCurrentSessionId() || undefined,
- message: userInput || undefined,
- mode: editMode.value,
- },
- (chunk: string) => {
- parseSSEData(chunk, aiMsgIndex, originTaskId);
- if (currentTaskId.value === originTaskId) scrollToBottom();
- }
- );
- if (result.session_id) {
- const originTask = taskList.value.find((t) => t.id === originTaskId);
- if (originTask && !originTask.sessionId) {
- const taskName = userInput || `文件:${file.name}`;
- originTask.sessionId = result.session_id;
- originTask.name = taskName.substring(0, 20) + (taskName.length > 20 ? '...' : '');
- if (originTask.id !== result.session_id) {
- taskList.value = taskList.value.filter((t) => t.id !== result.session_id);
- originTask.id = result.session_id;
- historyLoadedTasks.value.add(result.session_id);
- }
- if (currentTaskId.value === originTaskId) {
- currentTaskId.value = result.session_id;
- }
- }
- }
- } finally {
- const originTask = taskList.value.find((t) => t.id === originTaskId);
- if (originTask) originTask.isStreaming = false;
- }
- };
- const scrollToBottom = async () => {
- await nextTick();
- if (!chatMessagesRef.value?.isAtBottom) return;
- const el = chatMessagesRef.value?.messagesRef;
- if (el) {
- el.scrollTop = el.scrollHeight;
- }
- };
- watch(
- () => props.visible,
- async (newVisible) => {
- if (!newVisible) {
- const currentTask = taskList.value.find((t) => t.id === currentTaskId.value);
- if (currentTask) {
- currentTask.messages = [...messages.value];
- }
- } else {
- await fetchSessionList();
- fetchModelMsg();
- // 去除重复的空白任务,只保留一个
- taskList.value = taskList.value.filter((task, index) => {
- if (task.sessionId) return true;
- return index === taskList.value.findIndex((t) => !t.sessionId);
- });
- // 默认选中第一条历史记录
- const firstHistoryTask = taskList.value.find((t) => t.sessionId);
- let targetTask: Task;
- if (firstHistoryTask) {
- targetTask = firstHistoryTask;
- } else {
- // 没有历史记录时才创建空白新任务
- targetTask = {
- id: `task-${Date.now()}`,
- name: '新任务',
- sessionId: '',
- messages: getDefaultMessages(),
- attachedFiles: [],
- };
- taskList.value.unshift(targetTask);
- }
- currentTaskId.value = targetTask.id;
- // 如果是历史任务,加载其消息
- if (targetTask.sessionId && !historyLoadedTasks.value.has(targetTask.id)) {
- loading.value = true;
- try {
- const res = await getDetail(targetTask.sessionId);
- const messages = res?.messages || (Array.isArray(res) ? res : res?.data);
- if (Array.isArray(messages)) {
- targetTask.messages = transformHistoryToMessages(messages);
- }
- historyLoadedTasks.value.add(targetTask.id);
- } catch (error) {
- console.error('加载历史会话失败:', error);
- } finally {
- loading.value = false;
- }
- }
- if (targetTask.sessionId) {
- fetchContext(targetTask.sessionId);
- fetchSessionMode(targetTask.sessionId);
- } else {
- contextUsed.value = 0;
- contextPercent.value = 0;
- contextBreakdown.value = { messages: 0, mcp: 0, skills: 0, system_prompt: 0, other: 0 };
- editMode.value = 'full';
- }
- messages.value = targetTask.messages && targetTask.messages.length > 0 ? [...targetTask.messages] : getDefaultMessages();
- previewFile.value = null;
- pendingFile.value = null;
- showFileList.value = false;
- inputMessage.value = '';
- await nextTick(() => {
- chatMessagesRef.value?.forceScrollToBottom();
- });
- }
- }
- );
- // 拖拽相关(使用普通变量避免 mousemove 触发 Vue 响应式导致卡顿)
- let isDragging = false;
- let dragStartX = 0;
- let dragStartY = 0;
- let modalStartLeft = 0;
- let modalStartTop = 0;
- let draggedEl: HTMLElement | null = null;
- const findModalWrap = (target: HTMLElement): HTMLElement | null =>
- target.closest<HTMLElement>('.zxm-modal-wrap, .ant-modal-wrap, [class*="modal-wrap"]');
- const queryModalWrap = (): HTMLElement | null => document.querySelector<HTMLElement>('.zxm-modal-wrap, .ant-modal-wrap, [class*="modal-wrap"]');
- const centerModal = () => {
- nextTick(() => {
- const wrap = queryModalWrap();
- if (wrap) {
- wrap.style.position = '';
- wrap.style.left = '';
- wrap.style.top = '';
- wrap.style.right = '';
- wrap.style.bottom = '';
- wrap.style.width = '';
- wrap.style.height = '';
- wrap.style.margin = '';
- wrap.style.transform = '';
- }
- draggedEl = null;
- });
- };
- const onDragStart = (e: MouseEvent) => {
- if (isFullscreen.value) return;
- draggedEl = findModalWrap(e.target as HTMLElement) || queryModalWrap();
- if (!draggedEl) return;
- isDragging = true;
- dragStartX = e.clientX;
- dragStartY = e.clientY;
- const rect = draggedEl.getBoundingClientRect();
- modalStartLeft = rect.left;
- modalStartTop = rect.top;
- draggedEl.style.position = 'fixed';
- draggedEl.style.left = `${rect.left}px`;
- draggedEl.style.top = `${rect.top}px`;
- draggedEl.style.margin = '0';
- draggedEl.style.transform = 'none';
- document.addEventListener('mousemove', onDragMove);
- document.addEventListener('mouseup', onDragEnd);
- };
- const onDragMove = (e: MouseEvent) => {
- if (!isDragging || !draggedEl) return;
- draggedEl.style.left = `${modalStartLeft + (e.clientX - dragStartX)}px`;
- draggedEl.style.top = `${modalStartTop + (e.clientY - dragStartY)}px`;
- };
- const onDragEnd = () => {
- isDragging = false;
- document.removeEventListener('mousemove', onDragMove);
- document.removeEventListener('mouseup', onDragEnd);
- };
- watch(
- () => props.visible,
- (newVisible) => {
- if (newVisible) {
- centerModal();
- }
- }
- );
- onMounted(async () => {
- // fetchSessionList moved to watch(visible) to avoid unnecessary API calls
- });
- onBeforeUnmount(() => {
- document.removeEventListener('mousemove', onDragMove);
- document.removeEventListener('mouseup', onDragEnd);
- if (downloadConfirmTimer) {
- clearTimeout(downloadConfirmTimer);
- downloadConfirmTimer = null;
- }
- });
- </script>
- <style scoped lang="less">
- .ai-container {
- display: flex;
- height: 700px;
- gap: 10px;
- overflow: hidden;
- font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, 'Helvetica Neue', Arial, sans-serif;
- }
- .collapse-btn {
- position: absolute;
- top: 16px;
- left: 24px;
- z-index: 10;
- width: 32px;
- height: 32px;
- background: #1a6696;
- border-radius: 4px;
- display: flex;
- align-items: center;
- justify-content: center;
- cursor: pointer;
- transition: background 0.3s;
- &:hover {
- background: #1f7ab8;
- }
- .collapse-icon {
- width: 16px;
- height: 16px;
- background-image: var(--img-chat-collapse-icon);
- background-repeat: no-repeat;
- background-size: 100% 100%;
- &.collapsed {
- background-image: var(--img-chat-expand-icon);
- }
- }
- }
- .task-panel-wrapper {
- width: 300px;
- flex-shrink: 0;
- overflow: hidden;
- transition:
- width 0.35s cubic-bezier(0.4, 0, 0.2, 1),
- margin 0.35s cubic-bezier(0.4, 0, 0.2, 1),
- opacity 0.25s ease;
- &.collapsed {
- width: 0;
- margin: 0;
- opacity: 0;
- }
- }
- .chat-panel {
- flex: 1;
- display: flex;
- position: relative;
- flex-direction: column;
- background-image: var(--img-chat-panel-bg);
- background-repeat: no-repeat;
- background-size: 100% 100%;
- border-radius: 4px;
- overflow: hidden;
- min-width: 0;
- .download-confirm-bar {
- display: flex;
- align-items: center;
- justify-content: space-between;
- padding: 10px 16px;
- margin: 0 16px;
- background: #0a2a3f;
- border: 1px solid #1a4a6f;
- border-radius: 8px;
- flex-shrink: 0;
- .download-confirm-text {
- font-size: 13px;
- color: #e0e6ed;
- overflow: hidden;
- text-overflow: ellipsis;
- white-space: nowrap;
- margin-right: 12px;
- }
- .download-confirm-actions {
- display: flex;
- gap: 8px;
- flex-shrink: 0;
- }
- .download-confirm-btn {
- padding: 4px 14px;
- border-radius: 4px;
- font-size: 12px;
- cursor: pointer;
- border: none;
- transition: all 0.2s;
- &.download-btn {
- background: #0a84ff;
- color: #fff;
- &:hover {
- background: #3a9bfd;
- }
- }
- &.cancel-btn {
- background: rgba(255, 255, 255, 0.08);
- color: #e0e6ed;
- border: 1px solid rgba(63, 80, 106, 0.5);
- &:hover {
- background: rgba(255, 255, 255, 0.15);
- }
- }
- }
- }
- :deep(.chat-header) {
- display: flex;
- padding: 12px 20px;
- flex-shrink: 0;
- align-items: center;
- background: rgba(2, 53, 100, 0.3);
- .header-icon {
- width: 35px;
- height: 28px;
- background-image: var(--img-chat-header-icon);
- background-repeat: no-repeat;
- background-size: 100% 100%;
- margin-right: 10px;
- }
- .chat-header-title {
- font-size: 16px;
- color: #e0e6ed;
- overflow: hidden;
- text-overflow: ellipsis;
- white-space: nowrap;
- margin-left: 10px;
- }
- .chat-header-title-wrapper {
- display: flex;
- align-items: center;
- flex: 1;
- min-width: 0;
- &:hover .title-edit-btn {
- opacity: 1;
- }
- .title-edit-btn {
- width: 28px;
- height: 28px;
- flex-shrink: 0;
- background-image: var(--img-chat-edit-icon);
- background-repeat: no-repeat;
- background-size: 16px 16px;
- background-position: center;
- cursor: pointer;
- opacity: 0;
- transition: opacity 0.2s;
- border-radius: 4px;
- margin-right: 4px;
- &:hover {
- background-color: rgba(10, 132, 255, 0.2);
- }
- }
- .chat-header-title {
- margin-left: 0;
- flex: 1;
- min-width: 0;
- }
- .title-edit-input {
- flex: 1;
- min-width: 0;
- height: 28px;
- padding: 0 8px;
- font-size: 14px;
- color: #e0e6ed;
- background: rgba(10, 132, 255, 0.1);
- border: 1px solid rgba(10, 132, 255, 0.5);
- border-radius: 4px;
- outline: none;
- &:focus {
- border-color: rgba(10, 132, 255, 0.8);
- }
- }
- }
- .nav-btn {
- width: 28px;
- height: 28px;
- display: flex;
- align-items: center;
- justify-content: center;
- cursor: pointer;
- border-radius: 4px;
- transition: background 0.2s;
- &:hover:not(.disabled) {
- background: rgba(10, 132, 255, 0.15);
- }
- &.disabled {
- opacity: 0.3;
- cursor: not-allowed;
- }
- .nav-icon {
- width: 16px;
- height: 16px;
- background-repeat: no-repeat;
- background-size: 100% 100%;
- }
- .prev-icon {
- background-image: var(--img-chat-prev-icon);
- }
- .next-icon {
- background-image: var(--img-chat-next-icon);
- }
- .add-icon {
- background-image: var(--img-chat-options-add-icon);
- }
- }
- .upload-bg {
- cursor: pointer;
- width: 36px;
- height: 36px;
- background-image: var(--img-chat-close-bg);
- background-repeat: no-repeat;
- background-size: 100% 100%;
- display: flex;
- align-items: center;
- justify-content: center;
- margin-left: auto;
- position: relative;
- }
- .download-icon {
- width: 20px;
- height: 20px;
- background-image: var(--img-chat-download-icon);
- background-repeat: no-repeat;
- background-size: 100% 100%;
- }
- }
- }
- .right-panel {
- width: calc(50% - 140px);
- height: 100%;
- display: flex;
- flex-direction: column;
- background-image: var(--img-chat-panel-bg);
- background-repeat: no-repeat;
- background-size: 100% 100%;
- border-radius: 4px;
- flex-shrink: 0;
- }
- .draggable-title {
- cursor: grab;
- user-select: none;
- &:active {
- cursor: grabbing;
- }
- &.no-drag {
- cursor: default;
- &:active {
- cursor: default;
- }
- }
- }
- </style>
- <style lang="less">
- .ai-assistant-modal {
- .zxm-modal-content {
- background-image: var(--img-chat-modal-bg);
- background-repeat: no-repeat;
- background-size: 100% 100%;
- background-color: unset !important;
- box-shadow: none;
- padding: 0;
- border: none !important;
- }
- .zxm-modal-close {
- background-image: var(--img-chat-close-bg);
- background-repeat: no-repeat;
- background-size: 100% 100%;
- top: 0px;
- right: 0px;
- width: 38px;
- height: 38px;
- .zxm-modal-close-x {
- width: 38px;
- height: 38px;
- }
- svg {
- width: 26px;
- height: 26px;
- margin-bottom: 4px;
- }
- }
- .maximize-btn {
- position: absolute;
- top: 0px;
- right: 56px;
- width: 38px;
- height: 38px;
- background-image: var(--img-chat-close-bg);
- background-repeat: no-repeat;
- background-size: 100% 100%;
- display: flex;
- align-items: center;
- justify-content: center;
- cursor: pointer;
- z-index: 10;
- .maximize-icon {
- width: 22px;
- height: 22px;
- background-image: var(--img-chat-maximize-icon);
- background-repeat: no-repeat;
- background-size: 100% 100%;
- &.minimized {
- background-image: var(--img-chat-minimize-icon);
- }
- }
- }
- &.fullscreen {
- top: 0 !important;
- padding: 0 !important;
- max-width: 100vw !important;
- margin: 0 !important;
- background-color: #09172c;
- .zxm-modal-wrap,
- .ant-modal-wrap {
- padding: 0 !important;
- margin: 0 !important;
- top: 0 !important;
- }
- .zxm-modal-content {
- width: 100vw !important;
- height: 100vh !important;
- max-width: 100vw !important;
- margin: 0;
- border-radius: 0;
- overflow: hidden;
- background-image: var(--img-chat-fs-modal-bg);
- }
- .zxm-modal-header {
- height: 90px;
- background-image: var(--img-chat-fs-header-bg) !important;
- background-repeat: no-repeat;
- background-size: 100% 100%;
- margin-bottom: 16px;
- }
- .no-drag {
- cursor: default;
- font-size: 32px !important;
- }
- .zxm-modal-title {
- height: 90px;
- }
- .zxm-modal-body {
- height: calc(100vh - 120px);
- overflow: hidden;
- padding: 0 24px 12px;
- }
- .ai-container {
- height: 100%;
- overflow: hidden;
- }
- .chat-panel {
- background-image: var(--img-chat-fs-panel-bg) !important;
- }
- .chat-header {
- padding: 0 32px;
- height: 50px;
- }
- .collapse-btn {
- top: 60px;
- background-image: var(--img-chat-fs-collapse-btn-bg) !important;
- background-repeat: no-repeat;
- background-size: 100% 100%;
- }
- .task-list-panel {
- padding: 20px;
- background-image: var(--img-chat-fs-task-panel-bg) !important;
- background-repeat: no-repeat !important;
- background-size: 100% 100% !important;
- }
- .options-area {
- gap: 12px;
- }
- .options-area-item {
- background-image: var(--img-chat-fs-options-item-bg) !important;
- background-repeat: no-repeat !important;
- background-size: 100% 100% !important;
- &.active,
- &:active {
- background-image: var(--img-chat-fs-options-item-active-bg) !important;
- }
- .options-img {
- background-image: none !important;
- }
- }
- .chat-header-title {
- height: 40px;
- line-height: 40px;
- position: relative;
- background-image: var(--img-chat-fs-header-title-bg) !important;
- background-repeat: no-repeat !important;
- background-size: auto 100% !important;
- padding: 0 28px;
- &::before {
- content: '';
- position: absolute;
- left: 0;
- top: 50%;
- transform: translateY(-50%);
- width: 40px;
- height: 40px;
- background-image: var(--img-chat-fs-header-title-icon);
- background-repeat: no-repeat;
- background-size: 100% 100%;
- }
- }
- .chat-header-title-wrapper {
- .title-edit-input {
- height: 36px;
- font-size: 16px;
- background: rgba(10, 132, 255, 0.15);
- border-color: rgba(10, 132, 255, 0.6);
- }
- .title-edit-btn {
- width: 24px;
- height: 24px;
- background-size: 16px 16px;
- }
- }
- .chat-input-area {
- margin: 24px;
- }
- }
- .zxm-modal-header {
- background-color: unset !important;
- background: unset;
- border: none !important;
- padding: 8px;
- backdrop-filter: unset;
- display: flex;
- justify-content: center;
- }
- .zxm-modal-title {
- width: 100%;
- height: 60px;
- display: flex;
- align-items: center;
- justify-content: center;
- .draggable-title {
- color: #fff;
- font-family: var(--vet-font-family);
- letter-spacing: 3px;
- font-size: 24px;
- font-weight: 100;
- line-height: 1.4;
- }
- }
- .zxm-modal-body {
- padding: 12px 24px;
- }
- }
- .delete-task-confirm-modal {
- .zxm-modal-confirm-title,
- .zxm-modal-confirm-content {
- color: #fff;
- }
- }
- </style>
|