1
0

AiAssistantModal.vue 58 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976
  1. <template>
  2. <a-modal
  3. :visible="props.visible"
  4. @cancel="emit('close')"
  5. :width="isFullscreen ? '100vw' : 1400"
  6. :footer="null"
  7. destroyOnClose
  8. :class="['ai-assistant-modal', { fullscreen: isFullscreen }]"
  9. >
  10. <template #title>
  11. <div :class="['draggable-title', { 'no-drag': isFullscreen }]" @mousedown="onDragStart">"通安智风"大模型</div>
  12. </template>
  13. <!-- 最大化/还原按钮 -->
  14. <div class="maximize-btn" @click="toggleFullscreen">
  15. <div :class="['maximize-icon', { minimized: isFullscreen }]"></div>
  16. </div>
  17. <!-- 收起/展开按钮 -->
  18. <div class="collapse-btn" @click="togglePanel">
  19. <div :class="['collapse-icon', { collapsed: panelCollapsed }]"></div>
  20. </div>
  21. <div class="ai-container">
  22. <!-- 左侧任务列表 -->
  23. <div :class="['task-panel-wrapper', { collapsed: panelCollapsed }]">
  24. <TaskListPanel
  25. :taskList="taskList"
  26. :currentTaskId="currentTaskId"
  27. @switch-task="switchTask"
  28. @create-task="createNewTask"
  29. @delete-task="handleDeleteTask"
  30. @pin-task="handlePinTask"
  31. />
  32. </div>
  33. <!-- 中间聊天区域 -->
  34. <div class="chat-panel">
  35. <!-- 顶部任务选择器 -->
  36. <div class="chat-header">
  37. <template v-if="panelCollapsed">
  38. <div :class="['nav-btn', { disabled: !canGoPrev }]" @click="goToPrev">
  39. <div class="nav-icon prev-icon"></div>
  40. </div>
  41. <div :class="['nav-btn', { disabled: !canGoNext }]" @click="goToNext">
  42. <div class="nav-icon next-icon"></div>
  43. </div>
  44. <div class="nav-btn" @click="createNewTask">
  45. <div class="nav-icon add-icon"></div>
  46. </div>
  47. </template>
  48. <div v-if="currentTask?.sessionId" class="chat-header-title-wrapper">
  49. <template v-if="editingTitle">
  50. <input v-model="editTitleValue" class="title-edit-input" @keyup.enter="saveTitle" @keyup.escape="cancelEditTitle" @blur="saveTitle" />
  51. </template>
  52. <template v-else>
  53. <div class="title-edit-btn" @click="startEditTitle" title="编辑标题"></div>
  54. <span class="chat-header-title">{{ currentTask.name }}</span>
  55. </template>
  56. </div>
  57. <div v-if="currentWordUrl" class="upload-bg" @click="downloadWordReport">
  58. <div class="download-icon"></div>
  59. </div>
  60. </div>
  61. <!-- 附件列表面板 -->
  62. <FileListPanel :visible="showFileList" :files="getCurrentTaskFiles()" @close="showFileList = false" @file-click="openFilePreview" />
  63. <!-- 消息列表 -->
  64. <ChatMessages
  65. ref="chatMessagesRef"
  66. :messages="messages"
  67. @file-preview="openFilePreview"
  68. @download-word="downloadWordFile"
  69. @approve="handleApprove"
  70. @reject="handleReject"
  71. />
  72. <!-- 下载确认条 -->
  73. <div v-if="downloadConfirm && downloadConfirmTaskId === currentTaskId" class="download-confirm-bar">
  74. <span class="download-confirm-text">是否下载 {{ downloadConfirm.filename }} 到本地?</span>
  75. <div class="download-confirm-actions">
  76. <button class="download-confirm-btn download-btn" @click="doDownload">下载</button>
  77. <button class="download-confirm-btn cancel-btn" @click="clearDownloadConfirm">取消</button>
  78. </div>
  79. </div>
  80. <!-- 任务进度条 -->
  81. <TodoListBar v-if="showTodoBar" :todos="currentTodos" />
  82. <!-- 输入区域 -->
  83. <ChatInputArea
  84. ref="chatInputRef"
  85. v-model="inputMessage"
  86. :pendingFile="pendingFile"
  87. :loading="loading || !!pendingApprovalSessionId"
  88. :contextUsed="contextUsed"
  89. :contextMax="contextMax"
  90. :contextPercent="contextPercent"
  91. :contextBreakdown="contextBreakdown"
  92. :initialThinkLevel="thinkLevel"
  93. :initialEditMode="editMode"
  94. :taskList="taskList"
  95. :currentTaskId="currentTaskId"
  96. @send="handleSendMessage"
  97. @file-upload="triggerFileUpload"
  98. @file-change="handleFileUpload"
  99. @remove-pending-file="removePendingFile"
  100. @think-level-change="handleThinkLevelChange"
  101. @edit-mode-change="handleEditModeChange"
  102. @update:selected-sessions="handleUpdateSelectedSessions"
  103. />
  104. </div>
  105. <!-- 右侧文件预览面板 -->
  106. <div v-if="previewFile" class="right-panel">
  107. <FilePreviewPanel :file="previewFile" @close="removePreviewFile" />
  108. </div>
  109. </div>
  110. </a-modal>
  111. </template>
  112. <script setup lang="ts">
  113. import { ref, nextTick, watch, computed, onMounted, onBeforeUnmount } from 'vue';
  114. import dayjs from 'dayjs';
  115. import {
  116. unifiedStream,
  117. reviewPdfStream,
  118. chatResumeStream,
  119. getHistoryList,
  120. getDetail,
  121. deleteSession,
  122. pinSession,
  123. editSessionTitle,
  124. getContext,
  125. switchThinking,
  126. getModelMsg,
  127. getSessionMode,
  128. putSessionMode,
  129. } from '../api';
  130. import { message, Modal } from 'ant-design-vue';
  131. import TaskListPanel from './chatModal/TaskListPanel.vue';
  132. import FileListPanel from './chatModal/FileListPanel.vue';
  133. import ChatMessages from './chatModal/ChatMessages.vue';
  134. import ChatInputArea from './chatModal/ChatInputArea.vue';
  135. import FilePreviewPanel from './chatModal/FilePreviewPanel.vue';
  136. import TodoListBar from './chatModal/TodoListBar.vue';
  137. import type { AttachedFile, Message, Task } from './chatModal/types';
  138. interface Props {
  139. visible: boolean;
  140. }
  141. interface Emits {
  142. (e: 'close'): void;
  143. }
  144. const props = defineProps<Props>();
  145. const emit = defineEmits<Emits>();
  146. const taskList = ref<Task[]>([]);
  147. // 从接口获取会话列表
  148. const fetchSessionList = async () => {
  149. try {
  150. const res = await getHistoryList({});
  151. const sessions = res?.sessions || res?.data || [];
  152. if (Array.isArray(sessions)) {
  153. const apiTasks: Task[] = sessions.map((item: { session_id: string; title: string; updated_at: string; sort_order?: number }) => ({
  154. id: item.session_id,
  155. name: item.title || '未命名会话',
  156. sessionId: item.session_id,
  157. messages: [],
  158. attachedFiles: [],
  159. updatedAt: item.updated_at,
  160. sortOrder: item.sort_order,
  161. }));
  162. const mergedTasks = apiTasks.map((apiTask) => {
  163. const existing = taskList.value.find((t) => t.id === apiTask.id);
  164. if (existing) {
  165. return {
  166. ...apiTask,
  167. messages: existing.messages,
  168. attachedFiles: existing.attachedFiles,
  169. wordUrl: existing.wordUrl,
  170. };
  171. }
  172. return apiTask;
  173. });
  174. const localOnlyTasks = taskList.value.filter((t) => !t.sessionId && !apiTasks.find((a) => a.id === t.id));
  175. taskList.value = [...localOnlyTasks, ...mergedTasks];
  176. return mergedTasks;
  177. }
  178. } catch (error) {
  179. console.error('获取会话列表失败:', error);
  180. }
  181. return [];
  182. };
  183. const currentTaskId = ref('');
  184. const chatInputRef = ref<InstanceType<typeof ChatInputArea>>();
  185. const chatMessagesRef = ref<InstanceType<typeof ChatMessages>>();
  186. const previewFile = ref<AttachedFile | null>(null);
  187. const showFileList = ref(false);
  188. const pendingFile = ref<AttachedFile | null>(null);
  189. const messages = ref<Message[]>([]);
  190. const contextUsed = ref(0);
  191. const contextMax = ref(1000000);
  192. const contextPercent = ref(0);
  193. const thinkLevel = ref('off');
  194. const editMode = ref('full');
  195. const pendingApprovalSessionId = ref('');
  196. const pendingApprovalThreadId = ref('');
  197. const downloadConfirm = ref<{ url: string; filename: string } | null>(null);
  198. const downloadConfirmTaskId = ref('');
  199. let downloadConfirmTimer: ReturnType<typeof setTimeout> | null = null;
  200. const clearDownloadConfirm = () => {
  201. downloadConfirm.value = null;
  202. downloadConfirmTaskId.value = '';
  203. if (downloadConfirmTimer) {
  204. clearTimeout(downloadConfirmTimer);
  205. downloadConfirmTimer = null;
  206. }
  207. };
  208. const startDownloadConfirmTimer = () => {
  209. if (downloadConfirmTimer) clearTimeout(downloadConfirmTimer);
  210. downloadConfirmTimer = setTimeout(() => {
  211. clearDownloadConfirm();
  212. }, 10000);
  213. };
  214. const contextBreakdown = ref({ messages: 0, mcp: 0, skills: 0, system_prompt: 0, other: 0 });
  215. const currentTodos = ref<Array<{ content: string; status: string }>>([]);
  216. const showTodoBar = ref(false);
  217. const syncTodoBarFromMessages = () => {
  218. for (let i = messages.value.length - 1; i >= 0; i--) {
  219. const msg = messages.value[i];
  220. if (msg.type === 'ai' && msg.thinkingSteps) {
  221. for (let j = msg.thinkingSteps.length - 1; j >= 0; j--) {
  222. const step = msg.thinkingSteps[j];
  223. if (step.type === 'updated_todo_list' && step.todos) {
  224. currentTodos.value = [...step.todos];
  225. showTodoBar.value = true;
  226. return;
  227. }
  228. }
  229. }
  230. }
  231. showTodoBar.value = false;
  232. currentTodos.value = [];
  233. };
  234. const panelCollapsed = ref(false);
  235. const togglePanel = () => {
  236. panelCollapsed.value = !panelCollapsed.value;
  237. };
  238. const editingTitle = ref(false);
  239. const editTitleValue = ref('');
  240. const startEditTitle = () => {
  241. if (!currentTask.value?.sessionId) return;
  242. editTitleValue.value = currentTask.value.name;
  243. editingTitle.value = true;
  244. nextTick(() => {
  245. const input = document.querySelector('.title-edit-input') as HTMLInputElement;
  246. input?.focus();
  247. input?.select();
  248. });
  249. };
  250. const saveTitle = async () => {
  251. const newTitle = editTitleValue.value.trim();
  252. if (!currentTask.value?.sessionId || !newTitle || newTitle === currentTask.value.name) {
  253. editingTitle.value = false;
  254. return;
  255. }
  256. try {
  257. await editSessionTitle(currentTask.value.sessionId, newTitle);
  258. currentTask.value.name = newTitle;
  259. message.success('标题修改成功');
  260. } catch {
  261. message.error('标题修改失败');
  262. }
  263. editingTitle.value = false;
  264. };
  265. const cancelEditTitle = () => {
  266. editingTitle.value = false;
  267. };
  268. const isFullscreen = ref(false);
  269. const toggleFullscreen = () => {
  270. isFullscreen.value = !isFullscreen.value;
  271. nextTick(() => {
  272. const wraps = document.querySelectorAll<HTMLElement>('.zxm-modal-wrap, .ant-modal-wrap, [class*="modal-wrap"]');
  273. wraps.forEach((wrap) => {
  274. if (isFullscreen.value) {
  275. wrap.style.position = '';
  276. wrap.style.left = '';
  277. wrap.style.top = '0';
  278. wrap.style.right = '';
  279. wrap.style.bottom = '';
  280. wrap.style.width = '';
  281. wrap.style.height = '';
  282. wrap.style.margin = '0';
  283. wrap.style.padding = '0';
  284. wrap.style.transform = '';
  285. } else {
  286. wrap.style.position = '';
  287. wrap.style.left = '';
  288. wrap.style.top = '';
  289. wrap.style.right = '';
  290. wrap.style.bottom = '';
  291. wrap.style.width = '';
  292. wrap.style.height = '';
  293. wrap.style.margin = '';
  294. wrap.style.padding = '';
  295. wrap.style.transform = '';
  296. }
  297. });
  298. draggedEl = null;
  299. if (!isFullscreen.value) {
  300. centerModal();
  301. }
  302. });
  303. };
  304. const inputMessage = ref('');
  305. const loading = ref(false);
  306. const selectedSessions = ref<Array<{ id: string; name: string }>>([]);
  307. const getCurrentSessionId = (): string => {
  308. const currentTask = taskList.value.find((t) => t.id === currentTaskId.value);
  309. return currentTask?.sessionId || '';
  310. };
  311. const historyLoadedTasks = ref<Set<string>>(new Set());
  312. const setCurrentSessionId = (sessionId: string) => {
  313. const currentTask = taskList.value.find((t) => t.id === currentTaskId.value);
  314. if (currentTask && currentTask.id !== sessionId) {
  315. taskList.value = taskList.value.filter((t) => t.id !== sessionId);
  316. currentTask.id = sessionId;
  317. currentTask.sessionId = sessionId;
  318. currentTaskId.value = sessionId;
  319. historyLoadedTasks.value.add(sessionId);
  320. }
  321. };
  322. const switchTask = async (taskId: string) => {
  323. const currentTask = taskList.value.find((t) => t.id === currentTaskId.value);
  324. if (currentTask) {
  325. currentTask.messages = [...messages.value];
  326. }
  327. currentTaskId.value = taskId;
  328. const newTask = taskList.value.find((t) => t.id === taskId);
  329. if (!newTask) return;
  330. inputMessage.value = '';
  331. pendingFile.value = null;
  332. previewFile.value = null;
  333. showFileList.value = false;
  334. if (newTask.sessionId && !historyLoadedTasks.value.has(taskId)) {
  335. loading.value = true;
  336. try {
  337. const res = await getDetail(newTask.sessionId);
  338. const messages = res?.messages || (Array.isArray(res) ? res : res?.data);
  339. if (Array.isArray(messages)) {
  340. newTask.messages = transformHistoryToMessages(messages);
  341. }
  342. historyLoadedTasks.value.add(taskId);
  343. } catch (error) {
  344. console.error('加载历史会话失败:', error);
  345. } finally {
  346. loading.value = false;
  347. }
  348. }
  349. if (newTask.sessionId) {
  350. fetchContext(newTask.sessionId);
  351. fetchSessionMode(newTask.sessionId);
  352. } else {
  353. contextUsed.value = 0;
  354. contextPercent.value = 0;
  355. contextBreakdown.value = { messages: 0, mcp: 0, skills: 0, system_prompt: 0, other: 0 };
  356. editMode.value = 'full';
  357. }
  358. messages.value = newTask.messages && newTask.messages.length > 0 ? [...newTask.messages] : getDefaultMessages();
  359. syncTodoBarFromMessages();
  360. await nextTick();
  361. chatMessagesRef.value?.forceScrollToBottom();
  362. };
  363. const createNewTask = () => {
  364. const existingBlank = taskList.value.find((t) => !t.sessionId);
  365. if (existingBlank) {
  366. switchTask(existingBlank.id);
  367. return;
  368. }
  369. const newTask: Task = {
  370. id: `task-${Date.now()}`,
  371. name: '新任务',
  372. sessionId: '',
  373. messages: getDefaultMessages(),
  374. attachedFiles: [],
  375. };
  376. contextUsed.value = 0;
  377. contextPercent.value = 0;
  378. contextBreakdown.value = { messages: 0, mcp: 0, skills: 0, system_prompt: 0, other: 0 };
  379. editMode.value = 'full';
  380. taskList.value.unshift(newTask);
  381. switchTask(newTask.id);
  382. };
  383. const handlePinTask = async (task: Task) => {
  384. if (!task.sessionId) {
  385. message.warning('请先发送消息后再置顶');
  386. return;
  387. }
  388. try {
  389. await pinSession(task.sessionId);
  390. await fetchSessionList();
  391. } catch {
  392. message.error('置顶操作失败');
  393. }
  394. };
  395. const handleThinkLevelChange = async (levelKey: string) => {
  396. try {
  397. await switchThinking(levelKey);
  398. } catch {
  399. message.error('切换思考级别失败');
  400. }
  401. };
  402. const handleUpdateSelectedSessions = (sessions: Array<{ id: string; name: string }>) => {
  403. selectedSessions.value = sessions;
  404. };
  405. const getSessionRefIconUrl = () => {
  406. const val = getComputedStyle(document.documentElement).getPropertyValue('--img-chat-popup-session-icon').trim();
  407. return val.replace(/^url\(["']?/, '').replace(/["']?\)$/, '');
  408. };
  409. const handleEditModeChange = async (modeKey: string) => {
  410. editMode.value = modeKey;
  411. const sessionId = getCurrentSessionId();
  412. if (!sessionId) return;
  413. try {
  414. await putSessionMode(sessionId, modeKey);
  415. } catch {
  416. message.error('切换模式失败');
  417. }
  418. };
  419. const handleApprove = async () => {
  420. const sessionId = pendingApprovalSessionId.value || getCurrentSessionId();
  421. if (!sessionId) return;
  422. const approveTask = taskList.value.find((t) => t.sessionId === sessionId);
  423. if (!approveTask) return;
  424. const taskMessages = approveTask.messages;
  425. const lastMsg = taskMessages[taskMessages.length - 1];
  426. if (!lastMsg || !lastMsg.isPendingApproval) return;
  427. // 复用同一条消息继续渲染:清除审批状态,恢复 loading,重置前端计时起点
  428. lastMsg.isPendingApproval = false;
  429. lastMsg.pendingApprovalData = undefined;
  430. lastMsg.isLoading = true;
  431. lastMsg.generateStartTime = Date.now();
  432. // thinkingSteps、thinkingContent、baseDurationMs 保持不变,后续继续累积
  433. const aiMsgIndex = taskMessages.length - 1;
  434. approveTask.messages = [...taskMessages];
  435. if (currentTaskId.value === approveTask.id) {
  436. messages.value = approveTask.messages;
  437. await scrollToBottom();
  438. }
  439. loading.value = true;
  440. approveTask.isStreaming = true;
  441. showTodoBar.value = false;
  442. currentTodos.value = [];
  443. try {
  444. const result = await chatResumeStream(
  445. {
  446. session_id: sessionId,
  447. thread_id: pendingApprovalThreadId.value || undefined,
  448. action: 'approve',
  449. },
  450. (chunk: string) => {
  451. parseSSEData(chunk, aiMsgIndex, approveTask.id);
  452. if (currentTaskId.value === approveTask.id) scrollToBottom();
  453. }
  454. );
  455. if (result.session_id) {
  456. setCurrentSessionId(result.session_id);
  457. }
  458. } catch (error) {
  459. console.error('审批继续执行失败:', error);
  460. message.error('审批失败,请重试');
  461. lastMsg.isLoading = false;
  462. if (!lastMsg.content) {
  463. lastMsg.content = '抱歉,审批请求失败,请稍后重试。';
  464. }
  465. } finally {
  466. loading.value = false;
  467. approveTask.isStreaming = false;
  468. pendingApprovalSessionId.value = '';
  469. pendingApprovalThreadId.value = '';
  470. if (currentTaskId.value === approveTask.id) {
  471. await scrollToBottom();
  472. }
  473. }
  474. };
  475. const handleReject = async () => {
  476. const sessionId = pendingApprovalSessionId.value || getCurrentSessionId();
  477. if (!sessionId) return;
  478. const rejectTask = taskList.value.find((t) => t.sessionId === sessionId);
  479. if (!rejectTask) return;
  480. const taskMessages = rejectTask.messages;
  481. const lastMsg = taskMessages[taskMessages.length - 1];
  482. if (!lastMsg || !lastMsg.isPendingApproval) return;
  483. // 复用同一条消息:清除审批状态,标记为已拒绝
  484. lastMsg.isPendingApproval = false;
  485. lastMsg.pendingApprovalData = undefined;
  486. lastMsg.isLoading = false;
  487. lastMsg.content = (lastMsg.content ? lastMsg.content + '\n\n' : '') + '已拒绝执行计划。';
  488. rejectTask.messages = [...taskMessages];
  489. pendingApprovalSessionId.value = '';
  490. pendingApprovalThreadId.value = '';
  491. try {
  492. await chatResumeStream(
  493. {
  494. session_id: sessionId,
  495. thread_id: pendingApprovalThreadId.value || undefined,
  496. action: 'reject',
  497. },
  498. () => {}
  499. );
  500. } catch (error) {
  501. console.error('拒绝操作失败:', error);
  502. }
  503. if (currentTaskId.value === rejectTask.id) {
  504. messages.value = rejectTask.messages;
  505. await scrollToBottom();
  506. }
  507. };
  508. const handleDeleteTask = (task: Task, _index: number) => {
  509. Modal.confirm({
  510. title: '提示',
  511. content: '是否删除该对话?',
  512. okText: '确认',
  513. cancelText: '取消',
  514. wrapClassName: 'delete-task-confirm-modal',
  515. onOk: async () => {
  516. try {
  517. if (task.sessionId) {
  518. await deleteSession(task.sessionId);
  519. }
  520. const realIndex = taskList.value.findIndex((t) => t.id === task.id);
  521. if (realIndex !== -1) {
  522. taskList.value.splice(realIndex, 1);
  523. }
  524. if (currentTaskId.value === task.id) {
  525. if (taskList.value.length > 0) {
  526. switchTask(taskList.value[0].id);
  527. } else {
  528. messages.value = [];
  529. currentTaskId.value = '';
  530. }
  531. }
  532. message.success('删除成功');
  533. } catch {
  534. message.error('删除失败');
  535. }
  536. },
  537. });
  538. };
  539. const getDefaultMessages = (): Message[] => {
  540. return [];
  541. };
  542. const normalizeLineBreaks = (str: string): string => {
  543. if (!str) return '';
  544. return str.replace(/\\n/g, '\n').replace(/\r\n/g, '\n');
  545. };
  546. const transformHistoryToMessages = (data: Array<{ role?: string; type?: string; content: string; created_at?: string }>): Message[] => {
  547. const messages: Message[] = [];
  548. for (const item of data) {
  549. const normalizedContent = normalizeLineBreaks(item.content);
  550. const time = item.created_at ? dayjs(item.created_at).format('HH:mm') : '';
  551. const createdAt = item.created_at || '';
  552. // 新格式:role 字段 (user/assistant)
  553. if (item.role === 'user') {
  554. messages.push({ type: 'user', content: normalizedContent, time, createdAt });
  555. } else if (item.role === 'assistant') {
  556. messages.push({ type: 'ai', content: normalizedContent, time, createdAt });
  557. }
  558. // 兼容旧格式:type 字段
  559. else if (item.type === 'user_message') {
  560. messages.push({ type: 'user', content: normalizedContent, time, createdAt });
  561. } else if (item.type === 'model_thinking') {
  562. const lastAiMsg = messages[messages.length - 1];
  563. if (lastAiMsg && lastAiMsg.type === 'ai') {
  564. lastAiMsg.content += normalizedContent;
  565. lastAiMsg.content = lastAiMsg.content.replace(/\|\|\|SPLIT_CONTENT\|\|\|/g, '');
  566. } else {
  567. messages.push({ type: 'ai', content: normalizedContent, time, createdAt });
  568. }
  569. }
  570. }
  571. return messages;
  572. };
  573. const triggerFileUpload = () => {
  574. chatInputRef.value?.fileInputRef?.click();
  575. };
  576. const handleFileUpload = async (event: Event) => {
  577. const target = event.target as HTMLInputElement;
  578. const file = target.files?.[0];
  579. if (!file) return;
  580. try {
  581. const newFile: AttachedFile = {
  582. id: `file-${Date.now()}`,
  583. name: file.name,
  584. size: file.size,
  585. type: file.type,
  586. uploadTime: dayjs().format('YYYY-MM-DD HH:mm'),
  587. originalFile: file,
  588. };
  589. const reader = new FileReader();
  590. reader.onload = (e) => {
  591. newFile.preview = e.target?.result as string;
  592. };
  593. reader.readAsDataURL(file);
  594. pendingFile.value = newFile;
  595. message.success(`文件 "${file.name}" 已添加,点击发送按钮提交`);
  596. } catch (error) {
  597. console.error('文件处理失败:', error);
  598. message.error('文件处理失败,请重试');
  599. }
  600. target.value = '';
  601. };
  602. const removePendingFile = () => {
  603. pendingFile.value = null;
  604. };
  605. const removePreviewFile = () => {
  606. previewFile.value = null;
  607. };
  608. const openFilePreview = (file: AttachedFile) => {
  609. previewFile.value = file;
  610. const msgIndex = messages.value.findIndex((m) => m.attachedFile?.id === file.id);
  611. if (msgIndex !== -1) {
  612. nextTick(() => {
  613. const messageElements = chatMessagesRef.value?.messagesRef?.querySelectorAll('.message-wrapper');
  614. if (messageElements && messageElements[msgIndex]) {
  615. (messageElements[msgIndex] as HTMLElement).scrollIntoView({
  616. behavior: 'smooth',
  617. block: 'center',
  618. });
  619. }
  620. });
  621. }
  622. };
  623. const getCurrentTaskFiles = (): AttachedFile[] => {
  624. const currentTask = taskList.value.find((t) => t.id === currentTaskId.value);
  625. return currentTask?.attachedFiles || [];
  626. };
  627. const currentTask = computed(() => taskList.value.find((t) => t.id === currentTaskId.value));
  628. const currentWordUrl = computed(() => {
  629. return currentTask.value?.wordUrl || '';
  630. });
  631. const currentTaskIndex = computed(() => taskList.value.findIndex((t) => t.id === currentTaskId.value));
  632. const canGoPrev = computed(() => currentTaskIndex.value > 0);
  633. const canGoNext = computed(() => currentTaskIndex.value >= 0 && currentTaskIndex.value < taskList.value.length - 1);
  634. const goToPrev = () => {
  635. if (!canGoPrev.value) return;
  636. const prevTask = taskList.value[currentTaskIndex.value - 1];
  637. if (prevTask) switchTask(prevTask.id);
  638. };
  639. const goToNext = () => {
  640. if (!canGoNext.value) return;
  641. const nextTask = taskList.value[currentTaskIndex.value + 1];
  642. if (nextTask) switchTask(nextTask.id);
  643. };
  644. const downloadWordReport = () => {
  645. const url = currentWordUrl.value;
  646. if (!url) return;
  647. const a = document.createElement('a');
  648. a.href = url;
  649. a.download = '';
  650. a.target = '_blank';
  651. document.body.appendChild(a);
  652. a.click();
  653. document.body.removeChild(a);
  654. };
  655. const doDownload = () => {
  656. if (!downloadConfirm.value) return;
  657. const a = document.createElement('a');
  658. a.href = downloadConfirm.value.url;
  659. a.download = downloadConfirm.value.filename;
  660. document.body.appendChild(a);
  661. a.click();
  662. document.body.removeChild(a);
  663. clearDownloadConfirm();
  664. };
  665. const downloadWordFile = (url: string) => {
  666. if (!url) return;
  667. const a = document.createElement('a');
  668. a.href = url;
  669. a.download = '';
  670. a.target = '_blank';
  671. document.body.appendChild(a);
  672. a.click();
  673. document.body.removeChild(a);
  674. };
  675. const handleSendMessage = async () => {
  676. const hasText = inputMessage.value.trim();
  677. const hasFile = pendingFile.value;
  678. if (!hasText) {
  679. message.warning('请输入消息内容');
  680. return;
  681. }
  682. if (loading.value) return;
  683. if (pendingApprovalSessionId.value) {
  684. message.warning('请先审批执行计划');
  685. return;
  686. }
  687. const sessionPrefix = selectedSessions.value.length > 0 ? selectedSessions.value.map((s) => `#session:${s.id}`).join(' ') + ' ' : '';
  688. const userInput = sessionPrefix + inputMessage.value.trim();
  689. let displayContent = inputMessage.value.trim();
  690. if (selectedSessions.value.length > 0) {
  691. const names = selectedSessions.value.map((s) => s.name).join('、');
  692. const iconUrl = getSessionRefIconUrl();
  693. displayContent = `[<img src="${iconUrl}" class="session-ref-icon" /> 引用 ${selectedSessions.value.length} 个会话:${names}] ${displayContent}`;
  694. }
  695. const fileToSend = pendingFile.value;
  696. inputMessage.value = '';
  697. pendingFile.value = null;
  698. selectedSessions.value = [];
  699. try {
  700. loading.value = true;
  701. await nextTick();
  702. chatMessagesRef.value?.forceScrollToBottom();
  703. if (hasFile) {
  704. await sendWithAttachment(fileToSend!, userInput, displayContent);
  705. } else {
  706. await sendTextOnly(userInput, displayContent);
  707. }
  708. } catch (error) {
  709. console.error('发送消息失败:', error);
  710. message.error('发送失败,请重试');
  711. const lastMsg = messages.value[messages.value.length - 1];
  712. if (lastMsg && lastMsg.type === 'ai' && lastMsg.isLoading) {
  713. messages.value.pop();
  714. }
  715. const errorMsg: Message = {
  716. type: 'ai',
  717. content: '抱歉,请求失败,请稍后重试。',
  718. time: dayjs().format('HH:mm'),
  719. };
  720. messages.value.push(errorMsg);
  721. const currentTask = taskList.value.find((t) => t.id === currentTaskId.value);
  722. if (currentTask) {
  723. currentTask.messages = [...messages.value];
  724. }
  725. } finally {
  726. loading.value = false;
  727. await scrollToBottom();
  728. }
  729. };
  730. const extractAgentName = (toolName: string): string => {
  731. const nameMap: Record<string, string> = {
  732. form_review: '形式审查',
  733. verify_coal_face_ventilation: '采煤工作面需风量计算核验',
  734. verify_tunneling_face_ventilation: '掘进工作面需风量计算核验',
  735. verify_chamber_ventilation: '硐室需风量计算核验',
  736. verify_other_points_ventilation: '其他地点需风量计算核验',
  737. check_data_by_gas_report: '瓦斯数据一致性审查',
  738. check_data_by_face_design: '设计规程一致性审查',
  739. check_data_by_vent_report: '测风报表一致性审查',
  740. check_current_month_plan: '日期有效性审查',
  741. get_key_translate: '计算参数对照',
  742. calculate_ventilation: '需风量计算',
  743. get_ventilation_data: '需风量查询',
  744. recalculate_ventilation: '需风量重计算',
  745. get_plan_required_wind: '需风量提取',
  746. get_model_calculated_wind: '三维模型解算风量提取',
  747. get_sensor_wind: '巷道监测风量提取',
  748. merge_wind_by_location: '地点风量智能合并',
  749. check_wind_compliance: '风量检查',
  750. };
  751. return nameMap[toolName] || nameMap[toolName.toLowerCase()] || '智能分析助手';
  752. };
  753. // 累积所有步骤,保留完整历史
  754. const upsertStep = (steps: any[], step: any) => {
  755. steps.push(step);
  756. };
  757. const fetchModelMsg = async () => {
  758. try {
  759. const res = await getModelMsg();
  760. if (res?.thinking_level) {
  761. thinkLevel.value = res.thinking_level;
  762. }
  763. } catch (e) {
  764. console.error('获取模型信息失败:', e);
  765. }
  766. };
  767. const fetchSessionMode = async (sessionId: string) => {
  768. try {
  769. const res = await getSessionMode(sessionId);
  770. if (res?.mode) {
  771. editMode.value = res.mode;
  772. }
  773. } catch (e) {
  774. console.error('获取会话模式失败:', e);
  775. }
  776. };
  777. const fetchContext = async (sessionId: string) => {
  778. try {
  779. const res = await getContext(sessionId);
  780. if (res?.current_usage != null) {
  781. contextUsed.value = res.current_usage;
  782. }
  783. if (res?.total_limit != null) {
  784. contextMax.value = res.total_limit;
  785. }
  786. if (res?.usage_pct != null) {
  787. contextPercent.value = res.usage_pct;
  788. }
  789. if (res?.breakdown) {
  790. contextBreakdown.value = res.breakdown;
  791. }
  792. } catch (e) {
  793. console.error('获取上下文容量失败:', e);
  794. }
  795. };
  796. const handleSSEMessage = (data: any, aiMsgIndex: number, taskId: string) => {
  797. const streamingTask = taskList.value.find((t) => t.id === taskId);
  798. if (!streamingTask) return;
  799. // 当前正在查看流式任务时,新消息被 push 到 messages.value 而非 task.messages
  800. // 所以需要从 messages.value 读取;否则从任务存储的 messages 读取
  801. const isViewingTask = currentTaskId.value === taskId;
  802. const sourceArr = isViewingTask ? messages.value : streamingTask.messages;
  803. const aiMsg = sourceArr[aiMsgIndex];
  804. if (!aiMsg) return;
  805. const normalizedContent = normalizeLineBreaks(data.content || '');
  806. // 初始化 thinkingSteps 数组
  807. if (!aiMsg.thinkingSteps) {
  808. aiMsg.thinkingSteps = [];
  809. }
  810. switch (data.type) {
  811. // token 流式内容 - 直接拼接到消息内容
  812. case 'token':
  813. if (normalizedContent) {
  814. aiMsg.content += normalizedContent;
  815. }
  816. break;
  817. // thinking_token - 模型思考过程内容
  818. case 'thinking_token':
  819. if (normalizedContent) {
  820. aiMsg.thinkingContent = (aiMsg.thinkingContent || '') + normalizedContent;
  821. }
  822. break;
  823. // 系统进度消息 - 仅当 agent 不是 system 时才作为 thinking step
  824. case 'progress': {
  825. if (data.agent && data.agent !== 'system') {
  826. upsertStep(aiMsg.thinkingSteps!, {
  827. type: 'executing',
  828. agent: data.agent,
  829. message: data.message || '',
  830. timestamp: Date.now(),
  831. });
  832. }
  833. break;
  834. }
  835. // agent 开始处理
  836. case 'agent_start': {
  837. upsertStep(aiMsg.thinkingSteps!, {
  838. type: 'agent_start',
  839. agent: data.cn_agent || data.agent || '智能助手',
  840. message: data.message || '开始处理...',
  841. timestamp: Date.now(),
  842. });
  843. break;
  844. }
  845. // agent 任务列表更新(同一 agent 的 todos 更新已有条目,不重复添加)
  846. case 'agent_todos':
  847. case 'updated_todo_list': {
  848. const agentName = data.cn_agent || data.agent || '智能助手';
  849. const existingIdx = aiMsg.thinkingSteps!.findIndex((s) => s.type === 'updated_todo_list' && s.agent === agentName);
  850. if (existingIdx !== -1) {
  851. aiMsg.thinkingSteps![existingIdx].todos = data.todos || [];
  852. aiMsg.thinkingSteps![existingIdx].timestamp = Date.now();
  853. } else {
  854. aiMsg.thinkingSteps!.push({
  855. type: 'updated_todo_list',
  856. agent: agentName,
  857. todos: data.todos || [],
  858. message: data.message || '任务进度已更新',
  859. timestamp: Date.now(),
  860. });
  861. }
  862. currentTodos.value = [...(data.todos || [])];
  863. showTodoBar.value = true;
  864. break;
  865. }
  866. // agent 执行中(工具调用)
  867. case 'agent_executing':
  868. case 'executing': {
  869. upsertStep(aiMsg.thinkingSteps!, {
  870. type: 'executing',
  871. agent: data.cn_agent || data.agent || '智能助手',
  872. tool: (data.cn_tools || data.tools || []).join('、'),
  873. message: data.message || '',
  874. timestamp: Date.now(),
  875. });
  876. break;
  877. }
  878. // 工具结果
  879. case 'agent_tool_result':
  880. case 'tool_result': {
  881. upsertStep(aiMsg.thinkingSteps!, {
  882. type: 'tool_result',
  883. agent: data.cn_agent || data.agent || '智能助手',
  884. tool: data.cn_tool || data.tool || '',
  885. message: data.message || '执行完成',
  886. timestamp: Date.now(),
  887. });
  888. if (data.download_url) {
  889. downloadConfirm.value = { url: data.download_url, filename: data.filename || '文件' };
  890. downloadConfirmTaskId.value = taskId;
  891. startDownloadConfirmTimer();
  892. }
  893. break;
  894. }
  895. // agent 完成
  896. case 'agent_done': {
  897. upsertStep(aiMsg.thinkingSteps!, {
  898. type: 'agent_done',
  899. agent: data.cn_agent || data.agent || '智能助手',
  900. message: `${(data.message || '审查完成').replace(/(\d+ms)/g, '')}${data.duration_ms ? `(${(data.duration_ms / 1000).toFixed(0)}s)` : ''}${data.progress ? ` [${data.progress}]` : ''}`,
  901. timestamp: Date.now(),
  902. });
  903. // 累加后端返回的各段耗时,并重置前端计时起点,避免重复计算已验证的时间段
  904. if (data.duration_ms) {
  905. aiMsg.baseDurationMs = (aiMsg.baseDurationMs || 0) + data.duration_ms;
  906. aiMsg.generateStartTime = Date.now();
  907. }
  908. if (data.preview) {
  909. aiMsg.content += data.preview;
  910. }
  911. break;
  912. }
  913. // 旧格式兼容
  914. case 'model_thinking':
  915. if (normalizedContent) {
  916. aiMsg.content += normalizedContent;
  917. aiMsg.content = aiMsg.content.replace(/\|\|\|SPLIT_CONTENT\|\|\|/g, '');
  918. }
  919. break;
  920. case 'tool_select': {
  921. upsertStep(aiMsg.thinkingSteps!, {
  922. type: 'tool_call',
  923. agent: extractAgentName(normalizedContent),
  924. tool: normalizedContent,
  925. message: `选择工具:${normalizedContent}`,
  926. timestamp: Date.now(),
  927. });
  928. break;
  929. }
  930. case 'error':
  931. upsertStep(aiMsg.thinkingSteps!, {
  932. type: 'tool_result',
  933. agent: '系统',
  934. message: `❌ 执行失败:${normalizedContent}`,
  935. timestamp: Date.now(),
  936. });
  937. aiMsg.isLoading = false;
  938. break;
  939. case 'word_download':
  940. if (normalizedContent) {
  941. aiMsg.wordDownloadUrl = normalizedContent;
  942. streamingTask.wordUrl = normalizedContent;
  943. }
  944. break;
  945. case 'done':
  946. if (data.session_id) {
  947. aiMsg.sessionId = data.session_id;
  948. fetchContext(data.session_id);
  949. }
  950. if (data.duration_ms) {
  951. aiMsg.durationMs = (aiMsg.baseDurationMs || 0) + data.duration_ms;
  952. }
  953. aiMsg.isLoading = false;
  954. break;
  955. case 'system':
  956. if (normalizedContent) {
  957. aiMsg.content += normalizedContent.replace(/\n/g, ' \n');
  958. }
  959. break;
  960. case 'interrupt': {
  961. // 优先使用 agent_done 已设置的后端时间,否则用前端计时
  962. const elapsedMs = aiMsg.baseDurationMs || (aiMsg.generateStartTime ? Date.now() - aiMsg.generateStartTime : 0);
  963. aiMsg.isLoading = false;
  964. aiMsg.isPendingApproval = true;
  965. const interruptSessionId = data.session_id || streamingTask.sessionId;
  966. aiMsg.pendingApprovalData = {
  967. message: data.message || '智能体制定了执行计划,等待您的审批...',
  968. sessionId: interruptSessionId,
  969. threadId: data.thread_id,
  970. interrupts: data.interrupts,
  971. elapsedMs,
  972. prevThinkingContent: aiMsg.thinkingContent,
  973. };
  974. pendingApprovalSessionId.value = interruptSessionId;
  975. pendingApprovalThreadId.value = data.thread_id || '';
  976. break;
  977. }
  978. }
  979. // 保存到流式任务的 messages,并同步 UI
  980. if (isViewingTask) {
  981. streamingTask.messages = [...messages.value];
  982. } else {
  983. streamingTask.messages = [...streamingTask.messages];
  984. }
  985. };
  986. const parseSSEData = (chunk: string, aiMsgIndex: number, taskId: string) => {
  987. const lines = chunk.split('\n');
  988. for (const lineRaw of lines) {
  989. const line = lineRaw.trim();
  990. if (!line) continue;
  991. if (line.startsWith('data:')) {
  992. try {
  993. const jsonStr = line.substring(5).trim();
  994. const data = JSON.parse(jsonStr);
  995. handleSSEMessage(data, aiMsgIndex, taskId);
  996. } catch (error) {
  997. console.error('解析 SSE data 行失败:', error, line);
  998. }
  999. continue;
  1000. }
  1001. try {
  1002. const data = JSON.parse(line);
  1003. handleSSEMessage(data, aiMsgIndex, taskId);
  1004. continue;
  1005. } catch {
  1006. // not json
  1007. }
  1008. handleSSEMessage({ type: 'model_thinking', content: line }, aiMsgIndex, taskId);
  1009. }
  1010. };
  1011. const sendTextOnly = async (userInput: string, displayContent?: string) => {
  1012. const originTaskId = currentTaskId.value;
  1013. const now = dayjs();
  1014. const userMsg: Message = {
  1015. type: 'user',
  1016. content: displayContent || userInput,
  1017. time: now.format('HH:mm'),
  1018. createdAt: now.toISOString(),
  1019. };
  1020. messages.value.push(userMsg);
  1021. await scrollToBottom();
  1022. const aiMsgIndex = messages.value.length;
  1023. const aiMsg: Message = {
  1024. type: 'ai',
  1025. content: '',
  1026. time: now.format('HH:mm'),
  1027. createdAt: now.toISOString(),
  1028. isLoading: true,
  1029. thinkingSteps: [],
  1030. generateStartTime: Date.now(),
  1031. };
  1032. messages.value.push(aiMsg);
  1033. await scrollToBottom();
  1034. showTodoBar.value = false;
  1035. currentTodos.value = [];
  1036. const originTask = taskList.value.find((t) => t.id === originTaskId);
  1037. if (originTask) originTask.isStreaming = true;
  1038. try {
  1039. const result = await unifiedStream(
  1040. {
  1041. message: userInput,
  1042. session_id: getCurrentSessionId() || undefined,
  1043. mode: editMode.value,
  1044. },
  1045. (chunk: string) => {
  1046. parseSSEData(chunk, aiMsgIndex, originTaskId);
  1047. if (currentTaskId.value === originTaskId) scrollToBottom();
  1048. }
  1049. );
  1050. if (result.session_id) {
  1051. const originTask = taskList.value.find((t) => t.id === originTaskId);
  1052. if (originTask && !originTask.sessionId) {
  1053. originTask.sessionId = result.session_id;
  1054. originTask.name = userInput.substring(0, 20) + (userInput.length > 20 ? '...' : '');
  1055. if (originTask.id !== result.session_id) {
  1056. taskList.value = taskList.value.filter((t) => t.id !== result.session_id);
  1057. originTask.id = result.session_id;
  1058. historyLoadedTasks.value.add(result.session_id);
  1059. }
  1060. if (currentTaskId.value === originTaskId) {
  1061. currentTaskId.value = result.session_id;
  1062. }
  1063. }
  1064. }
  1065. } finally {
  1066. const originTask = taskList.value.find((t) => t.id === originTaskId);
  1067. if (originTask) originTask.isStreaming = false;
  1068. }
  1069. };
  1070. const sendWithAttachment = async (file: AttachedFile, userInput: string, displayContent?: string) => {
  1071. const originTaskId = currentTaskId.value;
  1072. let currentTask = taskList.value.find((t) => t.id === originTaskId);
  1073. if (currentTask) {
  1074. currentTask.attachedFiles.push(file);
  1075. } else {
  1076. throw new Error('未找到当前任务');
  1077. }
  1078. const now = dayjs();
  1079. const userMsg: Message = {
  1080. type: 'user',
  1081. content: displayContent || userInput || `上传了文件:${file.name}`,
  1082. time: now.format('HH:mm'),
  1083. createdAt: now.toISOString(),
  1084. attachedFile: file,
  1085. };
  1086. messages.value.push(userMsg);
  1087. await scrollToBottom();
  1088. const aiMsgIndex = messages.value.length;
  1089. const aiMsg: Message = {
  1090. type: 'ai',
  1091. content: '',
  1092. time: now.format('HH:mm'),
  1093. createdAt: now.toISOString(),
  1094. isLoading: true,
  1095. thinkingSteps: [],
  1096. generateStartTime: Date.now(),
  1097. };
  1098. messages.value.push(aiMsg);
  1099. await scrollToBottom();
  1100. showTodoBar.value = false;
  1101. currentTodos.value = [];
  1102. if (!file.originalFile) {
  1103. throw new Error('缺少原始文件对象');
  1104. }
  1105. const originTask = taskList.value.find((t) => t.id === originTaskId);
  1106. if (originTask) originTask.isStreaming = true;
  1107. try {
  1108. const result = await reviewPdfStream(
  1109. {
  1110. file: file.originalFile!,
  1111. session_id: getCurrentSessionId() || undefined,
  1112. message: userInput || undefined,
  1113. mode: editMode.value,
  1114. },
  1115. (chunk: string) => {
  1116. parseSSEData(chunk, aiMsgIndex, originTaskId);
  1117. if (currentTaskId.value === originTaskId) scrollToBottom();
  1118. }
  1119. );
  1120. if (result.session_id) {
  1121. const originTask = taskList.value.find((t) => t.id === originTaskId);
  1122. if (originTask && !originTask.sessionId) {
  1123. const taskName = userInput || `文件:${file.name}`;
  1124. originTask.sessionId = result.session_id;
  1125. originTask.name = taskName.substring(0, 20) + (taskName.length > 20 ? '...' : '');
  1126. if (originTask.id !== result.session_id) {
  1127. taskList.value = taskList.value.filter((t) => t.id !== result.session_id);
  1128. originTask.id = result.session_id;
  1129. historyLoadedTasks.value.add(result.session_id);
  1130. }
  1131. if (currentTaskId.value === originTaskId) {
  1132. currentTaskId.value = result.session_id;
  1133. }
  1134. }
  1135. }
  1136. } finally {
  1137. const originTask = taskList.value.find((t) => t.id === originTaskId);
  1138. if (originTask) originTask.isStreaming = false;
  1139. }
  1140. };
  1141. const scrollToBottom = async () => {
  1142. await nextTick();
  1143. if (!chatMessagesRef.value?.isAtBottom) return;
  1144. const el = chatMessagesRef.value?.messagesRef;
  1145. if (el) {
  1146. el.scrollTop = el.scrollHeight;
  1147. }
  1148. };
  1149. watch(
  1150. () => props.visible,
  1151. async (newVisible) => {
  1152. if (!newVisible) {
  1153. const currentTask = taskList.value.find((t) => t.id === currentTaskId.value);
  1154. if (currentTask) {
  1155. currentTask.messages = [...messages.value];
  1156. }
  1157. } else {
  1158. await fetchSessionList();
  1159. fetchModelMsg();
  1160. // 去除重复的空白任务,只保留一个
  1161. taskList.value = taskList.value.filter((task, index) => {
  1162. if (task.sessionId) return true;
  1163. return index === taskList.value.findIndex((t) => !t.sessionId);
  1164. });
  1165. // 默认选中第一条历史记录
  1166. const firstHistoryTask = taskList.value.find((t) => t.sessionId);
  1167. let targetTask: Task;
  1168. if (firstHistoryTask) {
  1169. targetTask = firstHistoryTask;
  1170. } else {
  1171. // 没有历史记录时才创建空白新任务
  1172. targetTask = {
  1173. id: `task-${Date.now()}`,
  1174. name: '新任务',
  1175. sessionId: '',
  1176. messages: getDefaultMessages(),
  1177. attachedFiles: [],
  1178. };
  1179. taskList.value.unshift(targetTask);
  1180. }
  1181. currentTaskId.value = targetTask.id;
  1182. // 如果是历史任务,加载其消息
  1183. if (targetTask.sessionId && !historyLoadedTasks.value.has(targetTask.id)) {
  1184. loading.value = true;
  1185. try {
  1186. const res = await getDetail(targetTask.sessionId);
  1187. const messages = res?.messages || (Array.isArray(res) ? res : res?.data);
  1188. if (Array.isArray(messages)) {
  1189. targetTask.messages = transformHistoryToMessages(messages);
  1190. }
  1191. historyLoadedTasks.value.add(targetTask.id);
  1192. } catch (error) {
  1193. console.error('加载历史会话失败:', error);
  1194. } finally {
  1195. loading.value = false;
  1196. }
  1197. }
  1198. if (targetTask.sessionId) {
  1199. fetchContext(targetTask.sessionId);
  1200. fetchSessionMode(targetTask.sessionId);
  1201. } else {
  1202. contextUsed.value = 0;
  1203. contextPercent.value = 0;
  1204. contextBreakdown.value = { messages: 0, mcp: 0, skills: 0, system_prompt: 0, other: 0 };
  1205. editMode.value = 'full';
  1206. }
  1207. messages.value = targetTask.messages && targetTask.messages.length > 0 ? [...targetTask.messages] : getDefaultMessages();
  1208. previewFile.value = null;
  1209. pendingFile.value = null;
  1210. showFileList.value = false;
  1211. inputMessage.value = '';
  1212. await nextTick(() => {
  1213. chatMessagesRef.value?.forceScrollToBottom();
  1214. });
  1215. }
  1216. }
  1217. );
  1218. // 拖拽相关(使用普通变量避免 mousemove 触发 Vue 响应式导致卡顿)
  1219. let isDragging = false;
  1220. let dragStartX = 0;
  1221. let dragStartY = 0;
  1222. let modalStartLeft = 0;
  1223. let modalStartTop = 0;
  1224. let draggedEl: HTMLElement | null = null;
  1225. const findModalWrap = (target: HTMLElement): HTMLElement | null =>
  1226. target.closest<HTMLElement>('.zxm-modal-wrap, .ant-modal-wrap, [class*="modal-wrap"]');
  1227. const queryModalWrap = (): HTMLElement | null => document.querySelector<HTMLElement>('.zxm-modal-wrap, .ant-modal-wrap, [class*="modal-wrap"]');
  1228. const centerModal = () => {
  1229. nextTick(() => {
  1230. const wrap = queryModalWrap();
  1231. if (wrap) {
  1232. wrap.style.position = '';
  1233. wrap.style.left = '';
  1234. wrap.style.top = '';
  1235. wrap.style.right = '';
  1236. wrap.style.bottom = '';
  1237. wrap.style.width = '';
  1238. wrap.style.height = '';
  1239. wrap.style.margin = '';
  1240. wrap.style.transform = '';
  1241. }
  1242. draggedEl = null;
  1243. });
  1244. };
  1245. const onDragStart = (e: MouseEvent) => {
  1246. if (isFullscreen.value) return;
  1247. draggedEl = findModalWrap(e.target as HTMLElement) || queryModalWrap();
  1248. if (!draggedEl) return;
  1249. isDragging = true;
  1250. dragStartX = e.clientX;
  1251. dragStartY = e.clientY;
  1252. const rect = draggedEl.getBoundingClientRect();
  1253. modalStartLeft = rect.left;
  1254. modalStartTop = rect.top;
  1255. draggedEl.style.position = 'fixed';
  1256. draggedEl.style.left = `${rect.left}px`;
  1257. draggedEl.style.top = `${rect.top}px`;
  1258. draggedEl.style.margin = '0';
  1259. draggedEl.style.transform = 'none';
  1260. document.addEventListener('mousemove', onDragMove);
  1261. document.addEventListener('mouseup', onDragEnd);
  1262. };
  1263. const onDragMove = (e: MouseEvent) => {
  1264. if (!isDragging || !draggedEl) return;
  1265. draggedEl.style.left = `${modalStartLeft + (e.clientX - dragStartX)}px`;
  1266. draggedEl.style.top = `${modalStartTop + (e.clientY - dragStartY)}px`;
  1267. };
  1268. const onDragEnd = () => {
  1269. isDragging = false;
  1270. document.removeEventListener('mousemove', onDragMove);
  1271. document.removeEventListener('mouseup', onDragEnd);
  1272. };
  1273. watch(
  1274. () => props.visible,
  1275. (newVisible) => {
  1276. if (newVisible) {
  1277. centerModal();
  1278. }
  1279. }
  1280. );
  1281. onMounted(async () => {
  1282. // fetchSessionList moved to watch(visible) to avoid unnecessary API calls
  1283. });
  1284. onBeforeUnmount(() => {
  1285. document.removeEventListener('mousemove', onDragMove);
  1286. document.removeEventListener('mouseup', onDragEnd);
  1287. if (downloadConfirmTimer) {
  1288. clearTimeout(downloadConfirmTimer);
  1289. downloadConfirmTimer = null;
  1290. }
  1291. });
  1292. </script>
  1293. <style scoped lang="less">
  1294. .ai-container {
  1295. display: flex;
  1296. height: 700px;
  1297. gap: 10px;
  1298. overflow: hidden;
  1299. font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, 'Helvetica Neue', Arial, sans-serif;
  1300. }
  1301. .collapse-btn {
  1302. position: absolute;
  1303. top: 16px;
  1304. left: 24px;
  1305. z-index: 10;
  1306. width: 32px;
  1307. height: 32px;
  1308. background: #1a6696;
  1309. border-radius: 4px;
  1310. display: flex;
  1311. align-items: center;
  1312. justify-content: center;
  1313. cursor: pointer;
  1314. transition: background 0.3s;
  1315. &:hover {
  1316. background: #1f7ab8;
  1317. }
  1318. .collapse-icon {
  1319. width: 16px;
  1320. height: 16px;
  1321. background-image: var(--img-chat-collapse-icon);
  1322. background-repeat: no-repeat;
  1323. background-size: 100% 100%;
  1324. &.collapsed {
  1325. background-image: var(--img-chat-expand-icon);
  1326. }
  1327. }
  1328. }
  1329. .task-panel-wrapper {
  1330. width: 300px;
  1331. flex-shrink: 0;
  1332. overflow: hidden;
  1333. transition:
  1334. width 0.35s cubic-bezier(0.4, 0, 0.2, 1),
  1335. margin 0.35s cubic-bezier(0.4, 0, 0.2, 1),
  1336. opacity 0.25s ease;
  1337. &.collapsed {
  1338. width: 0;
  1339. margin: 0;
  1340. opacity: 0;
  1341. }
  1342. }
  1343. .chat-panel {
  1344. flex: 1;
  1345. display: flex;
  1346. position: relative;
  1347. flex-direction: column;
  1348. background-image: var(--img-chat-panel-bg);
  1349. background-repeat: no-repeat;
  1350. background-size: 100% 100%;
  1351. border-radius: 4px;
  1352. overflow: hidden;
  1353. min-width: 0;
  1354. .download-confirm-bar {
  1355. display: flex;
  1356. align-items: center;
  1357. justify-content: space-between;
  1358. padding: 10px 16px;
  1359. margin: 0 16px;
  1360. background: #0a2a3f;
  1361. border: 1px solid #1a4a6f;
  1362. border-radius: 8px;
  1363. flex-shrink: 0;
  1364. .download-confirm-text {
  1365. font-size: 13px;
  1366. color: #e0e6ed;
  1367. overflow: hidden;
  1368. text-overflow: ellipsis;
  1369. white-space: nowrap;
  1370. margin-right: 12px;
  1371. }
  1372. .download-confirm-actions {
  1373. display: flex;
  1374. gap: 8px;
  1375. flex-shrink: 0;
  1376. }
  1377. .download-confirm-btn {
  1378. padding: 4px 14px;
  1379. border-radius: 4px;
  1380. font-size: 12px;
  1381. cursor: pointer;
  1382. border: none;
  1383. transition: all 0.2s;
  1384. &.download-btn {
  1385. background: #0a84ff;
  1386. color: #fff;
  1387. &:hover {
  1388. background: #3a9bfd;
  1389. }
  1390. }
  1391. &.cancel-btn {
  1392. background: rgba(255, 255, 255, 0.08);
  1393. color: #e0e6ed;
  1394. border: 1px solid rgba(63, 80, 106, 0.5);
  1395. &:hover {
  1396. background: rgba(255, 255, 255, 0.15);
  1397. }
  1398. }
  1399. }
  1400. }
  1401. :deep(.chat-header) {
  1402. display: flex;
  1403. padding: 12px 20px;
  1404. flex-shrink: 0;
  1405. align-items: center;
  1406. background: rgba(2, 53, 100, 0.3);
  1407. .header-icon {
  1408. width: 35px;
  1409. height: 28px;
  1410. background-image: var(--img-chat-header-icon);
  1411. background-repeat: no-repeat;
  1412. background-size: 100% 100%;
  1413. margin-right: 10px;
  1414. }
  1415. .chat-header-title {
  1416. font-size: 16px;
  1417. color: #e0e6ed;
  1418. overflow: hidden;
  1419. text-overflow: ellipsis;
  1420. white-space: nowrap;
  1421. margin-left: 10px;
  1422. }
  1423. .chat-header-title-wrapper {
  1424. display: flex;
  1425. align-items: center;
  1426. flex: 1;
  1427. min-width: 0;
  1428. &:hover .title-edit-btn {
  1429. opacity: 1;
  1430. }
  1431. .title-edit-btn {
  1432. width: 28px;
  1433. height: 28px;
  1434. flex-shrink: 0;
  1435. background-image: var(--img-chat-edit-icon);
  1436. background-repeat: no-repeat;
  1437. background-size: 16px 16px;
  1438. background-position: center;
  1439. cursor: pointer;
  1440. opacity: 0;
  1441. transition: opacity 0.2s;
  1442. border-radius: 4px;
  1443. margin-right: 4px;
  1444. &:hover {
  1445. background-color: rgba(10, 132, 255, 0.2);
  1446. }
  1447. }
  1448. .chat-header-title {
  1449. margin-left: 0;
  1450. flex: 1;
  1451. min-width: 0;
  1452. }
  1453. .title-edit-input {
  1454. flex: 1;
  1455. min-width: 0;
  1456. height: 28px;
  1457. padding: 0 8px;
  1458. font-size: 14px;
  1459. color: #e0e6ed;
  1460. background: rgba(10, 132, 255, 0.1);
  1461. border: 1px solid rgba(10, 132, 255, 0.5);
  1462. border-radius: 4px;
  1463. outline: none;
  1464. &:focus {
  1465. border-color: rgba(10, 132, 255, 0.8);
  1466. }
  1467. }
  1468. }
  1469. .nav-btn {
  1470. width: 28px;
  1471. height: 28px;
  1472. display: flex;
  1473. align-items: center;
  1474. justify-content: center;
  1475. cursor: pointer;
  1476. border-radius: 4px;
  1477. transition: background 0.2s;
  1478. &:hover:not(.disabled) {
  1479. background: rgba(10, 132, 255, 0.15);
  1480. }
  1481. &.disabled {
  1482. opacity: 0.3;
  1483. cursor: not-allowed;
  1484. }
  1485. .nav-icon {
  1486. width: 16px;
  1487. height: 16px;
  1488. background-repeat: no-repeat;
  1489. background-size: 100% 100%;
  1490. }
  1491. .prev-icon {
  1492. background-image: var(--img-chat-prev-icon);
  1493. }
  1494. .next-icon {
  1495. background-image: var(--img-chat-next-icon);
  1496. }
  1497. .add-icon {
  1498. background-image: var(--img-chat-options-add-icon);
  1499. }
  1500. }
  1501. .upload-bg {
  1502. cursor: pointer;
  1503. width: 36px;
  1504. height: 36px;
  1505. background-image: var(--img-chat-close-bg);
  1506. background-repeat: no-repeat;
  1507. background-size: 100% 100%;
  1508. display: flex;
  1509. align-items: center;
  1510. justify-content: center;
  1511. margin-left: auto;
  1512. position: relative;
  1513. }
  1514. .download-icon {
  1515. width: 20px;
  1516. height: 20px;
  1517. background-image: var(--img-chat-download-icon);
  1518. background-repeat: no-repeat;
  1519. background-size: 100% 100%;
  1520. }
  1521. }
  1522. }
  1523. .right-panel {
  1524. width: calc(50% - 140px);
  1525. height: 100%;
  1526. display: flex;
  1527. flex-direction: column;
  1528. background-image: var(--img-chat-panel-bg);
  1529. background-repeat: no-repeat;
  1530. background-size: 100% 100%;
  1531. border-radius: 4px;
  1532. flex-shrink: 0;
  1533. }
  1534. .draggable-title {
  1535. cursor: grab;
  1536. user-select: none;
  1537. &:active {
  1538. cursor: grabbing;
  1539. }
  1540. &.no-drag {
  1541. cursor: default;
  1542. &:active {
  1543. cursor: default;
  1544. }
  1545. }
  1546. }
  1547. </style>
  1548. <style lang="less">
  1549. .ai-assistant-modal {
  1550. .zxm-modal-content {
  1551. background-image: var(--img-chat-modal-bg);
  1552. background-repeat: no-repeat;
  1553. background-size: 100% 100%;
  1554. background-color: unset !important;
  1555. box-shadow: none;
  1556. padding: 0;
  1557. border: none !important;
  1558. }
  1559. .zxm-modal-close {
  1560. background-image: var(--img-chat-close-bg);
  1561. background-repeat: no-repeat;
  1562. background-size: 100% 100%;
  1563. top: 0px;
  1564. right: 0px;
  1565. width: 38px;
  1566. height: 38px;
  1567. .zxm-modal-close-x {
  1568. width: 38px;
  1569. height: 38px;
  1570. }
  1571. svg {
  1572. width: 26px;
  1573. height: 26px;
  1574. margin-bottom: 4px;
  1575. }
  1576. }
  1577. .maximize-btn {
  1578. position: absolute;
  1579. top: 0px;
  1580. right: 56px;
  1581. width: 38px;
  1582. height: 38px;
  1583. background-image: var(--img-chat-close-bg);
  1584. background-repeat: no-repeat;
  1585. background-size: 100% 100%;
  1586. display: flex;
  1587. align-items: center;
  1588. justify-content: center;
  1589. cursor: pointer;
  1590. z-index: 10;
  1591. .maximize-icon {
  1592. width: 22px;
  1593. height: 22px;
  1594. background-image: var(--img-chat-maximize-icon);
  1595. background-repeat: no-repeat;
  1596. background-size: 100% 100%;
  1597. &.minimized {
  1598. background-image: var(--img-chat-minimize-icon);
  1599. }
  1600. }
  1601. }
  1602. &.fullscreen {
  1603. top: 0 !important;
  1604. padding: 0 !important;
  1605. max-width: 100vw !important;
  1606. margin: 0 !important;
  1607. background-color: #09172c;
  1608. .zxm-modal-wrap,
  1609. .ant-modal-wrap {
  1610. padding: 0 !important;
  1611. margin: 0 !important;
  1612. top: 0 !important;
  1613. }
  1614. .zxm-modal-content {
  1615. width: 100vw !important;
  1616. height: 100vh !important;
  1617. max-width: 100vw !important;
  1618. margin: 0;
  1619. border-radius: 0;
  1620. overflow: hidden;
  1621. background-image: var(--img-chat-fs-modal-bg);
  1622. }
  1623. .zxm-modal-header {
  1624. height: 90px;
  1625. background-image: var(--img-chat-fs-header-bg) !important;
  1626. background-repeat: no-repeat;
  1627. background-size: 100% 100%;
  1628. margin-bottom: 16px;
  1629. }
  1630. .no-drag {
  1631. cursor: default;
  1632. font-size: 32px !important;
  1633. }
  1634. .zxm-modal-title {
  1635. height: 90px;
  1636. }
  1637. .zxm-modal-body {
  1638. height: calc(100vh - 120px);
  1639. overflow: hidden;
  1640. padding: 0 24px 12px;
  1641. }
  1642. .ai-container {
  1643. height: 100%;
  1644. overflow: hidden;
  1645. }
  1646. .chat-panel {
  1647. background-image: var(--img-chat-fs-panel-bg) !important;
  1648. }
  1649. .chat-header {
  1650. padding: 0 32px;
  1651. height: 50px;
  1652. }
  1653. .collapse-btn {
  1654. top: 60px;
  1655. background-image: var(--img-chat-fs-collapse-btn-bg) !important;
  1656. background-repeat: no-repeat;
  1657. background-size: 100% 100%;
  1658. }
  1659. .task-list-panel {
  1660. padding: 20px;
  1661. background-image: var(--img-chat-fs-task-panel-bg) !important;
  1662. background-repeat: no-repeat !important;
  1663. background-size: 100% 100% !important;
  1664. }
  1665. .options-area {
  1666. gap: 12px;
  1667. }
  1668. .options-area-item {
  1669. background-image: var(--img-chat-fs-options-item-bg) !important;
  1670. background-repeat: no-repeat !important;
  1671. background-size: 100% 100% !important;
  1672. &.active,
  1673. &:active {
  1674. background-image: var(--img-chat-fs-options-item-active-bg) !important;
  1675. }
  1676. .options-img {
  1677. background-image: none !important;
  1678. }
  1679. }
  1680. .chat-header-title {
  1681. height: 40px;
  1682. line-height: 40px;
  1683. position: relative;
  1684. background-image: var(--img-chat-fs-header-title-bg) !important;
  1685. background-repeat: no-repeat !important;
  1686. background-size: auto 100% !important;
  1687. padding: 0 28px;
  1688. &::before {
  1689. content: '';
  1690. position: absolute;
  1691. left: 0;
  1692. top: 50%;
  1693. transform: translateY(-50%);
  1694. width: 40px;
  1695. height: 40px;
  1696. background-image: var(--img-chat-fs-header-title-icon);
  1697. background-repeat: no-repeat;
  1698. background-size: 100% 100%;
  1699. }
  1700. }
  1701. .chat-header-title-wrapper {
  1702. .title-edit-input {
  1703. height: 36px;
  1704. font-size: 16px;
  1705. background: rgba(10, 132, 255, 0.15);
  1706. border-color: rgba(10, 132, 255, 0.6);
  1707. }
  1708. .title-edit-btn {
  1709. width: 24px;
  1710. height: 24px;
  1711. background-size: 16px 16px;
  1712. }
  1713. }
  1714. .chat-input-area {
  1715. margin: 24px;
  1716. }
  1717. }
  1718. .zxm-modal-header {
  1719. background-color: unset !important;
  1720. background: unset;
  1721. border: none !important;
  1722. padding: 8px;
  1723. backdrop-filter: unset;
  1724. display: flex;
  1725. justify-content: center;
  1726. }
  1727. .zxm-modal-title {
  1728. width: 100%;
  1729. height: 60px;
  1730. display: flex;
  1731. align-items: center;
  1732. justify-content: center;
  1733. .draggable-title {
  1734. color: #fff;
  1735. font-family: var(--vet-font-family);
  1736. letter-spacing: 3px;
  1737. font-size: 24px;
  1738. font-weight: 100;
  1739. line-height: 1.4;
  1740. }
  1741. }
  1742. .zxm-modal-body {
  1743. padding: 12px 24px;
  1744. }
  1745. }
  1746. .delete-task-confirm-modal {
  1747. .zxm-modal-confirm-title,
  1748. .zxm-modal-confirm-content {
  1749. color: #fff;
  1750. }
  1751. }
  1752. </style>