1
0

AiAssistantModal.vue 76 KB

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