1
0

AiAssistantModal.vue 82 KB

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