AiAssistantModal.vue 88 KB

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