AiAssistantModal.vue 74 KB

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