| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466 |
- <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"
- @delete-message="handleDeleteMessage"
- />
- <!-- 任务进度条 -->
- <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,
- deleteMessage,
- 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<{
- id?: number;
- 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({ id: item.id, type: 'user', content: normalizedContent, time, createdAt });
- } else if (item.role === 'assistant') {
- const msg: Message = { id: item.id, 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({ id: item.id, 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,
- });
- };
- // 删除单条消息:先删数据库行,后端再清空该会话内存线程,下轮从数据库重建上下文
- const handleDeleteMessage = (msg: Message) => {
- if (!msg.id) return;
- Modal.confirm({
- title: '提示',
- content: '删除后该消息将不再进入模型上下文,是否继续?',
- okText: '确认',
- cancelText: '取消',
- wrapClassName: 'delete-task-confirm-modal',
- onOk: async () => {
- try {
- await deleteMessage(msg.id!);
- message.success('消息已删除');
- messages.value = messages.value.filter((m) => m !== msg);
- const task = currentTask.value;
- if (task) {
- task.messages = task.messages.filter((m) => m !== msg);
- }
- } catch {
- message.error('删除失败');
- }
- },
- });
- };
- // 在右侧面板新建标签页展示 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 !important;
- }
- }
- .delete-task-confirm-modal {
- .zxm-modal-confirm-title,
- .zxm-modal-confirm-content {
- color: #fff;
- }
- }
- </style>
|