| 12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438 |
- <template>
- <a-modal
- :visible="props.visible"
- @cancel="emit('close')"
- :width="modalWidth"
- :footer="null"
- destroyOnClose
- :closable="showControls"
- :zIndex="props.zIndex"
- :class="['ai-assistant-modal', { fullscreen: isFullscreen }]"
- >
- <template #title>
- <div :class="['draggable-title', { 'no-drag': isFullscreen }]" @mousedown="onDragStart">"通安智风"大模型</div>
- </template>
- <!-- 最大化/还原按钮 -->
- <div v-if="showControls" class="maximize-btn" @click="toggleFullscreen">
- <div :class="['maximize-icon', { minimized: isFullscreen }]"></div>
- </div>
- <!-- 收起/展开按钮 -->
- <div class="collapse-btn" @click="togglePanel">
- <div :class="['collapse-icon', { collapsed: panelCollapsed }]"></div>
- </div>
- <div class="ai-container">
- <!-- 左侧任务列表 -->
- <div :class="['task-panel-wrapper', { collapsed: panelCollapsed }]">
- <TaskListPanel
- :taskList="taskList"
- :currentTaskId="currentTaskId"
- @switch-task="switchTask"
- @create-task="createNewTask"
- @delete-task="handleDeleteTask"
- @pin-task="handlePinTask"
- @toggle-skill="toggleSkillPanel"
- @toggle-sub-agents="toggleSubAgentPanel"
- @toggle-schedules="toggleSchedulePanel"
- />
- </div>
- <!-- 右侧内容区:根据 activePanel 切换显示 -->
- <!-- 聊天区域 -->
- <template v-if="activePanel === 'chat'">
- <div class="chat-panel">
- <!-- 顶部任务选择器 -->
- <ChatHeader
- :currentTask="currentTask"
- :panelCollapsed="panelCollapsed"
- :canGoPrev="canGoPrev"
- :canGoNext="canGoNext"
- :currentWordUrl="currentWordUrl"
- @go-to-prev="goToPrev"
- @go-to-next="goToNext"
- @create-task="createNewTask"
- @save-title="handleSaveTitle"
- @download-word="downloadWordReport"
- />
- <!-- 附件列表面板 -->
- <FileListPanel :visible="showFileList" :files="getCurrentTaskFiles()" @close="showFileList = false" @file-click="openFilePreview" />
- <!-- 消息列表 -->
- <ChatMessages
- ref="chatMessagesRef"
- :messages="messages"
- @file-preview="openFilePreview"
- @download-word="downloadWordFile"
- @open-file-preview="handleOpenFilePreview"
- @ask-user-submit="handleAskUserSubmit"
- @ask-user-cancel="handleAskUserCancel"
- @agent-detail-click="handleAgentDetailClick"
- @open-markdown-tab="openMarkdownPreviewTab"
- />
- <!-- 任务进度条 -->
- <TodoListBar v-if="showTodoBar" :todos="currentTodos" />
- <!-- 输入区域 -->
- <ChatInputArea
- ref="chatInputRef"
- v-model="inputMessage"
- :pendingFile="pendingFile"
- :loading="loading || !!currentPendingApproval"
- :streaming="streaming"
- :contextUsed="contextUsed"
- :contextMax="contextMax"
- :contextPercent="contextPercent"
- :contextBreakdown="contextBreakdown"
- :usageLimit="usageToday?.limit_tokens ?? 0"
- :usageSpent="usageToday?.spent_tokens ?? 0"
- :usageRemaining="usageToday?.remaining_tokens ?? 0"
- :usageByModel="usageToday?.by_model ?? []"
- :initialThinkLevel="thinkLevel"
- :initialEditMode="editMode"
- :taskList="taskList"
- :currentTaskId="currentTaskId"
- @send="handleSendMessage"
- @stop="stopStreaming"
- @file-upload="triggerFileUpload"
- @file-change="handleFileUpload"
- @remove-pending-file="removePendingFile"
- @pending-file-preview="openFilePreview"
- @think-level-change="handleThinkLevelChange"
- @edit-mode-change="handleEditModeChange"
- @update:selected-sessions="handleUpdateSelectedSessions"
- @update:selected-skill="handleUpdateSelectedSkill"
- />
- </div>
- <!-- 右侧辅助面板(标签页容器,与 chat-panel 并列,带滑入滑出动画) -->
- <Transition name="right-panel-slide" @after-leave="onPanelLeaveEnd">
- <RightPanelTabs
- v-if="currentRightPanels.tabs.length > 0"
- :tabs="currentRightPanels.tabs"
- :activeTabId="currentRightPanels.activeTabId"
- :messages="messages"
- @switch-tab="activateTab"
- @close-tab="closeTab"
- @save-success="handleSaveSuccess"
- @schedule-deleted="handleScheduleDeleted"
- @schedule-updated="handleScheduleUpdated"
- @open-schedule-session="handleOpenScheduleSession"
- @open-markdown-tab="openMarkdownPreviewTab"
- />
- </Transition>
- </template>
- <!-- 技能面板 -->
- <div v-if="activePanel === 'skill'" class="right-panel full">
- <SkillPanel @close="activePanel = 'chat'" />
- </div>
- <!-- 子智能体面板 -->
- <div v-if="activePanel === 'sub-agents'" class="right-panel full">
- <SubAgentPanel @close="activePanel = 'chat'" />
- </div>
- <!-- 定时任务面板 -->
- <div v-if="activePanel === 'schedules'" class="right-panel full">
- <SchedulePanel
- ref="schedulePanelRef"
- @close="activePanel = 'chat'"
- @open-session="handleOpenScheduleSession"
- @data-changed="fetchScheduleListForDetail"
- />
- </div>
- </div>
- </a-modal>
- </template>
- <script setup lang="ts">
- import { ref, nextTick, watch, computed, onBeforeUnmount } from 'vue';
- import dayjs from 'dayjs';
- import {
- unifiedStream,
- reviewPdfStream,
- chatResumeStream,
- getHistoryList,
- getDetail,
- deleteSession,
- pinSession,
- editSessionTitle,
- getContext,
- switchThinking,
- getModelMsg,
- getSessionMode,
- putSessionMode,
- getTodayUsage,
- StreamError,
- } from '../api';
- import { message, Modal } from 'ant-design-vue';
- import TaskListPanel from './chatModal/TaskListPanel.vue';
- import ChatHeader from './chatModal/ChatHeader.vue';
- import FileListPanel from './chatModal/FileListPanel.vue';
- import ChatMessages from './chatModal/ChatMessages.vue';
- import type { AgentDetailData } from './chatModal/ChatMessages.vue';
- import ChatInputArea from './chatModal/ChatInputArea.vue';
- import TodoListBar from './chatModal/TodoListBar.vue';
- import SkillPanel from './chatModal/SkillPanel.vue';
- import SubAgentPanel from './chatModal/SubAgentPanel.vue';
- import SchedulePanel from './chatModal/SchedulePanel.vue';
- import RightPanelTabs from './chatModal/RightPanelTabs.vue';
- import { getScheduleList } from '../api';
- import type { TodayUsage } from '../api';
- import type { AttachedFile, Message, Task, RightPanelTab, RightPanelState, SseEvent } from './chatModal/types';
- import { isTextFile, isVideoFile, isAudioFile, isWordFile, isExcelFile, isCsvFile } from './chatModal/utils';
- interface Props {
- visible: boolean;
- // 初始即全屏显示(首页等嵌入场景)
- defaultFullscreen?: boolean;
- // 是否显示窗口控制按钮(最大化/还原、关闭)
- showControls?: boolean;
- zIndex?: number;
- }
- interface Emits {
- (e: 'close'): void;
- }
- const props = withDefaults(defineProps<Props>(), {
- defaultFullscreen: false,
- showControls: true,
- });
- const emit = defineEmits<Emits>();
- const taskList = ref<Task[]>([]);
- // 已从接口拉取过的会话 id,用于识别流式期间后端新建的会话
- const knownApiSessionIds = new Set<string>();
- // 从接口获取会话列表
- const fetchSessionList = async () => {
- try {
- const res = await getHistoryList({});
- const sessions = res?.sessions || res?.data || [];
- if (Array.isArray(sessions)) {
- const apiTasks: Task[] = sessions.map((item: { session_id: string; title: string; updated_at: string; sort_order?: number }) => ({
- id: item.session_id,
- name: item.title || '未命名会话',
- sessionId: item.session_id,
- messages: [],
- attachedFiles: [],
- updatedAt: item.updated_at,
- sortOrder: item.sort_order,
- }));
- // Build lookup maps for O(1) access
- const existingTaskMap = new Map(taskList.value.map((t) => [t.id, t]));
- const apiTaskIds = new Set(apiTasks.map((t) => t.id));
- // 流式中的空白任务:后端已为其创建会话,但前端要等流结束才拿到 session_id。
- // 该会话在接口里是一条全新记录,归并回空白任务而不是单独插入,避免列表出现重复条目
- let blankStreamingTask: Task | null = taskList.value.find((t) => !t.sessionId && t.isStreaming) || null;
- const mergedTasks: Task[] = [];
- for (const apiTask of apiTasks) {
- if (blankStreamingTask && (blankStreamingTask.pendingSessionId === apiTask.id || !knownApiSessionIds.has(apiTask.id))) {
- blankStreamingTask.pendingSessionId = apiTask.id;
- blankStreamingTask.name = apiTask.name;
- blankStreamingTask.updatedAt = apiTask.updatedAt;
- blankStreamingTask.sortOrder = apiTask.sortOrder;
- blankStreamingTask = null;
- continue;
- }
- const existing = existingTaskMap.get(apiTask.id);
- if (existing) {
- // 原地更新以保持对象引用,避免流式回调持有的任务引用失效(isStreaming 等状态丢失)
- existing.name = apiTask.name;
- existing.updatedAt = apiTask.updatedAt;
- existing.sortOrder = apiTask.sortOrder;
- mergedTasks.push(existing);
- } else {
- mergedTasks.push(apiTask);
- }
- }
- apiTasks.forEach((apiTask) => knownApiSessionIds.add(apiTask.id));
- const localOnlyTasks = taskList.value.filter((t) => !t.sessionId && !apiTaskIds.has(t.id));
- taskList.value = [...localOnlyTasks, ...mergedTasks];
- return mergedTasks;
- }
- } catch (error) {
- console.error('获取会话列表失败:', error);
- }
- return [];
- };
- const currentTaskId = ref('');
- const chatInputRef = ref<InstanceType<typeof ChatInputArea>>();
- const chatMessagesRef = ref<InstanceType<typeof ChatMessages>>();
- const showFileList = ref(false);
- const activePanel = ref<'chat' | 'skill' | 'sub-agents' | 'schedules'>('chat');
- const scheduleListForDetail = ref<any[]>([]);
- const fetchScheduleListForDetail = async () => {
- try {
- const res = await getScheduleList();
- scheduleListForDetail.value = res?.tasks || res?.data || (Array.isArray(res) ? res : []);
- } catch {
- scheduleListForDetail.value = [];
- }
- };
- const pendingFile = ref<AttachedFile | null>(null);
- const activeFileReader = ref<FileReader | null>(null);
- const messages = ref<Message[]>([]);
- const usageToday = ref<TodayUsage | null>(null);
- const fetchTodayUsage = async () => {
- try {
- const res = await getTodayUsage();
- if (res && typeof res === 'object') {
- usageToday.value = res;
- }
- } catch (e) {
- console.error('获取今日用量失败:', e);
- }
- };
- const contextUsed = ref(0);
- const contextMax = ref(1000000);
- const contextPercent = ref(0);
- const thinkLevel = ref('off');
- const editMode = ref('full');
- const contextBreakdown = ref({ messages: 0, mcp: 0, skills: 0, system_prompt: 0, other: 0 });
- const currentTodos = ref<Array<{ content: string; status: string }>>([]);
- const showTodoBar = ref(false);
- const syncTodoBarFromMessages = () => {
- for (let i = messages.value.length - 1; i >= 0; i--) {
- const msg = messages.value[i];
- if (msg.type === 'ai' && msg.thinkingSteps) {
- for (let j = msg.thinkingSteps.length - 1; j >= 0; j--) {
- const step = msg.thinkingSteps[j];
- if (step.type === 'updated_todo_list' && step.todos) {
- currentTodos.value = [...step.todos];
- showTodoBar.value = true;
- return;
- }
- }
- }
- }
- showTodoBar.value = false;
- currentTodos.value = [];
- };
- const panelCollapsed = ref(false);
- const togglePanel = () => {
- panelCollapsed.value = !panelCollapsed.value;
- };
- const toggleSidePanel = (panel: 'skill' | 'schedules' | 'sub-agents') => {
- if (activePanel.value === panel) {
- activePanel.value = 'chat';
- } else {
- activePanel.value = panel;
- }
- };
- // Keep backward-compatible aliases
- const toggleSkillPanel = () => toggleSidePanel('skill');
- const toggleSchedulePanel = () => toggleSidePanel('schedules');
- const toggleSubAgentPanel = () => toggleSidePanel('sub-agents');
- const handleOpenScheduleSession = async (sessionId: string, prompt?: string) => {
- activePanel.value = 'chat';
- await fetchSessionList();
- await fetchScheduleListForDetail();
- const existing = taskList.value.find((t) => t.sessionId === sessionId);
- if (existing) {
- await switchTask(existing.id);
- } else {
- const newTask: Task = {
- id: sessionId,
- name: '定时任务',
- sessionId,
- messages: [],
- attachedFiles: [],
- };
- taskList.value.unshift(newTask);
- historyLoadedTasks.delete(sessionId);
- await switchTask(newTask.id);
- }
- // 如果有 prompt,自动发送消息
- if (prompt) {
- inputMessage.value = prompt;
- await nextTick();
- await handleSendMessage();
- }
- };
- const schedulePanelRef = ref();
- const handleScheduleDeleted = () => {
- const task = currentTask.value;
- if (task?.rightPanels) {
- const tab = task.rightPanels.tabs.find((t) => t.type === 'schedule');
- if (tab) removeTab(task.rightPanels, tab.id);
- }
- fetchScheduleListForDetail();
- schedulePanelRef.value?.fetchScheduleList?.();
- };
- const handleScheduleUpdated = async () => {
- await fetchScheduleListForDetail();
- // 同步标签内任务对象为最新数据(编辑/启停后)
- const task = currentTask.value;
- const tab = task?.rightPanels?.tabs.find((t) => t.type === 'schedule');
- if (tab?.type === 'schedule') {
- const fresh = scheduleListForDetail.value.find((s: any) => s.id === tab.task.id);
- if (fresh) tab.task = fresh;
- }
- schedulePanelRef.value?.fetchScheduleList?.();
- };
- // 标题保存(由 ChatHeader 子组件触发,父组件负责 API 调用和状态更新)
- const handleSaveTitle = async (newTitle: string) => {
- if (!currentTask.value?.sessionId) return;
- try {
- await editSessionTitle(currentTask.value.sessionId, newTitle);
- currentTask.value.name = newTitle;
- message.success('标题修改成功');
- } catch {
- message.error('标题修改失败');
- }
- };
- const isFullscreen = ref(!!props.defaultFullscreen);
- // 响应式视口宽度,用于计算 modal 最大宽度不超过屏幕
- const viewportWidth = ref(window.innerWidth);
- const onResize = () => {
- viewportWidth.value = window.innerWidth;
- };
- window.addEventListener('resize', onResize);
- const currentTask = computed(() => taskList.value.find((t) => t.id === currentTaskId.value));
- const currentRightPanels = computed<RightPanelState>(() => {
- const task = currentTask.value;
- return task?.rightPanels || { tabs: [], activeTabId: null };
- });
- // 是否有右侧辅助面板(标签页容器)与 chat-panel 并列显示
- const hasRightPanel = computed(() => {
- if (activePanel.value !== 'chat') return false;
- return currentRightPanels.value.tabs.length > 0;
- });
- // 面板离开动画标记:确保 modal 在面板退出动画结束后才收缩宽度
- const isPanelLeaving = ref(false);
- const modalShouldExpand = computed(() => hasRightPanel.value || isPanelLeaving.value);
- // modal 宽度:全屏100vw / 有右侧面板时1600px(不超视口)/ 默认1400px
- const modalWidth = computed(() => {
- if (isFullscreen.value) return '100vw';
- if (modalShouldExpand.value) return Math.min(1600, viewportWidth.value);
- return 1400;
- });
- // 右侧面板离开动画结束后,允许 modal 宽度收缩
- const onPanelLeaveEnd = () => {
- isPanelLeaving.value = false;
- };
- // 监听右侧面板从有到无,标记正在离开状态,防止 modal 宽度提前收缩
- watch(hasRightPanel, (newVal, oldVal) => {
- if (oldVal && !newVal) {
- isPanelLeaving.value = true;
- }
- });
- // 全屏切换,附带缩放动画效果
- const toggleFullscreen = () => {
- const enteringFs = !isFullscreen.value;
- isFullscreen.value = enteringFs;
- nextTick(() => {
- // 给 modal-content 添加缩放动画类,动画结束后自动移除
- const content = document.querySelector<HTMLElement>('.ai-assistant-modal .zxm-modal-content');
- if (content) {
- const animClass = enteringFs ? 'modal-zoom-in-anim' : 'modal-zoom-out-anim';
- content.classList.remove('modal-zoom-in-anim', 'modal-zoom-out-anim');
- void content.offsetWidth; // 强制重排,确保动画重新触发
- content.classList.add(animClass);
- content.addEventListener('animationend', () => content.classList.remove(animClass), { once: true });
- }
- applyWrapStyles(isFullscreen.value);
- draggedEl = null;
- if (!isFullscreen.value) {
- centerModal();
- }
- });
- };
- const inputMessage = ref('');
- const selectedSessions = ref<Array<{ id: string; name: string }>>([]);
- const selectedSkill = ref<{ name: string; display_name: string } | null>(null);
- // 按任务维度的状态存储
- const taskPendingApprovals = ref<Map<string, { sessionId: string; threadId: string }>>(new Map());
- // loading 和 streaming 共享同一个计算属性,基于当前任务的 isStreaming 状态
- const loading = computed(() => {
- const currentTask = taskList.value.find((t) => t.id === currentTaskId.value);
- return currentTask?.isStreaming ?? false;
- });
- const streaming = loading;
- // 获取当前任务的待审批状态
- const currentPendingApproval = computed(() => {
- return taskPendingApprovals.value.get(currentTaskId.value);
- });
- // Non-reactive Map for AbortControllers - only used imperatively, no need for Vue reactivity
- const taskAbortControllers = new Map<string, AbortController>();
- // 设置任务的AbortController
- const setTaskAbortController = (taskId: string, controller: AbortController | null) => {
- if (controller) {
- taskAbortControllers.set(taskId, controller);
- } else {
- taskAbortControllers.delete(taskId);
- }
- };
- // 设置任务的审批状态
- const setTaskPendingApproval = (taskId: string, sessionId: string, threadId: string) => {
- const map = new Map(taskPendingApprovals.value);
- map.set(taskId, { sessionId, threadId });
- taskPendingApprovals.value = map;
- };
- // 清除任务的审批状态
- const clearTaskPendingApproval = (taskId: string) => {
- const map = new Map(taskPendingApprovals.value);
- map.delete(taskId);
- taskPendingApprovals.value = map;
- };
- // 停止指定任务的流式传输
- const stopTaskStreaming = (taskId: string) => {
- const controller = taskAbortControllers.get(taskId);
- controller?.abort();
- };
- const stopStreaming = () => {
- stopTaskStreaming(currentTaskId.value);
- };
- const getCurrentSessionId = (): string => {
- const currentTask = taskList.value.find((t) => t.id === currentTaskId.value);
- return currentTask?.sessionId || '';
- };
- // Non-reactive lookup cache - Vue 3 does not track Set mutations on ref<Set>
- const historyLoadedTasks = new Set<string>();
- const setCurrentSessionId = (sessionId: string) => {
- const currentTask = taskList.value.find((t) => t.id === currentTaskId.value);
- if (currentTask && currentTask.id !== sessionId) {
- taskList.value = taskList.value.filter((t) => t.id !== sessionId);
- currentTask.id = sessionId;
- currentTask.sessionId = sessionId;
- currentTaskId.value = sessionId;
- historyLoadedTasks.add(sessionId);
- }
- };
- const switchTask = async (taskId: string) => {
- activePanel.value = 'chat';
- const currentTask = taskList.value.find((t) => t.id === currentTaskId.value);
- if (currentTask) {
- currentTask.messages = [...messages.value];
- }
- currentTaskId.value = taskId;
- const newTask = taskList.value.find((t) => t.id === taskId);
- if (!newTask) return;
- inputMessage.value = '';
- pendingFile.value = null;
- showFileList.value = false;
- if (newTask.sessionId && !historyLoadedTasks.has(taskId)) {
- if (newTask.isStreaming) return; // 新任务正在流式中,无需加载历史
- try {
- const res = await getDetail(newTask.sessionId);
- const messages = res?.messages || (Array.isArray(res) ? res : res?.data);
- if (Array.isArray(messages)) {
- newTask.messages = transformHistoryToMessages(messages);
- }
- historyLoadedTasks.add(taskId);
- } catch (error) {
- console.error('加载历史会话失败:', error);
- }
- }
- if (newTask.sessionId) {
- fetchContext(newTask.sessionId);
- fetchSessionMode(newTask.sessionId);
- } else {
- contextUsed.value = 0;
- contextPercent.value = 0;
- contextBreakdown.value = { messages: 0, mcp: 0, skills: 0, system_prompt: 0, other: 0 };
- editMode.value = 'full';
- }
- messages.value = newTask.messages && newTask.messages.length > 0 ? [...newTask.messages] : getDefaultMessages();
- syncTodoBarFromMessages();
- // 切换任务时检测是否为定时任务会话:自动打开/关闭定时任务详情标签
- const scheduleItem = newTask.sessionId ? scheduleListForDetail.value.find((s: any) => s.feedback_session_id === newTask.sessionId) : undefined;
- const panelState = getPanelState(newTask);
- const existingScheduleTab = panelState.tabs.find((t) => t.type === 'schedule');
- if (scheduleItem) {
- if (existingScheduleTab) {
- panelState.activeTabId = existingScheduleTab.id;
- } else {
- panelState.tabs.push({ id: 'schedule', type: 'schedule', title: scheduleItem.name || '定时任务', task: scheduleItem });
- panelState.activeTabId = 'schedule';
- }
- } else if (existingScheduleTab) {
- removeTab(panelState, existingScheduleTab.id);
- }
- await nextTick();
- chatMessagesRef.value?.forceScrollToBottom();
- };
- const createNewTask = () => {
- const existingBlank = taskList.value.find((t) => !t.sessionId && t.messages.length === 0);
- if (existingBlank) {
- switchTask(existingBlank.id);
- return;
- }
- const newTask: Task = {
- id: `task-${Date.now()}`,
- name: '新任务',
- sessionId: '',
- messages: getDefaultMessages(),
- attachedFiles: [],
- };
- contextUsed.value = 0;
- contextPercent.value = 0;
- contextBreakdown.value = { messages: 0, mcp: 0, skills: 0, system_prompt: 0, other: 0 };
- editMode.value = 'full';
- taskList.value.unshift(newTask);
- switchTask(newTask.id);
- };
- const handlePinTask = async (task: Task) => {
- if (!task.sessionId) {
- message.warning('请先发送消息后再置顶');
- return;
- }
- try {
- await pinSession(task.sessionId);
- await fetchSessionList();
- } catch {
- message.error('置顶操作失败');
- }
- };
- const handleThinkLevelChange = async (levelKey: string) => {
- try {
- await switchThinking(levelKey);
- } catch {
- message.error('切换思考级别失败');
- }
- };
- const handleUpdateSelectedSessions = (sessions: Array<{ id: string; name: string }>) => {
- selectedSessions.value = sessions;
- };
- const handleUpdateSelectedSkill = (skill: { name: string; display_name: string } | null) => {
- selectedSkill.value = skill;
- };
- const getSkillRefIconUrl = () => {
- const val = getComputedStyle(document.documentElement).getPropertyValue('--img-chat-options-skill-icon').trim();
- return val.replace(/^url\(["']?/, '').replace(/["']?\)$/, '');
- };
- const getSessionRefIconUrl = () => {
- const val = getComputedStyle(document.documentElement).getPropertyValue('--img-chat-popup-session-icon').trim();
- return val.replace(/^url\(["']?/, '').replace(/["']?\)$/, '');
- };
- const handleEditModeChange = async (modeKey: string) => {
- editMode.value = modeKey;
- const sessionId = getCurrentSessionId();
- if (!sessionId) return;
- try {
- await putSessionMode(sessionId, modeKey);
- } catch {
- message.error('切换模式失败');
- }
- };
- const findPendingApprovalTask = (): { taskId: string; approval: { sessionId: string; threadId?: string } } | null => {
- // 优先用当前任务 ID 查找
- let approval = currentPendingApproval.value;
- if (approval) return { taskId: currentTaskId.value, approval };
- // 遍历所有审批(可能任务 ID 已变,用 sessionId 做回退匹配)
- for (const [taskId, a] of taskPendingApprovals.value.entries()) {
- return { taskId, approval: a };
- }
- return null;
- };
- const handleAskUserSubmit = async (answers: string[]) => {
- // 防重复提交:如果当前任务正在流式中,忽略
- const currentTask = taskList.value.find((t) => t.id === currentTaskId.value);
- if (currentTask?.isStreaming) return;
- const found = findPendingApprovalTask();
- // 优先从 taskPendingApprovals 获取,若被清除则从消息的 pendingApprovalData 回退
- let sessionId = found?.approval.sessionId;
- let threadId = found?.approval.threadId;
- const foundTaskId = found?.taskId;
- // 查找任务:优先用 foundTaskId,回退到 currentTaskId
- let task = foundTaskId ? taskList.value.find((t) => t.id === foundTaskId) : null;
- if (!task) task = taskList.value.find((t) => t.id === currentTaskId.value);
- if (!task) return;
- // 切换到目标任务(如果不在当前视图)
- if (task.id !== currentTaskId.value) {
- await switchTask(task.id);
- }
- // 使用正确的消息数组:当前视图用 messages.value,否则用 task.messages
- const isViewingTask = currentTaskId.value === task.id;
- const sourceArr = isViewingTask ? messages.value : task.messages;
- const lastMsg = sourceArr[sourceArr.length - 1];
- if (!lastMsg || !lastMsg.isPendingApproval) return;
- // 若 taskPendingApprovals 已被清除,从消息的 pendingApprovalData 回退取值
- if (!sessionId && lastMsg.pendingApprovalData) {
- sessionId = lastMsg.pendingApprovalData.sessionId;
- threadId = lastMsg.pendingApprovalData.threadId;
- }
- if (!sessionId) return;
- lastMsg.isPendingApproval = false;
- lastMsg.pendingApprovalData = undefined;
- lastMsg.isLoading = true;
- lastMsg.generateStartTime = Date.now();
- const aiMsgIndex = sourceArr.length - 1;
- // 强制触发 Vue 响应式更新
- if (isViewingTask) {
- messages.value = [...sourceArr];
- }
- task.messages = [...sourceArr];
- task.isStreaming = true;
- showTodoBar.value = false;
- currentTodos.value = [];
- const controller = new AbortController();
- setTaskAbortController(task.id, controller);
- try {
- const result = await chatResumeStream(
- {
- session_id: sessionId,
- thread_id: threadId || undefined,
- status: 'answered',
- answers,
- signal: controller.signal,
- },
- (data: SseEvent) => {
- parseSSEData(data, aiMsgIndex, task.id);
- if (currentTaskId.value === task.id) scrollToBottomThrottled();
- }
- );
- if (result.session_id) {
- setCurrentSessionId(result.session_id);
- }
- } catch (error) {
- if ((error as Error)?.name === 'AbortError') {
- lastMsg.isLoading = false;
- lastMsg.durationMs = (lastMsg.baseDurationMs || 0) + (lastMsg.generateStartTime ? Date.now() - lastMsg.generateStartTime : 0);
- if (!lastMsg.content) {
- lastMsg.content = '已停止生成。';
- }
- } else {
- console.error('提交答案失败:', error);
- const isStreamError = error instanceof StreamError;
- message.error(isStreamError ? error.message : '提交失败,请重试');
- if (isStreamError) fetchTodayUsage();
- lastMsg.isLoading = false;
- lastMsg.durationMs = (lastMsg.baseDurationMs || 0) + (lastMsg.generateStartTime ? Date.now() - lastMsg.generateStartTime : 0);
- if (!lastMsg.content) {
- lastMsg.content = isStreamError ? error.message : '抱歉,提交请求失败,请稍后重试。';
- }
- }
- } finally {
- setTaskAbortController(task.id, null);
- task.isStreaming = false;
- // 仅当消息不再处于审批状态时才清除(避免 resume 流返回新 interrupt 被误清)
- if (!lastMsg.isPendingApproval) {
- clearTaskPendingApproval(task.id);
- }
- if (currentTaskId.value === task.id) {
- await scrollToBottom();
- }
- }
- };
- const handleAskUserCancel = async () => {
- // 防重复操作:如果当前任务正在流式中,忽略
- const currentTask = taskList.value.find((t) => t.id === currentTaskId.value);
- if (currentTask?.isStreaming) return;
- const found = findPendingApprovalTask();
- // 优先从 taskPendingApprovals 获取,若被清除则从消息的 pendingApprovalData 回退
- let sessionId = found?.approval.sessionId;
- let threadId = found?.approval.threadId;
- const foundTaskId = found?.taskId;
- // 查找任务:优先用 foundTaskId,回退到 currentTaskId
- let task = foundTaskId ? taskList.value.find((t) => t.id === foundTaskId) : null;
- if (!task) task = taskList.value.find((t) => t.id === currentTaskId.value);
- if (!task) return;
- // 切换到目标任务(如果不在当前视图)
- if (task.id !== currentTaskId.value) {
- await switchTask(task.id);
- }
- // 使用正确的消息数组
- const isViewingTask = currentTaskId.value === task.id;
- const sourceArr = isViewingTask ? messages.value : task.messages;
- const lastMsg = sourceArr[sourceArr.length - 1];
- if (!lastMsg || !lastMsg.isPendingApproval) return;
- // 若 taskPendingApprovals 已被清除,从消息的 pendingApprovalData 回退取值
- if (!sessionId && lastMsg.pendingApprovalData) {
- sessionId = lastMsg.pendingApprovalData.sessionId;
- threadId = lastMsg.pendingApprovalData.threadId;
- }
- if (!sessionId) return;
- // 冻结累计耗时到 durationMs,避免取消后计时消失
- lastMsg.durationMs = (lastMsg.baseDurationMs || 0) + (lastMsg.generateStartTime ? Date.now() - lastMsg.generateStartTime : 0);
- lastMsg.isPendingApproval = false;
- lastMsg.pendingApprovalData = undefined;
- lastMsg.isLoading = false;
- lastMsg.content = (lastMsg.content ? lastMsg.content + '\n\n' : '') + '已取消提问。';
- task.messages = [...sourceArr];
- if (isViewingTask) {
- messages.value = task.messages;
- }
- clearTaskPendingApproval(task.id);
- try {
- await chatResumeStream(
- {
- session_id: sessionId,
- thread_id: threadId || undefined,
- status: 'cancelled',
- },
- () => {}
- );
- } catch (error) {
- console.error('取消操作失败:', error);
- }
- task.isStreaming = false;
- if (currentTaskId.value === task.id) {
- messages.value = task.messages;
- await scrollToBottom();
- }
- };
- const handleDeleteTask = (task: Task, _index: number) => {
- Modal.confirm({
- title: '提示',
- content: '是否删除该对话?',
- okText: '确认',
- cancelText: '取消',
- wrapClassName: 'delete-task-confirm-modal',
- onOk: async () => {
- try {
- if (task.sessionId) {
- await deleteSession(task.sessionId);
- }
- const realIndex = taskList.value.findIndex((t) => t.id === task.id);
- if (realIndex !== -1) {
- taskList.value.splice(realIndex, 1);
- }
- if (currentTaskId.value === task.id) {
- if (taskList.value.length > 0) {
- switchTask(taskList.value[0].id);
- } else {
- messages.value = [];
- currentTaskId.value = '';
- }
- }
- message.success('删除成功');
- } catch {
- message.error('删除失败');
- }
- },
- });
- };
- const getDefaultMessages = (): Message[] => {
- return [];
- };
- const normalizeLineBreaks = (str: string): string => {
- if (!str) return '';
- return str.replace(/\\n/g, '\n').replace(/\r\n/g, '\n');
- };
- const transformHistoryToMessages = (
- data: Array<{
- role?: string;
- type?: string;
- content: string;
- created_at?: string;
- report_url?: string;
- report_filename?: string;
- citations?: any;
- }>
- ): Message[] => {
- const messages: Message[] = [];
- for (const item of data) {
- const normalizedContent = normalizeLineBreaks(item.content);
- const time = item.created_at ? dayjs(item.created_at).format('HH:mm') : '';
- const createdAt = item.created_at || '';
- // 新格式:role 字段 (user/assistant)
- if (item.role === 'user') {
- messages.push({ type: 'user', content: normalizedContent, time, createdAt });
- } else if (item.role === 'assistant') {
- const msg: Message = { type: 'ai', content: normalizedContent, time, createdAt };
- if (item.report_url && item.report_filename) {
- msg.downloadFiles = [{ url: item.report_url, filename: item.report_filename }];
- }
- if (item.citations) {
- // 历史接口返回 citations 为扁平数组,SSE 事件返回 { items, model_only },统一归一化
- const raw = item.citations;
- if (Array.isArray(raw)) {
- msg.citations = { items: raw, model_only: raw.length === 0 };
- } else {
- msg.citations = raw;
- }
- }
- messages.push(msg);
- }
- // 兼容旧格式:type 字段
- else if (item.type === 'user_message') {
- messages.push({ type: 'user', content: normalizedContent, time, createdAt });
- } else if (item.type === 'model_thinking') {
- const lastAiMsg = messages[messages.length - 1];
- if (lastAiMsg && lastAiMsg.type === 'ai') {
- lastAiMsg.content += normalizedContent;
- lastAiMsg.content = lastAiMsg.content.replace(/\|\|\|SPLIT_CONTENT\|\|\|/g, '');
- } else {
- messages.push({ type: 'ai', content: normalizedContent, time, createdAt });
- }
- }
- }
- return messages;
- };
- const triggerFileUpload = () => {
- chatInputRef.value?.fileInputRef?.click();
- };
- const handleFileUpload = async (event: Event) => {
- const target = event.target as HTMLInputElement;
- const file = target.files?.[0];
- if (!file) return;
- if (isVideoFile(file.name) || isAudioFile(file.name)) {
- message.warning('不支持上传音频和视频文件');
- target.value = '';
- return;
- }
- try {
- const newFile: AttachedFile = {
- id: `file-${Date.now()}`,
- name: file.name,
- size: file.size,
- type: file.type,
- uploadTime: dayjs().format('YYYY-MM-DD HH:mm'),
- originalFile: file,
- };
- // Abort previous FileReader if still in progress
- if (activeFileReader.value) {
- activeFileReader.value.abort();
- activeFileReader.value = null;
- }
- const reader = new FileReader();
- activeFileReader.value = reader;
- reader.onload = (e) => {
- activeFileReader.value = null;
- if (isTextFile(file.name) || isCsvFile(file.name)) {
- newFile.content = e.target?.result as string;
- } else if (isWordFile(file.name) || isExcelFile(file.name)) {
- newFile.arrayBuffer = e.target?.result as ArrayBuffer;
- } else {
- newFile.preview = e.target?.result as string;
- }
- };
- if (isTextFile(file.name) || isCsvFile(file.name)) {
- reader.readAsText(file);
- } else if (isWordFile(file.name) || isExcelFile(file.name)) {
- reader.readAsArrayBuffer(file);
- } else {
- reader.readAsDataURL(file);
- }
- pendingFile.value = newFile;
- message.success(`文件 "${file.name}" 已添加,点击发送按钮提交`);
- } catch (error) {
- console.error('文件处理失败:', error);
- message.error('文件处理失败,请重试');
- }
- target.value = '';
- };
- const removePendingFile = () => {
- pendingFile.value = null;
- };
- const openFileTab = (file: AttachedFile, editable: boolean) => {
- const task = currentTask.value;
- if (!task) return;
- const state = getPanelState(task);
- const existing = state.tabs.find((t) => t.type === 'file' && t.file.id === file.id);
- if (existing) {
- // 编辑入口可升级已有标签为可编辑;预览入口不降级
- if (editable) existing.editable = true;
- state.activeTabId = existing.id;
- return;
- }
- openTab({ id: nextTabId(), type: 'file', title: file.name, file, editable });
- };
- const handleAgentDetailClick = (data: AgentDetailData) => {
- const task = currentTask.value;
- if (!task) return;
- const state = getPanelState(task);
- const existing = state.tabs.find(
- (t) => t.type === 'agent' && t.messageIndex === data.messageIndex && (t.agentId || '') === (data.agentId || '') && t.agent === data.agent
- );
- if (existing) {
- if (state.activeTabId === existing.id) {
- // 保持原交互:再次点击已激活的 agent 则关闭
- removeTab(state, existing.id);
- } else {
- state.activeTabId = existing.id;
- }
- return;
- }
- openTab({
- id: nextTabId(),
- type: 'agent',
- title: data.agent,
- messageIndex: data.messageIndex,
- agent: data.agent,
- agentId: data.agentId,
- });
- };
- // 在右侧面板新建标签页展示 Markdown 代码块渲染效果(相同内容复用同一标签)
- const openMarkdownPreviewTab = (payload: { title: string; content: string }) => {
- let hash = 0;
- for (let i = 0; i < payload.content.length; i++) {
- hash = (hash * 31 + payload.content.charCodeAt(i)) | 0;
- }
- openFileTab(
- {
- id: `md-preview-${hash}`,
- name: `${payload.title}.md`,
- size: payload.content.length,
- type: 'text/markdown',
- content: payload.content,
- uploadTime: '',
- },
- false
- );
- };
- const openFilePreview = (file: AttachedFile) => {
- openFileTab(file, false);
- const msgIndex = messages.value.findIndex((m) => m.attachedFile?.id === file.id);
- if (msgIndex !== -1) {
- nextTick(() => {
- const messageElements = chatMessagesRef.value?.messagesRef?.querySelectorAll('.message-wrapper');
- if (messageElements && messageElements[msgIndex]) {
- (messageElements[msgIndex] as HTMLElement).scrollIntoView({
- behavior: 'smooth',
- block: 'center',
- });
- }
- });
- }
- };
- const getCurrentTaskFiles = (): AttachedFile[] => {
- const currentTask = taskList.value.find((t) => t.id === currentTaskId.value);
- return currentTask?.attachedFiles || [];
- };
- // 右侧辅助面板标签页状态(按任务维度保存,切换任务自动恢复)
- let tabSeq = 0;
- const nextTabId = () => `panel-${Date.now()}-${tabSeq++}`;
- const getPanelState = (task: Task): RightPanelState => {
- if (!task.rightPanels) {
- task.rightPanels = { tabs: [], activeTabId: null };
- }
- return task.rightPanels;
- };
- const openTab = (tab: RightPanelTab) => {
- const task = currentTask.value;
- if (!task) return;
- const state = getPanelState(task);
- state.tabs.push(tab);
- state.activeTabId = tab.id;
- };
- const activateTab = (tabId: string) => {
- const task = currentTask.value;
- if (!task?.rightPanels) return;
- if (task.rightPanels.tabs.some((t) => t.id === tabId)) {
- task.rightPanels.activeTabId = tabId;
- }
- };
- const removeTab = (state: RightPanelState, tabId: string) => {
- const idx = state.tabs.findIndex((t) => t.id === tabId);
- if (idx === -1) return;
- state.tabs.splice(idx, 1);
- if (state.activeTabId === tabId) {
- state.activeTabId = state.tabs.length ? (state.tabs[idx] || state.tabs[idx - 1]).id : null;
- }
- };
- const closeTab = (tabId: string) => {
- const task = currentTask.value;
- if (!task?.rightPanels) return;
- removeTab(task.rightPanels, tabId);
- };
- const currentWordUrl = computed(() => {
- return currentTask.value?.wordUrl || '';
- });
- const currentTaskIndex = computed(() => taskList.value.findIndex((t) => t.id === currentTaskId.value));
- const canGoPrev = computed(() => currentTaskIndex.value > 0);
- const canGoNext = computed(() => currentTaskIndex.value >= 0 && currentTaskIndex.value < taskList.value.length - 1);
- const goToPrev = () => {
- if (!canGoPrev.value) return;
- const prevTask = taskList.value[currentTaskIndex.value - 1];
- if (prevTask) switchTask(prevTask.id);
- };
- const goToNext = () => {
- if (!canGoNext.value) return;
- const nextTask = taskList.value[currentTaskIndex.value + 1];
- if (nextTask) switchTask(nextTask.id);
- };
- const downloadWordFile = (url: string) => {
- if (!url) return;
- const a = document.createElement('a');
- a.href = url;
- a.download = '';
- a.target = '_blank';
- document.body.appendChild(a);
- a.click();
- document.body.removeChild(a);
- };
- const downloadWordReport = () => downloadWordFile(currentWordUrl.value);
- const handleOpenFilePreview = (file: AttachedFile) => {
- openFileTab(file, true);
- };
- const handleSaveSuccess = (content: string) => {
- const task = currentTask.value;
- const tab = task?.rightPanels?.tabs.find((t) => t.id === task.rightPanels?.activeTabId);
- if (tab?.type === 'file') {
- tab.file = { ...tab.file, content };
- }
- };
- const handleSendMessage = async () => {
- const hasText = inputMessage.value.trim();
- const hasFile = pendingFile.value;
- if (!hasText) {
- message.warning('请输入消息内容');
- return;
- }
- if (loading.value) return;
- if (currentPendingApproval.value) {
- message.warning('请先审批执行计划');
- return;
- }
- const sessionPrefix = selectedSessions.value.length > 0 ? selectedSessions.value.map((s) => `#session:${s.id}`).join(' ') + ' ' : '';
- const skillPrefix = selectedSkill.value ? `#skill:${selectedSkill.value.name} ` : '';
- const userInput = skillPrefix + sessionPrefix + inputMessage.value.trim();
- let displayContent = inputMessage.value.trim();
- if (selectedSkill.value) {
- const skillIconUrl = getSkillRefIconUrl();
- displayContent = `[<img src="${skillIconUrl}" class="session-ref-icon" /> 技能:${selectedSkill.value.display_name}] ${displayContent}`;
- }
- if (selectedSessions.value.length > 0) {
- const names = selectedSessions.value.map((s) => s.name).join('、');
- const iconUrl = getSessionRefIconUrl();
- displayContent = `[<img src="${iconUrl}" class="session-ref-icon" /> 引用 ${selectedSessions.value.length} 个会话:${names}] ${displayContent}`;
- }
- const fileToSend = pendingFile.value;
- inputMessage.value = '';
- pendingFile.value = null;
- selectedSessions.value = [];
- selectedSkill.value = null;
- try {
- await nextTick();
- chatMessagesRef.value?.forceScrollToBottom();
- if (hasFile) {
- await sendWithAttachment(fileToSend!, userInput, displayContent);
- } else {
- await sendTextOnly(userInput, displayContent);
- }
- } catch (error) {
- console.error('发送消息失败:', error);
- const isStreamError = error instanceof StreamError;
- const errText = isStreamError ? error.message : '发送失败,请重试';
- message.error(errText);
- if (isStreamError) fetchTodayUsage();
- const lastMsg = messages.value[messages.value.length - 1];
- if (lastMsg && lastMsg.type === 'ai' && lastMsg.isLoading) {
- messages.value.pop();
- }
- const errorMsg: Message = {
- type: 'ai',
- content: isStreamError ? error.message : '抱歉,请求失败,请稍后重试。',
- time: dayjs().format('HH:mm'),
- };
- messages.value.push(errorMsg);
- const currentTask = taskList.value.find((t) => t.id === currentTaskId.value);
- if (currentTask) {
- currentTask.messages = [...messages.value];
- }
- } finally {
- await scrollToBottom(true);
- }
- };
- const extractAgentName = (toolName: string): string => {
- const nameMap: Record<string, string> = {
- form_review: '形式审查',
- verify_coal_face_ventilation: '采煤工作面需风量计算核验',
- verify_tunneling_face_ventilation: '掘进工作面需风量计算核验',
- verify_chamber_ventilation: '硐室需风量计算核验',
- verify_other_points_ventilation: '其他地点需风量计算核验',
- check_data_by_gas_report: '瓦斯数据一致性审查',
- check_data_by_face_design: '设计规程一致性审查',
- check_data_by_vent_report: '测风报表一致性审查',
- check_current_month_plan: '日期有效性审查',
- get_key_translate: '计算参数对照',
- calculate_ventilation: '需风量计算',
- get_ventilation_data: '需风量查询',
- recalculate_ventilation: '需风量重计算',
- get_plan_required_wind: '需风量提取',
- get_model_calculated_wind: '三维模型解算风量提取',
- get_sensor_wind: '巷道监测风量提取',
- merge_wind_by_location: '地点风量智能合并',
- check_wind_compliance: '风量检查',
- };
- return nameMap[toolName] || nameMap[toolName.toLowerCase()] || '智能分析助手';
- };
- // 累积所有步骤,保留完整历史
- const upsertStep = (steps: any[], step: any) => {
- steps.push(step);
- };
- const fetchModelMsg = async () => {
- try {
- const res = await getModelMsg();
- if (res?.thinking_level) {
- thinkLevel.value = res.thinking_level;
- }
- } catch (e) {
- console.error('获取模型信息失败:', e);
- }
- };
- const fetchSessionMode = async (sessionId: string) => {
- try {
- const res = await getSessionMode(sessionId);
- if (res?.mode) {
- editMode.value = res.mode;
- }
- } catch (e) {
- console.error('获取会话模式失败:', e);
- }
- };
- const fetchContext = async (sessionId: string) => {
- try {
- const res = await getContext(sessionId);
- contextUsed.value = res?.current_usage ?? 0;
- contextMax.value = res?.total_limit ?? 0;
- contextPercent.value = res?.usage_pct ?? 0;
- contextBreakdown.value = res?.breakdown ?? { messages: 0, mcp: 0, skills: 0, system_prompt: 0, other: 0 };
- } catch (e) {
- console.error('获取上下文容量失败:', e);
- contextUsed.value = 0;
- contextMax.value = 0;
- contextPercent.value = 0;
- contextBreakdown.value = { messages: 0, mcp: 0, skills: 0, system_prompt: 0, other: 0 };
- }
- };
- const handleSSEMessage = (data: any, aiMsgIndex: number, taskId: string) => {
- const streamingTask = taskList.value.find((t) => t.id === taskId);
- if (!streamingTask) return;
- // 当前正在查看流式任务时,新消息被 push 到 messages.value 而非 task.messages
- // 所以需要从 messages.value 读取;否则从任务存储的 messages 读取
- const isViewingTask = currentTaskId.value === taskId;
- const sourceArr = isViewingTask ? messages.value : streamingTask.messages;
- const aiMsg = sourceArr[aiMsgIndex];
- if (!aiMsg) return;
- const normalizedContent = normalizeLineBreaks(data.content || '');
- // 初始化 thinkingSteps 数组
- if (!aiMsg.thinkingSteps) {
- aiMsg.thinkingSteps = [];
- }
- switch (data.type) {
- // token 流式内容 - 直接拼接到消息内容
- case 'token':
- if (normalizedContent) {
- if (data.source === 'subagent' && data.agent_id) {
- // subagent 的输出内容归属到对应的 agent step
- const targetStep = aiMsg.thinkingSteps!.findLast((s) => s.type === 'agent_start' && s.agentId === data.agent_id);
- if (targetStep) {
- targetStep.content = (targetStep.content || '') + normalizedContent;
- }
- } else {
- // main 模型输出,保持原有逻辑
- aiMsg.content += normalizedContent;
- }
- }
- break;
- // thinking / thinking_token - 模型思考过程内容
- case 'thinking':
- case 'thinking_token':
- if (normalizedContent) {
- if (data.source === 'subagent' && data.agent_id) {
- // subagent 的思考内容归属到对应的 agent step
- const targetStep = aiMsg.thinkingSteps!.findLast((s) => s.type === 'agent_start' && s.agentId === data.agent_id);
- if (targetStep) {
- targetStep.thinkingContent = (targetStep.thinkingContent || '') + normalizedContent;
- }
- } else {
- // main 模型思考,保持原有逻辑
- aiMsg.thinkingContent = (aiMsg.thinkingContent || '') + normalizedContent;
- }
- }
- break;
- // 系统进度消息 - 仅当 agent 不是 system 时才作为 thinking step
- case 'progress': {
- if (data.agent && data.agent !== 'system') {
- upsertStep(aiMsg.thinkingSteps!, {
- type: 'executing',
- agent: data.cn_agent || data.agent,
- agentId: data.agent_id,
- message: data.message || '',
- timestamp: Date.now(),
- });
- }
- break;
- }
- // agent 开始处理
- case 'agent_start': {
- upsertStep(aiMsg.thinkingSteps!, {
- type: 'agent_start',
- agent: data.cn_agent || data.agent || '智能助手',
- agentId: data.agent_id,
- subagentType: data.subagent_type,
- message: data.message || '开始处理...',
- timestamp: Date.now(),
- });
- break;
- }
- // agent 任务列表更新(同一 agent 的 todos 更新已有条目,不重复添加)
- case 'agent_todos':
- case 'updated_todo_list': {
- const agentName = data.cn_agent || data.agent || '智能助手';
- const agentId = data.agent_id;
- const existingIdx = aiMsg.thinkingSteps!.findIndex(
- (s) => s.type === 'updated_todo_list' && (agentId ? s.agentId === agentId : s.agent === agentName)
- );
- if (existingIdx !== -1) {
- aiMsg.thinkingSteps![existingIdx].todos = data.todos || [];
- aiMsg.thinkingSteps![existingIdx].timestamp = Date.now();
- } else {
- aiMsg.thinkingSteps!.push({
- type: 'updated_todo_list',
- agent: agentName,
- agentId,
- todos: data.todos || [],
- message: data.message || '任务进度已更新',
- timestamp: Date.now(),
- });
- }
- // todos 与任务绑定:仅当用户正在查看该任务时才更新进度条,避免流式期间切换/新建任务后串台
- if (isViewingTask) {
- currentTodos.value = [...(data.todos || [])];
- showTodoBar.value = true;
- }
- break;
- }
- // agent 执行中(工具调用)
- case 'agent_executing':
- case 'executing': {
- upsertStep(aiMsg.thinkingSteps!, {
- type: 'executing',
- agent: data.cn_agent || data.agent || '智能助手',
- agentId: data.agent_id,
- tool: (data.cn_tools || data.tools || []).join('、'),
- message: data.message || '',
- timestamp: Date.now(),
- });
- break;
- }
- // 工具结果
- case 'agent_tool_result':
- case 'tool_result': {
- upsertStep(aiMsg.thinkingSteps!, {
- type: 'tool_result',
- agent: data.cn_agent || data.agent || '智能助手',
- agentId: data.agent_id,
- tool: data.cn_tool || data.tool || '',
- message: data.message || '执行完成',
- timestamp: Date.now(),
- });
- if (data.download_url) {
- if (!aiMsg.downloadFiles) aiMsg.downloadFiles = [];
- aiMsg.downloadFiles.push({ url: data.download_url, filename: data.filename || '文件' });
- }
- break;
- }
- // agent 完成
- case 'agent_done': {
- upsertStep(aiMsg.thinkingSteps!, {
- type: 'agent_done',
- agent: data.cn_agent || data.agent || '智能助手',
- agentId: data.agent_id,
- message: `${(data.message || '审查完成').replace(/(\d+ms)/g, '')}${data.duration_ms ? `(${(data.duration_ms / 1000).toFixed(0)}s)` : ''}${data.progress ? ` [${data.progress}]` : ''}`,
- timestamp: Date.now(),
- });
- // 累加后端返回的各段耗时,并重置前端计时起点,避免重复计算已验证的时间段
- if (data.duration_ms) {
- aiMsg.baseDurationMs = (aiMsg.baseDurationMs || 0) + data.duration_ms;
- aiMsg.generateStartTime = Date.now();
- }
- if (data.preview) {
- aiMsg.content += data.preview;
- }
- break;
- }
- // 旧格式兼容
- case 'model_thinking':
- if (normalizedContent) {
- aiMsg.content += normalizedContent;
- aiMsg.content = aiMsg.content.replace(/\|\|\|SPLIT_CONTENT\|\|\|/g, '');
- }
- break;
- case 'tool_select': {
- upsertStep(aiMsg.thinkingSteps!, {
- type: 'tool_call',
- agent: data.cn_agent || extractAgentName(normalizedContent),
- agentId: data.agent_id,
- tool: normalizedContent,
- message: `选择工具:${normalizedContent}`,
- timestamp: Date.now(),
- });
- break;
- }
- case 'error':
- upsertStep(aiMsg.thinkingSteps!, {
- type: 'tool_result',
- agent: data.cn_agent || '系统',
- agentId: data.agent_id,
- message: `❌ 执行失败:${normalizedContent}`,
- timestamp: Date.now(),
- });
- aiMsg.isLoading = false;
- streamingTask.isStreaming = false;
- // 后端未返回耗时,冻结前端伪计时
- aiMsg.durationMs = (aiMsg.baseDurationMs || 0) + (aiMsg.generateStartTime ? Date.now() - aiMsg.generateStartTime : 0);
- break;
- case 'citations': {
- aiMsg.citations = {
- items: data.items || [],
- model_only: data.model_only || false,
- message: data.message,
- };
- break;
- }
- case 'word_download':
- if (normalizedContent) {
- aiMsg.wordDownloadUrl = normalizedContent;
- streamingTask.wordUrl = normalizedContent;
- }
- break;
- case 'done':
- if (data.session_id) {
- aiMsg.sessionId = data.session_id;
- fetchContext(data.session_id);
- }
- // 对话结束后刷新今日用量
- fetchTodayUsage();
- aiMsg.durationMs = data.duration_ms
- ? (aiMsg.baseDurationMs || 0) + data.duration_ms
- : (aiMsg.baseDurationMs || 0) + (aiMsg.generateStartTime ? Date.now() - aiMsg.generateStartTime : 0);
- aiMsg.isLoading = false;
- streamingTask.isStreaming = false;
- break;
- case 'system':
- if (normalizedContent) {
- aiMsg.content += normalizedContent.replace(/\n/g, ' \n');
- }
- break;
- case 'interrupt': {
- // 后端各段耗时 + 前端当前段计时,吸收进 baseDurationMs 保证审批继续后计时连续
- const elapsedMs = (aiMsg.baseDurationMs || 0) + (aiMsg.generateStartTime ? Date.now() - aiMsg.generateStartTime : 0);
- aiMsg.baseDurationMs = elapsedMs;
- aiMsg.isLoading = false;
- // 流已结束,等待用户回答;提交答案后 handleAskUserSubmit 会重新置为流式中
- streamingTask.isStreaming = false;
- aiMsg.isPendingApproval = true;
- const interruptSessionId = data.session_id || streamingTask.sessionId;
- aiMsg.pendingApprovalData = {
- message: data.message || '智能体需要您回答一些问题以继续...',
- sessionId: interruptSessionId,
- threadId: data.thread_id,
- interrupts: data.interrupts,
- elapsedMs,
- prevThinkingContent: aiMsg.thinkingContent,
- plan: data.plan,
- ask_user: data.ask_user,
- answers: data.ask_user?.questions?.map(() => '') || [],
- };
- setTaskPendingApproval(taskId, interruptSessionId, data.thread_id || '');
- // 直接初始化 ask_user 答案状态,不依赖 watch(避免任务切换/时序问题)
- if (data.ask_user?.questions) {
- nextTick(() => {
- chatMessagesRef.value?.initAskUserAnswers(aiMsgIndex, data.ask_user!.questions);
- });
- }
- break;
- }
- }
- // 保存到流式任务的 messages,并同步 UI
- // Always create a new array reference to trigger Vue reactivity
- const updatedMessages = isViewingTask ? [...messages.value] : [...streamingTask.messages];
- streamingTask.messages = updatedMessages;
- if (isViewingTask) {
- messages.value = updatedMessages;
- }
- };
- const parseSSEData = (data: SseEvent, aiMsgIndex: number, taskId: string) => {
- handleSSEMessage(data, aiMsgIndex, taskId);
- };
- const sendTextOnly = async (userInput: string, displayContent?: string) => {
- const originTaskId = currentTaskId.value;
- const now = dayjs();
- const userMsg: Message = {
- type: 'user',
- content: displayContent || userInput,
- time: now.format('HH:mm'),
- createdAt: now.toISOString(),
- };
- messages.value.push(userMsg);
- await nextTick();
- chatMessagesRef.value?.forceScrollToBottom();
- const aiMsgIndex = messages.value.length;
- const aiMsg: Message = {
- type: 'ai',
- content: '',
- time: now.format('HH:mm'),
- createdAt: now.toISOString(),
- isLoading: true,
- thinkingSteps: [],
- generateStartTime: Date.now(),
- };
- messages.value.push(aiMsg);
- showTodoBar.value = false;
- currentTodos.value = [];
- const originTask = taskList.value.find((t) => t.id === originTaskId);
- if (originTask) originTask.isStreaming = true;
- const controller = new AbortController();
- setTaskAbortController(originTaskId, controller);
- try {
- const result = await unifiedStream(
- {
- message: userInput,
- session_id: getCurrentSessionId() || undefined,
- mode: editMode.value,
- signal: controller.signal,
- },
- (data: SseEvent) => {
- parseSSEData(data, aiMsgIndex, originTaskId);
- if (currentTaskId.value === originTaskId) scrollToBottomThrottled();
- }
- );
- if (result.session_id) {
- const originTask = taskList.value.find((t) => t.id === originTaskId);
- if (originTask && !originTask.sessionId) {
- originTask.sessionId = result.session_id;
- // 流式期间若列表已用后端标题归并过该任务,则保留后端标题;否则用首条消息命名
- if (originTask.pendingSessionId !== result.session_id) {
- originTask.name = userInput.substring(0, 20) + (userInput.length > 20 ? '...' : '');
- }
- originTask.pendingSessionId = undefined;
- if (originTask.id !== result.session_id) {
- // 将 AbortController 从旧 ID 迁移到新 ID
- const controller = taskAbortControllers.get(originTaskId);
- if (controller) {
- setTaskAbortController(originTaskId, null);
- setTaskAbortController(result.session_id, controller);
- }
- taskList.value = taskList.value.filter((t) => t.id !== result.session_id);
- originTask.id = result.session_id;
- historyLoadedTasks.add(result.session_id);
- // 迁移审批状态 key(任务 ID 变了,审批 Map 的 key 也要跟着变)
- const approvalEntry = taskPendingApprovals.value.get(originTaskId);
- if (approvalEntry) {
- const map = new Map(taskPendingApprovals.value);
- map.delete(originTaskId);
- map.set(result.session_id, approvalEntry);
- taskPendingApprovals.value = map;
- }
- }
- if (currentTaskId.value === originTaskId) {
- currentTaskId.value = result.session_id;
- }
- }
- }
- } catch (error) {
- // 用户主动停止生成
- if ((error as Error)?.name === 'AbortError') {
- const originTask = taskList.value.find((t) => t.id === originTaskId);
- const arr = currentTaskId.value === originTaskId ? messages.value : originTask?.messages;
- const aiMsg = arr?.[aiMsgIndex];
- if (aiMsg) {
- aiMsg.isLoading = false;
- // 后端未返回耗时,冻结前端伪计时
- aiMsg.durationMs = (aiMsg.baseDurationMs || 0) + (aiMsg.generateStartTime ? Date.now() - aiMsg.generateStartTime : 0);
- if (!aiMsg.content) {
- aiMsg.content = '已停止生成。';
- }
- }
- if (originTask && currentTaskId.value !== originTaskId) {
- originTask.messages = [...(arr || [])];
- }
- return;
- }
- throw error;
- } finally {
- // 任务在流结束时可能已被改名为后端 session_id,需要使用最终的 ID 清理状态
- const finalTaskId = originTask?.id || originTaskId;
- setTaskAbortController(finalTaskId, null);
- if (originTask) originTask.isStreaming = false;
- }
- };
- const sendWithAttachment = async (file: AttachedFile, userInput: string, displayContent?: string) => {
- const originTaskId = currentTaskId.value;
- let currentTask = taskList.value.find((t) => t.id === originTaskId);
- if (currentTask) {
- currentTask.attachedFiles.push(file);
- } else {
- throw new Error('未找到当前任务');
- }
- const now = dayjs();
- const userMsg: Message = {
- type: 'user',
- content: displayContent || userInput || `上传了文件:${file.name}`,
- time: now.format('HH:mm'),
- createdAt: now.toISOString(),
- attachedFile: file,
- };
- messages.value.push(userMsg);
- await nextTick();
- chatMessagesRef.value?.forceScrollToBottom();
- const aiMsgIndex = messages.value.length;
- const aiMsg: Message = {
- type: 'ai',
- content: '',
- time: now.format('HH:mm'),
- createdAt: now.toISOString(),
- isLoading: true,
- thinkingSteps: [],
- generateStartTime: Date.now(),
- };
- messages.value.push(aiMsg);
- showTodoBar.value = false;
- currentTodos.value = [];
- if (!file.originalFile) {
- throw new Error('缺少原始文件对象');
- }
- const originTask = taskList.value.find((t) => t.id === originTaskId);
- if (originTask) originTask.isStreaming = true;
- const controller = new AbortController();
- setTaskAbortController(originTaskId, controller);
- try {
- const result = await reviewPdfStream(
- {
- file: file.originalFile!,
- session_id: getCurrentSessionId() || undefined,
- message: userInput || undefined,
- mode: editMode.value,
- signal: controller.signal,
- },
- (data: SseEvent) => {
- parseSSEData(data, aiMsgIndex, originTaskId);
- if (currentTaskId.value === originTaskId) scrollToBottomThrottled();
- }
- );
- if (result.session_id) {
- const originTask = taskList.value.find((t) => t.id === originTaskId);
- if (originTask && !originTask.sessionId) {
- originTask.sessionId = result.session_id;
- if (originTask.pendingSessionId !== result.session_id) {
- const taskName = userInput || `文件:${file.name}`;
- originTask.name = taskName.substring(0, 20) + (taskName.length > 20 ? '...' : '');
- }
- originTask.pendingSessionId = undefined;
- if (originTask.id !== result.session_id) {
- // 将 AbortController 从旧 ID 迁移到新 ID
- const controller = taskAbortControllers.get(originTaskId);
- if (controller) {
- setTaskAbortController(originTaskId, null);
- setTaskAbortController(result.session_id, controller);
- }
- taskList.value = taskList.value.filter((t) => t.id !== result.session_id);
- originTask.id = result.session_id;
- historyLoadedTasks.add(result.session_id);
- // 迁移审批状态 key
- const approvalEntry = taskPendingApprovals.value.get(originTaskId);
- if (approvalEntry) {
- const map = new Map(taskPendingApprovals.value);
- map.delete(originTaskId);
- map.set(result.session_id, approvalEntry);
- taskPendingApprovals.value = map;
- }
- }
- if (currentTaskId.value === originTaskId) {
- currentTaskId.value = result.session_id;
- }
- }
- }
- } catch (error) {
- // 用户主动停止生成
- if ((error as Error)?.name === 'AbortError') {
- const originTask = taskList.value.find((t) => t.id === originTaskId);
- const arr = currentTaskId.value === originTaskId ? messages.value : originTask?.messages;
- const aiMsg = arr?.[aiMsgIndex];
- if (aiMsg) {
- aiMsg.isLoading = false;
- // 后端未返回耗时,冻结前端伪计时
- aiMsg.durationMs = (aiMsg.baseDurationMs || 0) + (aiMsg.generateStartTime ? Date.now() - aiMsg.generateStartTime : 0);
- if (!aiMsg.content) {
- aiMsg.content = '已停止生成。';
- }
- }
- if (originTask && currentTaskId.value !== originTaskId) {
- originTask.messages = [...(arr || [])];
- }
- return;
- }
- throw error;
- } finally {
- // 任务在流结束时可能已被改名为后端 session_id,需要使用最终的 ID 清理状态
- const finalTaskId = originTask?.id || originTaskId;
- setTaskAbortController(finalTaskId, null);
- if (originTask) originTask.isStreaming = false;
- }
- };
- // Throttled version for SSE streaming (no await, uses rAF)
- let scrollRafId: number | null = null;
- const scrollToBottomThrottled = (force = false) => {
- if (scrollRafId) cancelAnimationFrame(scrollRafId);
- scrollRafId = requestAnimationFrame(async () => {
- scrollRafId = null;
- await nextTick();
- if (!force && !chatMessagesRef.value?.isAtBottom) return;
- const el = chatMessagesRef.value?.messagesRef;
- if (el) {
- el.scrollTop = el.scrollHeight - el.clientHeight;
- }
- });
- };
- // Async version for explicit await calls
- const scrollToBottom = async (force = false) => {
- await nextTick();
- if (!force && !chatMessagesRef.value?.isAtBottom) return;
- const el = chatMessagesRef.value?.messagesRef;
- if (el) {
- el.scrollTop = el.scrollHeight - el.clientHeight;
- }
- };
- watch(
- () => props.visible,
- async (newVisible) => {
- if (!newVisible) {
- const currentTask = taskList.value.find((t) => t.id === currentTaskId.value);
- if (currentTask) {
- currentTask.messages = [...messages.value];
- }
- } else {
- await fetchSessionList();
- fetchModelMsg();
- fetchScheduleListForDetail();
- fetchTodayUsage();
- // 去除重复的空白任务,只保留一个
- taskList.value = taskList.value.filter((task, index) => {
- if (task.sessionId) return true;
- return index === taskList.value.findIndex((t) => !t.sessionId);
- });
- // 优先回到关闭前所在的任务(如流式中的新任务),否则默认选中第一条历史记录
- const firstHistoryTask = taskList.value.find((t) => t.sessionId);
- const prevTask = taskList.value.find((t) => t.id === currentTaskId.value);
- let targetTask: Task;
- if (prevTask) {
- targetTask = prevTask;
- } else if (firstHistoryTask) {
- targetTask = firstHistoryTask;
- } else {
- // 没有历史记录时才创建空白新任务
- targetTask = {
- id: `task-${Date.now()}`,
- name: '新任务',
- sessionId: '',
- messages: getDefaultMessages(),
- attachedFiles: [],
- };
- taskList.value.unshift(targetTask);
- }
- currentTaskId.value = targetTask.id;
- // 如果是历史任务,加载其消息
- if (targetTask.sessionId && !historyLoadedTasks.has(targetTask.id)) {
- try {
- const res = await getDetail(targetTask.sessionId);
- const messages = res?.messages || (Array.isArray(res) ? res : res?.data);
- if (Array.isArray(messages)) {
- targetTask.messages = transformHistoryToMessages(messages);
- }
- historyLoadedTasks.add(targetTask.id);
- } catch (error) {
- console.error('加载历史会话失败:', error);
- }
- }
- if (targetTask.sessionId) {
- fetchContext(targetTask.sessionId);
- fetchSessionMode(targetTask.sessionId);
- } else {
- contextUsed.value = 0;
- contextPercent.value = 0;
- contextBreakdown.value = { messages: 0, mcp: 0, skills: 0, system_prompt: 0, other: 0 };
- editMode.value = 'full';
- }
- messages.value = targetTask.messages && targetTask.messages.length > 0 ? [...targetTask.messages] : getDefaultMessages();
- syncTodoBarFromMessages();
- pendingFile.value = null;
- showFileList.value = false;
- inputMessage.value = '';
- await nextTick(() => {
- chatMessagesRef.value?.forceScrollToBottom();
- });
- }
- }
- );
- // 拖拽相关(使用普通变量避免 mousemove 触发 Vue 响应式导致卡顿)
- let isDragging = false;
- let dragStartX = 0;
- let dragStartY = 0;
- let modalStartLeft = 0;
- let modalStartTop = 0;
- let draggedEl: HTMLElement | null = null;
- const findModalWrap = (target: HTMLElement): HTMLElement | null =>
- target.closest<HTMLElement>('.zxm-modal-wrap, .ant-modal-wrap, [class*="modal-wrap"]');
- const queryModalWrap = (): HTMLElement | null => document.querySelector<HTMLElement>('.zxm-modal-wrap, .ant-modal-wrap, [class*="modal-wrap"]');
- // 统一处理 modal-wrap 内联样式:全屏时置顶铺满,否则恢复默认
- const applyWrapStyles = (fullscreen: boolean) => {
- const wraps = document.querySelectorAll<HTMLElement>('.zxm-modal-wrap, .ant-modal-wrap, [class*="modal-wrap"]');
- wraps.forEach((wrap) => {
- wrap.style.position = '';
- wrap.style.left = '';
- wrap.style.top = fullscreen ? '0' : '';
- wrap.style.right = '';
- wrap.style.bottom = '';
- wrap.style.width = '';
- wrap.style.height = '';
- wrap.style.margin = fullscreen ? '0' : '';
- wrap.style.padding = fullscreen ? '0' : '';
- wrap.style.transform = '';
- });
- };
- const centerModal = () => {
- nextTick(() => {
- applyWrapStyles(isFullscreen.value);
- draggedEl = null;
- });
- };
- const onDragStart = (e: MouseEvent) => {
- if (isFullscreen.value) return;
- draggedEl = findModalWrap(e.target as HTMLElement) || queryModalWrap();
- if (!draggedEl) return;
- isDragging = true;
- dragStartX = e.clientX;
- dragStartY = e.clientY;
- const rect = draggedEl.getBoundingClientRect();
- modalStartLeft = rect.left;
- modalStartTop = rect.top;
- draggedEl.style.position = 'fixed';
- draggedEl.style.left = `${rect.left}px`;
- draggedEl.style.top = `${rect.top}px`;
- draggedEl.style.margin = '0';
- draggedEl.style.transform = 'none';
- document.addEventListener('mousemove', onDragMove);
- document.addEventListener('mouseup', onDragEnd);
- };
- const onDragMove = (e: MouseEvent) => {
- if (!isDragging || !draggedEl) return;
- draggedEl.style.left = `${modalStartLeft + (e.clientX - dragStartX)}px`;
- draggedEl.style.top = `${modalStartTop + (e.clientY - dragStartY)}px`;
- };
- const onDragEnd = () => {
- isDragging = false;
- document.removeEventListener('mousemove', onDragMove);
- document.removeEventListener('mouseup', onDragEnd);
- };
- watch(
- () => props.visible,
- (newVisible) => {
- if (newVisible) {
- centerModal();
- }
- }
- );
- onBeforeUnmount(() => {
- document.removeEventListener('mousemove', onDragMove);
- document.removeEventListener('mouseup', onDragEnd);
- window.removeEventListener('resize', onResize);
- // 组件卸载时主动断开所有任务的流式连接
- taskAbortControllers.forEach((controller) => controller.abort());
- // Abort in-flight FileReader if any
- if (activeFileReader.value) {
- activeFileReader.value.abort();
- activeFileReader.value = null;
- }
- });
- </script>
- <style scoped lang="less">
- .ai-container {
- display: flex;
- height: 700px;
- gap: 10px;
- overflow: hidden;
- font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, 'Helvetica Neue', Arial, sans-serif;
- }
- .collapse-btn {
- position: absolute;
- top: 16px;
- left: 24px;
- z-index: 10;
- width: 32px;
- height: 32px;
- background: #1a6696;
- border-radius: 4px;
- display: flex;
- align-items: center;
- justify-content: center;
- cursor: pointer;
- transition: background 0.3s;
- &:hover {
- background: #1f7ab8;
- }
- .collapse-icon {
- width: 16px;
- height: 16px;
- background-image: var(--img-chat-collapse-icon);
- background-repeat: no-repeat;
- background-size: 100% 100%;
- &.collapsed {
- background-image: var(--img-chat-expand-icon);
- }
- }
- }
- .task-panel-wrapper {
- width: 300px;
- flex-shrink: 0;
- overflow: hidden;
- transition:
- width 0.35s cubic-bezier(0.4, 0, 0.2, 1),
- margin 0.35s cubic-bezier(0.4, 0, 0.2, 1),
- opacity 0.25s ease;
- &.collapsed {
- width: 0;
- margin: 0;
- opacity: 0;
- }
- }
- .chat-panel {
- flex: 1;
- display: flex;
- position: relative;
- flex-direction: column;
- background-image: var(--img-chat-panel-bg);
- background-repeat: no-repeat;
- background-size: 100% 100%;
- border-radius: 4px;
- overflow: hidden;
- min-width: 0;
- }
- .right-panel {
- width: calc(50% - 140px);
- height: 100%;
- display: flex;
- flex-direction: column;
- background-image: var(--img-chat-panel-bg);
- background-repeat: no-repeat;
- background-size: 100% 100%;
- border-radius: 4px;
- &.full {
- flex: 1;
- width: auto;
- min-width: 0;
- }
- flex-shrink: 0;
- }
- /* 右侧面板滑入滑出过渡动画 */
- :deep(.right-panel-slide-enter-active) {
- transition:
- opacity 0.3s ease,
- transform 0.3s ease;
- }
- :deep(.right-panel-slide-leave-active) {
- transition:
- opacity 0.25s ease,
- transform 0.25s ease;
- }
- :deep(.right-panel-slide-enter-from) {
- opacity: 0;
- transform: translateX(30px);
- }
- :deep(.right-panel-slide-leave-to) {
- opacity: 0;
- transform: translateX(30px);
- }
- .draggable-title {
- cursor: grab;
- user-select: none;
- &:active {
- cursor: grabbing;
- }
- &.no-drag {
- cursor: default;
- &:active {
- cursor: default;
- }
- }
- }
- </style>
- <style lang="less">
- .ai-assistant-modal {
- .zxm-modal-content {
- background-image: var(--img-chat-modal-bg);
- background-repeat: no-repeat;
- background-size: 100% 100%;
- background-color: unset !important;
- box-shadow: none;
- padding: 0;
- border: none !important;
- transition: width 0.3s ease;
- }
- /* 全屏切换缩放动画 */
- @keyframes modal-zoom-in {
- from {
- transform: scale(0.85);
- opacity: 0.6;
- }
- to {
- transform: scale(1);
- opacity: 1;
- }
- }
- @keyframes modal-zoom-out {
- from {
- transform: scale(1.15);
- opacity: 0.6;
- }
- to {
- transform: scale(1);
- opacity: 1;
- }
- }
- .zxm-modal-content.modal-zoom-in-anim {
- animation: modal-zoom-in 0.3s ease forwards;
- }
- .zxm-modal-content.modal-zoom-out-anim {
- animation: modal-zoom-out 0.3s ease forwards;
- }
- .zxm-modal-close {
- background-image: var(--img-chat-close-bg);
- background-repeat: no-repeat;
- background-size: 100% 100%;
- top: 12px;
- right: 20px;
- width: 38px;
- height: 38px;
- .zxm-modal-close-x {
- width: 38px;
- height: 38px;
- }
- svg {
- width: 26px;
- height: 26px;
- margin-bottom: 4px;
- }
- }
- .maximize-btn {
- position: absolute;
- top: 12px;
- right: 72px;
- width: 38px;
- height: 38px;
- background-image: var(--img-chat-close-bg);
- background-repeat: no-repeat;
- background-size: 100% 100%;
- display: flex;
- align-items: center;
- justify-content: center;
- cursor: pointer;
- z-index: 10;
- .maximize-icon {
- width: 22px;
- height: 22px;
- background-image: var(--img-chat-maximize-icon);
- background-repeat: no-repeat;
- background-size: 100% 100%;
- &.minimized {
- background-image: var(--img-chat-minimize-icon);
- }
- }
- }
- &.fullscreen {
- top: 0 !important;
- padding: 0 !important;
- max-width: 100vw !important;
- margin: 0 !important;
- background-color: #09172c;
- .zxm-modal-wrap,
- .ant-modal-wrap {
- padding: 0 !important;
- margin: 0 !important;
- top: 0 !important;
- }
- .zxm-modal-content {
- width: 100vw !important;
- height: 100vh !important;
- max-width: 100vw !important;
- margin: 0;
- border-radius: 0;
- overflow: hidden;
- background-image: var(--img-chat-fs-modal-bg);
- }
- .zxm-modal-header {
- height: 90px;
- background-image: var(--img-chat-fs-header-bg) !important;
- background-repeat: no-repeat;
- background-size: 100% 100%;
- margin-bottom: 16px;
- }
- .no-drag {
- cursor: default;
- font-size: 32px !important;
- }
- .zxm-modal-title {
- height: 90px;
- }
- .zxm-modal-body {
- height: calc(100vh - 120px);
- overflow: hidden;
- padding: 0 24px 12px;
- }
- .ai-container {
- height: 100%;
- overflow: hidden;
- }
- .chat-panel {
- background-image: var(--img-chat-fs-panel-bg) !important;
- }
- .chat-header {
- padding: 0 12px;
- height: 50px;
- }
- .collapse-btn {
- top: 60px;
- background-image: var(--img-chat-fs-collapse-btn-bg) !important;
- background-repeat: no-repeat;
- background-size: 100% 100%;
- }
- .task-list-panel {
- padding: 20px;
- background-image: var(--img-chat-fs-task-panel-bg) !important;
- background-repeat: no-repeat !important;
- background-size: 100% 100% !important;
- }
- .options-area {
- gap: 12px;
- }
- .options-area-item {
- background-image: var(--img-chat-fs-options-item-bg) !important;
- background-repeat: no-repeat !important;
- background-size: 100% 100% !important;
- &.active,
- &:active {
- background-image: var(--img-chat-fs-options-item-active-bg) !important;
- }
- .options-img {
- background-image: none !important;
- }
- }
- .chat-header-title {
- height: 40px;
- line-height: 40px;
- position: relative;
- background-image: var(--img-chat-fs-header-title-bg) !important;
- background-repeat: no-repeat !important;
- background-size: auto 100% !important;
- padding: 0 28px;
- &::before {
- content: '';
- position: absolute;
- left: 0;
- top: 50%;
- transform: translateY(-50%);
- width: 40px;
- height: 40px;
- background-image: var(--img-chat-fs-header-title-icon);
- background-repeat: no-repeat;
- background-size: 100% 100%;
- }
- }
- .chat-header-title-wrapper {
- .title-edit-input {
- height: 36px;
- font-size: 16px;
- background: rgba(10, 132, 255, 0.15);
- border-color: rgba(10, 132, 255, 0.6);
- }
- .title-edit-btn {
- width: 24px;
- height: 24px;
- background-size: 16px 16px;
- }
- }
- .chat-input-area {
- margin: 24px;
- }
- .right-panel {
- background-image: var(--img-chat-fs-panel-bg) !important;
- }
- :deep(.panel-tab-bar) {
- padding: 14px 16px 0;
- }
- .schedule-panel,
- .skill-panel,
- .sub-agent-panel {
- background-image: var(--img-chat-fs-panel-bg) !important;
- }
- }
- .zxm-modal-header {
- background-color: unset !important;
- background: unset;
- border: none !important;
- padding: 8px;
- backdrop-filter: unset;
- display: flex;
- justify-content: center;
- }
- .zxm-modal-title {
- width: 100%;
- height: 60px;
- display: flex;
- align-items: center;
- justify-content: center;
- .draggable-title {
- color: #fff;
- font-family: var(--vet-font-family);
- letter-spacing: 3px;
- font-size: 24px;
- font-weight: 100;
- line-height: 1.4;
- }
- }
- .zxm-modal-body {
- padding: 12px 24px;
- }
- }
- .delete-task-confirm-modal {
- .zxm-modal-confirm-title,
- .zxm-modal-confirm-content {
- color: #fff;
- }
- }
- </style>
|