1
0

AiAssistantModal.vue 33 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119
  1. <template>
  2. <a-modal :visible="props.visible" @cancel="emit('close')" :width="1400" :footer="null" destroyOnClose class="ai-assistant-modal">
  3. <template #title>
  4. <div class="draggable-title" @mousedown="onDragStart">"通安智风"大模型</div>
  5. </template>
  6. <div class="ai-container">
  7. <!-- 左侧任务列表 -->
  8. <TaskListPanel
  9. :taskList="taskList"
  10. :currentTaskId="currentTaskId"
  11. @switch-task="switchTask"
  12. @create-task="createNewTask"
  13. @delete-task="handleDeleteTask"
  14. />
  15. <!-- 中间聊天区域 -->
  16. <div class="chat-panel">
  17. <!-- 顶部任务选择器 -->
  18. <div class="chat-header">
  19. <a-select
  20. v-model:value="currentTaskId"
  21. style="width: 300px"
  22. @change="handleTaskChange"
  23. :getContainer="false"
  24. popup-class-name="ai-task-select-dropdown"
  25. >
  26. <a-select-option v-for="task in taskList" :key="task.id" :value="task.id">
  27. {{ task.name }}
  28. </a-select-option>
  29. </a-select>
  30. <div v-if="currentWordUrl" class="upload-bg" @click="downloadWordReport">
  31. <div class="download-icon"></div>
  32. </div>
  33. </div>
  34. <!-- 附件列表面板 -->
  35. <FileListPanel :visible="showFileList" :files="getCurrentTaskFiles()" @close="showFileList = false" @file-click="openFilePreview" />
  36. <!-- 消息列表 -->
  37. <ChatMessages ref="chatMessagesRef" :messages="messages" @file-preview="openFilePreview" @download-word="downloadWordFile" />
  38. <!-- 输入区域 -->
  39. <ChatInputArea
  40. ref="chatInputRef"
  41. v-model="inputMessage"
  42. :pendingFile="pendingFile"
  43. :loading="loading"
  44. @send="handleSendMessage"
  45. @file-upload="triggerFileUpload"
  46. @file-change="handleFileUpload"
  47. @remove-pending-file="removePendingFile"
  48. />
  49. </div>
  50. <!-- 右侧文件预览面板 -->
  51. <div v-if="previewFile" class="right-panel">
  52. <FilePreviewPanel :file="previewFile" @close="removePreviewFile" />
  53. </div>
  54. </div>
  55. </a-modal>
  56. </template>
  57. <script setup lang="ts">
  58. import { ref, nextTick, watch, computed, onMounted, onBeforeUnmount } from 'vue';
  59. import dayjs from 'dayjs';
  60. import { unifiedStream, getHistoryList, getDetail, deleteSession } from '../api';
  61. import { message, Modal } from 'ant-design-vue';
  62. import { isPdfFile } from './chatModal/utils';
  63. import TaskListPanel from './chatModal/TaskListPanel.vue';
  64. import FileListPanel from './chatModal/FileListPanel.vue';
  65. import ChatMessages from './chatModal/ChatMessages.vue';
  66. import ChatInputArea from './chatModal/ChatInputArea.vue';
  67. import FilePreviewPanel from './chatModal/FilePreviewPanel.vue';
  68. import type { AttachedFile, Message, Task } from './chatModal/types';
  69. interface Props {
  70. visible: boolean;
  71. }
  72. interface Emits {
  73. (e: 'close'): void;
  74. }
  75. const props = defineProps<Props>();
  76. const emit = defineEmits<Emits>();
  77. const taskList = ref<Task[]>([]);
  78. // 从接口获取会话列表
  79. const fetchSessionList = async () => {
  80. try {
  81. const res = await getHistoryList({});
  82. const sessions = res?.sessions || res?.data || [];
  83. if (Array.isArray(sessions)) {
  84. const apiTasks: Task[] = sessions.map((item: { session_id: string; title: string }) => ({
  85. id: item.session_id,
  86. name: item.title || '未命名会话',
  87. sessionId: item.session_id,
  88. messages: [],
  89. attachedFiles: [],
  90. }));
  91. const mergedTasks = apiTasks.map((apiTask) => {
  92. const existing = taskList.value.find((t) => t.id === apiTask.id);
  93. if (existing) {
  94. return {
  95. ...apiTask,
  96. messages: existing.messages,
  97. attachedFiles: existing.attachedFiles,
  98. wordUrl: existing.wordUrl,
  99. };
  100. }
  101. return apiTask;
  102. });
  103. const localOnlyTasks = taskList.value.filter((t) => !t.sessionId && !apiTasks.find((a) => a.id === t.id));
  104. taskList.value = [...localOnlyTasks, ...mergedTasks];
  105. return mergedTasks;
  106. }
  107. } catch (error) {
  108. console.error('获取会话列表失败:', error);
  109. }
  110. return [];
  111. };
  112. const currentTaskId = ref('');
  113. const chatInputRef = ref<InstanceType<typeof ChatInputArea>>();
  114. const chatMessagesRef = ref<InstanceType<typeof ChatMessages>>();
  115. const previewFile = ref<AttachedFile | null>(null);
  116. const showFileList = ref(false);
  117. const pendingFile = ref<AttachedFile | null>(null);
  118. const messages = ref<Message[]>([
  119. {
  120. type: 'ai',
  121. content: '您好!我是通安智风助手,请问有什么可以帮助您的吗?',
  122. time: dayjs().format('HH:mm'),
  123. },
  124. ]);
  125. const inputMessage = ref('');
  126. const loading = ref(false);
  127. const getCurrentSessionId = (): string => {
  128. const currentTask = taskList.value.find((t) => t.id === currentTaskId.value);
  129. return currentTask?.sessionId || '';
  130. };
  131. const historyLoadedTasks = ref<Set<string>>(new Set());
  132. const setCurrentSessionId = (sessionId: string) => {
  133. const currentTask = taskList.value.find((t) => t.id === currentTaskId.value);
  134. if (currentTask && currentTask.id !== sessionId) {
  135. taskList.value = taskList.value.filter((t) => t.id !== sessionId);
  136. currentTask.id = sessionId;
  137. currentTask.sessionId = sessionId;
  138. currentTaskId.value = sessionId;
  139. historyLoadedTasks.value.add(sessionId);
  140. }
  141. };
  142. const switchTask = async (taskId: string) => {
  143. const currentTask = taskList.value.find((t) => t.id === currentTaskId.value);
  144. if (currentTask) {
  145. currentTask.messages = [...messages.value];
  146. }
  147. currentTaskId.value = taskId;
  148. const newTask = taskList.value.find((t) => t.id === taskId);
  149. if (!newTask) return;
  150. if (newTask.sessionId) {
  151. taskList.value = taskList.value.filter((t) => t.sessionId);
  152. }
  153. inputMessage.value = '';
  154. pendingFile.value = null;
  155. previewFile.value = null;
  156. showFileList.value = false;
  157. if (newTask.sessionId && !historyLoadedTasks.value.has(taskId)) {
  158. loading.value = true;
  159. try {
  160. const res = await getDetail(newTask.sessionId);
  161. const messages = res?.messages || (Array.isArray(res) ? res : res?.data);
  162. if (Array.isArray(messages)) {
  163. newTask.messages = transformHistoryToMessages(messages);
  164. }
  165. historyLoadedTasks.value.add(taskId);
  166. } catch (error) {
  167. console.error('加载历史会话失败:', error);
  168. } finally {
  169. loading.value = false;
  170. }
  171. }
  172. messages.value = newTask.messages && newTask.messages.length > 0 ? [...newTask.messages] : getDefaultMessages();
  173. await nextTick();
  174. scrollToBottom();
  175. };
  176. const handleTaskChange = (taskId: string) => {
  177. switchTask(taskId);
  178. };
  179. const createNewTask = () => {
  180. const existingBlank = taskList.value.find((t) => !t.sessionId);
  181. if (existingBlank) {
  182. switchTask(existingBlank.id);
  183. return;
  184. }
  185. const newTask: Task = {
  186. id: `task-${Date.now()}`,
  187. name: '新任务',
  188. sessionId: '',
  189. messages: getDefaultMessages(),
  190. attachedFiles: [],
  191. };
  192. taskList.value.unshift(newTask);
  193. switchTask(newTask.id);
  194. };
  195. const handleDeleteTask = (task: Task, index: number) => {
  196. Modal.confirm({
  197. title: '提示',
  198. content: '是否删除该对话?',
  199. okText: '确认',
  200. cancelText: '取消',
  201. onOk: async () => {
  202. try {
  203. if (task.sessionId) {
  204. await deleteSession(task.sessionId);
  205. }
  206. taskList.value.splice(index, 1);
  207. if (currentTaskId.value === task.id) {
  208. if (taskList.value.length > 0) {
  209. switchTask(taskList.value[0].id);
  210. } else {
  211. messages.value = [];
  212. currentTaskId.value = '';
  213. }
  214. }
  215. message.success('删除成功');
  216. } catch {
  217. message.error('删除失败');
  218. }
  219. },
  220. });
  221. };
  222. const getDefaultMessages = (): Message[] => {
  223. return [
  224. {
  225. type: 'ai',
  226. content: '您好!我是通安智风助手,请问有什么可以帮助您的吗?',
  227. time: dayjs().format('HH:mm'),
  228. },
  229. ];
  230. };
  231. const normalizeLineBreaks = (str: string): string => {
  232. if (!str) return '';
  233. return str.replace(/\\n/g, '\n').replace(/\r\n/g, '\n');
  234. };
  235. const transformHistoryToMessages = (data: Array<{ role?: string; type?: string; content: string; created_at?: string }>): Message[] => {
  236. const messages: Message[] = [];
  237. for (const item of data) {
  238. const normalizedContent = normalizeLineBreaks(item.content);
  239. const time = item.created_at ? dayjs(item.created_at).format('HH:mm') : '';
  240. const createdAt = item.created_at || '';
  241. // 新格式:role 字段 (user/assistant)
  242. if (item.role === 'user') {
  243. messages.push({ type: 'user', content: normalizedContent, time, createdAt });
  244. } else if (item.role === 'assistant') {
  245. messages.push({ type: 'ai', content: normalizedContent, time, createdAt });
  246. }
  247. // 兼容旧格式:type 字段
  248. else if (item.type === 'user_message') {
  249. messages.push({ type: 'user', content: normalizedContent, time, createdAt });
  250. } else if (item.type === 'model_thinking') {
  251. const lastAiMsg = messages[messages.length - 1];
  252. if (lastAiMsg && lastAiMsg.type === 'ai') {
  253. lastAiMsg.content += normalizedContent;
  254. lastAiMsg.content = lastAiMsg.content.replace(/\|\|\|SPLIT_CONTENT\|\|\|/g, '');
  255. } else {
  256. messages.push({ type: 'ai', content: normalizedContent, time, createdAt });
  257. }
  258. }
  259. }
  260. return messages;
  261. };
  262. const triggerFileUpload = () => {
  263. chatInputRef.value?.fileInputRef?.click();
  264. };
  265. const handleFileUpload = async (event: Event) => {
  266. const target = event.target as HTMLInputElement;
  267. const file = target.files?.[0];
  268. if (!file) return;
  269. if (!isPdfFile(file.name)) {
  270. message.error('仅支持 PDF 文件格式');
  271. target.value = '';
  272. return;
  273. }
  274. try {
  275. const newFile: AttachedFile = {
  276. id: `file-${Date.now()}`,
  277. name: file.name,
  278. size: file.size,
  279. type: file.type,
  280. uploadTime: dayjs().format('YYYY-MM-DD HH:mm'),
  281. originalFile: file,
  282. };
  283. const reader = new FileReader();
  284. reader.onload = (e) => {
  285. newFile.preview = e.target?.result as string;
  286. };
  287. reader.readAsDataURL(file);
  288. pendingFile.value = newFile;
  289. message.success(`文件 "${file.name}" 已添加,点击发送按钮提交`);
  290. } catch (error) {
  291. console.error('文件处理失败:', error);
  292. message.error('文件处理失败,请重试');
  293. }
  294. target.value = '';
  295. };
  296. const removePendingFile = () => {
  297. pendingFile.value = null;
  298. };
  299. const removePreviewFile = () => {
  300. previewFile.value = null;
  301. };
  302. const openFilePreview = (file: AttachedFile) => {
  303. previewFile.value = file;
  304. const msgIndex = messages.value.findIndex((m) => m.attachedFile?.id === file.id);
  305. if (msgIndex !== -1) {
  306. nextTick(() => {
  307. const messageElements = chatMessagesRef.value?.messagesRef?.querySelectorAll('.message-wrapper');
  308. if (messageElements && messageElements[msgIndex]) {
  309. (messageElements[msgIndex] as HTMLElement).scrollIntoView({
  310. behavior: 'smooth',
  311. block: 'center',
  312. });
  313. }
  314. });
  315. }
  316. };
  317. const getCurrentTaskFiles = (): AttachedFile[] => {
  318. const currentTask = taskList.value.find((t) => t.id === currentTaskId.value);
  319. return currentTask?.attachedFiles || [];
  320. };
  321. const currentWordUrl = computed(() => {
  322. const currentTask = taskList.value.find((t) => t.id === currentTaskId.value);
  323. return currentTask?.wordUrl || '';
  324. });
  325. const downloadWordReport = () => {
  326. const url = currentWordUrl.value;
  327. if (!url) return;
  328. const a = document.createElement('a');
  329. a.href = url;
  330. a.download = '';
  331. a.target = '_blank';
  332. document.body.appendChild(a);
  333. a.click();
  334. document.body.removeChild(a);
  335. };
  336. const downloadWordFile = (url: string) => {
  337. if (!url) return;
  338. const a = document.createElement('a');
  339. a.href = url;
  340. a.download = '';
  341. a.target = '_blank';
  342. document.body.appendChild(a);
  343. a.click();
  344. document.body.removeChild(a);
  345. };
  346. const handleSendMessage = async () => {
  347. const hasText = inputMessage.value.trim();
  348. const hasFile = pendingFile.value;
  349. if (!hasText) {
  350. message.warning('请输入消息内容');
  351. return;
  352. }
  353. if (loading.value) return;
  354. const userInput = inputMessage.value.trim();
  355. const fileToSend = pendingFile.value;
  356. inputMessage.value = '';
  357. pendingFile.value = null;
  358. try {
  359. loading.value = true;
  360. if (hasFile) {
  361. await sendWithAttachment(fileToSend!, userInput);
  362. } else {
  363. await sendTextOnly(userInput);
  364. }
  365. } catch (error) {
  366. console.error('发送消息失败:', error);
  367. message.error('发送失败,请重试');
  368. const lastMsg = messages.value[messages.value.length - 1];
  369. if (lastMsg && lastMsg.type === 'ai' && lastMsg.isLoading) {
  370. messages.value.pop();
  371. }
  372. const errorMsg: Message = {
  373. type: 'ai',
  374. content: '抱歉,请求失败,请稍后重试。',
  375. time: dayjs().format('HH:mm'),
  376. };
  377. messages.value.push(errorMsg);
  378. const currentTask = taskList.value.find((t) => t.id === currentTaskId.value);
  379. if (currentTask) {
  380. currentTask.messages = [...messages.value];
  381. }
  382. } finally {
  383. loading.value = false;
  384. await scrollToBottom();
  385. }
  386. };
  387. const extractAgentName = (toolName: string): string => {
  388. const nameMap: Record<string, string> = {
  389. form_review: '形式审查',
  390. verify_coal_face_ventilation: '采煤工作面需风量计算核验',
  391. verify_tunneling_face_ventilation: '掘进工作面需风量计算核验',
  392. verify_chamber_ventilation: '硐室需风量计算核验',
  393. verify_other_points_ventilation: '其他地点需风量计算核验',
  394. check_data_by_gas_report: '瓦斯数据一致性审查',
  395. check_data_by_face_design: '设计规程一致性审查',
  396. check_data_by_vent_report: '测风报表一致性审查',
  397. check_current_month_plan: '日期有效性审查',
  398. get_key_translate: '计算参数对照',
  399. calculate_ventilation: '需风量计算',
  400. get_ventilation_data: '需风量查询',
  401. recalculate_ventilation: '需风量重计算',
  402. get_plan_required_wind: '需风量提取',
  403. get_model_calculated_wind: '三维模型解算风量提取',
  404. get_sensor_wind: '巷道监测风量提取',
  405. merge_wind_by_location: '地点风量智能合并',
  406. check_wind_compliance: '风量检查',
  407. };
  408. return nameMap[toolName] || nameMap[toolName.toLowerCase()] || '智能分析助手';
  409. };
  410. // 每个 agent 只保留最新一条步骤,新数据替换旧数据
  411. const upsertStep = (steps: any[], step: any) => {
  412. const agentName = step.agent || '系统';
  413. const idx = steps.findIndex((s) => (s.agent || '系统') === agentName && s.type !== 'updated_todo_list');
  414. if (idx !== -1) {
  415. steps.splice(idx, 1, step);
  416. } else {
  417. steps.push(step);
  418. }
  419. };
  420. const handleSSEMessage = (data: any, aiMsgIndex: number) => {
  421. const aiMsg = messages.value[aiMsgIndex];
  422. const normalizedContent = normalizeLineBreaks(data.content || '');
  423. // 初始化 thinkingSteps 数组
  424. if (!aiMsg.thinkingSteps) {
  425. aiMsg.thinkingSteps = [];
  426. }
  427. switch (data.type) {
  428. // token 流式内容 - 直接拼接到消息内容
  429. case 'token':
  430. if (normalizedContent) {
  431. aiMsg.content += normalizedContent;
  432. }
  433. break;
  434. // 系统进度消息 - 仅当 agent 不是 system 时才作为 thinking step
  435. case 'progress': {
  436. if (data.agent && data.agent !== 'system') {
  437. upsertStep(aiMsg.thinkingSteps!, {
  438. type: 'executing',
  439. agent: data.agent,
  440. message: data.message || '',
  441. timestamp: Date.now(),
  442. });
  443. }
  444. break;
  445. }
  446. // agent 开始处理
  447. case 'agent_start': {
  448. upsertStep(aiMsg.thinkingSteps!, {
  449. type: 'agent_start',
  450. agent: data.cn_agent || data.agent || '智能助手',
  451. message: data.message || '开始处理...',
  452. timestamp: Date.now(),
  453. });
  454. break;
  455. }
  456. // agent 任务列表更新(同一 agent 的 todos 更新已有条目,不重复添加)
  457. case 'agent_todos':
  458. case 'updated_todo_list': {
  459. const agentName = data.cn_agent || data.agent || '智能助手';
  460. const existingIdx = aiMsg.thinkingSteps!.findIndex((s) => s.type === 'updated_todo_list' && s.agent === agentName);
  461. if (existingIdx !== -1) {
  462. aiMsg.thinkingSteps![existingIdx].todos = data.todos || [];
  463. aiMsg.thinkingSteps![existingIdx].timestamp = Date.now();
  464. } else {
  465. aiMsg.thinkingSteps!.push({
  466. type: 'updated_todo_list',
  467. agent: agentName,
  468. todos: data.todos || [],
  469. message: data.message || '任务进度已更新',
  470. timestamp: Date.now(),
  471. });
  472. }
  473. break;
  474. }
  475. // agent 执行中(工具调用)
  476. case 'agent_executing':
  477. case 'executing': {
  478. upsertStep(aiMsg.thinkingSteps!, {
  479. type: 'executing',
  480. agent: data.cn_agent || data.agent || '智能助手',
  481. tool: (data.cn_tools || data.tools || []).join('、'),
  482. message: data.message || '',
  483. timestamp: Date.now(),
  484. });
  485. break;
  486. }
  487. // 工具结果
  488. case 'agent_tool_result':
  489. case 'tool_result': {
  490. upsertStep(aiMsg.thinkingSteps!, {
  491. type: 'tool_result',
  492. agent: data.cn_agent || data.agent || '智能助手',
  493. tool: data.cn_tool || data.tool || '',
  494. message: data.message || '执行完成',
  495. timestamp: Date.now(),
  496. });
  497. break;
  498. }
  499. // agent 完成
  500. case 'agent_done': {
  501. upsertStep(aiMsg.thinkingSteps!, {
  502. type: 'agent_done',
  503. agent: data.cn_agent || data.agent || '智能助手',
  504. message: `${data.message || '审查完成'}${data.duration_ms ? `(${(data.duration_ms / 1000).toFixed(0)}s)` : ''}${data.progress ? ` [${data.progress}]` : ''}`,
  505. timestamp: Date.now(),
  506. });
  507. if (data.preview) {
  508. aiMsg.content += data.preview;
  509. }
  510. break;
  511. }
  512. // 旧格式兼容
  513. case 'model_thinking':
  514. if (normalizedContent) {
  515. aiMsg.content += normalizedContent;
  516. aiMsg.content = aiMsg.content.replace(/\|\|\|SPLIT_CONTENT\|\|\|/g, '');
  517. }
  518. break;
  519. case 'tool_select': {
  520. upsertStep(aiMsg.thinkingSteps!, {
  521. type: 'tool_call',
  522. agent: extractAgentName(normalizedContent),
  523. tool: normalizedContent,
  524. message: `选择工具:${normalizedContent}`,
  525. timestamp: Date.now(),
  526. });
  527. break;
  528. }
  529. case 'error':
  530. upsertStep(aiMsg.thinkingSteps!, {
  531. type: 'tool_result',
  532. agent: '系统',
  533. message: `❌ 执行失败:${normalizedContent}`,
  534. timestamp: Date.now(),
  535. });
  536. aiMsg.isLoading = false;
  537. break;
  538. case 'word_download':
  539. if (normalizedContent) {
  540. aiMsg.wordDownloadUrl = normalizedContent;
  541. const wordTask = taskList.value.find((t) => t.id === currentTaskId.value);
  542. if (wordTask) wordTask.wordUrl = normalizedContent;
  543. }
  544. break;
  545. case 'done':
  546. if (data.session_id) {
  547. aiMsg.sessionId = data.session_id;
  548. }
  549. if (data.duration_ms) {
  550. aiMsg.durationMs = data.duration_ms;
  551. }
  552. aiMsg.isLoading = false;
  553. break;
  554. case 'system':
  555. if (normalizedContent) {
  556. aiMsg.content += normalizedContent.replace(/\n/g, ' \n');
  557. }
  558. break;
  559. }
  560. const currentTask = taskList.value.find((t) => t.id === currentTaskId.value);
  561. if (currentTask) {
  562. currentTask.messages = [...messages.value];
  563. }
  564. };
  565. const parseSSEData = (chunk: string, aiMsgIndex: number) => {
  566. const lines = chunk.split('\n');
  567. for (const lineRaw of lines) {
  568. const line = lineRaw.trim();
  569. if (!line) continue;
  570. if (line.startsWith('data:')) {
  571. try {
  572. const jsonStr = line.substring(5).trim();
  573. const data = JSON.parse(jsonStr);
  574. handleSSEMessage(data, aiMsgIndex);
  575. } catch (error) {
  576. console.error('解析 SSE data 行失败:', error, line);
  577. }
  578. continue;
  579. }
  580. try {
  581. const data = JSON.parse(line);
  582. handleSSEMessage(data, aiMsgIndex);
  583. continue;
  584. } catch {
  585. // not json
  586. }
  587. handleSSEMessage({ type: 'model_thinking', content: line }, aiMsgIndex);
  588. }
  589. };
  590. const sendTextOnly = async (userInput: string) => {
  591. const now = dayjs();
  592. const userMsg: Message = {
  593. type: 'user',
  594. content: userInput,
  595. time: now.format('HH:mm'),
  596. createdAt: now.toISOString(),
  597. };
  598. messages.value.push(userMsg);
  599. await scrollToBottom();
  600. const aiMsgIndex = messages.value.length;
  601. const aiMsg: Message = {
  602. type: 'ai',
  603. content: '',
  604. time: now.format('HH:mm'),
  605. createdAt: now.toISOString(),
  606. isLoading: true,
  607. thinkingSteps: [],
  608. generateStartTime: Date.now(),
  609. };
  610. messages.value.push(aiMsg);
  611. await scrollToBottom();
  612. const result = await unifiedStream(
  613. {
  614. message: userInput,
  615. session_id: getCurrentSessionId() || undefined,
  616. },
  617. (chunk: string) => {
  618. parseSSEData(chunk, aiMsgIndex);
  619. scrollToBottom();
  620. }
  621. );
  622. if (result.session_id) {
  623. const taskBeforeUpdate = taskList.value.find((t) => t.id === currentTaskId.value);
  624. const isNewTask = taskBeforeUpdate && !taskBeforeUpdate.sessionId;
  625. setCurrentSessionId(result.session_id);
  626. if (isNewTask) {
  627. taskBeforeUpdate.name = userInput.substring(0, 20) + (userInput.length > 20 ? '...' : '');
  628. }
  629. }
  630. const currentTask = taskList.value.find((t) => t.id === currentTaskId.value);
  631. if (currentTask) {
  632. currentTask.messages = [...messages.value];
  633. }
  634. };
  635. const sendWithAttachment = async (file: AttachedFile, userInput: string) => {
  636. let currentTask = taskList.value.find((t) => t.id === currentTaskId.value);
  637. if (currentTask) {
  638. currentTask.attachedFiles.push(file);
  639. } else {
  640. throw new Error('未找到当前任务');
  641. }
  642. const now = dayjs();
  643. const userMsg: Message = {
  644. type: 'user',
  645. content: userInput || `上传了文件:${file.name}`,
  646. time: now.format('HH:mm'),
  647. createdAt: now.toISOString(),
  648. attachedFile: file,
  649. };
  650. messages.value.push(userMsg);
  651. await scrollToBottom();
  652. const aiMsgIndex = messages.value.length;
  653. const aiMsg: Message = {
  654. type: 'ai',
  655. content: '',
  656. time: now.format('HH:mm'),
  657. createdAt: now.toISOString(),
  658. isLoading: true,
  659. thinkingSteps: [],
  660. generateStartTime: Date.now(),
  661. };
  662. messages.value.push(aiMsg);
  663. await scrollToBottom();
  664. if (!file.originalFile) {
  665. throw new Error('缺少原始文件对象');
  666. }
  667. const result = await unifiedStream(
  668. {
  669. message: userInput || `上传了文件:${file.name}`,
  670. session_id: getCurrentSessionId() || undefined,
  671. file: file.originalFile,
  672. },
  673. (chunk: string) => {
  674. parseSSEData(chunk, aiMsgIndex);
  675. scrollToBottom();
  676. }
  677. );
  678. if (result.session_id) {
  679. setCurrentSessionId(result.session_id);
  680. }
  681. currentTask = taskList.value.find((t) => t.id === currentTaskId.value);
  682. if (currentTask) {
  683. currentTask.messages = [...messages.value];
  684. }
  685. };
  686. const scrollToBottom = async () => {
  687. await nextTick();
  688. if (!chatMessagesRef.value?.isAtBottom) return;
  689. const el = chatMessagesRef.value?.messagesRef;
  690. if (el) {
  691. el.scrollTop = el.scrollHeight;
  692. }
  693. };
  694. watch(
  695. () => props.visible,
  696. async (newVisible) => {
  697. if (!newVisible) {
  698. const currentTask = taskList.value.find((t) => t.id === currentTaskId.value);
  699. if (currentTask) {
  700. currentTask.messages = [...messages.value];
  701. }
  702. } else {
  703. await fetchSessionList();
  704. // 去除重复的空白任务,只保留一个
  705. taskList.value = taskList.value.filter((task, index) => {
  706. if (task.sessionId) return true;
  707. return index === taskList.value.findIndex((t) => !t.sessionId);
  708. });
  709. // 默认选中第一条历史记录
  710. const firstHistoryTask = taskList.value.find((t) => t.sessionId);
  711. let targetTask: Task;
  712. if (firstHistoryTask) {
  713. targetTask = firstHistoryTask;
  714. } else {
  715. // 没有历史记录时才创建空白新任务
  716. targetTask = {
  717. id: `task-${Date.now()}`,
  718. name: '新任务',
  719. sessionId: '',
  720. messages: getDefaultMessages(),
  721. attachedFiles: [],
  722. };
  723. taskList.value.unshift(targetTask);
  724. }
  725. currentTaskId.value = targetTask.id;
  726. // 如果是历史任务,加载其消息
  727. if (targetTask.sessionId && !historyLoadedTasks.value.has(targetTask.id)) {
  728. loading.value = true;
  729. try {
  730. const res = await getDetail(targetTask.sessionId);
  731. const messages = res?.messages || (Array.isArray(res) ? res : res?.data);
  732. if (Array.isArray(messages)) {
  733. targetTask.messages = transformHistoryToMessages(messages);
  734. }
  735. historyLoadedTasks.value.add(targetTask.id);
  736. } catch (error) {
  737. console.error('加载历史会话失败:', error);
  738. } finally {
  739. loading.value = false;
  740. }
  741. }
  742. messages.value = targetTask.messages && targetTask.messages.length > 0 ? [...targetTask.messages] : getDefaultMessages();
  743. previewFile.value = null;
  744. pendingFile.value = null;
  745. showFileList.value = false;
  746. inputMessage.value = '';
  747. await nextTick(() => {
  748. scrollToBottom();
  749. });
  750. }
  751. }
  752. );
  753. // 拖拽相关(使用普通变量避免 mousemove 触发 Vue 响应式导致卡顿)
  754. let isDragging = false;
  755. let dragStartX = 0;
  756. let dragStartY = 0;
  757. let modalStartLeft = 0;
  758. let modalStartTop = 0;
  759. let draggedEl: HTMLElement | null = null;
  760. const findModalWrap = (target: HTMLElement): HTMLElement | null =>
  761. target.closest<HTMLElement>('.zxm-modal-wrap, .ant-modal-wrap, [class*="modal-wrap"]');
  762. const queryModalWrap = (): HTMLElement | null => document.querySelector<HTMLElement>('.zxm-modal-wrap, .ant-modal-wrap, [class*="modal-wrap"]');
  763. const centerModal = () => {
  764. nextTick(() => {
  765. const wrap = queryModalWrap();
  766. if (wrap) {
  767. wrap.style.position = '';
  768. wrap.style.left = '';
  769. wrap.style.top = '';
  770. wrap.style.right = '';
  771. wrap.style.bottom = '';
  772. wrap.style.width = '';
  773. wrap.style.height = '';
  774. wrap.style.margin = '';
  775. wrap.style.transform = '';
  776. }
  777. draggedEl = null;
  778. });
  779. };
  780. const onDragStart = (e: MouseEvent) => {
  781. draggedEl = findModalWrap(e.target as HTMLElement) || queryModalWrap();
  782. if (!draggedEl) return;
  783. isDragging = true;
  784. dragStartX = e.clientX;
  785. dragStartY = e.clientY;
  786. const rect = draggedEl.getBoundingClientRect();
  787. modalStartLeft = rect.left;
  788. modalStartTop = rect.top;
  789. draggedEl.style.position = 'fixed';
  790. draggedEl.style.left = `${rect.left}px`;
  791. draggedEl.style.top = `${rect.top}px`;
  792. draggedEl.style.margin = '0';
  793. draggedEl.style.transform = 'none';
  794. document.addEventListener('mousemove', onDragMove);
  795. document.addEventListener('mouseup', onDragEnd);
  796. };
  797. const onDragMove = (e: MouseEvent) => {
  798. if (!isDragging || !draggedEl) return;
  799. draggedEl.style.left = `${modalStartLeft + (e.clientX - dragStartX)}px`;
  800. draggedEl.style.top = `${modalStartTop + (e.clientY - dragStartY)}px`;
  801. };
  802. const onDragEnd = () => {
  803. isDragging = false;
  804. document.removeEventListener('mousemove', onDragMove);
  805. document.removeEventListener('mouseup', onDragEnd);
  806. };
  807. watch(
  808. () => props.visible,
  809. (newVisible) => {
  810. if (newVisible) {
  811. centerModal();
  812. }
  813. }
  814. );
  815. onMounted(async () => {
  816. // fetchSessionList moved to watch(visible) to avoid unnecessary API calls
  817. });
  818. onBeforeUnmount(() => {
  819. document.removeEventListener('mousemove', onDragMove);
  820. document.removeEventListener('mouseup', onDragEnd);
  821. });
  822. </script>
  823. <style scoped lang="less">
  824. .ai-container {
  825. display: flex;
  826. height: 700px;
  827. gap: 10px;
  828. overflow: hidden;
  829. font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, 'Helvetica Neue', Arial, sans-serif;
  830. }
  831. .chat-panel {
  832. flex: 1;
  833. display: flex;
  834. position: relative;
  835. flex-direction: column;
  836. background-image: var(--img-chat-panel-bg);
  837. background-repeat: no-repeat;
  838. background-size: 100% 100%;
  839. border-radius: 4px;
  840. overflow: hidden;
  841. min-width: 0;
  842. :deep(.chat-header) {
  843. display: flex;
  844. padding: 12px 20px;
  845. flex-shrink: 0;
  846. align-items: center;
  847. .header-icon {
  848. width: 35px;
  849. height: 28px;
  850. background-image: var(--img-chat-header-icon);
  851. background-repeat: no-repeat;
  852. background-size: 100% 100%;
  853. margin-right: 10px;
  854. }
  855. .zxm-select-selector {
  856. height: 40px;
  857. background-image: var(--img-chat-selector-bg);
  858. background-repeat: no-repeat;
  859. background-size: 100% 100%;
  860. border: none;
  861. border-color: unset !important;
  862. box-shadow: unset !important;
  863. color: #e0e6ed;
  864. background-color: unset;
  865. border-radius: 0;
  866. padding-left: 40px;
  867. padding-top: 10px;
  868. }
  869. .zxm-select-arrow {
  870. color: #e0e6ed;
  871. }
  872. .zxm-select-selection-item {
  873. color: #e0e6ed;
  874. }
  875. .upload-bg {
  876. cursor: pointer;
  877. width: 36px;
  878. height: 36px;
  879. background-image: var(--img-chat-upload-bg);
  880. background-repeat: no-repeat;
  881. background-size: 100% 100%;
  882. display: flex;
  883. align-items: center;
  884. justify-content: center;
  885. margin-left: auto;
  886. position: relative;
  887. }
  888. .download-icon {
  889. width: 20px;
  890. height: 20px;
  891. background-image: var(--img-chat-download-icon);
  892. background-repeat: no-repeat;
  893. background-size: 100% 100%;
  894. }
  895. }
  896. }
  897. .right-panel {
  898. width: calc(50% - 140px);
  899. height: 100%;
  900. display: flex;
  901. flex-direction: column;
  902. background: linear-gradient(to bottom, rgba(10, 132, 255, 0.08), rgba(2, 22, 50, 0.95));
  903. border: 2px solid rgba(63, 80, 106, 0.5);
  904. border-radius: 4px;
  905. flex-shrink: 0;
  906. }
  907. .draggable-title {
  908. cursor: grab;
  909. user-select: none;
  910. &:active {
  911. cursor: grabbing;
  912. }
  913. }
  914. </style>
  915. <style lang="less">
  916. .ai-assistant-modal {
  917. .zxm-modal-content {
  918. background-image: var(--img-chat-modal-bg);
  919. background-repeat: no-repeat;
  920. background-size: 100% 100%;
  921. background-color: unset !important;
  922. box-shadow: none;
  923. padding: 0;
  924. border: none !important;
  925. }
  926. .zxm-modal-close {
  927. background-image: var(--img-chat-close-bg);
  928. background-repeat: no-repeat;
  929. background-size: 100% 100%;
  930. top: -6px;
  931. right: -6px;
  932. width: 38px;
  933. height: 38px;
  934. .zxm-modal-close-x {
  935. width: 38px;
  936. height: 38px;
  937. }
  938. svg {
  939. width: 26px;
  940. height: 26px;
  941. margin-bottom: 4px;
  942. }
  943. }
  944. .zxm-modal-header {
  945. background-color: unset !important;
  946. background: unset;
  947. border: none !important;
  948. padding: 8px;
  949. backdrop-filter: unset;
  950. display: flex;
  951. justify-content: center;
  952. }
  953. .zxm-modal-title {
  954. width: 100%;
  955. height: 60px;
  956. display: flex;
  957. align-items: center;
  958. justify-content: center;
  959. .draggable-title {
  960. color: #fff;
  961. font-family: var(--vet-font-family);
  962. letter-spacing: 3px;
  963. font-size: 24px;
  964. font-weight: 100;
  965. line-height: 1.4;
  966. }
  967. }
  968. .zxm-modal-body {
  969. padding: 12px 24px;
  970. }
  971. }
  972. .ai-task-select-dropdown {
  973. background-color: rgba(10, 132, 255, 0.1);
  974. .zxm-select-item {
  975. color: #e0e6ed;
  976. }
  977. .zxm-select-item-option-selected {
  978. color: #e0e6ed !important;
  979. background-color: rgba(10, 132, 255, 0.15) !important;
  980. }
  981. }
  982. </style>