1
0

AiAssistantModal.vue 73 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300
  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. if (!found) return;
  598. const { approval } = found;
  599. const sessionId = approval.sessionId;
  600. if (!sessionId) return;
  601. const task = taskList.value.find((t) => t.sessionId === sessionId);
  602. if (!task) return;
  603. const taskMessages = task.messages;
  604. const lastMsg = taskMessages[taskMessages.length - 1];
  605. if (!lastMsg || !lastMsg.isPendingApproval) return;
  606. lastMsg.isPendingApproval = false;
  607. lastMsg.pendingApprovalData = undefined;
  608. lastMsg.isLoading = true;
  609. lastMsg.generateStartTime = Date.now();
  610. const aiMsgIndex = taskMessages.length - 1;
  611. task.messages = [...taskMessages];
  612. if (currentTaskId.value === task.id) {
  613. messages.value = task.messages;
  614. }
  615. task.isStreaming = true;
  616. showTodoBar.value = false;
  617. currentTodos.value = [];
  618. const controller = new AbortController();
  619. setTaskAbortController(task.id, controller);
  620. try {
  621. const result = await chatResumeStream(
  622. {
  623. session_id: sessionId,
  624. thread_id: approval.threadId || undefined,
  625. status: 'answered',
  626. answers,
  627. signal: controller.signal,
  628. },
  629. (data: SseEvent) => {
  630. parseSSEData(data, aiMsgIndex, task.id);
  631. if (currentTaskId.value === task.id) scrollToBottomThrottled();
  632. }
  633. );
  634. if (result.session_id) {
  635. setCurrentSessionId(result.session_id);
  636. }
  637. } catch (error) {
  638. if ((error as Error)?.name === 'AbortError') {
  639. lastMsg.isLoading = false;
  640. lastMsg.durationMs = (lastMsg.baseDurationMs || 0) + (lastMsg.generateStartTime ? Date.now() - lastMsg.generateStartTime : 0);
  641. if (!lastMsg.content) {
  642. lastMsg.content = '已停止生成。';
  643. }
  644. } else {
  645. console.error('提交答案失败:', error);
  646. message.error('提交失败,请重试');
  647. lastMsg.isLoading = false;
  648. lastMsg.durationMs = (lastMsg.baseDurationMs || 0) + (lastMsg.generateStartTime ? Date.now() - lastMsg.generateStartTime : 0);
  649. if (!lastMsg.content) {
  650. lastMsg.content = '抱歉,提交请求失败,请稍后重试。';
  651. }
  652. }
  653. } finally {
  654. setTaskAbortController(task.id, null);
  655. task.isStreaming = false;
  656. clearTaskPendingApproval(task.id);
  657. if (currentTaskId.value === task.id) {
  658. await scrollToBottom();
  659. }
  660. }
  661. };
  662. const handleAskUserCancel = async () => {
  663. const found = await findPendingApprovalTask();
  664. if (!found) return;
  665. const { approval } = found;
  666. const sessionId = approval.sessionId;
  667. if (!sessionId) return;
  668. const task = taskList.value.find((t) => t.sessionId === sessionId);
  669. if (!task) return;
  670. const taskMessages = task.messages;
  671. const lastMsg = taskMessages[taskMessages.length - 1];
  672. if (!lastMsg || !lastMsg.isPendingApproval) return;
  673. // 冻结累计耗时到 durationMs,避免取消后计时消失
  674. lastMsg.durationMs = (lastMsg.baseDurationMs || 0) + (lastMsg.generateStartTime ? Date.now() - lastMsg.generateStartTime : 0);
  675. lastMsg.isPendingApproval = false;
  676. lastMsg.pendingApprovalData = undefined;
  677. lastMsg.isLoading = false;
  678. lastMsg.content = (lastMsg.content ? lastMsg.content + '\n\n' : '') + '已取消提问。';
  679. task.messages = [...taskMessages];
  680. clearTaskPendingApproval(task.id);
  681. try {
  682. await chatResumeStream(
  683. {
  684. session_id: sessionId,
  685. thread_id: approval.threadId || undefined,
  686. status: 'cancelled',
  687. },
  688. () => {}
  689. );
  690. } catch (error) {
  691. console.error('取消操作失败:', error);
  692. }
  693. task.isStreaming = false;
  694. if (currentTaskId.value === task.id) {
  695. messages.value = task.messages;
  696. await scrollToBottom();
  697. }
  698. };
  699. const handleDeleteTask = (task: Task, _index: number) => {
  700. Modal.confirm({
  701. title: '提示',
  702. content: '是否删除该对话?',
  703. okText: '确认',
  704. cancelText: '取消',
  705. wrapClassName: 'delete-task-confirm-modal',
  706. onOk: async () => {
  707. try {
  708. if (task.sessionId) {
  709. await deleteSession(task.sessionId);
  710. }
  711. const realIndex = taskList.value.findIndex((t) => t.id === task.id);
  712. if (realIndex !== -1) {
  713. taskList.value.splice(realIndex, 1);
  714. }
  715. if (currentTaskId.value === task.id) {
  716. if (taskList.value.length > 0) {
  717. switchTask(taskList.value[0].id);
  718. } else {
  719. messages.value = [];
  720. currentTaskId.value = '';
  721. }
  722. }
  723. message.success('删除成功');
  724. } catch {
  725. message.error('删除失败');
  726. }
  727. },
  728. });
  729. };
  730. const getDefaultMessages = (): Message[] => {
  731. return [];
  732. };
  733. const normalizeLineBreaks = (str: string): string => {
  734. if (!str) return '';
  735. return str.replace(/\\n/g, '\n').replace(/\r\n/g, '\n');
  736. };
  737. const transformHistoryToMessages = (
  738. data: Array<{
  739. role?: string;
  740. type?: string;
  741. content: string;
  742. created_at?: string;
  743. report_url?: string;
  744. report_filename?: string;
  745. citations?: any;
  746. }>
  747. ): Message[] => {
  748. const messages: Message[] = [];
  749. for (const item of data) {
  750. const normalizedContent = normalizeLineBreaks(item.content);
  751. const time = item.created_at ? dayjs(item.created_at).format('HH:mm') : '';
  752. const createdAt = item.created_at || '';
  753. // 新格式:role 字段 (user/assistant)
  754. if (item.role === 'user') {
  755. messages.push({ type: 'user', content: normalizedContent, time, createdAt });
  756. } else if (item.role === 'assistant') {
  757. const msg: Message = { type: 'ai', content: normalizedContent, time, createdAt };
  758. if (item.report_url && item.report_filename) {
  759. msg.downloadFiles = [{ url: item.report_url, filename: item.report_filename }];
  760. }
  761. if (item.citations) {
  762. // 历史接口返回 citations 为扁平数组,SSE 事件返回 { items, model_only },统一归一化
  763. const raw = item.citations;
  764. if (Array.isArray(raw)) {
  765. msg.citations = { items: raw, model_only: raw.length === 0 };
  766. } else {
  767. msg.citations = raw;
  768. }
  769. }
  770. messages.push(msg);
  771. }
  772. // 兼容旧格式:type 字段
  773. else if (item.type === 'user_message') {
  774. messages.push({ type: 'user', content: normalizedContent, time, createdAt });
  775. } else if (item.type === 'model_thinking') {
  776. const lastAiMsg = messages[messages.length - 1];
  777. if (lastAiMsg && lastAiMsg.type === 'ai') {
  778. lastAiMsg.content += normalizedContent;
  779. lastAiMsg.content = lastAiMsg.content.replace(/\|\|\|SPLIT_CONTENT\|\|\|/g, '');
  780. } else {
  781. messages.push({ type: 'ai', content: normalizedContent, time, createdAt });
  782. }
  783. }
  784. }
  785. return messages;
  786. };
  787. const triggerFileUpload = () => {
  788. chatInputRef.value?.fileInputRef?.click();
  789. };
  790. const handleFileUpload = async (event: Event) => {
  791. const target = event.target as HTMLInputElement;
  792. const file = target.files?.[0];
  793. if (!file) return;
  794. if (isVideoFile(file.name) || isAudioFile(file.name)) {
  795. message.warning('不支持上传音频和视频文件');
  796. target.value = '';
  797. return;
  798. }
  799. try {
  800. const newFile: AttachedFile = {
  801. id: `file-${Date.now()}`,
  802. name: file.name,
  803. size: file.size,
  804. type: file.type,
  805. uploadTime: dayjs().format('YYYY-MM-DD HH:mm'),
  806. originalFile: file,
  807. };
  808. // Abort previous FileReader if still in progress
  809. if (activeFileReader.value) {
  810. activeFileReader.value.abort();
  811. activeFileReader.value = null;
  812. }
  813. const reader = new FileReader();
  814. activeFileReader.value = reader;
  815. reader.onload = (e) => {
  816. activeFileReader.value = null;
  817. if (isTextFile(file.name) || isCsvFile(file.name)) {
  818. newFile.content = e.target?.result as string;
  819. } else if (isWordFile(file.name) || isExcelFile(file.name)) {
  820. newFile.arrayBuffer = e.target?.result as ArrayBuffer;
  821. } else {
  822. newFile.preview = e.target?.result as string;
  823. }
  824. };
  825. if (isTextFile(file.name) || isCsvFile(file.name)) {
  826. reader.readAsText(file);
  827. } else if (isWordFile(file.name) || isExcelFile(file.name)) {
  828. reader.readAsArrayBuffer(file);
  829. } else {
  830. reader.readAsDataURL(file);
  831. }
  832. pendingFile.value = newFile;
  833. message.success(`文件 "${file.name}" 已添加,点击发送按钮提交`);
  834. } catch (error) {
  835. console.error('文件处理失败:', error);
  836. message.error('文件处理失败,请重试');
  837. }
  838. target.value = '';
  839. };
  840. const removePendingFile = () => {
  841. pendingFile.value = null;
  842. };
  843. const removePreviewFile = () => {
  844. previewFile.value = null;
  845. previewEditable.value = false;
  846. // 关闭文件预览后,恢复定时任务详情面板
  847. const sessionId = currentTask.value?.sessionId;
  848. if (sessionId && scheduleListForDetail.value.some((s: any) => s.feedback_session_id === sessionId)) {
  849. showScheduleDetail.value = true;
  850. }
  851. };
  852. const openFilePreview = (file: AttachedFile) => {
  853. previewFile.value = file;
  854. previewEditable.value = false;
  855. showScheduleDetail.value = false;
  856. const msgIndex = messages.value.findIndex((m) => m.attachedFile?.id === file.id);
  857. if (msgIndex !== -1) {
  858. nextTick(() => {
  859. const messageElements = chatMessagesRef.value?.messagesRef?.querySelectorAll('.message-wrapper');
  860. if (messageElements && messageElements[msgIndex]) {
  861. (messageElements[msgIndex] as HTMLElement).scrollIntoView({
  862. behavior: 'smooth',
  863. block: 'center',
  864. });
  865. }
  866. });
  867. }
  868. };
  869. const getCurrentTaskFiles = (): AttachedFile[] => {
  870. const currentTask = taskList.value.find((t) => t.id === currentTaskId.value);
  871. return currentTask?.attachedFiles || [];
  872. };
  873. const currentTask = computed(() => taskList.value.find((t) => t.id === currentTaskId.value));
  874. const currentWordUrl = computed(() => {
  875. return currentTask.value?.wordUrl || '';
  876. });
  877. const currentTaskIndex = computed(() => taskList.value.findIndex((t) => t.id === currentTaskId.value));
  878. const canGoPrev = computed(() => currentTaskIndex.value > 0);
  879. const canGoNext = computed(() => currentTaskIndex.value >= 0 && currentTaskIndex.value < taskList.value.length - 1);
  880. const goToPrev = () => {
  881. if (!canGoPrev.value) return;
  882. const prevTask = taskList.value[currentTaskIndex.value - 1];
  883. if (prevTask) switchTask(prevTask.id);
  884. };
  885. const goToNext = () => {
  886. if (!canGoNext.value) return;
  887. const nextTask = taskList.value[currentTaskIndex.value + 1];
  888. if (nextTask) switchTask(nextTask.id);
  889. };
  890. const downloadWordFile = (url: string) => {
  891. if (!url) return;
  892. const a = document.createElement('a');
  893. a.href = url;
  894. a.download = '';
  895. a.target = '_blank';
  896. document.body.appendChild(a);
  897. a.click();
  898. document.body.removeChild(a);
  899. };
  900. const downloadWordReport = () => downloadWordFile(currentWordUrl.value);
  901. const handleOpenFilePreview = (file: AttachedFile) => {
  902. previewFile.value = file;
  903. previewEditable.value = true;
  904. showScheduleDetail.value = false;
  905. };
  906. const handleSaveSuccess = (content: string) => {
  907. if (previewFile.value) {
  908. previewFile.value = { ...previewFile.value, content };
  909. }
  910. };
  911. const handleSendMessage = async () => {
  912. const hasText = inputMessage.value.trim();
  913. const hasFile = pendingFile.value;
  914. if (!hasText) {
  915. message.warning('请输入消息内容');
  916. return;
  917. }
  918. if (loading.value) return;
  919. if (currentPendingApproval.value) {
  920. message.warning('请先审批执行计划');
  921. return;
  922. }
  923. const sessionPrefix = selectedSessions.value.length > 0 ? selectedSessions.value.map((s) => `#session:${s.id}`).join(' ') + ' ' : '';
  924. const skillPrefix = selectedSkill.value ? `#skill:${selectedSkill.value.name} ` : '';
  925. const userInput = skillPrefix + sessionPrefix + inputMessage.value.trim();
  926. let displayContent = inputMessage.value.trim();
  927. if (selectedSkill.value) {
  928. const skillIconUrl = getSkillRefIconUrl();
  929. displayContent = `[<img src="${skillIconUrl}" class="session-ref-icon" /> 技能:${selectedSkill.value.display_name}] ${displayContent}`;
  930. }
  931. if (selectedSessions.value.length > 0) {
  932. const names = selectedSessions.value.map((s) => s.name).join('、');
  933. const iconUrl = getSessionRefIconUrl();
  934. displayContent = `[<img src="${iconUrl}" class="session-ref-icon" /> 引用 ${selectedSessions.value.length} 个会话:${names}] ${displayContent}`;
  935. }
  936. const fileToSend = pendingFile.value;
  937. inputMessage.value = '';
  938. pendingFile.value = null;
  939. selectedSessions.value = [];
  940. selectedSkill.value = null;
  941. try {
  942. await nextTick();
  943. chatMessagesRef.value?.forceScrollToBottom();
  944. if (hasFile) {
  945. await sendWithAttachment(fileToSend!, userInput, displayContent);
  946. } else {
  947. await sendTextOnly(userInput, displayContent);
  948. }
  949. } catch (error) {
  950. console.error('发送消息失败:', error);
  951. message.error('发送失败,请重试');
  952. const lastMsg = messages.value[messages.value.length - 1];
  953. if (lastMsg && lastMsg.type === 'ai' && lastMsg.isLoading) {
  954. messages.value.pop();
  955. }
  956. const errorMsg: Message = {
  957. type: 'ai',
  958. content: '抱歉,请求失败,请稍后重试。',
  959. time: dayjs().format('HH:mm'),
  960. };
  961. messages.value.push(errorMsg);
  962. const currentTask = taskList.value.find((t) => t.id === currentTaskId.value);
  963. if (currentTask) {
  964. currentTask.messages = [...messages.value];
  965. }
  966. } finally {
  967. await scrollToBottom(true);
  968. }
  969. };
  970. const extractAgentName = (toolName: string): string => {
  971. const nameMap: Record<string, string> = {
  972. form_review: '形式审查',
  973. verify_coal_face_ventilation: '采煤工作面需风量计算核验',
  974. verify_tunneling_face_ventilation: '掘进工作面需风量计算核验',
  975. verify_chamber_ventilation: '硐室需风量计算核验',
  976. verify_other_points_ventilation: '其他地点需风量计算核验',
  977. check_data_by_gas_report: '瓦斯数据一致性审查',
  978. check_data_by_face_design: '设计规程一致性审查',
  979. check_data_by_vent_report: '测风报表一致性审查',
  980. check_current_month_plan: '日期有效性审查',
  981. get_key_translate: '计算参数对照',
  982. calculate_ventilation: '需风量计算',
  983. get_ventilation_data: '需风量查询',
  984. recalculate_ventilation: '需风量重计算',
  985. get_plan_required_wind: '需风量提取',
  986. get_model_calculated_wind: '三维模型解算风量提取',
  987. get_sensor_wind: '巷道监测风量提取',
  988. merge_wind_by_location: '地点风量智能合并',
  989. check_wind_compliance: '风量检查',
  990. };
  991. return nameMap[toolName] || nameMap[toolName.toLowerCase()] || '智能分析助手';
  992. };
  993. // 累积所有步骤,保留完整历史
  994. const upsertStep = (steps: any[], step: any) => {
  995. steps.push(step);
  996. };
  997. const fetchModelMsg = async () => {
  998. try {
  999. const res = await getModelMsg();
  1000. if (res?.thinking_level) {
  1001. thinkLevel.value = res.thinking_level;
  1002. }
  1003. } catch (e) {
  1004. console.error('获取模型信息失败:', e);
  1005. }
  1006. };
  1007. const fetchSessionMode = async (sessionId: string) => {
  1008. try {
  1009. const res = await getSessionMode(sessionId);
  1010. if (res?.mode) {
  1011. editMode.value = res.mode;
  1012. }
  1013. } catch (e) {
  1014. console.error('获取会话模式失败:', e);
  1015. }
  1016. };
  1017. const fetchContext = async (sessionId: string) => {
  1018. try {
  1019. const res = await getContext(sessionId);
  1020. contextUsed.value = res?.current_usage ?? 0;
  1021. contextMax.value = res?.total_limit ?? 0;
  1022. contextPercent.value = res?.usage_pct ?? 0;
  1023. contextBreakdown.value = res?.breakdown ?? { messages: 0, mcp: 0, skills: 0, system_prompt: 0, other: 0 };
  1024. } catch (e) {
  1025. console.error('获取上下文容量失败:', e);
  1026. contextUsed.value = 0;
  1027. contextMax.value = 0;
  1028. contextPercent.value = 0;
  1029. contextBreakdown.value = { messages: 0, mcp: 0, skills: 0, system_prompt: 0, other: 0 };
  1030. }
  1031. };
  1032. const handleSSEMessage = (data: any, aiMsgIndex: number, taskId: string) => {
  1033. const streamingTask = taskList.value.find((t) => t.id === taskId);
  1034. if (!streamingTask) return;
  1035. // 当前正在查看流式任务时,新消息被 push 到 messages.value 而非 task.messages
  1036. // 所以需要从 messages.value 读取;否则从任务存储的 messages 读取
  1037. const isViewingTask = currentTaskId.value === taskId;
  1038. const sourceArr = isViewingTask ? messages.value : streamingTask.messages;
  1039. const aiMsg = sourceArr[aiMsgIndex];
  1040. if (!aiMsg) return;
  1041. const normalizedContent = normalizeLineBreaks(data.content || '');
  1042. // 初始化 thinkingSteps 数组
  1043. if (!aiMsg.thinkingSteps) {
  1044. aiMsg.thinkingSteps = [];
  1045. }
  1046. switch (data.type) {
  1047. // token 流式内容 - 直接拼接到消息内容
  1048. case 'token':
  1049. if (normalizedContent) {
  1050. aiMsg.content += normalizedContent;
  1051. }
  1052. break;
  1053. // thinking_token - 模型思考过程内容
  1054. case 'thinking_token':
  1055. if (normalizedContent) {
  1056. aiMsg.thinkingContent = (aiMsg.thinkingContent || '') + normalizedContent;
  1057. }
  1058. break;
  1059. // 系统进度消息 - 仅当 agent 不是 system 时才作为 thinking step
  1060. case 'progress': {
  1061. if (data.agent && data.agent !== 'system') {
  1062. upsertStep(aiMsg.thinkingSteps!, {
  1063. type: 'executing',
  1064. agent: data.agent,
  1065. message: data.message || '',
  1066. timestamp: Date.now(),
  1067. });
  1068. }
  1069. break;
  1070. }
  1071. // agent 开始处理
  1072. case 'agent_start': {
  1073. upsertStep(aiMsg.thinkingSteps!, {
  1074. type: 'agent_start',
  1075. agent: data.cn_agent || data.agent || '智能助手',
  1076. message: data.message || '开始处理...',
  1077. timestamp: Date.now(),
  1078. });
  1079. break;
  1080. }
  1081. // agent 任务列表更新(同一 agent 的 todos 更新已有条目,不重复添加)
  1082. case 'agent_todos':
  1083. case 'updated_todo_list': {
  1084. const agentName = data.cn_agent || data.agent || '智能助手';
  1085. const existingIdx = aiMsg.thinkingSteps!.findIndex((s) => s.type === 'updated_todo_list' && s.agent === agentName);
  1086. if (existingIdx !== -1) {
  1087. aiMsg.thinkingSteps![existingIdx].todos = data.todos || [];
  1088. aiMsg.thinkingSteps![existingIdx].timestamp = Date.now();
  1089. } else {
  1090. aiMsg.thinkingSteps!.push({
  1091. type: 'updated_todo_list',
  1092. agent: agentName,
  1093. todos: data.todos || [],
  1094. message: data.message || '任务进度已更新',
  1095. timestamp: Date.now(),
  1096. });
  1097. }
  1098. currentTodos.value = [...(data.todos || [])];
  1099. showTodoBar.value = true;
  1100. break;
  1101. }
  1102. // agent 执行中(工具调用)
  1103. case 'agent_executing':
  1104. case 'executing': {
  1105. upsertStep(aiMsg.thinkingSteps!, {
  1106. type: 'executing',
  1107. agent: data.cn_agent || data.agent || '智能助手',
  1108. tool: (data.cn_tools || data.tools || []).join('、'),
  1109. message: data.message || '',
  1110. timestamp: Date.now(),
  1111. });
  1112. break;
  1113. }
  1114. // 工具结果
  1115. case 'agent_tool_result':
  1116. case 'tool_result': {
  1117. upsertStep(aiMsg.thinkingSteps!, {
  1118. type: 'tool_result',
  1119. agent: data.cn_agent || data.agent || '智能助手',
  1120. tool: data.cn_tool || data.tool || '',
  1121. message: data.message || '执行完成',
  1122. timestamp: Date.now(),
  1123. });
  1124. if (data.download_url) {
  1125. if (!aiMsg.downloadFiles) aiMsg.downloadFiles = [];
  1126. aiMsg.downloadFiles.push({ url: data.download_url, filename: data.filename || '文件' });
  1127. }
  1128. break;
  1129. }
  1130. // agent 完成
  1131. case 'agent_done': {
  1132. upsertStep(aiMsg.thinkingSteps!, {
  1133. type: 'agent_done',
  1134. agent: data.cn_agent || data.agent || '智能助手',
  1135. message: `${(data.message || '审查完成').replace(/(\d+ms)/g, '')}${data.duration_ms ? `(${(data.duration_ms / 1000).toFixed(0)}s)` : ''}${data.progress ? ` [${data.progress}]` : ''}`,
  1136. timestamp: Date.now(),
  1137. });
  1138. // 累加后端返回的各段耗时,并重置前端计时起点,避免重复计算已验证的时间段
  1139. if (data.duration_ms) {
  1140. aiMsg.baseDurationMs = (aiMsg.baseDurationMs || 0) + data.duration_ms;
  1141. aiMsg.generateStartTime = Date.now();
  1142. }
  1143. if (data.preview) {
  1144. aiMsg.content += data.preview;
  1145. }
  1146. break;
  1147. }
  1148. // 旧格式兼容
  1149. case 'model_thinking':
  1150. if (normalizedContent) {
  1151. aiMsg.content += normalizedContent;
  1152. aiMsg.content = aiMsg.content.replace(/\|\|\|SPLIT_CONTENT\|\|\|/g, '');
  1153. }
  1154. break;
  1155. case 'tool_select': {
  1156. upsertStep(aiMsg.thinkingSteps!, {
  1157. type: 'tool_call',
  1158. agent: extractAgentName(normalizedContent),
  1159. tool: normalizedContent,
  1160. message: `选择工具:${normalizedContent}`,
  1161. timestamp: Date.now(),
  1162. });
  1163. break;
  1164. }
  1165. case 'error':
  1166. upsertStep(aiMsg.thinkingSteps!, {
  1167. type: 'tool_result',
  1168. agent: '系统',
  1169. message: `❌ 执行失败:${normalizedContent}`,
  1170. timestamp: Date.now(),
  1171. });
  1172. aiMsg.isLoading = false;
  1173. streamingTask.isStreaming = false;
  1174. // 后端未返回耗时,冻结前端伪计时
  1175. aiMsg.durationMs = (aiMsg.baseDurationMs || 0) + (aiMsg.generateStartTime ? Date.now() - aiMsg.generateStartTime : 0);
  1176. break;
  1177. case 'citations': {
  1178. aiMsg.citations = {
  1179. items: data.items || [],
  1180. model_only: data.model_only || false,
  1181. message: data.message,
  1182. };
  1183. break;
  1184. }
  1185. case 'word_download':
  1186. if (normalizedContent) {
  1187. aiMsg.wordDownloadUrl = normalizedContent;
  1188. streamingTask.wordUrl = normalizedContent;
  1189. }
  1190. break;
  1191. case 'done':
  1192. if (data.session_id) {
  1193. aiMsg.sessionId = data.session_id;
  1194. fetchContext(data.session_id);
  1195. }
  1196. aiMsg.durationMs = data.duration_ms
  1197. ? (aiMsg.baseDurationMs || 0) + data.duration_ms
  1198. : (aiMsg.baseDurationMs || 0) + (aiMsg.generateStartTime ? Date.now() - aiMsg.generateStartTime : 0);
  1199. aiMsg.isLoading = false;
  1200. streamingTask.isStreaming = false;
  1201. break;
  1202. case 'system':
  1203. if (normalizedContent) {
  1204. aiMsg.content += normalizedContent.replace(/\n/g, ' \n');
  1205. }
  1206. break;
  1207. case 'interrupt': {
  1208. // 后端各段耗时 + 前端当前段计时,吸收进 baseDurationMs 保证审批继续后计时连续
  1209. const elapsedMs = (aiMsg.baseDurationMs || 0) + (aiMsg.generateStartTime ? Date.now() - aiMsg.generateStartTime : 0);
  1210. aiMsg.baseDurationMs = elapsedMs;
  1211. aiMsg.isLoading = false;
  1212. // 流已结束,等待用户回答;提交答案后 handleAskUserSubmit 会重新置为流式中
  1213. streamingTask.isStreaming = false;
  1214. aiMsg.isPendingApproval = true;
  1215. const interruptSessionId = data.session_id || streamingTask.sessionId;
  1216. aiMsg.pendingApprovalData = {
  1217. message: data.message || '智能体需要您回答一些问题以继续...',
  1218. sessionId: interruptSessionId,
  1219. threadId: data.thread_id,
  1220. interrupts: data.interrupts,
  1221. elapsedMs,
  1222. prevThinkingContent: aiMsg.thinkingContent,
  1223. plan: data.plan,
  1224. ask_user: data.ask_user,
  1225. answers: data.ask_user?.questions?.map(() => '') || [],
  1226. };
  1227. setTaskPendingApproval(taskId, interruptSessionId, data.thread_id || '');
  1228. // 直接初始化 ask_user 答案状态,不依赖 watch(避免任务切换/时序问题)
  1229. if (data.ask_user?.questions) {
  1230. nextTick(() => {
  1231. chatMessagesRef.value?.initAskUserAnswers(aiMsgIndex, data.ask_user!.questions);
  1232. });
  1233. }
  1234. break;
  1235. }
  1236. }
  1237. // 保存到流式任务的 messages,并同步 UI
  1238. // Always create a new array reference to trigger Vue reactivity
  1239. const updatedMessages = isViewingTask ? [...messages.value] : [...streamingTask.messages];
  1240. streamingTask.messages = updatedMessages;
  1241. if (isViewingTask) {
  1242. messages.value = updatedMessages;
  1243. }
  1244. };
  1245. const parseSSEData = (data: SseEvent, aiMsgIndex: number, taskId: string) => {
  1246. handleSSEMessage(data, aiMsgIndex, taskId);
  1247. };
  1248. const sendTextOnly = async (userInput: string, displayContent?: string) => {
  1249. const originTaskId = currentTaskId.value;
  1250. const now = dayjs();
  1251. const userMsg: Message = {
  1252. type: 'user',
  1253. content: displayContent || userInput,
  1254. time: now.format('HH:mm'),
  1255. createdAt: now.toISOString(),
  1256. };
  1257. messages.value.push(userMsg);
  1258. await nextTick();
  1259. chatMessagesRef.value?.forceScrollToBottom();
  1260. const aiMsgIndex = messages.value.length;
  1261. const aiMsg: Message = {
  1262. type: 'ai',
  1263. content: '',
  1264. time: now.format('HH:mm'),
  1265. createdAt: now.toISOString(),
  1266. isLoading: true,
  1267. thinkingSteps: [],
  1268. generateStartTime: Date.now(),
  1269. };
  1270. messages.value.push(aiMsg);
  1271. showTodoBar.value = false;
  1272. currentTodos.value = [];
  1273. const originTask = taskList.value.find((t) => t.id === originTaskId);
  1274. if (originTask) originTask.isStreaming = true;
  1275. const controller = new AbortController();
  1276. setTaskAbortController(originTaskId, controller);
  1277. try {
  1278. const result = await unifiedStream(
  1279. {
  1280. message: userInput,
  1281. session_id: getCurrentSessionId() || undefined,
  1282. mode: editMode.value,
  1283. signal: controller.signal,
  1284. },
  1285. (data: SseEvent) => {
  1286. parseSSEData(data, aiMsgIndex, originTaskId);
  1287. if (currentTaskId.value === originTaskId) scrollToBottomThrottled();
  1288. }
  1289. );
  1290. if (result.session_id) {
  1291. const originTask = taskList.value.find((t) => t.id === originTaskId);
  1292. if (originTask && !originTask.sessionId) {
  1293. originTask.sessionId = result.session_id;
  1294. // 流式期间若列表已用后端标题归并过该任务,则保留后端标题;否则用首条消息命名
  1295. if (originTask.pendingSessionId !== result.session_id) {
  1296. originTask.name = userInput.substring(0, 20) + (userInput.length > 20 ? '...' : '');
  1297. }
  1298. originTask.pendingSessionId = undefined;
  1299. if (originTask.id !== result.session_id) {
  1300. // 将 AbortController 从旧 ID 迁移到新 ID
  1301. const controller = taskAbortControllers.get(originTaskId);
  1302. if (controller) {
  1303. setTaskAbortController(originTaskId, null);
  1304. setTaskAbortController(result.session_id, controller);
  1305. }
  1306. taskList.value = taskList.value.filter((t) => t.id !== result.session_id);
  1307. originTask.id = result.session_id;
  1308. historyLoadedTasks.add(result.session_id);
  1309. }
  1310. if (currentTaskId.value === originTaskId) {
  1311. currentTaskId.value = result.session_id;
  1312. }
  1313. }
  1314. }
  1315. } catch (error) {
  1316. // 用户主动停止生成
  1317. if ((error as Error)?.name === 'AbortError') {
  1318. const originTask = taskList.value.find((t) => t.id === originTaskId);
  1319. const arr = currentTaskId.value === originTaskId ? messages.value : originTask?.messages;
  1320. const aiMsg = arr?.[aiMsgIndex];
  1321. if (aiMsg) {
  1322. aiMsg.isLoading = false;
  1323. // 后端未返回耗时,冻结前端伪计时
  1324. aiMsg.durationMs = (aiMsg.baseDurationMs || 0) + (aiMsg.generateStartTime ? Date.now() - aiMsg.generateStartTime : 0);
  1325. if (!aiMsg.content) {
  1326. aiMsg.content = '已停止生成。';
  1327. }
  1328. }
  1329. if (originTask && currentTaskId.value !== originTaskId) {
  1330. originTask.messages = [...(arr || [])];
  1331. }
  1332. return;
  1333. }
  1334. throw error;
  1335. } finally {
  1336. // 任务在流结束时可能已被改名为后端 session_id,需要使用最终的 ID 清理状态
  1337. const finalTaskId = originTask?.id || originTaskId;
  1338. setTaskAbortController(finalTaskId, null);
  1339. if (originTask) originTask.isStreaming = false;
  1340. }
  1341. };
  1342. const sendWithAttachment = async (file: AttachedFile, userInput: string, displayContent?: string) => {
  1343. const originTaskId = currentTaskId.value;
  1344. let currentTask = taskList.value.find((t) => t.id === originTaskId);
  1345. if (currentTask) {
  1346. currentTask.attachedFiles.push(file);
  1347. } else {
  1348. throw new Error('未找到当前任务');
  1349. }
  1350. const now = dayjs();
  1351. const userMsg: Message = {
  1352. type: 'user',
  1353. content: displayContent || userInput || `上传了文件:${file.name}`,
  1354. time: now.format('HH:mm'),
  1355. createdAt: now.toISOString(),
  1356. attachedFile: file,
  1357. };
  1358. messages.value.push(userMsg);
  1359. await nextTick();
  1360. chatMessagesRef.value?.forceScrollToBottom();
  1361. const aiMsgIndex = messages.value.length;
  1362. const aiMsg: Message = {
  1363. type: 'ai',
  1364. content: '',
  1365. time: now.format('HH:mm'),
  1366. createdAt: now.toISOString(),
  1367. isLoading: true,
  1368. thinkingSteps: [],
  1369. generateStartTime: Date.now(),
  1370. };
  1371. messages.value.push(aiMsg);
  1372. showTodoBar.value = false;
  1373. currentTodos.value = [];
  1374. if (!file.originalFile) {
  1375. throw new Error('缺少原始文件对象');
  1376. }
  1377. const originTask = taskList.value.find((t) => t.id === originTaskId);
  1378. if (originTask) originTask.isStreaming = true;
  1379. const controller = new AbortController();
  1380. setTaskAbortController(originTaskId, controller);
  1381. try {
  1382. const result = await reviewPdfStream(
  1383. {
  1384. file: file.originalFile!,
  1385. session_id: getCurrentSessionId() || undefined,
  1386. message: userInput || undefined,
  1387. mode: editMode.value,
  1388. signal: controller.signal,
  1389. },
  1390. (data: SseEvent) => {
  1391. parseSSEData(data, aiMsgIndex, originTaskId);
  1392. if (currentTaskId.value === originTaskId) scrollToBottomThrottled();
  1393. }
  1394. );
  1395. if (result.session_id) {
  1396. const originTask = taskList.value.find((t) => t.id === originTaskId);
  1397. if (originTask && !originTask.sessionId) {
  1398. originTask.sessionId = result.session_id;
  1399. if (originTask.pendingSessionId !== result.session_id) {
  1400. const taskName = userInput || `文件:${file.name}`;
  1401. originTask.name = taskName.substring(0, 20) + (taskName.length > 20 ? '...' : '');
  1402. }
  1403. originTask.pendingSessionId = undefined;
  1404. if (originTask.id !== result.session_id) {
  1405. // 将 AbortController 从旧 ID 迁移到新 ID
  1406. const controller = taskAbortControllers.get(originTaskId);
  1407. if (controller) {
  1408. setTaskAbortController(originTaskId, null);
  1409. setTaskAbortController(result.session_id, controller);
  1410. }
  1411. taskList.value = taskList.value.filter((t) => t.id !== result.session_id);
  1412. originTask.id = result.session_id;
  1413. historyLoadedTasks.add(result.session_id);
  1414. }
  1415. if (currentTaskId.value === originTaskId) {
  1416. currentTaskId.value = result.session_id;
  1417. }
  1418. }
  1419. }
  1420. } catch (error) {
  1421. // 用户主动停止生成
  1422. if ((error as Error)?.name === 'AbortError') {
  1423. const originTask = taskList.value.find((t) => t.id === originTaskId);
  1424. const arr = currentTaskId.value === originTaskId ? messages.value : originTask?.messages;
  1425. const aiMsg = arr?.[aiMsgIndex];
  1426. if (aiMsg) {
  1427. aiMsg.isLoading = false;
  1428. // 后端未返回耗时,冻结前端伪计时
  1429. aiMsg.durationMs = (aiMsg.baseDurationMs || 0) + (aiMsg.generateStartTime ? Date.now() - aiMsg.generateStartTime : 0);
  1430. if (!aiMsg.content) {
  1431. aiMsg.content = '已停止生成。';
  1432. }
  1433. }
  1434. if (originTask && currentTaskId.value !== originTaskId) {
  1435. originTask.messages = [...(arr || [])];
  1436. }
  1437. return;
  1438. }
  1439. throw error;
  1440. } finally {
  1441. // 任务在流结束时可能已被改名为后端 session_id,需要使用最终的 ID 清理状态
  1442. const finalTaskId = originTask?.id || originTaskId;
  1443. setTaskAbortController(finalTaskId, null);
  1444. if (originTask) originTask.isStreaming = false;
  1445. }
  1446. };
  1447. // Throttled version for SSE streaming (no await, uses rAF)
  1448. let scrollRafId: number | null = null;
  1449. const scrollToBottomThrottled = (force = false) => {
  1450. if (scrollRafId) cancelAnimationFrame(scrollRafId);
  1451. scrollRafId = requestAnimationFrame(async () => {
  1452. scrollRafId = null;
  1453. await nextTick();
  1454. if (!force && !chatMessagesRef.value?.isAtBottom) return;
  1455. const el = chatMessagesRef.value?.messagesRef;
  1456. if (el) {
  1457. el.scrollTop = el.scrollHeight - el.clientHeight;
  1458. }
  1459. });
  1460. };
  1461. // Async version for explicit await calls
  1462. const scrollToBottom = async (force = false) => {
  1463. await nextTick();
  1464. if (!force && !chatMessagesRef.value?.isAtBottom) return;
  1465. const el = chatMessagesRef.value?.messagesRef;
  1466. if (el) {
  1467. el.scrollTop = el.scrollHeight - el.clientHeight;
  1468. }
  1469. };
  1470. watch(
  1471. () => props.visible,
  1472. async (newVisible) => {
  1473. if (!newVisible) {
  1474. const currentTask = taskList.value.find((t) => t.id === currentTaskId.value);
  1475. if (currentTask) {
  1476. currentTask.messages = [...messages.value];
  1477. }
  1478. } else {
  1479. await fetchSessionList();
  1480. fetchModelMsg();
  1481. fetchScheduleListForDetail();
  1482. // 去除重复的空白任务,只保留一个
  1483. taskList.value = taskList.value.filter((task, index) => {
  1484. if (task.sessionId) return true;
  1485. return index === taskList.value.findIndex((t) => !t.sessionId);
  1486. });
  1487. // 优先回到关闭前所在的任务(如流式中的新任务),否则默认选中第一条历史记录
  1488. const firstHistoryTask = taskList.value.find((t) => t.sessionId);
  1489. const prevTask = taskList.value.find((t) => t.id === currentTaskId.value);
  1490. let targetTask: Task;
  1491. if (prevTask) {
  1492. targetTask = prevTask;
  1493. } else if (firstHistoryTask) {
  1494. targetTask = firstHistoryTask;
  1495. } else {
  1496. // 没有历史记录时才创建空白新任务
  1497. targetTask = {
  1498. id: `task-${Date.now()}`,
  1499. name: '新任务',
  1500. sessionId: '',
  1501. messages: getDefaultMessages(),
  1502. attachedFiles: [],
  1503. };
  1504. taskList.value.unshift(targetTask);
  1505. }
  1506. currentTaskId.value = targetTask.id;
  1507. // 如果是历史任务,加载其消息
  1508. if (targetTask.sessionId && !historyLoadedTasks.has(targetTask.id)) {
  1509. try {
  1510. const res = await getDetail(targetTask.sessionId);
  1511. const messages = res?.messages || (Array.isArray(res) ? res : res?.data);
  1512. if (Array.isArray(messages)) {
  1513. targetTask.messages = transformHistoryToMessages(messages);
  1514. }
  1515. historyLoadedTasks.add(targetTask.id);
  1516. } catch (error) {
  1517. console.error('加载历史会话失败:', error);
  1518. }
  1519. }
  1520. if (targetTask.sessionId) {
  1521. fetchContext(targetTask.sessionId);
  1522. fetchSessionMode(targetTask.sessionId);
  1523. } else {
  1524. contextUsed.value = 0;
  1525. contextPercent.value = 0;
  1526. contextBreakdown.value = { messages: 0, mcp: 0, skills: 0, system_prompt: 0, other: 0 };
  1527. editMode.value = 'full';
  1528. }
  1529. messages.value = targetTask.messages && targetTask.messages.length > 0 ? [...targetTask.messages] : getDefaultMessages();
  1530. previewFile.value = null;
  1531. pendingFile.value = null;
  1532. showFileList.value = false;
  1533. inputMessage.value = '';
  1534. await nextTick(() => {
  1535. chatMessagesRef.value?.forceScrollToBottom();
  1536. });
  1537. }
  1538. }
  1539. );
  1540. // 拖拽相关(使用普通变量避免 mousemove 触发 Vue 响应式导致卡顿)
  1541. let isDragging = false;
  1542. let dragStartX = 0;
  1543. let dragStartY = 0;
  1544. let modalStartLeft = 0;
  1545. let modalStartTop = 0;
  1546. let draggedEl: HTMLElement | null = null;
  1547. const findModalWrap = (target: HTMLElement): HTMLElement | null =>
  1548. target.closest<HTMLElement>('.zxm-modal-wrap, .ant-modal-wrap, [class*="modal-wrap"]');
  1549. const queryModalWrap = (): HTMLElement | null => document.querySelector<HTMLElement>('.zxm-modal-wrap, .ant-modal-wrap, [class*="modal-wrap"]');
  1550. const centerModal = () => {
  1551. nextTick(() => {
  1552. const wrap = queryModalWrap();
  1553. if (wrap) {
  1554. wrap.style.position = '';
  1555. wrap.style.left = '';
  1556. wrap.style.top = '';
  1557. wrap.style.right = '';
  1558. wrap.style.bottom = '';
  1559. wrap.style.width = '';
  1560. wrap.style.height = '';
  1561. wrap.style.margin = '';
  1562. wrap.style.transform = '';
  1563. }
  1564. draggedEl = null;
  1565. });
  1566. };
  1567. const onDragStart = (e: MouseEvent) => {
  1568. if (isFullscreen.value) return;
  1569. draggedEl = findModalWrap(e.target as HTMLElement) || queryModalWrap();
  1570. if (!draggedEl) return;
  1571. isDragging = true;
  1572. dragStartX = e.clientX;
  1573. dragStartY = e.clientY;
  1574. const rect = draggedEl.getBoundingClientRect();
  1575. modalStartLeft = rect.left;
  1576. modalStartTop = rect.top;
  1577. draggedEl.style.position = 'fixed';
  1578. draggedEl.style.left = `${rect.left}px`;
  1579. draggedEl.style.top = `${rect.top}px`;
  1580. draggedEl.style.margin = '0';
  1581. draggedEl.style.transform = 'none';
  1582. document.addEventListener('mousemove', onDragMove);
  1583. document.addEventListener('mouseup', onDragEnd);
  1584. };
  1585. const onDragMove = (e: MouseEvent) => {
  1586. if (!isDragging || !draggedEl) return;
  1587. draggedEl.style.left = `${modalStartLeft + (e.clientX - dragStartX)}px`;
  1588. draggedEl.style.top = `${modalStartTop + (e.clientY - dragStartY)}px`;
  1589. };
  1590. const onDragEnd = () => {
  1591. isDragging = false;
  1592. document.removeEventListener('mousemove', onDragMove);
  1593. document.removeEventListener('mouseup', onDragEnd);
  1594. };
  1595. watch(
  1596. () => props.visible,
  1597. (newVisible) => {
  1598. if (newVisible) {
  1599. centerModal();
  1600. }
  1601. }
  1602. );
  1603. onBeforeUnmount(() => {
  1604. document.removeEventListener('mousemove', onDragMove);
  1605. document.removeEventListener('mouseup', onDragEnd);
  1606. // 组件卸载时主动断开所有任务的流式连接
  1607. taskAbortControllers.forEach((controller) => controller.abort());
  1608. // Abort in-flight FileReader if any
  1609. if (activeFileReader.value) {
  1610. activeFileReader.value.abort();
  1611. activeFileReader.value = null;
  1612. }
  1613. });
  1614. </script>
  1615. <style scoped lang="less">
  1616. .ai-container {
  1617. display: flex;
  1618. height: 700px;
  1619. gap: 10px;
  1620. overflow: hidden;
  1621. font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, 'Helvetica Neue', Arial, sans-serif;
  1622. }
  1623. .collapse-btn {
  1624. position: absolute;
  1625. top: 16px;
  1626. left: 24px;
  1627. z-index: 10;
  1628. width: 32px;
  1629. height: 32px;
  1630. background: #1a6696;
  1631. border-radius: 4px;
  1632. display: flex;
  1633. align-items: center;
  1634. justify-content: center;
  1635. cursor: pointer;
  1636. transition: background 0.3s;
  1637. &:hover {
  1638. background: #1f7ab8;
  1639. }
  1640. .collapse-icon {
  1641. width: 16px;
  1642. height: 16px;
  1643. background-image: var(--img-chat-collapse-icon);
  1644. background-repeat: no-repeat;
  1645. background-size: 100% 100%;
  1646. &.collapsed {
  1647. background-image: var(--img-chat-expand-icon);
  1648. }
  1649. }
  1650. }
  1651. .task-panel-wrapper {
  1652. width: 300px;
  1653. flex-shrink: 0;
  1654. overflow: hidden;
  1655. transition:
  1656. width 0.35s cubic-bezier(0.4, 0, 0.2, 1),
  1657. margin 0.35s cubic-bezier(0.4, 0, 0.2, 1),
  1658. opacity 0.25s ease;
  1659. &.collapsed {
  1660. width: 0;
  1661. margin: 0;
  1662. opacity: 0;
  1663. }
  1664. }
  1665. .chat-panel {
  1666. flex: 1;
  1667. display: flex;
  1668. position: relative;
  1669. flex-direction: column;
  1670. background-image: var(--img-chat-panel-bg);
  1671. background-repeat: no-repeat;
  1672. background-size: 100% 100%;
  1673. border-radius: 4px;
  1674. overflow: hidden;
  1675. min-width: 0;
  1676. :deep(.chat-header) {
  1677. display: flex;
  1678. padding: 12px 20px;
  1679. flex-shrink: 0;
  1680. align-items: center;
  1681. background: rgba(2, 53, 100, 0.3);
  1682. .header-icon {
  1683. width: 35px;
  1684. height: 28px;
  1685. background-image: var(--img-chat-header-icon);
  1686. background-repeat: no-repeat;
  1687. background-size: 100% 100%;
  1688. margin-right: 10px;
  1689. }
  1690. .chat-header-title {
  1691. font-size: 16px;
  1692. color: #e0e6ed;
  1693. overflow: hidden;
  1694. text-overflow: ellipsis;
  1695. white-space: nowrap;
  1696. margin-left: 10px;
  1697. }
  1698. .chat-header-title-wrapper {
  1699. display: flex;
  1700. align-items: center;
  1701. flex: 1;
  1702. min-width: 0;
  1703. &:hover .title-edit-btn {
  1704. opacity: 1;
  1705. }
  1706. .title-edit-btn {
  1707. width: 28px;
  1708. height: 28px;
  1709. flex-shrink: 0;
  1710. background-image: var(--img-chat-edit-icon);
  1711. background-repeat: no-repeat;
  1712. background-size: 16px 16px;
  1713. background-position: center;
  1714. cursor: pointer;
  1715. opacity: 0;
  1716. transition: opacity 0.2s;
  1717. border-radius: 4px;
  1718. margin-right: 4px;
  1719. &:hover {
  1720. background-color: rgba(10, 132, 255, 0.2);
  1721. }
  1722. }
  1723. .chat-header-title {
  1724. margin-left: 0;
  1725. flex: 1;
  1726. min-width: 0;
  1727. }
  1728. .title-edit-input {
  1729. flex: 1;
  1730. min-width: 0;
  1731. height: 28px;
  1732. padding: 0 8px;
  1733. font-size: 14px;
  1734. color: #e0e6ed;
  1735. background: rgba(10, 132, 255, 0.1);
  1736. border: 1px solid rgba(10, 132, 255, 0.5);
  1737. border-radius: 4px;
  1738. outline: none;
  1739. &:focus {
  1740. border-color: rgba(10, 132, 255, 0.8);
  1741. }
  1742. }
  1743. }
  1744. .nav-btn {
  1745. width: 28px;
  1746. height: 28px;
  1747. display: flex;
  1748. align-items: center;
  1749. justify-content: center;
  1750. cursor: pointer;
  1751. border-radius: 4px;
  1752. transition: background 0.2s;
  1753. &:hover:not(.disabled) {
  1754. background: rgba(10, 132, 255, 0.15);
  1755. }
  1756. &.disabled {
  1757. opacity: 0.3;
  1758. cursor: not-allowed;
  1759. }
  1760. .nav-icon {
  1761. width: 16px;
  1762. height: 16px;
  1763. background-repeat: no-repeat;
  1764. background-size: 100% 100%;
  1765. }
  1766. .prev-icon {
  1767. background-image: var(--img-chat-prev-icon);
  1768. }
  1769. .next-icon {
  1770. background-image: var(--img-chat-next-icon);
  1771. }
  1772. .add-icon {
  1773. background-image: var(--img-chat-options-add-icon);
  1774. }
  1775. }
  1776. .upload-bg {
  1777. cursor: pointer;
  1778. width: 36px;
  1779. height: 36px;
  1780. background-image: var(--img-chat-close-bg);
  1781. background-repeat: no-repeat;
  1782. background-size: 100% 100%;
  1783. display: flex;
  1784. align-items: center;
  1785. justify-content: center;
  1786. margin-left: auto;
  1787. position: relative;
  1788. }
  1789. .download-icon {
  1790. width: 20px;
  1791. height: 20px;
  1792. background-image: var(--img-chat-download-icon);
  1793. background-repeat: no-repeat;
  1794. background-size: 100% 100%;
  1795. }
  1796. }
  1797. }
  1798. .right-panel {
  1799. width: calc(50% - 140px);
  1800. height: 100%;
  1801. display: flex;
  1802. flex-direction: column;
  1803. background-image: var(--img-chat-panel-bg);
  1804. background-repeat: no-repeat;
  1805. background-size: 100% 100%;
  1806. border-radius: 4px;
  1807. &.full {
  1808. flex: 1;
  1809. width: auto;
  1810. min-width: 0;
  1811. }
  1812. &.narrow {
  1813. width: 320px;
  1814. flex-shrink: 0;
  1815. }
  1816. flex-shrink: 0;
  1817. }
  1818. .draggable-title {
  1819. cursor: grab;
  1820. user-select: none;
  1821. &:active {
  1822. cursor: grabbing;
  1823. }
  1824. &.no-drag {
  1825. cursor: default;
  1826. &:active {
  1827. cursor: default;
  1828. }
  1829. }
  1830. }
  1831. </style>
  1832. <style lang="less">
  1833. .ai-assistant-modal {
  1834. .zxm-modal-content {
  1835. background-image: var(--img-chat-modal-bg);
  1836. background-repeat: no-repeat;
  1837. background-size: 100% 100%;
  1838. background-color: unset !important;
  1839. box-shadow: none;
  1840. padding: 0;
  1841. border: none !important;
  1842. }
  1843. .zxm-modal-close {
  1844. background-image: var(--img-chat-close-bg);
  1845. background-repeat: no-repeat;
  1846. background-size: 100% 100%;
  1847. top: 12px;
  1848. right: 20px;
  1849. width: 38px;
  1850. height: 38px;
  1851. .zxm-modal-close-x {
  1852. width: 38px;
  1853. height: 38px;
  1854. }
  1855. svg {
  1856. width: 26px;
  1857. height: 26px;
  1858. margin-bottom: 4px;
  1859. }
  1860. }
  1861. .maximize-btn {
  1862. position: absolute;
  1863. top: 12px;
  1864. right: 72px;
  1865. width: 38px;
  1866. height: 38px;
  1867. background-image: var(--img-chat-close-bg);
  1868. background-repeat: no-repeat;
  1869. background-size: 100% 100%;
  1870. display: flex;
  1871. align-items: center;
  1872. justify-content: center;
  1873. cursor: pointer;
  1874. z-index: 10;
  1875. .maximize-icon {
  1876. width: 22px;
  1877. height: 22px;
  1878. background-image: var(--img-chat-maximize-icon);
  1879. background-repeat: no-repeat;
  1880. background-size: 100% 100%;
  1881. &.minimized {
  1882. background-image: var(--img-chat-minimize-icon);
  1883. }
  1884. }
  1885. }
  1886. &.fullscreen {
  1887. top: 0 !important;
  1888. padding: 0 !important;
  1889. max-width: 100vw !important;
  1890. margin: 0 !important;
  1891. background-color: #09172c;
  1892. .zxm-modal-wrap,
  1893. .ant-modal-wrap {
  1894. padding: 0 !important;
  1895. margin: 0 !important;
  1896. top: 0 !important;
  1897. }
  1898. .zxm-modal-content {
  1899. width: 100vw !important;
  1900. height: 100vh !important;
  1901. max-width: 100vw !important;
  1902. margin: 0;
  1903. border-radius: 0;
  1904. overflow: hidden;
  1905. background-image: var(--img-chat-fs-modal-bg);
  1906. }
  1907. .zxm-modal-header {
  1908. height: 90px;
  1909. background-image: var(--img-chat-fs-header-bg) !important;
  1910. background-repeat: no-repeat;
  1911. background-size: 100% 100%;
  1912. margin-bottom: 16px;
  1913. }
  1914. .no-drag {
  1915. cursor: default;
  1916. font-size: 32px !important;
  1917. }
  1918. .zxm-modal-title {
  1919. height: 90px;
  1920. }
  1921. .zxm-modal-body {
  1922. height: calc(100vh - 120px);
  1923. overflow: hidden;
  1924. padding: 0 24px 12px;
  1925. }
  1926. .ai-container {
  1927. height: 100%;
  1928. overflow: hidden;
  1929. }
  1930. .chat-panel {
  1931. background-image: var(--img-chat-fs-panel-bg) !important;
  1932. }
  1933. .chat-header {
  1934. padding: 0 32px;
  1935. height: 50px;
  1936. }
  1937. .collapse-btn {
  1938. top: 60px;
  1939. background-image: var(--img-chat-fs-collapse-btn-bg) !important;
  1940. background-repeat: no-repeat;
  1941. background-size: 100% 100%;
  1942. }
  1943. .task-list-panel {
  1944. padding: 20px;
  1945. background-image: var(--img-chat-fs-task-panel-bg) !important;
  1946. background-repeat: no-repeat !important;
  1947. background-size: 100% 100% !important;
  1948. }
  1949. .options-area {
  1950. gap: 12px;
  1951. }
  1952. .options-area-item {
  1953. background-image: var(--img-chat-fs-options-item-bg) !important;
  1954. background-repeat: no-repeat !important;
  1955. background-size: 100% 100% !important;
  1956. &.active,
  1957. &:active {
  1958. background-image: var(--img-chat-fs-options-item-active-bg) !important;
  1959. }
  1960. .options-img {
  1961. background-image: none !important;
  1962. }
  1963. }
  1964. .chat-header-title {
  1965. height: 40px;
  1966. line-height: 40px;
  1967. position: relative;
  1968. background-image: var(--img-chat-fs-header-title-bg) !important;
  1969. background-repeat: no-repeat !important;
  1970. background-size: auto 100% !important;
  1971. padding: 0 28px;
  1972. &::before {
  1973. content: '';
  1974. position: absolute;
  1975. left: 0;
  1976. top: 50%;
  1977. transform: translateY(-50%);
  1978. width: 40px;
  1979. height: 40px;
  1980. background-image: var(--img-chat-fs-header-title-icon);
  1981. background-repeat: no-repeat;
  1982. background-size: 100% 100%;
  1983. }
  1984. }
  1985. .chat-header-title-wrapper {
  1986. .title-edit-input {
  1987. height: 36px;
  1988. font-size: 16px;
  1989. background: rgba(10, 132, 255, 0.15);
  1990. border-color: rgba(10, 132, 255, 0.6);
  1991. }
  1992. .title-edit-btn {
  1993. width: 24px;
  1994. height: 24px;
  1995. background-size: 16px 16px;
  1996. }
  1997. }
  1998. .chat-input-area {
  1999. margin: 24px;
  2000. }
  2001. .right-panel {
  2002. background-image: var(--img-chat-fs-panel-bg) !important;
  2003. }
  2004. .schedule-panel,
  2005. .skill-panel,
  2006. .sub-agent-panel {
  2007. background-image: var(--img-chat-fs-panel-bg) !important;
  2008. }
  2009. .schedule-detail-panel {
  2010. background-image: var(--img-chat-fs-task-panel-bg) !important;
  2011. }
  2012. }
  2013. .zxm-modal-header {
  2014. background-color: unset !important;
  2015. background: unset;
  2016. border: none !important;
  2017. padding: 8px;
  2018. backdrop-filter: unset;
  2019. display: flex;
  2020. justify-content: center;
  2021. }
  2022. .zxm-modal-title {
  2023. width: 100%;
  2024. height: 60px;
  2025. display: flex;
  2026. align-items: center;
  2027. justify-content: center;
  2028. .draggable-title {
  2029. color: #fff;
  2030. font-family: var(--vet-font-family);
  2031. letter-spacing: 3px;
  2032. font-size: 24px;
  2033. font-weight: 100;
  2034. line-height: 1.4;
  2035. }
  2036. }
  2037. .zxm-modal-body {
  2038. padding: 12px 24px;
  2039. }
  2040. }
  2041. .delete-task-confirm-modal {
  2042. .zxm-modal-confirm-title,
  2043. .zxm-modal-confirm-content {
  2044. color: #fff;
  2045. }
  2046. }
  2047. </style>