1
0

AiAssistantModal.vue 72 KB

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