zj-plugin-intelligent 1.2.5-beta.7 → 1.2.5-beta.8
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
|
@@ -939,7 +939,7 @@ eval("\n\nvar _interopRequireWildcard = __webpack_require__(/*! ./node_modules/_
|
|
|
939
939
|
/***/ (function(module, exports, __webpack_require__) {
|
|
940
940
|
|
|
941
941
|
"use strict";
|
|
942
|
-
eval("\n\nvar _interopRequireDefault = __webpack_require__(/*! ./node_modules/_@babel_runtime@7.28.4@@babel/runtime/helpers/interopRequireDefault.js */ \"./node_modules/_@babel_runtime@7.28.4@@babel/runtime/helpers/interopRequireDefault.js\").default;\nObject.defineProperty(exports, \"__esModule\", {\n value: true\n});\nexports.default = void 0;\n__webpack_require__(/*! core-js/modules/es.error.cause.js */ \"./node_modules/_core-js@3.45.1@core-js/modules/es.error.cause.js\");\n__webpack_require__(/*! core-js/modules/es.array.push.js */ \"./node_modules/_core-js@3.45.1@core-js/modules/es.array.push.js\");\n__webpack_require__(/*! core-js/modules/es.array-buffer.detached.js */ \"./node_modules/_core-js@3.45.1@core-js/modules/es.array-buffer.detached.js\");\n__webpack_require__(/*! core-js/modules/es.array-buffer.transfer.js */ \"./node_modules/_core-js@3.45.1@core-js/modules/es.array-buffer.transfer.js\");\n__webpack_require__(/*! core-js/modules/es.array-buffer.transfer-to-fixed-length.js */ \"./node_modules/_core-js@3.45.1@core-js/modules/es.array-buffer.transfer-to-fixed-length.js\");\n__webpack_require__(/*! core-js/modules/es.iterator.constructor.js */ \"./node_modules/_core-js@3.45.1@core-js/modules/es.iterator.constructor.js\");\n__webpack_require__(/*! core-js/modules/es.iterator.filter.js */ \"./node_modules/_core-js@3.45.1@core-js/modules/es.iterator.filter.js\");\n__webpack_require__(/*! core-js/modules/es.iterator.find.js */ \"./node_modules/_core-js@3.45.1@core-js/modules/es.iterator.find.js\");\n__webpack_require__(/*! core-js/modules/es.iterator.for-each.js */ \"./node_modules/_core-js@3.45.1@core-js/modules/es.iterator.for-each.js\");\n__webpack_require__(/*! core-js/modules/es.iterator.map.js */ \"./node_modules/_core-js@3.45.1@core-js/modules/es.iterator.map.js\");\n__webpack_require__(/*! core-js/modules/es.typed-array.at.js */ \"./node_modules/_core-js@3.45.1@core-js/modules/es.typed-array.at.js\");\n__webpack_require__(/*! core-js/modules/es.typed-array.find-last.js */ \"./node_modules/_core-js@3.45.1@core-js/modules/es.typed-array.find-last.js\");\n__webpack_require__(/*! core-js/modules/es.typed-array.find-last-index.js */ \"./node_modules/_core-js@3.45.1@core-js/modules/es.typed-array.find-last-index.js\");\n__webpack_require__(/*! core-js/modules/es.typed-array.set.js */ \"./node_modules/_core-js@3.45.1@core-js/modules/es.typed-array.set.js\");\n__webpack_require__(/*! core-js/modules/es.typed-array.to-reversed.js */ \"./node_modules/_core-js@3.45.1@core-js/modules/es.typed-array.to-reversed.js\");\n__webpack_require__(/*! core-js/modules/es.typed-array.to-sorted.js */ \"./node_modules/_core-js@3.45.1@core-js/modules/es.typed-array.to-sorted.js\");\n__webpack_require__(/*! core-js/modules/es.typed-array.with.js */ \"./node_modules/_core-js@3.45.1@core-js/modules/es.typed-array.with.js\");\nvar _apichat = __webpack_require__(/*! @lib/api/apichat */ \"./src/lib/api/apichat.js\");\nvar _markdownIt = _interopRequireDefault(__webpack_require__(/*! markdown-it */ \"./node_modules/_markdown-it@14.1.0@markdown-it/index.mjs\"));\nvar _html2canvas = _interopRequireDefault(__webpack_require__(/*! html2canvas */ \"./node_modules/_html2canvas@1.4.1@html2canvas/dist/html2canvas.js\"));\nvar _index = __webpack_require__(/*! @lib/socket/fileManager/obs/index */ \"./src/lib/socket/fileManager/obs/index.js\");\nvar _index2 = _interopRequireDefault(__webpack_require__(/*! @lib/socket/utils/index */ \"./src/lib/socket/utils/index.js\"));\nvar _cookie = __webpack_require__(/*! @lib/utils/cookie.js */ \"./src/lib/utils/cookie.js\");\nvar _apiObs = _interopRequireDefault(__webpack_require__(/*! @lib/api/apiObs */ \"./src/lib/api/apiObs.js\"));\nconst md = new _markdownIt.default({\n breaks: true,\n html: false,\n linkify: true,\n typographer: true\n});\nmd.enable('table');\nvar _default = exports.default = {\n name: 'ChatMain',\n props: {\n Ak: {\n type: String,\n default: ''\n },\n Sk: {\n type: String,\n default: ''\n },\n imAccount: {\n type: String,\n default: ''\n },\n companyNo: {\n type: String,\n default: ''\n },\n isIntelShow: {\n default: false,\n type: Boolean\n },\n chatImToken: {\n default: '',\n type: String\n }\n },\n data() {\n return {\n agentList: [],\n currentAgent: '',\n currentAgentDesc: '',\n sessionsLoaded: false,\n searchKeyword: '',\n agentSuggestions: [],\n showAgentSuggestions: false,\n sessionList: [],\n activeSessionId: '',\n messages: [],\n loadingMore: false,\n sending: false,\n waitTimer: null,\n waitSeconds: 0,\n canceling: false,\n msgPage: 1,\n msgMaxPage: 1,\n msgTotal: 0,\n inputText: '',\n eventSource: null,\n showToolInfo: false,\n showDownBtn: false,\n // 控制向下箭头显隐\n lastScrollTop: 0,\n scrollTimer: null,\n // 滚动防抖(新增)\n showAgentSelect: true,\n isMobile: false,\n showSidebar: false,\n showH5List: false,\n // H5列表模式(展示会话列表而非聊天详情)\n _scrollTimer: null,\n agentInfo: {},\n contentCache: {},\n // 流式分行缓存 key=msg._key\n loadingSessionMsg: false,\n // 会话消息加载中标记\n greeting: '',\n longPressTimer: null,\n longPressed: false,\n // H5 语音输入\n voiceMode: false,\n // true=语音模式,false=文字模式\n isRecording: false,\n // 是否正在录音\n recordDuration: 0,\n // 录音时长(秒)\n recordingTimer: null,\n // 时长计时器\n audioContext: null,\n // AudioContext 实例\n audioStream: null,\n // MediaStream(用于清理)\n audioProcessor: null,\n // ScriptProcessorNode\n audioChunks: [],\n // Float32Array 数据块\n isCancelSwipe: false,\n // 是否上滑取消\n recordStartY: 0 // 触摸起始Y坐标\n };\n },\n created() {\n if (this.Ak || this.Sk) {\n (0, _apichat.setApiAuth)(this.Ak, this.Sk, this.imAccount, this.companyNo, this.chatImToken);\n }\n this.loadAgents();\n this.loadSessions();\n },\n mounted() {\n this.updateViewportState();\n window.addEventListener('resize', this.updateViewportState, {\n passive: true\n });\n },\n computed: {\n waitClass() {\n if (this.waitSeconds > 15) return 'wait-15';\n if (this.waitSeconds > 10) return 'wait-10';\n if (this.waitSeconds > 5) return 'wait-5';\n return '';\n },\n filteredSessions() {\n if (!this.searchKeyword) return this.sessionList;\n const kw = this.searchKeyword.toLowerCase();\n return this.sessionList.filter(s => {\n const name = (s.agentName || s.agentCode || '').toLowerCase();\n return name.includes(kw);\n });\n },\n currentAgentName() {\n if (!this.currentAgent) return '';\n const a = this.agentList.find(x => x.agentCode === this.currentAgent);\n return a ? a.agentName || a.agentCode : this.currentAgent;\n }\n },\n watch: {\n searchKeyword(val) {\n if (this.searchTimer) clearTimeout(this.searchTimer);\n if (!val.trim()) {\n this.agentSuggestions = [];\n this.showAgentSuggestions = false;\n this.closeSidebar();\n return;\n }\n this.searchTimer = setTimeout(() => {\n (0, _apichat.getChatAgents)(val.trim()).then(list => {\n this.agentSuggestions = list || [];\n this.showAgentSuggestions = this.agentSuggestions.length > 0;\n }).catch(() => {\n this.agentSuggestions = [];\n });\n }, 300);\n }\n // ak: {\n // handler(newVal) {\n // setApiAuth(newVal, this.sk)\n // },\n // immediate: true\n // },\n // sk: {\n // handler(newVal) {\n // setApiAuth(this.ak, newVal)\n // },\n // immediate: true\n // }\n },\n methods: {\n updateViewportState() {\n if (typeof window === 'undefined') return;\n const nextIsMobile = window.innerWidth <= 768;\n const wasMobile = this.isMobile;\n this.isMobile = nextIsMobile;\n if (!nextIsMobile) {\n this.showSidebar = false;\n this.showH5List = false;\n } else if (!wasMobile && nextIsMobile) {\n // 从桌面端切换到H5:如果加载了会话列表且无活跃会话,展示列表页\n if (this.sessionList.length > 0 && !this.activeSessionId) {\n this.showH5List = true;\n this.showAgentSelect = false;\n }\n }\n },\n toggleSidebar() {\n if (!this.isMobile) return;\n this.showSidebar = !this.showSidebar;\n },\n closeSidebar() {\n this.showSidebar = false;\n },\n // H5:调用原生返回上一级\n handleNativeBack() {\n if (this.$hybrid && typeof this.$hybrid.closePage === 'function') {\n this.$hybrid.closePage();\n } else if (window.history.length > 1) {\n window.history.back();\n }\n },\n // H5侧边栏返回按钮\n handleSidebarBack() {\n this.handleNativeBack();\n },\n agentjumpclick() {\n if (this.sending) {\n this.$message.warning('AI正在生成内容,暂时请不要切换对话');\n return;\n }\n this.currentAgent = '';\n this.currentAgentDesc = '';\n this.searchKeyword = '';\n this.activeSessionId = '';\n this.agentSuggestions = [];\n this.messages = [];\n this.showAgentSuggestions = false;\n this.showAgentSelect = true;\n this.showH5List = false;\n this.closeSidebar();\n },\n // H5:从详情页返回列表页\n goBackToList() {\n if (this.sending) {\n this.$message.warning('AI正在生成内容,暂时请不要切换对话');\n return;\n }\n // 关闭流连接\n if (this.eventSource) {\n this.eventSource.close();\n this.eventSource = null;\n }\n this.sending = false;\n this.clearWaitTimer();\n this.activeSessionId = '';\n this.messages = [];\n this.currentAgent = '';\n this.currentAgentDesc = '';\n this.agentInfo = {};\n this.contentCache = {};\n\n // 始终返回列表页\n this.showH5List = true;\n this.showAgentSelect = false;\n this.closeSidebar();\n },\n sendQuickMsg(message) {\n if (message) {\n this.inputText = message;\n this.sendMessage();\n }\n },\n formatMixText(str) {\n if (!str) return '';\n // 1. 中文 <=> 英文/数字 之间加空格\n let res = str.replace(/([a-zA-Z0-9])([\\u4e00-\\u9fff])/g, '$1 $2').replace(/([\\u4e00-\\u9fff])([a-zA-Z0-9])/g, '$1 $2');\n // 2. 连续英文单词分片粘连修复:字母紧跟字母中间加空格\n // 匹配 小写+大写 驼峰、连续分片拼接成一坨的英文\n res = res.replace(/([a-z])([A-Z])/g, '$1 $2');\n return res;\n },\n // 获取右侧头像样式(根据当前智能体在左侧列表中的位置决定颜色)\n getChatAvatarStyle(agent, avatar) {\n if (avatar) {\n return {\n backgroundImage: `url(${avatar})`,\n backgroundSize: 'cover',\n backgroundPosition: 'center',\n backgroundRepeat: 'no-repeat'\n };\n }\n const _agent = this.agentList.find(x => x.agentCode === agent);\n // 如果有网络图片,返回背景图样式\n if (agent.avatar) {\n return {\n backgroundImage: `url(${agent.avatar})`,\n backgroundSize: 'cover',\n backgroundPosition: 'center',\n backgroundRepeat: 'no-repeat'\n };\n }\n\n // 没有网络图片时,根据智能体在 agentList 中的索引位置决定颜色\n if (this.sessionList) {\n // 找到当前智能体在列表中的索引\n const index = this.sessionList.findIndex(item => item.agentCode === agent);\n if (index !== -1) {\n // 根据索引计算颜色类(4色循环)\n const colorIndex = index % 4 + 1;\n return {\n background: this.getGradientByColorIndex(colorIndex)\n };\n }\n }\n\n // 默认返回蓝色渐变\n return {\n background: 'linear-gradient(135deg, #1677ff, #4096ff)'\n };\n },\n // 根据颜色索引获取对应的渐变色\n getGradientByColorIndex(index) {\n const gradients = {\n 1: 'linear-gradient(135deg, #1677ff, #4096ff)',\n 2: 'linear-gradient(135deg, #52c41a, #73d13d)',\n 3: 'linear-gradient(135deg, #fa8c16, #ffa940)',\n 4: 'linear-gradient(135deg, #722ed1, #b37feb)'\n };\n return gradients[index] || gradients[1];\n },\n selectAgent(agentItem) {\n this.showAgentSelect = false;\n this.currentAgent = agentItem.agentCode;\n this.currentAgentName = agentItem.agentName;\n // 查找历史会话\n const existSession = this.sessionList.find(s => s.agentCode === agentItem.agentCode);\n if (existSession) {\n this.activeSessionId = existSession.id;\n this.switchSession(existSession);\n } else {\n this.createNewSession(agentItem.agentCode);\n }\n },\n createNewSession(agentCode) {\n // 你原有新建会话逻辑\n },\n // 检测是否滚动到底部,控制向下箭头显示隐藏\n checkScrollBottom(forceShowWhenNotBottom = false) {\n const el = this.$refs.messagesRef;\n if (!el) {\n this.showDownBtn = false;\n return;\n }\n const {\n scrollHeight,\n scrollTop,\n clientHeight\n } = el;\n const remain = scrollHeight - scrollTop - clientHeight;\n const atBottom = remain <= 80;\n if (atBottom) {\n this.showDownBtn = false;\n } else if (this.sending && scrollTop >= this.lastScrollTop && !forceShowWhenNotBottom) {\n // 发送AI回答时,如果用户没有主动向上滚动,就不要显示下箭头闪烁\n this.showDownBtn = false;\n } else {\n this.showDownBtn = true;\n }\n this.lastScrollTop = scrollTop;\n },\n // 固定最小高度:单行不撑开,超出才增高\n // H5 输入框获取焦点 - 滚动到可见区域(避免键盘遮挡)\n onInputFocus() {\n if (!this.isMobile) return;\n // 等待键盘弹出后再滚动\n setTimeout(() => {\n const footer = this.$el.querySelector('.chat-footer');\n if (footer) footer.scrollIntoView({\n behavior: 'smooth',\n block: 'end'\n });\n }, 350);\n },\n autoResizeTextarea() {\n const ta = this.$refs.taRef;\n if (!ta) return;\n // 根据端适配基准高度和最大高度\n const isMobile = this.isMobile;\n const baseH = isMobile ? 36 : 100;\n const maxH = isMobile ? 100 : 180;\n ta.style.height = `${baseH}px`;\n // 内容真实高度\n const realH = ta.scrollHeight;\n // 只有内容高度>基准才撑开,否则保持初始高度\n if (realH > baseH) {\n ta.style.height = `${Math.min(realH, maxH)}px`;\n }\n this.$nextTick(() => {\n this.checkScrollBottom(true);\n });\n },\n // Shift+Enter换行\n newLine(e) {\n // 取消浏览器默认行为\n e.preventDefault();\n // 拿到光标位置\n const ta = this.$refs.taRef;\n const start = ta.selectionStart;\n const end = ta.selectionEnd;\n // 在光标处插入换行符\n this.inputText = this.inputText.slice(0, start) + '\\n' + this.inputText.slice(end);\n // 光标定位到换行后\n this.$nextTick(() => {\n ta.selectionStart = ta.selectionEnd = start + 1;\n // 自动调整输入框高度\n this.autoResizeTextarea();\n });\n },\n toggleVoiceMode() {\n this.voiceMode = !this.voiceMode;\n if (!this.voiceMode) {\n // 切回文字模式时释放音频设备\n this.releaseAudio();\n }\n },\n // 确保音频设备已就绪(只请求一次权限,缓存 stream / AudioContext)\n async ensureAudioReady() {\n if (this.audioContext && this.audioStream) return true;\n if (!navigator.mediaDevices || !navigator.mediaDevices.getUserMedia) {\n alert('当前环境不支持麦克风访问');\n return false;\n }\n try {\n const stream = await navigator.mediaDevices.getUserMedia({\n audio: true\n });\n this.audioStream = stream;\n const audioContext = new (window.AudioContext || window.webkitAudioContext)({\n sampleRate: 16000\n });\n this.audioContext = audioContext;\n const source = audioContext.createMediaStreamSource(stream);\n const processor = audioContext.createScriptProcessor(4096, 1, 1);\n this.audioProcessor = processor;\n processor.onaudioprocess = e => {\n if (!this.isRecording) return;\n const inputData = e.inputBuffer.getChannelData(0);\n this.audioChunks.push(new Float32Array(inputData));\n };\n source.connect(processor);\n processor.connect(audioContext.destination);\n return true;\n } catch (err) {\n console.error('麦克风访问失败:', err);\n alert('麦克风权限被拒绝');\n return false;\n }\n },\n // H5语音录制 - 触摸开始\n async onRecordTouchStart(e) {\n if (this.sending) return;\n\n // 先确保音频已就绪(首次会请求权限并建立音频管线,后续复用)\n const ready = await this.ensureAudioReady();\n if (!ready) return;\n\n // 重置录音状态\n this.isCancelSwipe = false;\n this.recordStartY = e.touches[0].clientY;\n this.recordDuration = 0;\n this.audioChunks = [];\n\n // 音频就绪后才标记录制中并启动计时\n this.isRecording = true;\n this.recordingTimer = setInterval(() => {\n this.recordDuration++;\n if (this.recordDuration >= 60) {\n this.onRecordTouchEnd();\n }\n }, 1000);\n },\n // H5语音录制 - 触摸移动(检测上滑取消)\n onRecordTouchMove(e) {\n if (!this.isRecording) return;\n const touch = e.touches[0];\n const moveY = touch.clientY;\n const cancelThreshold = 60; // 上滑60px进入取消区域\n this.isCancelSwipe = this.recordStartY - moveY > cancelThreshold;\n },\n // H5语音录制 - 触摸结束\n onRecordTouchEnd() {\n if (!this.isRecording) return;\n this.isRecording = false;\n if (this.recordingTimer) {\n clearInterval(this.recordingTimer);\n this.recordingTimer = null;\n }\n this.stopAudioCapture(!this.isCancelSwipe);\n },\n // 停止音频采集并输出 WAV(保留音频设备,下次复用)\n stopAudioCapture(shouldSend) {\n this.isRecording = false;\n if (shouldSend && this.audioChunks.length > 0) {\n const wavBlob = this.encodePCMToWav(this.audioChunks, 16000);\n this.sendAudioBlob(wavBlob);\n }\n this.audioChunks = [];\n },\n // 取消录音(保留音频设备,下次复用)\n cancelRecording() {\n this.isRecording = false;\n if (this.recordingTimer) {\n clearInterval(this.recordingTimer);\n this.recordingTimer = null;\n }\n this.recordDuration = 0;\n this.isCancelSwipe = false;\n this.audioChunks = [];\n },\n // 释放音频资源(切换回文字模式或组件销毁时调用)\n releaseAudio() {\n this.cancelRecording();\n if (this.audioProcessor) {\n this.audioProcessor.disconnect();\n this.audioProcessor = null;\n }\n if (this.audioContext) {\n this.audioContext.close().catch(() => {});\n this.audioContext = null;\n }\n if (this.audioStream) {\n this.audioStream.getTracks().forEach(t => t.stop());\n this.audioStream = null;\n }\n },\n // 将 Float32 PCM 数据编码为 WAV Blob\n encodePCMToWav(chunks, sampleRate) {\n // 计算总采样数\n let totalLength = 0;\n for (const chunk of chunks) {\n totalLength += chunk.length;\n }\n\n // 转换为 Int16 PCM\n const pcmData = new Int16Array(totalLength);\n let offset = 0;\n for (const chunk of chunks) {\n for (let i = 0; i < chunk.length; i++) {\n const s = Math.max(-1, Math.min(1, chunk[i]));\n pcmData[offset++] = s < 0 ? s * 0x8000 : s * 0x7FFF;\n }\n }\n const numChannels = 1;\n const bitsPerSample = 16;\n const byteRate = sampleRate * numChannels * bitsPerSample / 8;\n const blockAlign = numChannels * bitsPerSample / 8;\n const dataSize = pcmData.length * (bitsPerSample / 8);\n const headerSize = 44;\n const totalSize = headerSize + dataSize;\n const buffer = new ArrayBuffer(totalSize);\n const view = new DataView(buffer);\n\n // RIFF header\n this._wavWriteString(view, 0, 'RIFF');\n view.setUint32(4, totalSize - 8, true);\n this._wavWriteString(view, 8, 'WAVE');\n\n // fmt chunk\n this._wavWriteString(view, 12, 'fmt ');\n view.setUint32(16, 16, true); // chunk size\n view.setUint16(20, 1, true); // PCM format\n view.setUint16(22, numChannels, true); // 单声道\n view.setUint32(24, sampleRate, true); // 采样率\n view.setUint32(28, byteRate, true);\n view.setUint16(32, blockAlign, true);\n view.setUint16(34, bitsPerSample, true);\n\n // data chunk\n this._wavWriteString(view, 36, 'data');\n view.setUint32(40, dataSize, true);\n\n // 写入 PCM 数据\n const pcmView = new Int16Array(buffer, headerSize, pcmData.length);\n pcmView.set(pcmData);\n return new Blob([buffer], {\n type: 'audio/wav'\n });\n },\n _wavWriteString(view, offset, str) {\n for (let i = 0; i < str.length; i++) {\n view.setUint8(offset + i, str.charCodeAt(i));\n }\n },\n // 发送音频\n sendAudioBlob(blob) {\n let appSeqId = _index2.default.getAppSeqId();\n let name = appSeqId + '.wav';\n const file = new File([blob], name, {\n type: 'audio/wav'\n });\n // TODO: 上传音频文件并调用 STT 接口\n this.sendAudioMessage(file);\n },\n sendAudioMessage(file) {\n // 插入本地 pending 消息\n const sttKey = 'stt_' + Date.now();\n const sttMsg = {\n role: 'user',\n content: '转化中...',\n _sttStatus: 'pending',\n _sttKey: sttKey,\n createTime: new Date().toISOString(),\n _key: sttKey\n };\n this.messages.push(sttMsg);\n this.scrollToBottom(true);\n (0, _index.fileUploadToObs)({\n _file: file,\n appSeqId: file.name\n }).then(resp => {\n if (resp.CommonMsg.Status === 200) {\n // 调用语音转文字接口\n return _apiObs.default.aliAudioToText({\n url: resp.obs_upload_data.obsUrl\n }).then(result => {\n if (result.code === '200' && result.data) {\n // 成功:删除 pending 消息,发送给后端\n const idx = this.messages.findIndex(m => m._sttKey === sttKey);\n if (idx !== -1) {\n this.messages.splice(idx, 1);\n }\n this.sendQuickMsg(result.data);\n } else {\n throw new Error(result.msg || '语音转文字失败');\n }\n });\n } else {\n throw new Error(resp.CommonMsg.Message || '文件上传失败');\n }\n }).catch(err => {\n console.error('语音转文字失败:', err);\n // 失败:更新为错误状态\n const idx = this.messages.findIndex(m => m._sttKey === sttKey);\n if (idx !== -1) {\n this.$set(this.messages, idx, {\n ...this.messages[idx],\n _sttStatus: 'error',\n content: '语音转文字失败'\n });\n }\n this.$message.error('语音转文字失败');\n });\n this.$message.success(`录音完成 (${this.recordDuration}s)`);\n },\n clearWaitTimer() {\n if (this.waitTimer) {\n clearInterval(this.waitTimer);\n this.waitTimer = null;\n }\n },\n loadAgents() {\n (0, _apichat.getChatAgents)().then(list => {\n this.agentList = list || [];\n // if (this.agentList.length > 0 && !this.currentAgent) {\n // const first = this.agentList[0]\n // this.currentAgent = first.agentCode\n // this.currentAgentDesc = first.description || ''\n // }\n }).catch(() => {});\n },\n loadSessions() {\n (0, _apichat.getSessionList)().then(list => {\n if (!this.activeSessionId) {\n this.sessionList = list || [];\n if (this.sessionList.length > 0) {\n if (this.isMobile) {\n // H5模式:不自动选中会话,展示列表页\n this.showAgentSelect = false;\n this.showH5List = true;\n this.showSidebar = false;\n } else {\n this.switchSession(this.sessionList[0]);\n }\n }\n if (this.sessionList.length === 0) {\n this.showAgentSelect = true;\n this.showH5List = false;\n }\n } else {\n this.sessionList = list || [];\n let _item = list.find(res => res.sessionId == this.activeSessionId);\n try {\n if (_item.suggestedQuestions) {\n _item.suggestedQuestions = JSON.parse(_item.suggestedQuestions);\n } else {\n _item.suggestedQuestions = [];\n }\n _item && (this.agentInfo = _item);\n } catch (err) {\n // JSON格式错误兜底空数组,防止页面报错\n this.agentInfo.questionArr = [];\n console.warn('快捷提问解析失败', err);\n }\n }\n }).catch(() => {});\n },\n onSearchClear() {\n this.agentSuggestions = [];\n this.showAgentSuggestions = false;\n },\n startChatWithAgent(agent) {\n console.log('选择了助手', agent.agentCode, this.currentAgent);\n if (agent.agentCode == this.currentAgent) {\n this.searchKeyword = '';\n this.agentSuggestions = [];\n this.showAgentSuggestions = false;\n return;\n }\n this.currentAgent = agent.agentCode;\n this.currentAgentDesc = agent.description || '';\n this.searchKeyword = '';\n this.agentInfo = {};\n this.agentSuggestions = [];\n this.messages = [];\n this.showAgentSuggestions = false;\n this.showAgentSelect = false;\n this.closeSidebar();\n if (this.isMobile) {\n this.showH5List = false; // H5:进入详情页,隐藏列表\n }\n const existing = this.sessionList.find(s => s.agentCode === agent.agentCode);\n if (existing) {\n this.switchSession(existing);\n } else {\n this.handleNewSession();\n }\n },\n handleNewSession() {\n if (!this.currentAgent) return;\n if (this.activeSessionId) this.closeOldSession();\n (0, _apichat.startSession)(this.currentAgent).then(res => {\n console.log(res, 'startChatWithAgentstartChatWithAgentstartChatWithAgent', this.agentInfo);\n this.activeSessionId = res.sessionId || '';\n this.loadSessions();\n const agent = this.agentList.find(a => a.agentCode === this.currentAgent);\n if (agent) this.addWelcomeMessage(agent);\n }).catch(() => {});\n },\n // H5长按删除 - 触摸开始\n onSessionTouchStart(s, e) {\n if (!this.isMobile) return;\n this.longPressed = false;\n this.longPressTimer = setTimeout(() => {\n this.longPressed = true;\n this.handleDeleteSession(s);\n }, 600);\n },\n // H5长按删除 - 触摸结束/移动(取消长按)\n onSessionTouchEnd() {\n if (this.longPressTimer) {\n clearTimeout(this.longPressTimer);\n this.longPressTimer = null;\n }\n },\n onSessionTouchMove() {\n if (this.longPressTimer) {\n clearTimeout(this.longPressTimer);\n this.longPressTimer = null;\n }\n },\n async switchSession(s) {\n if (this.longPressed) {\n this.longPressed = false;\n return;\n }\n if (this.sending) {\n this.$message.warning('AI正在生成内容,暂时请不要切换对话');\n return;\n }\n this.showAgentSelect = false;\n this.closeSidebar();\n if (this.isMobile) {\n this.showH5List = false; // H5:进入详情页,隐藏列表\n }\n if (this.activeSessionId === s.sessionId) return;\n this.contentCache = {};\n this.activeSessionId = s.sessionId;\n this.currentAgent = s.agentCode;\n console.log('进入');\n this.agentInfo = s;\n console.log('进入', this.agentInfo);\n try {\n if (s.suggestedQuestions) {\n this.agentInfo.suggestedQuestions = JSON.parse(s.suggestedQuestions);\n } else {\n this.agentInfo.suggestedQuestions = [];\n }\n } catch (err) {\n // JSON格式错误兜底空数组,防止页面报错\n this.agentInfo.questionArr = [];\n console.warn('快捷提问解析失败', err);\n }\n const agent = this.agentList.find(a => a.agentCode === s.agentCode);\n this.currentAgentDesc = agent ? agent.description || '' : '';\n this.msgPage = 1;\n this.msgTotal = 0;\n this.messages = []; // 先清空,但开启加载锁屏蔽空白页\n this.loadingSessionMsg = true; // 开启加载标记\n (0, _apichat.syncToken)((0, _cookie.getToken)(), s.sessionId);\n try {\n const res = await (0, _apichat.getSessionMessages)(s.sessionId, 1, 10);\n const list = Array.isArray(res) ? res : res.list || [];\n this.msgTotal = res.total || list.length;\n this.msgPage = 1;\n const asAsc = (list || []).slice().reverse();\n this.messages = asAsc.map(m => ({\n role: m.role,\n content: m.content || '',\n thinking: m.thinking || '',\n toolCalls: [],\n agentName: m.role === 'assistant' ? s.agentName || '' : '',\n createTime: m.createTime || null,\n _key: m.createTime ? 'msg_' + m.createTime : 'msg_' + Date.now() + '_' + Math.random()\n }));\n if (this.messages.length === 0 && agent) this.addWelcomeMessage(agent);\n await this.$nextTick();\n this.$nextTick(() => {\n this.scrollToBottomOnce();\n this.checkScrollBottom();\n });\n } catch (e) {\n this.messages = [];\n } finally {\n // 无论成功失败,结束后关闭加载锁\n this.loadingSessionMsg = false;\n }\n },\n loadMoreMessages() {\n const nextPage = this.msgPage + 1;\n const maxPage = Math.ceil(this.msgTotal / 10);\n if (nextPage > maxPage) {\n this.loadingMore = false;\n return;\n }\n (0, _apichat.getSessionMessages)(this.activeSessionId, nextPage, 10).then(res => {\n const list = Array.isArray(res) ? res : res.list || [];\n this.msgPage = nextPage;\n const asAsc = (list || []).slice().reverse();\n const prepend = asAsc.map(m => ({\n role: m.role,\n content: m.content || '',\n thinking: m.thinking || '',\n toolCalls: [],\n agentName: '',\n createTime: m.createTime || null,\n _key: m.createTime ? 'msg_' + m.createTime : 'msg_' + Date.now() + '_' + Math.random()\n }));\n const container = this.$refs.messagesRef;\n const oldScrollHeight = container ? container.scrollHeight : 0;\n const oldScrollTop = container ? container.scrollTop : 0;\n this.messages = [...prepend, ...this.messages];\n this.$nextTick(() => {\n if (container) {\n container.scrollTop = oldScrollTop + (container.scrollHeight - oldScrollHeight);\n }\n this.loadingMore = false;\n });\n }).catch(() => {\n this.loadingMore = false;\n });\n },\n onScrollMessages() {\n const container = this.$refs.messagesRef;\n if (!container || this.loadingMore) return;\n const isAtBottom = container.scrollTop + container.clientHeight >= container.scrollHeight - 100;\n this.checkScrollBottom();\n if (isAtBottom) return;\n if (container.scrollTop < 50 && this.msgPage < Math.ceil(this.msgTotal / 10)) {\n this.loadingMore = true;\n this.loadMoreMessages();\n }\n },\n handleDeleteSession(s) {\n this.$confirm(`确认删除「${s.agentName || s.agentCode}」的会话?`, '提示', {\n type: 'warning'\n }).then(() => {\n (0, _apichat.deleteSession)(s.sessionId).then(() => {\n if (this.activeSessionId === s.sessionId) {\n this.activeSessionId = '';\n this.messages = [];\n this.currentAgent = '';\n this.currentAgentDesc = '';\n if (this.isMobile) {\n this.showH5List = false;\n this.showAgentSelect = true;\n } else {\n this.showAgentSelect = true;\n }\n }\n this.loadSessions();\n });\n }).catch(() => {});\n },\n closeOldSession() {},\n onAgentChange(code) {\n const agent = this.agentList.find(a => a.agentCode === code);\n this.currentAgentDesc = agent ? agent.description || '' : '';\n this.handleNewSession();\n },\n addWelcomeMessage(agent) {\n this.greeting = '';\n // if (!agent) return\n // const name = agent.agentName || '助手';\n const _agent = this.agentList.find(x => x.agentCode === this.currentAgent);\n this.greeting = _agent.greeting || `很高兴为您服务,请问有什么可以帮到您?`;\n // this.messages.push({\n // role: 'assistant',\n // content: _content,\n // thinking: '',\n // agentName: name,\n // _key: 'welcome_' + Date.now()\n // })\n },\n async sendMessage() {\n const text = this.inputText.trim();\n if (!text || this.sending) return;\n if (!this.activeSessionId) {\n await (0, _apichat.startSession)(this.currentAgent).then(res => {\n this.activeSessionId = res.sessionId || '';\n this.loadSessions();\n });\n if (!this.activeSessionId) return;\n }\n this.inputText = '';\n const ta = this.$refs.taRef;\n const isMobile = this.isMobile;\n const baseH = isMobile ? 36 : 100;\n if (ta) {\n ta.style.height = baseH + 'px'; // 强制恢复初始高度\n }\n this.showDownBtn = false;\n this.messages.push({\n role: 'user',\n content: text,\n createTime: new Date().toISOString(),\n _key: 'user_' + Date.now() + '_' + Math.random()\n });\n const agentName = this.currentAgentName;\n const msgIdx = this.messages.push({\n role: \"assistant\",\n content: \"\",\n thinking: \"\",\n loading: true,\n toolCalls: [],\n agentName,\n createTime: new Date().toISOString(),\n _key: 'asst_' + Date.now() + '_' + Math.random()\n }) - 1;\n this.scrollToBottom(true);\n this.sending = true;\n this.waitSeconds = 0;\n if (this.waitTimer) clearInterval(this.waitTimer);\n this.waitTimer = setInterval(() => {\n this.waitSeconds++;\n }, 1000);\n let thinkingBuffer = '';\n let finalContent = '';\n let answerBuffer = '';\n let thinkDisplayed = 0;\n let typeTimer = null;\n typeTimer = setInterval(() => {\n if (!this.messages[msgIdx]) return;\n if (thinkDisplayed < thinkingBuffer.length) {\n thinkDisplayed += 50;\n if (thinkDisplayed > thinkingBuffer.length) thinkDisplayed = thinkingBuffer.length;\n this.messages[msgIdx].thinking = thinkingBuffer.substring(0, thinkDisplayed);\n this.scrollToBottom();\n } else if (finalContent && !this.messages[msgIdx].content) {\n clearInterval(typeTimer);\n const key = this.messages[msgIdx]._key;\n if (key) {\n this.$delete(this.contentCache, key);\n this.$delete(this.contentCache, key + '_t');\n }\n typeTimer = null;\n this.messages[msgIdx].content = finalContent;\n this.messages[msgIdx].thinking = thinkingBuffer;\n this.messages[msgIdx].loading = false;\n this.sending = false;\n this.clearWaitTimer();\n this.scrollToBottom();\n this.loadSessions();\n }\n }, 30);\n const url = (0, _apichat.createStreamUrl)(this.activeSessionId, text);\n if (this.eventSource) {\n this.eventSource.close();\n }\n this.eventSource = new EventSource(url);\n const es = this.eventSource;\n es.addEventListener('reasoning', e => {\n if (e.data) {\n const chunk = e.data;\n // 1. 先处理当前分片内部的中英文、数字、标点空格\n let cleanChunk = chunk.replace(/([a-z])([A-Z])/g, '$1 $2').replace(/([A-Z]+)([A-Z][a-z])/g, '$1 $2').replace(/([a-zA-Z])([\\u4e00-\\u9fff])/g, '$1 $2').replace(/([\\u4e00-\\u9fff])([a-zA-Z])/g, '$1 $2').replace(/([a-zA-Z])(\\d)/g, '$1 $2').replace(/(\\d)([a-zA-Z])/g, '$1 $2').replace(/\\s+([:,.!?])/g, '$1').replace(/([:,.!?])\\s+/g, '$1 ');\n cleanChunk = cleanChunk.replace(/\\s+/g, ' ');\n\n // 2. 关键:判断前一段末尾 + 当前段开头都是英文,补空格分隔\n const lastChar = thinkingBuffer.slice(-1);\n const firstChar = cleanChunk.slice(0, 1);\n const isLetter = c => /[a-zA-Z]/.test(c);\n if (isLetter(lastChar) && isLetter(firstChar)) {\n // 两段都是英文衔接,中间加空格\n thinkingBuffer += ' ' + cleanChunk;\n } else {\n thinkingBuffer += cleanChunk;\n }\n }\n });\n es.addEventListener('reasoning_result', e => {\n if (e.data) {\n thinkingBuffer = e.data;\n }\n });\n es.addEventListener('answer', e => {\n if (e.data) {\n answerBuffer += e.data;\n if (this.messages[msgIdx]) {\n this.messages[msgIdx].content += e.data.replace(/([a-zA-Z]+)([\\u4e00-\\u9fff])/g, '$1 $2').replace(/([\\u4e00-\\u9fff])([a-zA-Z]+)/g, '$1 $2').replace(/([a-z])([A-Z])/g, '$1 $2').replace(/([A-Z]+)([A-Z][a-z])/g, '$1 $2').replace(/([a-zA-Z])(\\d)/g, '$1 $2').replace(/(\\d)([a-zA-Z])/g, '$1 $2');\n this.scrollToBottom();\n }\n }\n });\n es.addEventListener('tool_result', e => {\n if (e.data && this.messages[msgIdx]) {\n if (!this.messages[msgIdx].toolCalls) this.messages[msgIdx].toolCalls = [];\n this.messages[msgIdx].toolCalls.push(e.data);\n this.scrollToBottom();\n }\n });\n es.addEventListener('agent_result', e => {\n finalContent = e.data || '';\n es.close();\n this.eventSource = null;\n if (this.messages[msgIdx]) {\n const key = this.messages[msgIdx]._key;\n if (key) this.$delete(this.contentCache, key);\n this.messages[msgIdx].content = finalContent;\n this.messages[msgIdx].thinking = thinkingBuffer;\n this.messages[msgIdx].loading = false;\n }\n this.sending = false;\n this.clearWaitTimer();\n if (typeTimer) {\n clearInterval(typeTimer);\n typeTimer = null;\n }\n this.scrollToBottom();\n this.loadSessions();\n });\n es.onerror = err => {\n console.log('[SSE] onerror', err);\n if (thinkingBuffer.length > 0 && !finalContent) finalContent = thinkingBuffer;\n if (!finalContent) finalContent = '❌ 连接中断';\n es.close();\n this.eventSource = null;\n if (this.messages[msgIdx]) {\n const key = this.messages[msgIdx]._key;\n if (key) this.$delete(this.contentCache, key);\n this.messages[msgIdx].content = finalContent;\n this.messages[msgIdx].thinking = thinkingBuffer;\n this.messages[msgIdx].loading = false;\n }\n this.sending = false;\n this.clearWaitTimer();\n if (typeTimer) {\n clearInterval(typeTimer);\n typeTimer = null;\n }\n this.scrollToBottom();\n };\n },\n stopAgent() {\n if (this.eventSource) {\n this.eventSource.close();\n this.eventSource = null;\n }\n if (this.activeSessionId) {\n (0, _apichat.stopStream)(this.activeSessionId).catch(() => {});\n }\n if (this.messages.length > 0) {\n const last = this.messages[this.messages.length - 1];\n if (last && last.loading) {\n last.content = last.content || last.thinking || '⏹ 已停止';\n last.loading = false;\n this.$delete(this.contentCache, last._key);\n }\n }\n this.sending = false;\n this.clearWaitTimer();\n },\n copyText(content) {\n if (!content) return;\n navigator.clipboard.writeText(content.replace(/<[^>]+>/g, '')).then(() => {\n this.$message({\n message: '已复制到剪贴板',\n type: 'success',\n duration: 1500\n });\n }).catch(() => {\n this.$message({\n message: '复制失败',\n type: 'error',\n duration: 2000\n });\n });\n },\n copyAsImage(content) {\n if (!content) return;\n // 创建临时容器渲染 Markdown\n const div = document.createElement('div');\n div.className = 'copy-image-render';\n div.style.cssText = 'position:fixed;left:-9999px;top:0;width:600px;padding:20px;background:#fff;font-size:14px;line-height:1.6;color:#333;border-radius:8px;font-family:-apple-system,BlinkMacSystemFont,sans-serif;';\n div.innerHTML = this.renderMarkdown(content);\n document.body.appendChild(div);\n this.$message({\n message: '正在生成图片...',\n type: 'info',\n duration: 2000\n });\n (0, _html2canvas.default)(div, {\n scale: 2,\n useCORS: true,\n backgroundColor: '#ffffff'\n }).then(canvas => {\n canvas.toBlob(blob => {\n if (blob) {\n navigator.clipboard.write([new ClipboardItem({\n 'image/png': blob\n })]).then(() => {\n this.$message({\n message: '图片已复制到剪贴板',\n type: 'success',\n duration: 1500\n });\n }).catch(() => {\n this.$message({\n message: '复制图片失败',\n type: 'error',\n duration: 2000\n });\n });\n }\n }, 'image/png');\n }).catch(() => {\n this.$message({\n message: '生成图片失败',\n type: 'error',\n duration: 2000\n });\n }).finally(() => {\n document.body.removeChild(div);\n });\n },\n formatTime(t) {\n if (!t) return '';\n const d = new Date(t.replace(' ', 'T'));\n const now = new Date();\n const diff = (now - d) / 1000;\n if (diff < 60) return '刚刚';\n if (diff < 3600) return Math.floor(diff / 60) + '分钟前';\n if (diff < 86400) return Math.floor(diff / 3600) + '小时前';\n return d.getMonth() + 1 + '/' + d.getDate();\n },\n getInitial(name) {\n if (!name) return '?';\n return name.charAt(0);\n },\n renderMarkdown(text) {\n if (!text) return '';\n try {\n return md.render(text);\n } catch (err) {\n return this.escapeHtml(text);\n }\n },\n renderStreaming(text, msgKey) {\n if (!text) return '';\n console.log('进入');\n const cache = this.contentCache[msgKey];\n const lines = text.split('\\n');\n const lastLineIdx = lines.length - 1;\n if (!cache) {\n try {\n const html = md.render(text);\n this.$set(this.contentCache, msgKey, {\n renderedLines: lastLineIdx,\n html,\n fullText: text\n });\n return html;\n } catch {\n return this.escapeHtml(text);\n }\n }\n if (text === cache.fullText) return cache.html;\n cache.fullText = text;\n\n // 行数没变,仅末尾追加字符,直接拼接尾行(原有逻辑不变)\n if (lastLineIdx === cache.renderedLines) {\n return cache.html + this.escapeHtml(lines[lastLineIdx]);\n }\n\n // 场景1:行数变少/文本回退截断,全量重渲染(原有分支保留,内部修复)\n if (lastLineIdx < cache.renderedLines) {\n try {\n // 重新截取所有完整行生成全新基础html,清空旧叠加内容\n const fullLines = lines.slice(0, lastLineIdx);\n let newBaseHtml = '';\n if (fullLines.length > 0) {\n newBaseHtml = md.render(fullLines.join('\\n'));\n }\n cache.html = newBaseHtml;\n cache.renderedLines = lastLineIdx;\n // 拼接尾行\n const lastLine = this.escapeHtml(lines[lastLineIdx]);\n return cache.html + (lastLine || '');\n } catch {\n return this.escapeHtml(text);\n }\n }\n\n // 场景2:新增完整行,修复:不再累加旧html,重新从0生成完整行基础\n if (cache.renderedLines < lastLineIdx) {\n // 关键修复:重新切片所有完整行,抛弃之前叠加的旧html,杜绝重复\n const allFullLines = lines.slice(0, lastLineIdx);\n let newBaseHtml = '';\n if (allFullLines.length > 0) {\n newBaseHtml = md.render(allFullLines.join('\\n'));\n }\n cache.html = newBaseHtml;\n cache.renderedLines = lastLineIdx;\n }\n const lastLine = this.escapeHtml(lines[lastLineIdx]);\n cache.renderedLines = lastLineIdx;\n return cache.html + (lastLine || '');\n },\n escapeHtml(text) {\n if (!text) return '';\n return text.replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>');\n },\n scrollToTop() {\n const el = this.$refs.messagesRef;\n if (el) el.scrollTop = 0;\n },\n scrollToBottom(force = false) {\n if (this.showDownBtn && !force) return;\n this.$nextTick(() => {\n const el = this.$refs.messagesRef;\n if (el) {\n el.scrollTop = el.scrollHeight;\n this.lastScrollTop = el.scrollTop;\n this.showDownBtn = false; // 滚动到底部后立刻隐藏箭头\n }\n });\n },\n scrollToBottomOnce() {\n // 清理旧定时器,防止任何泄漏\n clearTimeout(this._scrollTimer);\n this.$nextTick(() => {\n let retry = 0;\n const maxRetry = 6; // 重试6次,足够覆盖所有渲染延迟\n\n const tryScroll = () => {\n var _this$$refs;\n const el = (_this$$refs = this.$refs) === null || _this$$refs === void 0 ? void 0 : _this$$refs.messagesRef;\n if (!el) {\n this._scrollTimer = setTimeout(tryScroll, 50);\n return;\n }\n\n // 临时禁用平滑滚动,立即跳到底部\n const originalScrollBehavior = el.style.scrollBehavior;\n el.style.scrollBehavior = 'auto';\n el.scrollTop = el.scrollHeight - el.clientHeight;\n el.style.scrollBehavior = originalScrollBehavior;\n this.showDownBtn = false;\n };\n tryScroll();\n });\n }\n },\n beforeDestroy() {\n window.removeEventListener('resize', this.updateViewportState);\n this.releaseAudio();\n this.contentCache = {};\n clearTimeout(this._scrollTimer);\n if (this.eventSource) {\n this.eventSource.onerror = null;\n this.eventSource.close();\n this.eventSource = null;\n }\n if (this.waitTimer) {\n clearInterval(this.waitTimer);\n this.waitTimer = null;\n }\n if (this._typeTimer) {\n clearInterval(this._typeTimer);\n this._typeTimer = null;\n }\n }\n};\n\n//# sourceURL=webpack://ZjPluginIntelligent/./src/lib/components/chatMain/index.vue?./node_modules/_cache-loader@4.1.0@cache-loader/dist/cjs.js??ref--13-0!./node_modules/_babel-loader@8.4.1@babel-loader/lib!./node_modules/_cache-loader@4.1.0@cache-loader/dist/cjs.js??ref--1-0!./node_modules/_vue-loader@15.11.1@vue-loader/lib??vue-loader-options");
|
|
942
|
+
eval("\n\nvar _interopRequireDefault = __webpack_require__(/*! ./node_modules/_@babel_runtime@7.28.4@@babel/runtime/helpers/interopRequireDefault.js */ \"./node_modules/_@babel_runtime@7.28.4@@babel/runtime/helpers/interopRequireDefault.js\").default;\nObject.defineProperty(exports, \"__esModule\", {\n value: true\n});\nexports.default = void 0;\n__webpack_require__(/*! core-js/modules/es.error.cause.js */ \"./node_modules/_core-js@3.45.1@core-js/modules/es.error.cause.js\");\n__webpack_require__(/*! core-js/modules/es.array.push.js */ \"./node_modules/_core-js@3.45.1@core-js/modules/es.array.push.js\");\n__webpack_require__(/*! core-js/modules/es.array-buffer.detached.js */ \"./node_modules/_core-js@3.45.1@core-js/modules/es.array-buffer.detached.js\");\n__webpack_require__(/*! core-js/modules/es.array-buffer.transfer.js */ \"./node_modules/_core-js@3.45.1@core-js/modules/es.array-buffer.transfer.js\");\n__webpack_require__(/*! core-js/modules/es.array-buffer.transfer-to-fixed-length.js */ \"./node_modules/_core-js@3.45.1@core-js/modules/es.array-buffer.transfer-to-fixed-length.js\");\n__webpack_require__(/*! core-js/modules/es.iterator.constructor.js */ \"./node_modules/_core-js@3.45.1@core-js/modules/es.iterator.constructor.js\");\n__webpack_require__(/*! core-js/modules/es.iterator.filter.js */ \"./node_modules/_core-js@3.45.1@core-js/modules/es.iterator.filter.js\");\n__webpack_require__(/*! core-js/modules/es.iterator.find.js */ \"./node_modules/_core-js@3.45.1@core-js/modules/es.iterator.find.js\");\n__webpack_require__(/*! core-js/modules/es.iterator.for-each.js */ \"./node_modules/_core-js@3.45.1@core-js/modules/es.iterator.for-each.js\");\n__webpack_require__(/*! core-js/modules/es.iterator.map.js */ \"./node_modules/_core-js@3.45.1@core-js/modules/es.iterator.map.js\");\n__webpack_require__(/*! core-js/modules/es.typed-array.at.js */ \"./node_modules/_core-js@3.45.1@core-js/modules/es.typed-array.at.js\");\n__webpack_require__(/*! core-js/modules/es.typed-array.find-last.js */ \"./node_modules/_core-js@3.45.1@core-js/modules/es.typed-array.find-last.js\");\n__webpack_require__(/*! core-js/modules/es.typed-array.find-last-index.js */ \"./node_modules/_core-js@3.45.1@core-js/modules/es.typed-array.find-last-index.js\");\n__webpack_require__(/*! core-js/modules/es.typed-array.set.js */ \"./node_modules/_core-js@3.45.1@core-js/modules/es.typed-array.set.js\");\n__webpack_require__(/*! core-js/modules/es.typed-array.to-reversed.js */ \"./node_modules/_core-js@3.45.1@core-js/modules/es.typed-array.to-reversed.js\");\n__webpack_require__(/*! core-js/modules/es.typed-array.to-sorted.js */ \"./node_modules/_core-js@3.45.1@core-js/modules/es.typed-array.to-sorted.js\");\n__webpack_require__(/*! core-js/modules/es.typed-array.with.js */ \"./node_modules/_core-js@3.45.1@core-js/modules/es.typed-array.with.js\");\nvar _apichat = __webpack_require__(/*! @lib/api/apichat */ \"./src/lib/api/apichat.js\");\nvar _markdownIt = _interopRequireDefault(__webpack_require__(/*! markdown-it */ \"./node_modules/_markdown-it@14.1.0@markdown-it/index.mjs\"));\nvar _html2canvas = _interopRequireDefault(__webpack_require__(/*! html2canvas */ \"./node_modules/_html2canvas@1.4.1@html2canvas/dist/html2canvas.js\"));\nvar _index = __webpack_require__(/*! @lib/socket/fileManager/obs/index */ \"./src/lib/socket/fileManager/obs/index.js\");\nvar _index2 = _interopRequireDefault(__webpack_require__(/*! @lib/socket/utils/index */ \"./src/lib/socket/utils/index.js\"));\nvar _cookie = __webpack_require__(/*! @lib/utils/cookie.js */ \"./src/lib/utils/cookie.js\");\nvar _apiObs = _interopRequireDefault(__webpack_require__(/*! @lib/api/apiObs */ \"./src/lib/api/apiObs.js\"));\nconst md = new _markdownIt.default({\n breaks: true,\n html: false,\n linkify: true,\n typographer: true\n});\nmd.enable('table');\nvar _default = exports.default = {\n name: 'ChatMain',\n props: {\n Ak: {\n type: String,\n default: ''\n },\n Sk: {\n type: String,\n default: ''\n },\n imAccount: {\n type: String,\n default: ''\n },\n companyNo: {\n type: String,\n default: ''\n },\n isIntelShow: {\n default: false,\n type: Boolean\n },\n chatImToken: {\n default: '',\n type: String\n }\n },\n data() {\n return {\n agentList: [],\n currentAgent: '',\n currentAgentDesc: '',\n sessionsLoaded: false,\n searchKeyword: '',\n agentSuggestions: [],\n showAgentSuggestions: false,\n sessionList: [],\n activeSessionId: '',\n messages: [],\n loadingMore: false,\n sending: false,\n waitTimer: null,\n waitSeconds: 0,\n canceling: false,\n msgPage: 1,\n msgMaxPage: 1,\n msgTotal: 0,\n inputText: '',\n eventSource: null,\n showToolInfo: false,\n showDownBtn: false,\n // 控制向下箭头显隐\n lastScrollTop: 0,\n scrollTimer: null,\n // 滚动防抖(新增)\n showAgentSelect: true,\n isMobile: false,\n showSidebar: false,\n showH5List: false,\n // H5列表模式(展示会话列表而非聊天详情)\n _scrollTimer: null,\n agentInfo: {},\n contentCache: {},\n // 流式分行缓存 key=msg._key\n loadingSessionMsg: false,\n // 会话消息加载中标记\n greeting: '',\n longPressTimer: null,\n longPressed: false,\n // H5 语音输入\n voiceMode: false,\n // true=语音模式,false=文字模式\n isRecording: false,\n // 是否正在录音\n recordDuration: 0,\n // 录音时长(秒)\n recordingTimer: null,\n // 时长计时器\n audioContext: null,\n // AudioContext 实例\n audioStream: null,\n // MediaStream(用于清理)\n audioProcessor: null,\n // ScriptProcessorNode\n audioChunks: [],\n // Float32Array 数据块\n isCancelSwipe: false,\n // 是否上滑取消\n recordStartY: 0 // 触摸起始Y坐标\n };\n },\n created() {\n if (this.Ak || this.Sk) {\n (0, _apichat.setApiAuth)(this.Ak, this.Sk, this.imAccount, this.companyNo, this.chatImToken);\n }\n this.loadAgents();\n this.loadSessions();\n },\n mounted() {\n this.updateViewportState();\n window.addEventListener('resize', this.updateViewportState, {\n passive: true\n });\n // 监听 visualViewport 变化(键盘弹出/收起)\n if (window.visualViewport) {\n window.visualViewport.addEventListener('resize', this.onViewportResize, {\n passive: true\n });\n }\n },\n computed: {\n waitClass() {\n if (this.waitSeconds > 15) return 'wait-15';\n if (this.waitSeconds > 10) return 'wait-10';\n if (this.waitSeconds > 5) return 'wait-5';\n return '';\n },\n filteredSessions() {\n if (!this.searchKeyword) return this.sessionList;\n const kw = this.searchKeyword.toLowerCase();\n return this.sessionList.filter(s => {\n const name = (s.agentName || s.agentCode || '').toLowerCase();\n return name.includes(kw);\n });\n },\n currentAgentName() {\n if (!this.currentAgent) return '';\n const a = this.agentList.find(x => x.agentCode === this.currentAgent);\n return a ? a.agentName || a.agentCode : this.currentAgent;\n }\n },\n watch: {\n searchKeyword(val) {\n if (this.searchTimer) clearTimeout(this.searchTimer);\n if (!val.trim()) {\n this.agentSuggestions = [];\n this.showAgentSuggestions = false;\n this.closeSidebar();\n return;\n }\n this.searchTimer = setTimeout(() => {\n (0, _apichat.getChatAgents)(val.trim()).then(list => {\n this.agentSuggestions = list || [];\n this.showAgentSuggestions = this.agentSuggestions.length > 0;\n }).catch(() => {\n this.agentSuggestions = [];\n });\n }, 300);\n }\n // ak: {\n // handler(newVal) {\n // setApiAuth(newVal, this.sk)\n // },\n // immediate: true\n // },\n // sk: {\n // handler(newVal) {\n // setApiAuth(this.ak, newVal)\n // },\n // immediate: true\n // }\n },\n methods: {\n updateViewportState() {\n if (typeof window === 'undefined') return;\n const nextIsMobile = window.innerWidth <= 768;\n const wasMobile = this.isMobile;\n this.isMobile = nextIsMobile;\n if (!nextIsMobile) {\n this.showSidebar = false;\n this.showH5List = false;\n } else if (!wasMobile && nextIsMobile) {\n // 从桌面端切换到H5:如果加载了会话列表且无活跃会话,展示列表页\n if (this.sessionList.length > 0 && !this.activeSessionId) {\n this.showH5List = true;\n this.showAgentSelect = false;\n }\n }\n },\n toggleSidebar() {\n if (!this.isMobile) return;\n this.showSidebar = !this.showSidebar;\n },\n closeSidebar() {\n this.showSidebar = false;\n },\n // H5:调用原生返回上一级\n handleNativeBack() {\n if (this.$hybrid && typeof this.$hybrid.closePage === 'function') {\n this.$hybrid.closePage();\n } else if (window.history.length > 1) {\n window.history.back();\n }\n },\n // H5侧边栏返回按钮\n handleSidebarBack() {\n this.handleNativeBack();\n },\n agentjumpclick() {\n if (this.sending) {\n this.$message.warning('AI正在生成内容,暂时请不要切换对话');\n return;\n }\n this.currentAgent = '';\n this.currentAgentDesc = '';\n this.searchKeyword = '';\n this.activeSessionId = '';\n this.agentSuggestions = [];\n this.messages = [];\n this.showAgentSuggestions = false;\n this.showAgentSelect = true;\n this.showH5List = false;\n this.closeSidebar();\n },\n // H5:从详情页返回列表页\n goBackToList() {\n if (this.sending) {\n this.$message.warning('AI正在生成内容,暂时请不要切换对话');\n return;\n }\n // 关闭流连接\n if (this.eventSource) {\n this.eventSource.close();\n this.eventSource = null;\n }\n this.sending = false;\n this.clearWaitTimer();\n this.activeSessionId = '';\n this.messages = [];\n this.currentAgent = '';\n this.currentAgentDesc = '';\n this.agentInfo = {};\n this.contentCache = {};\n\n // 始终返回列表页\n this.showH5List = true;\n this.showAgentSelect = false;\n this.closeSidebar();\n },\n sendQuickMsg(message) {\n if (message) {\n this.inputText = message;\n this.sendMessage();\n }\n },\n formatMixText(str) {\n if (!str) return '';\n // 1. 中文 <=> 英文/数字 之间加空格\n let res = str.replace(/([a-zA-Z0-9])([\\u4e00-\\u9fff])/g, '$1 $2').replace(/([\\u4e00-\\u9fff])([a-zA-Z0-9])/g, '$1 $2');\n // 2. 连续英文单词分片粘连修复:字母紧跟字母中间加空格\n // 匹配 小写+大写 驼峰、连续分片拼接成一坨的英文\n res = res.replace(/([a-z])([A-Z])/g, '$1 $2');\n return res;\n },\n // 获取右侧头像样式(根据当前智能体在左侧列表中的位置决定颜色)\n getChatAvatarStyle(agent, avatar) {\n if (avatar) {\n return {\n backgroundImage: `url(${avatar})`,\n backgroundSize: 'cover',\n backgroundPosition: 'center',\n backgroundRepeat: 'no-repeat'\n };\n }\n const _agent = this.agentList.find(x => x.agentCode === agent);\n // 如果有网络图片,返回背景图样式\n if (agent.avatar) {\n return {\n backgroundImage: `url(${agent.avatar})`,\n backgroundSize: 'cover',\n backgroundPosition: 'center',\n backgroundRepeat: 'no-repeat'\n };\n }\n\n // 没有网络图片时,根据智能体在 agentList 中的索引位置决定颜色\n if (this.sessionList) {\n // 找到当前智能体在列表中的索引\n const index = this.sessionList.findIndex(item => item.agentCode === agent);\n if (index !== -1) {\n // 根据索引计算颜色类(4色循环)\n const colorIndex = index % 4 + 1;\n return {\n background: this.getGradientByColorIndex(colorIndex)\n };\n }\n }\n\n // 默认返回蓝色渐变\n return {\n background: 'linear-gradient(135deg, #1677ff, #4096ff)'\n };\n },\n // 根据颜色索引获取对应的渐变色\n getGradientByColorIndex(index) {\n const gradients = {\n 1: 'linear-gradient(135deg, #1677ff, #4096ff)',\n 2: 'linear-gradient(135deg, #52c41a, #73d13d)',\n 3: 'linear-gradient(135deg, #fa8c16, #ffa940)',\n 4: 'linear-gradient(135deg, #722ed1, #b37feb)'\n };\n return gradients[index] || gradients[1];\n },\n selectAgent(agentItem) {\n this.showAgentSelect = false;\n this.currentAgent = agentItem.agentCode;\n this.currentAgentName = agentItem.agentName;\n // 查找历史会话\n const existSession = this.sessionList.find(s => s.agentCode === agentItem.agentCode);\n if (existSession) {\n this.activeSessionId = existSession.id;\n this.switchSession(existSession);\n } else {\n this.createNewSession(agentItem.agentCode);\n }\n },\n createNewSession(agentCode) {\n // 你原有新建会话逻辑\n },\n // 检测是否滚动到底部,控制向下箭头显示隐藏\n checkScrollBottom(forceShowWhenNotBottom = false) {\n const el = this.$refs.messagesRef;\n if (!el) {\n this.showDownBtn = false;\n return;\n }\n const {\n scrollHeight,\n scrollTop,\n clientHeight\n } = el;\n const remain = scrollHeight - scrollTop - clientHeight;\n const atBottom = remain <= 80;\n if (atBottom) {\n this.showDownBtn = false;\n } else if (this.sending && scrollTop >= this.lastScrollTop && !forceShowWhenNotBottom) {\n // 发送AI回答时,如果用户没有主动向上滚动,就不要显示下箭头闪烁\n this.showDownBtn = false;\n } else {\n this.showDownBtn = true;\n }\n this.lastScrollTop = scrollTop;\n },\n // 固定最小高度:单行不撑开,超出才增高\n // H5 输入框获取焦点 - 滚动到底部让键盘不遮挡\n onInputFocus() {\n if (!this.isMobile) return;\n // 直接滚动窗口到底部,确保输入框可见\n setTimeout(() => {\n window.scrollTo(0, document.body.scrollHeight);\n }, 300);\n },\n // visualViewport 变化时(如键盘弹出)调整滚动位置\n onViewportResize() {\n if (!this.isMobile) return;\n const activeEl = document.activeElement;\n if (activeEl && (activeEl.tagName === 'TEXTAREA' || activeEl.tagName === 'INPUT')) {\n window.scrollTo(0, document.body.scrollHeight);\n }\n },\n autoResizeTextarea() {\n const ta = this.$refs.taRef;\n if (!ta) return;\n // 根据端适配基准高度和最大高度\n const isMobile = this.isMobile;\n const baseH = isMobile ? 36 : 100;\n const maxH = isMobile ? 100 : 180;\n ta.style.height = `${baseH}px`;\n // 内容真实高度\n const realH = ta.scrollHeight;\n // 只有内容高度>基准才撑开,否则保持初始高度\n if (realH > baseH) {\n ta.style.height = `${Math.min(realH, maxH)}px`;\n }\n this.$nextTick(() => {\n this.checkScrollBottom(true);\n });\n },\n // Shift+Enter换行\n newLine(e) {\n // 取消浏览器默认行为\n e.preventDefault();\n // 拿到光标位置\n const ta = this.$refs.taRef;\n const start = ta.selectionStart;\n const end = ta.selectionEnd;\n // 在光标处插入换行符\n this.inputText = this.inputText.slice(0, start) + '\\n' + this.inputText.slice(end);\n // 光标定位到换行后\n this.$nextTick(() => {\n ta.selectionStart = ta.selectionEnd = start + 1;\n // 自动调整输入框高度\n this.autoResizeTextarea();\n });\n },\n toggleVoiceMode() {\n this.voiceMode = !this.voiceMode;\n if (!this.voiceMode) {\n // 切回文字模式时释放音频设备\n this.releaseAudio();\n }\n },\n // 确保音频设备已就绪(只请求一次权限,缓存 stream / AudioContext)\n async ensureAudioReady() {\n if (this.audioContext && this.audioStream) return true;\n if (!navigator.mediaDevices || !navigator.mediaDevices.getUserMedia) {\n alert('当前环境不支持麦克风访问');\n return false;\n }\n try {\n const stream = await navigator.mediaDevices.getUserMedia({\n audio: true\n });\n this.audioStream = stream;\n const audioContext = new (window.AudioContext || window.webkitAudioContext)({\n sampleRate: 16000\n });\n this.audioContext = audioContext;\n const source = audioContext.createMediaStreamSource(stream);\n const processor = audioContext.createScriptProcessor(4096, 1, 1);\n this.audioProcessor = processor;\n processor.onaudioprocess = e => {\n if (!this.isRecording) return;\n const inputData = e.inputBuffer.getChannelData(0);\n this.audioChunks.push(new Float32Array(inputData));\n };\n source.connect(processor);\n processor.connect(audioContext.destination);\n return true;\n } catch (err) {\n console.error('麦克风访问失败:', err);\n alert('麦克风权限被拒绝');\n return false;\n }\n },\n // H5语音录制 - 触摸开始\n async onRecordTouchStart(e) {\n if (this.sending) return;\n\n // 先确保音频已就绪(首次会请求权限并建立音频管线,后续复用)\n const ready = await this.ensureAudioReady();\n if (!ready) return;\n\n // 重置录音状态\n this.isCancelSwipe = false;\n this.recordStartY = e.touches[0].clientY;\n this.recordDuration = 0;\n this.audioChunks = [];\n\n // 音频就绪后才标记录制中并启动计时\n this.isRecording = true;\n this.recordingTimer = setInterval(() => {\n this.recordDuration++;\n if (this.recordDuration >= 60) {\n this.onRecordTouchEnd();\n }\n }, 1000);\n },\n // H5语音录制 - 触摸移动(检测上滑取消)\n onRecordTouchMove(e) {\n if (!this.isRecording) return;\n const touch = e.touches[0];\n const moveY = touch.clientY;\n const cancelThreshold = 60; // 上滑60px进入取消区域\n this.isCancelSwipe = this.recordStartY - moveY > cancelThreshold;\n },\n // H5语音录制 - 触摸结束\n onRecordTouchEnd() {\n if (!this.isRecording) return;\n this.isRecording = false;\n if (this.recordingTimer) {\n clearInterval(this.recordingTimer);\n this.recordingTimer = null;\n }\n this.stopAudioCapture(!this.isCancelSwipe);\n },\n // 停止音频采集并输出 WAV(保留音频设备,下次复用)\n stopAudioCapture(shouldSend) {\n this.isRecording = false;\n if (shouldSend && this.audioChunks.length > 0) {\n const wavBlob = this.encodePCMToWav(this.audioChunks, 16000);\n this.sendAudioBlob(wavBlob);\n }\n this.audioChunks = [];\n },\n // 取消录音(保留音频设备,下次复用)\n cancelRecording() {\n this.isRecording = false;\n if (this.recordingTimer) {\n clearInterval(this.recordingTimer);\n this.recordingTimer = null;\n }\n this.recordDuration = 0;\n this.isCancelSwipe = false;\n this.audioChunks = [];\n },\n // 释放音频资源(切换回文字模式或组件销毁时调用)\n releaseAudio() {\n this.cancelRecording();\n if (this.audioProcessor) {\n this.audioProcessor.disconnect();\n this.audioProcessor = null;\n }\n if (this.audioContext) {\n this.audioContext.close().catch(() => {});\n this.audioContext = null;\n }\n if (this.audioStream) {\n this.audioStream.getTracks().forEach(t => t.stop());\n this.audioStream = null;\n }\n },\n // 将 Float32 PCM 数据编码为 WAV Blob\n encodePCMToWav(chunks, sampleRate) {\n // 计算总采样数\n let totalLength = 0;\n for (const chunk of chunks) {\n totalLength += chunk.length;\n }\n\n // 转换为 Int16 PCM\n const pcmData = new Int16Array(totalLength);\n let offset = 0;\n for (const chunk of chunks) {\n for (let i = 0; i < chunk.length; i++) {\n const s = Math.max(-1, Math.min(1, chunk[i]));\n pcmData[offset++] = s < 0 ? s * 0x8000 : s * 0x7FFF;\n }\n }\n const numChannels = 1;\n const bitsPerSample = 16;\n const byteRate = sampleRate * numChannels * bitsPerSample / 8;\n const blockAlign = numChannels * bitsPerSample / 8;\n const dataSize = pcmData.length * (bitsPerSample / 8);\n const headerSize = 44;\n const totalSize = headerSize + dataSize;\n const buffer = new ArrayBuffer(totalSize);\n const view = new DataView(buffer);\n\n // RIFF header\n this._wavWriteString(view, 0, 'RIFF');\n view.setUint32(4, totalSize - 8, true);\n this._wavWriteString(view, 8, 'WAVE');\n\n // fmt chunk\n this._wavWriteString(view, 12, 'fmt ');\n view.setUint32(16, 16, true); // chunk size\n view.setUint16(20, 1, true); // PCM format\n view.setUint16(22, numChannels, true); // 单声道\n view.setUint32(24, sampleRate, true); // 采样率\n view.setUint32(28, byteRate, true);\n view.setUint16(32, blockAlign, true);\n view.setUint16(34, bitsPerSample, true);\n\n // data chunk\n this._wavWriteString(view, 36, 'data');\n view.setUint32(40, dataSize, true);\n\n // 写入 PCM 数据\n const pcmView = new Int16Array(buffer, headerSize, pcmData.length);\n pcmView.set(pcmData);\n return new Blob([buffer], {\n type: 'audio/wav'\n });\n },\n _wavWriteString(view, offset, str) {\n for (let i = 0; i < str.length; i++) {\n view.setUint8(offset + i, str.charCodeAt(i));\n }\n },\n // 发送音频\n sendAudioBlob(blob) {\n let appSeqId = _index2.default.getAppSeqId();\n let name = appSeqId + '.wav';\n const file = new File([blob], name, {\n type: 'audio/wav'\n });\n // TODO: 上传音频文件并调用 STT 接口\n this.sendAudioMessage(file);\n },\n sendAudioMessage(file) {\n // 插入本地 pending 消息\n const sttKey = 'stt_' + Date.now();\n const sttMsg = {\n role: 'user',\n content: '转化中...',\n _sttStatus: 'pending',\n _sttKey: sttKey,\n createTime: new Date().toISOString(),\n _key: sttKey\n };\n this.messages.push(sttMsg);\n this.scrollToBottom(true);\n (0, _index.fileUploadToObs)({\n _file: file,\n appSeqId: file.name\n }).then(resp => {\n if (resp.CommonMsg.Status === 200) {\n // 调用语音转文字接口\n return _apiObs.default.aliAudioToText({\n url: resp.obs_upload_data.obsUrl\n }).then(result => {\n if (result.code === '200' && result.data) {\n // 成功:删除 pending 消息,发送给后端\n const idx = this.messages.findIndex(m => m._sttKey === sttKey);\n if (idx !== -1) {\n this.messages.splice(idx, 1);\n }\n this.sendQuickMsg(result.data);\n } else {\n throw new Error(result.msg || '语音转文字失败');\n }\n });\n } else {\n throw new Error(resp.CommonMsg.Message || '文件上传失败');\n }\n }).catch(err => {\n console.error('语音转文字失败:', err);\n // 失败:更新为错误状态\n const idx = this.messages.findIndex(m => m._sttKey === sttKey);\n if (idx !== -1) {\n this.$set(this.messages, idx, {\n ...this.messages[idx],\n _sttStatus: 'error',\n content: '语音转文字失败'\n });\n }\n this.$message.error('语音转文字失败');\n });\n this.$message.success(`录音完成 (${this.recordDuration}s)`);\n },\n clearWaitTimer() {\n if (this.waitTimer) {\n clearInterval(this.waitTimer);\n this.waitTimer = null;\n }\n },\n loadAgents() {\n (0, _apichat.getChatAgents)().then(list => {\n this.agentList = list || [];\n // if (this.agentList.length > 0 && !this.currentAgent) {\n // const first = this.agentList[0]\n // this.currentAgent = first.agentCode\n // this.currentAgentDesc = first.description || ''\n // }\n }).catch(() => {});\n },\n loadSessions() {\n (0, _apichat.getSessionList)().then(list => {\n if (!this.activeSessionId) {\n this.sessionList = list || [];\n if (this.sessionList.length > 0) {\n if (this.isMobile) {\n // H5模式:不自动选中会话,展示列表页\n this.showAgentSelect = false;\n this.showH5List = true;\n this.showSidebar = false;\n } else {\n this.switchSession(this.sessionList[0]);\n }\n }\n if (this.sessionList.length === 0) {\n this.showAgentSelect = true;\n this.showH5List = false;\n }\n } else {\n this.sessionList = list || [];\n let _item = list.find(res => res.sessionId == this.activeSessionId);\n try {\n if (_item.suggestedQuestions) {\n _item.suggestedQuestions = JSON.parse(_item.suggestedQuestions);\n } else {\n _item.suggestedQuestions = [];\n }\n _item && (this.agentInfo = _item);\n } catch (err) {\n // JSON格式错误兜底空数组,防止页面报错\n this.agentInfo.questionArr = [];\n console.warn('快捷提问解析失败', err);\n }\n }\n }).catch(() => {});\n },\n onSearchClear() {\n this.agentSuggestions = [];\n this.showAgentSuggestions = false;\n },\n startChatWithAgent(agent) {\n console.log('选择了助手', agent.agentCode, this.currentAgent);\n if (agent.agentCode == this.currentAgent) {\n this.searchKeyword = '';\n this.agentSuggestions = [];\n this.showAgentSuggestions = false;\n return;\n }\n this.currentAgent = agent.agentCode;\n this.currentAgentDesc = agent.description || '';\n this.searchKeyword = '';\n this.agentInfo = {};\n this.agentSuggestions = [];\n this.messages = [];\n this.showAgentSuggestions = false;\n this.showAgentSelect = false;\n this.closeSidebar();\n if (this.isMobile) {\n this.showH5List = false; // H5:进入详情页,隐藏列表\n }\n const existing = this.sessionList.find(s => s.agentCode === agent.agentCode);\n if (existing) {\n this.switchSession(existing);\n } else {\n this.handleNewSession();\n }\n },\n handleNewSession() {\n if (!this.currentAgent) return;\n if (this.activeSessionId) this.closeOldSession();\n (0, _apichat.startSession)(this.currentAgent).then(res => {\n console.log(res, 'startChatWithAgentstartChatWithAgentstartChatWithAgent', this.agentInfo);\n this.activeSessionId = res.sessionId || '';\n this.loadSessions();\n const agent = this.agentList.find(a => a.agentCode === this.currentAgent);\n if (agent) this.addWelcomeMessage(agent);\n }).catch(() => {});\n },\n // H5长按删除 - 触摸开始\n onSessionTouchStart(s, e) {\n if (!this.isMobile) return;\n this.longPressed = false;\n this.longPressTimer = setTimeout(() => {\n this.longPressed = true;\n this.handleDeleteSession(s);\n }, 600);\n },\n // H5长按删除 - 触摸结束/移动(取消长按)\n onSessionTouchEnd() {\n if (this.longPressTimer) {\n clearTimeout(this.longPressTimer);\n this.longPressTimer = null;\n }\n },\n onSessionTouchMove() {\n if (this.longPressTimer) {\n clearTimeout(this.longPressTimer);\n this.longPressTimer = null;\n }\n },\n async switchSession(s) {\n if (this.longPressed) {\n this.longPressed = false;\n return;\n }\n if (this.sending) {\n this.$message.warning('AI正在生成内容,暂时请不要切换对话');\n return;\n }\n this.showAgentSelect = false;\n this.closeSidebar();\n if (this.isMobile) {\n this.showH5List = false; // H5:进入详情页,隐藏列表\n }\n if (this.activeSessionId === s.sessionId) return;\n this.contentCache = {};\n this.activeSessionId = s.sessionId;\n this.currentAgent = s.agentCode;\n console.log('进入');\n this.agentInfo = s;\n console.log('进入', this.agentInfo);\n try {\n if (s.suggestedQuestions) {\n this.agentInfo.suggestedQuestions = JSON.parse(s.suggestedQuestions);\n } else {\n this.agentInfo.suggestedQuestions = [];\n }\n } catch (err) {\n // JSON格式错误兜底空数组,防止页面报错\n this.agentInfo.questionArr = [];\n console.warn('快捷提问解析失败', err);\n }\n const agent = this.agentList.find(a => a.agentCode === s.agentCode);\n this.currentAgentDesc = agent ? agent.description || '' : '';\n this.msgPage = 1;\n this.msgTotal = 0;\n this.messages = []; // 先清空,但开启加载锁屏蔽空白页\n this.loadingSessionMsg = true; // 开启加载标记\n (0, _apichat.syncToken)((0, _cookie.getToken)(), s.sessionId);\n try {\n const res = await (0, _apichat.getSessionMessages)(s.sessionId, 1, 10);\n const list = Array.isArray(res) ? res : res.list || [];\n this.msgTotal = res.total || list.length;\n this.msgPage = 1;\n const asAsc = (list || []).slice().reverse();\n this.messages = asAsc.map(m => ({\n role: m.role,\n content: m.content || '',\n thinking: m.thinking || '',\n toolCalls: [],\n agentName: m.role === 'assistant' ? s.agentName || '' : '',\n createTime: m.createTime || null,\n _key: m.createTime ? 'msg_' + m.createTime : 'msg_' + Date.now() + '_' + Math.random()\n }));\n if (this.messages.length === 0 && agent) this.addWelcomeMessage(agent);\n await this.$nextTick();\n this.$nextTick(() => {\n this.scrollToBottomOnce();\n this.checkScrollBottom();\n });\n } catch (e) {\n this.messages = [];\n } finally {\n // 无论成功失败,结束后关闭加载锁\n this.loadingSessionMsg = false;\n }\n },\n loadMoreMessages() {\n const nextPage = this.msgPage + 1;\n const maxPage = Math.ceil(this.msgTotal / 10);\n if (nextPage > maxPage) {\n this.loadingMore = false;\n return;\n }\n (0, _apichat.getSessionMessages)(this.activeSessionId, nextPage, 10).then(res => {\n const list = Array.isArray(res) ? res : res.list || [];\n this.msgPage = nextPage;\n const asAsc = (list || []).slice().reverse();\n const prepend = asAsc.map(m => ({\n role: m.role,\n content: m.content || '',\n thinking: m.thinking || '',\n toolCalls: [],\n agentName: '',\n createTime: m.createTime || null,\n _key: m.createTime ? 'msg_' + m.createTime : 'msg_' + Date.now() + '_' + Math.random()\n }));\n const container = this.$refs.messagesRef;\n const oldScrollHeight = container ? container.scrollHeight : 0;\n const oldScrollTop = container ? container.scrollTop : 0;\n this.messages = [...prepend, ...this.messages];\n this.$nextTick(() => {\n if (container) {\n container.scrollTop = oldScrollTop + (container.scrollHeight - oldScrollHeight);\n }\n this.loadingMore = false;\n });\n }).catch(() => {\n this.loadingMore = false;\n });\n },\n onScrollMessages() {\n const container = this.$refs.messagesRef;\n if (!container || this.loadingMore) return;\n const isAtBottom = container.scrollTop + container.clientHeight >= container.scrollHeight - 100;\n this.checkScrollBottom();\n if (isAtBottom) return;\n if (container.scrollTop < 50 && this.msgPage < Math.ceil(this.msgTotal / 10)) {\n this.loadingMore = true;\n this.loadMoreMessages();\n }\n },\n handleDeleteSession(s) {\n this.$confirm(`确认删除「${s.agentName || s.agentCode}」的会话?`, '提示', {\n type: 'warning'\n }).then(() => {\n (0, _apichat.deleteSession)(s.sessionId).then(() => {\n if (this.activeSessionId === s.sessionId) {\n this.activeSessionId = '';\n this.messages = [];\n this.currentAgent = '';\n this.currentAgentDesc = '';\n if (this.isMobile) {\n this.showH5List = false;\n this.showAgentSelect = true;\n } else {\n this.showAgentSelect = true;\n }\n }\n this.loadSessions();\n });\n }).catch(() => {});\n },\n closeOldSession() {},\n onAgentChange(code) {\n const agent = this.agentList.find(a => a.agentCode === code);\n this.currentAgentDesc = agent ? agent.description || '' : '';\n this.handleNewSession();\n },\n addWelcomeMessage(agent) {\n this.greeting = '';\n // if (!agent) return\n // const name = agent.agentName || '助手';\n const _agent = this.agentList.find(x => x.agentCode === this.currentAgent);\n this.greeting = _agent.greeting || `很高兴为您服务,请问有什么可以帮到您?`;\n // this.messages.push({\n // role: 'assistant',\n // content: _content,\n // thinking: '',\n // agentName: name,\n // _key: 'welcome_' + Date.now()\n // })\n },\n async sendMessage() {\n const text = this.inputText.trim();\n if (!text || this.sending) return;\n if (!this.activeSessionId) {\n await (0, _apichat.startSession)(this.currentAgent).then(res => {\n this.activeSessionId = res.sessionId || '';\n this.loadSessions();\n });\n if (!this.activeSessionId) return;\n }\n this.inputText = '';\n const ta = this.$refs.taRef;\n const isMobile = this.isMobile;\n const baseH = isMobile ? 36 : 100;\n if (ta) {\n ta.style.height = baseH + 'px'; // 强制恢复初始高度\n }\n this.showDownBtn = false;\n this.messages.push({\n role: 'user',\n content: text,\n createTime: new Date().toISOString(),\n _key: 'user_' + Date.now() + '_' + Math.random()\n });\n const agentName = this.currentAgentName;\n const msgIdx = this.messages.push({\n role: \"assistant\",\n content: \"\",\n thinking: \"\",\n loading: true,\n toolCalls: [],\n agentName,\n createTime: new Date().toISOString(),\n _key: 'asst_' + Date.now() + '_' + Math.random()\n }) - 1;\n this.scrollToBottom(true);\n this.sending = true;\n this.waitSeconds = 0;\n if (this.waitTimer) clearInterval(this.waitTimer);\n this.waitTimer = setInterval(() => {\n this.waitSeconds++;\n }, 1000);\n let thinkingBuffer = '';\n let finalContent = '';\n let answerBuffer = '';\n let thinkDisplayed = 0;\n let typeTimer = null;\n typeTimer = setInterval(() => {\n if (!this.messages[msgIdx]) return;\n if (thinkDisplayed < thinkingBuffer.length) {\n thinkDisplayed += 50;\n if (thinkDisplayed > thinkingBuffer.length) thinkDisplayed = thinkingBuffer.length;\n this.messages[msgIdx].thinking = thinkingBuffer.substring(0, thinkDisplayed);\n this.scrollToBottom();\n } else if (finalContent && !this.messages[msgIdx].content) {\n clearInterval(typeTimer);\n const key = this.messages[msgIdx]._key;\n if (key) {\n this.$delete(this.contentCache, key);\n this.$delete(this.contentCache, key + '_t');\n }\n typeTimer = null;\n this.messages[msgIdx].content = finalContent;\n this.messages[msgIdx].thinking = thinkingBuffer;\n this.messages[msgIdx].loading = false;\n this.sending = false;\n this.clearWaitTimer();\n this.scrollToBottom();\n this.loadSessions();\n }\n }, 30);\n const url = (0, _apichat.createStreamUrl)(this.activeSessionId, text);\n if (this.eventSource) {\n this.eventSource.close();\n }\n this.eventSource = new EventSource(url);\n const es = this.eventSource;\n es.addEventListener('reasoning', e => {\n if (e.data) {\n const chunk = e.data;\n // 1. 先处理当前分片内部的中英文、数字、标点空格\n let cleanChunk = chunk.replace(/([a-z])([A-Z])/g, '$1 $2').replace(/([A-Z]+)([A-Z][a-z])/g, '$1 $2').replace(/([a-zA-Z])([\\u4e00-\\u9fff])/g, '$1 $2').replace(/([\\u4e00-\\u9fff])([a-zA-Z])/g, '$1 $2').replace(/([a-zA-Z])(\\d)/g, '$1 $2').replace(/(\\d)([a-zA-Z])/g, '$1 $2').replace(/\\s+([:,.!?])/g, '$1').replace(/([:,.!?])\\s+/g, '$1 ');\n cleanChunk = cleanChunk.replace(/\\s+/g, ' ');\n\n // 2. 关键:判断前一段末尾 + 当前段开头都是英文,补空格分隔\n const lastChar = thinkingBuffer.slice(-1);\n const firstChar = cleanChunk.slice(0, 1);\n const isLetter = c => /[a-zA-Z]/.test(c);\n if (isLetter(lastChar) && isLetter(firstChar)) {\n // 两段都是英文衔接,中间加空格\n thinkingBuffer += ' ' + cleanChunk;\n } else {\n thinkingBuffer += cleanChunk;\n }\n }\n });\n es.addEventListener('reasoning_result', e => {\n if (e.data) {\n thinkingBuffer = e.data;\n }\n });\n es.addEventListener('answer', e => {\n if (e.data) {\n answerBuffer += e.data;\n if (this.messages[msgIdx]) {\n this.messages[msgIdx].content += e.data.replace(/([a-zA-Z]+)([\\u4e00-\\u9fff])/g, '$1 $2').replace(/([\\u4e00-\\u9fff])([a-zA-Z]+)/g, '$1 $2').replace(/([a-z])([A-Z])/g, '$1 $2').replace(/([A-Z]+)([A-Z][a-z])/g, '$1 $2').replace(/([a-zA-Z])(\\d)/g, '$1 $2').replace(/(\\d)([a-zA-Z])/g, '$1 $2');\n this.scrollToBottom();\n }\n }\n });\n es.addEventListener('tool_result', e => {\n if (e.data && this.messages[msgIdx]) {\n if (!this.messages[msgIdx].toolCalls) this.messages[msgIdx].toolCalls = [];\n this.messages[msgIdx].toolCalls.push(e.data);\n this.scrollToBottom();\n }\n });\n es.addEventListener('agent_result', e => {\n finalContent = e.data || '';\n es.close();\n this.eventSource = null;\n if (this.messages[msgIdx]) {\n const key = this.messages[msgIdx]._key;\n if (key) this.$delete(this.contentCache, key);\n this.messages[msgIdx].content = finalContent;\n this.messages[msgIdx].thinking = thinkingBuffer;\n this.messages[msgIdx].loading = false;\n }\n this.sending = false;\n this.clearWaitTimer();\n if (typeTimer) {\n clearInterval(typeTimer);\n typeTimer = null;\n }\n this.scrollToBottom();\n this.loadSessions();\n });\n es.onerror = err => {\n console.log('[SSE] onerror', err);\n if (thinkingBuffer.length > 0 && !finalContent) finalContent = thinkingBuffer;\n if (!finalContent) finalContent = '❌ 连接中断';\n es.close();\n this.eventSource = null;\n if (this.messages[msgIdx]) {\n const key = this.messages[msgIdx]._key;\n if (key) this.$delete(this.contentCache, key);\n this.messages[msgIdx].content = finalContent;\n this.messages[msgIdx].thinking = thinkingBuffer;\n this.messages[msgIdx].loading = false;\n }\n this.sending = false;\n this.clearWaitTimer();\n if (typeTimer) {\n clearInterval(typeTimer);\n typeTimer = null;\n }\n this.scrollToBottom();\n };\n },\n stopAgent() {\n if (this.eventSource) {\n this.eventSource.close();\n this.eventSource = null;\n }\n if (this.activeSessionId) {\n (0, _apichat.stopStream)(this.activeSessionId).catch(() => {});\n }\n if (this.messages.length > 0) {\n const last = this.messages[this.messages.length - 1];\n if (last && last.loading) {\n last.content = last.content || last.thinking || '⏹ 已停止';\n last.loading = false;\n this.$delete(this.contentCache, last._key);\n }\n }\n this.sending = false;\n this.clearWaitTimer();\n },\n copyText(content) {\n if (!content) return;\n navigator.clipboard.writeText(content.replace(/<[^>]+>/g, '')).then(() => {\n this.$message({\n message: '已复制到剪贴板',\n type: 'success',\n duration: 1500\n });\n }).catch(() => {\n this.$message({\n message: '复制失败',\n type: 'error',\n duration: 2000\n });\n });\n },\n copyAsImage(content) {\n if (!content) return;\n // 创建临时容器渲染 Markdown\n const div = document.createElement('div');\n div.className = 'copy-image-render';\n div.style.cssText = 'position:fixed;left:-9999px;top:0;width:600px;padding:20px;background:#fff;font-size:14px;line-height:1.6;color:#333;border-radius:8px;font-family:-apple-system,BlinkMacSystemFont,sans-serif;';\n div.innerHTML = this.renderMarkdown(content);\n document.body.appendChild(div);\n this.$message({\n message: '正在生成图片...',\n type: 'info',\n duration: 2000\n });\n (0, _html2canvas.default)(div, {\n scale: 2,\n useCORS: true,\n backgroundColor: '#ffffff'\n }).then(canvas => {\n canvas.toBlob(blob => {\n if (blob) {\n navigator.clipboard.write([new ClipboardItem({\n 'image/png': blob\n })]).then(() => {\n this.$message({\n message: '图片已复制到剪贴板',\n type: 'success',\n duration: 1500\n });\n }).catch(() => {\n this.$message({\n message: '复制图片失败',\n type: 'error',\n duration: 2000\n });\n });\n }\n }, 'image/png');\n }).catch(() => {\n this.$message({\n message: '生成图片失败',\n type: 'error',\n duration: 2000\n });\n }).finally(() => {\n document.body.removeChild(div);\n });\n },\n formatTime(t) {\n if (!t) return '';\n const d = new Date(t.replace(' ', 'T'));\n const now = new Date();\n const diff = (now - d) / 1000;\n if (diff < 60) return '刚刚';\n if (diff < 3600) return Math.floor(diff / 60) + '分钟前';\n if (diff < 86400) return Math.floor(diff / 3600) + '小时前';\n return d.getMonth() + 1 + '/' + d.getDate();\n },\n getInitial(name) {\n if (!name) return '?';\n return name.charAt(0);\n },\n renderMarkdown(text) {\n if (!text) return '';\n try {\n return md.render(text);\n } catch (err) {\n return this.escapeHtml(text);\n }\n },\n renderStreaming(text, msgKey) {\n if (!text) return '';\n console.log('进入');\n const cache = this.contentCache[msgKey];\n const lines = text.split('\\n');\n const lastLineIdx = lines.length - 1;\n if (!cache) {\n try {\n const html = md.render(text);\n this.$set(this.contentCache, msgKey, {\n renderedLines: lastLineIdx,\n html,\n fullText: text\n });\n return html;\n } catch {\n return this.escapeHtml(text);\n }\n }\n if (text === cache.fullText) return cache.html;\n cache.fullText = text;\n\n // 行数没变,仅末尾追加字符,直接拼接尾行(原有逻辑不变)\n if (lastLineIdx === cache.renderedLines) {\n return cache.html + this.escapeHtml(lines[lastLineIdx]);\n }\n\n // 场景1:行数变少/文本回退截断,全量重渲染(原有分支保留,内部修复)\n if (lastLineIdx < cache.renderedLines) {\n try {\n // 重新截取所有完整行生成全新基础html,清空旧叠加内容\n const fullLines = lines.slice(0, lastLineIdx);\n let newBaseHtml = '';\n if (fullLines.length > 0) {\n newBaseHtml = md.render(fullLines.join('\\n'));\n }\n cache.html = newBaseHtml;\n cache.renderedLines = lastLineIdx;\n // 拼接尾行\n const lastLine = this.escapeHtml(lines[lastLineIdx]);\n return cache.html + (lastLine || '');\n } catch {\n return this.escapeHtml(text);\n }\n }\n\n // 场景2:新增完整行,修复:不再累加旧html,重新从0生成完整行基础\n if (cache.renderedLines < lastLineIdx) {\n // 关键修复:重新切片所有完整行,抛弃之前叠加的旧html,杜绝重复\n const allFullLines = lines.slice(0, lastLineIdx);\n let newBaseHtml = '';\n if (allFullLines.length > 0) {\n newBaseHtml = md.render(allFullLines.join('\\n'));\n }\n cache.html = newBaseHtml;\n cache.renderedLines = lastLineIdx;\n }\n const lastLine = this.escapeHtml(lines[lastLineIdx]);\n cache.renderedLines = lastLineIdx;\n return cache.html + (lastLine || '');\n },\n escapeHtml(text) {\n if (!text) return '';\n return text.replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>');\n },\n scrollToTop() {\n const el = this.$refs.messagesRef;\n if (el) el.scrollTop = 0;\n },\n scrollToBottom(force = false) {\n if (this.showDownBtn && !force) return;\n this.$nextTick(() => {\n const el = this.$refs.messagesRef;\n if (el) {\n el.scrollTop = el.scrollHeight;\n this.lastScrollTop = el.scrollTop;\n this.showDownBtn = false; // 滚动到底部后立刻隐藏箭头\n }\n });\n },\n scrollToBottomOnce() {\n // 清理旧定时器,防止任何泄漏\n clearTimeout(this._scrollTimer);\n this.$nextTick(() => {\n let retry = 0;\n const maxRetry = 6; // 重试6次,足够覆盖所有渲染延迟\n\n const tryScroll = () => {\n var _this$$refs;\n const el = (_this$$refs = this.$refs) === null || _this$$refs === void 0 ? void 0 : _this$$refs.messagesRef;\n if (!el) {\n this._scrollTimer = setTimeout(tryScroll, 50);\n return;\n }\n\n // 临时禁用平滑滚动,立即跳到底部\n const originalScrollBehavior = el.style.scrollBehavior;\n el.style.scrollBehavior = 'auto';\n el.scrollTop = el.scrollHeight - el.clientHeight;\n el.style.scrollBehavior = originalScrollBehavior;\n this.showDownBtn = false;\n };\n tryScroll();\n });\n }\n },\n beforeDestroy() {\n window.removeEventListener('resize', this.updateViewportState);\n if (window.visualViewport) {\n window.visualViewport.removeEventListener('resize', this.onViewportResize);\n }\n this.releaseAudio();\n this.contentCache = {};\n clearTimeout(this._scrollTimer);\n if (this.eventSource) {\n this.eventSource.onerror = null;\n this.eventSource.close();\n this.eventSource = null;\n }\n if (this.waitTimer) {\n clearInterval(this.waitTimer);\n this.waitTimer = null;\n }\n if (this._typeTimer) {\n clearInterval(this._typeTimer);\n this._typeTimer = null;\n }\n }\n};\n\n//# sourceURL=webpack://ZjPluginIntelligent/./src/lib/components/chatMain/index.vue?./node_modules/_cache-loader@4.1.0@cache-loader/dist/cjs.js??ref--13-0!./node_modules/_babel-loader@8.4.1@babel-loader/lib!./node_modules/_cache-loader@4.1.0@cache-loader/dist/cjs.js??ref--1-0!./node_modules/_vue-loader@15.11.1@vue-loader/lib??vue-loader-options");
|
|
943
943
|
|
|
944
944
|
/***/ }),
|
|
945
945
|
|
|
@@ -12448,7 +12448,7 @@ eval("module.exports = function(originalModule) {\n\tif (!originalModule.webpack
|
|
|
12448
12448
|
/*! exports provided: name, version, main, private, scripts, dependencies, devDependencies, browserslist, directories, keywords, license, default */
|
|
12449
12449
|
/***/ (function(module) {
|
|
12450
12450
|
|
|
12451
|
-
eval("module.exports = JSON.parse(\"{\\\"name\\\":\\\"zj-plugin-intelligent\\\",\\\"version\\\":\\\"1.2.5-beta.
|
|
12451
|
+
eval("module.exports = JSON.parse(\"{\\\"name\\\":\\\"zj-plugin-intelligent\\\",\\\"version\\\":\\\"1.2.5-beta.8\\\",\\\"main\\\":\\\"lib/ZjPluginIntelligent.umd.min.js\\\",\\\"private\\\":false,\\\"scripts\\\":{\\\"serve\\\":\\\"vue-cli-service serve\\\",\\\"build\\\":\\\"vue-cli-service build\\\",\\\"lib\\\":\\\"vue-cli-service build --target lib --name ZjPluginIntelligent --dest lib src/lib/index.js\\\",\\\"lib:test\\\":\\\"vue-cli-service build --mode test --target lib --name ZjPluginIntelligent --dest lib src/lib/index.js\\\"},\\\"dependencies\\\":{\\\"html2canvas\\\":\\\"^1.4.1\\\",\\\"markdown-it\\\":\\\"^14.1.0\\\"},\\\"devDependencies\\\":{\\\"@babel/preset-env\\\":\\\"^7.14.9\\\",\\\"@vue/cli-plugin-babel\\\":\\\"~4.5.0\\\",\\\"@vue/cli-plugin-eslint\\\":\\\"^4.5.13\\\",\\\"@vue/cli-plugin-vuex\\\":\\\"~4.5.0\\\",\\\"@vue/cli-service\\\":\\\"~4.5.0\\\",\\\"axios\\\":\\\"^0.27.2\\\",\\\"babel-eslint\\\":\\\"^10.1.0\\\",\\\"babel-plugin-component\\\":\\\"^1.1.1\\\",\\\"compression-webpack-plugin\\\":\\\"^6.0.3\\\",\\\"core-js\\\":\\\"^3.6.5\\\",\\\"element-ui\\\":\\\"^2.15.4\\\",\\\"eslint\\\":\\\"^7.30.0\\\",\\\"eslint-plugin-vue\\\":\\\"^7.13.0\\\",\\\"js-cookie\\\":\\\"^2.2.1\\\",\\\"node-sass\\\":\\\"^4.12.0\\\",\\\"obs-upload\\\":\\\"^1.0.4-alpha.0\\\",\\\"reconnecting-websocket\\\":\\\"^4.4.0\\\",\\\"sass-loader\\\":\\\"^8.0.2\\\",\\\"snowflake-id\\\":\\\"^1.1.0\\\",\\\"vue\\\":\\\"^2.6.11\\\",\\\"vue-template-compiler\\\":\\\"^2.6.11\\\",\\\"vuex\\\":\\\"^3.4.0\\\",\\\"pako\\\":\\\"^2.1.0\\\",\\\"webpack-bundle-analyzer\\\":\\\"^4.4.2\\\"},\\\"browserslist\\\":[\\\"> 1%\\\",\\\"last 2 versions\\\",\\\"not dead\\\"],\\\"directories\\\":{\\\"lib\\\":\\\"lib\\\"},\\\"keywords\\\":[],\\\"license\\\":\\\"ISC\\\"}\");\n\n//# sourceURL=webpack://ZjPluginIntelligent/./package.json?");
|
|
12452
12452
|
|
|
12453
12453
|
/***/ }),
|
|
12454
12454
|
|
|
@@ -948,7 +948,7 @@ eval("\n\nvar _interopRequireWildcard = __webpack_require__(/*! ./node_modules/_
|
|
|
948
948
|
/***/ (function(module, exports, __webpack_require__) {
|
|
949
949
|
|
|
950
950
|
"use strict";
|
|
951
|
-
eval("\n\nvar _interopRequireDefault = __webpack_require__(/*! ./node_modules/_@babel_runtime@7.28.4@@babel/runtime/helpers/interopRequireDefault.js */ \"./node_modules/_@babel_runtime@7.28.4@@babel/runtime/helpers/interopRequireDefault.js\").default;\nObject.defineProperty(exports, \"__esModule\", {\n value: true\n});\nexports.default = void 0;\n__webpack_require__(/*! core-js/modules/es.error.cause.js */ \"./node_modules/_core-js@3.45.1@core-js/modules/es.error.cause.js\");\n__webpack_require__(/*! core-js/modules/es.array.push.js */ \"./node_modules/_core-js@3.45.1@core-js/modules/es.array.push.js\");\n__webpack_require__(/*! core-js/modules/es.array-buffer.detached.js */ \"./node_modules/_core-js@3.45.1@core-js/modules/es.array-buffer.detached.js\");\n__webpack_require__(/*! core-js/modules/es.array-buffer.transfer.js */ \"./node_modules/_core-js@3.45.1@core-js/modules/es.array-buffer.transfer.js\");\n__webpack_require__(/*! core-js/modules/es.array-buffer.transfer-to-fixed-length.js */ \"./node_modules/_core-js@3.45.1@core-js/modules/es.array-buffer.transfer-to-fixed-length.js\");\n__webpack_require__(/*! core-js/modules/es.iterator.constructor.js */ \"./node_modules/_core-js@3.45.1@core-js/modules/es.iterator.constructor.js\");\n__webpack_require__(/*! core-js/modules/es.iterator.filter.js */ \"./node_modules/_core-js@3.45.1@core-js/modules/es.iterator.filter.js\");\n__webpack_require__(/*! core-js/modules/es.iterator.find.js */ \"./node_modules/_core-js@3.45.1@core-js/modules/es.iterator.find.js\");\n__webpack_require__(/*! core-js/modules/es.iterator.for-each.js */ \"./node_modules/_core-js@3.45.1@core-js/modules/es.iterator.for-each.js\");\n__webpack_require__(/*! core-js/modules/es.iterator.map.js */ \"./node_modules/_core-js@3.45.1@core-js/modules/es.iterator.map.js\");\n__webpack_require__(/*! core-js/modules/es.typed-array.at.js */ \"./node_modules/_core-js@3.45.1@core-js/modules/es.typed-array.at.js\");\n__webpack_require__(/*! core-js/modules/es.typed-array.find-last.js */ \"./node_modules/_core-js@3.45.1@core-js/modules/es.typed-array.find-last.js\");\n__webpack_require__(/*! core-js/modules/es.typed-array.find-last-index.js */ \"./node_modules/_core-js@3.45.1@core-js/modules/es.typed-array.find-last-index.js\");\n__webpack_require__(/*! core-js/modules/es.typed-array.set.js */ \"./node_modules/_core-js@3.45.1@core-js/modules/es.typed-array.set.js\");\n__webpack_require__(/*! core-js/modules/es.typed-array.to-reversed.js */ \"./node_modules/_core-js@3.45.1@core-js/modules/es.typed-array.to-reversed.js\");\n__webpack_require__(/*! core-js/modules/es.typed-array.to-sorted.js */ \"./node_modules/_core-js@3.45.1@core-js/modules/es.typed-array.to-sorted.js\");\n__webpack_require__(/*! core-js/modules/es.typed-array.with.js */ \"./node_modules/_core-js@3.45.1@core-js/modules/es.typed-array.with.js\");\nvar _apichat = __webpack_require__(/*! @lib/api/apichat */ \"./src/lib/api/apichat.js\");\nvar _markdownIt = _interopRequireDefault(__webpack_require__(/*! markdown-it */ \"./node_modules/_markdown-it@14.1.0@markdown-it/index.mjs\"));\nvar _html2canvas = _interopRequireDefault(__webpack_require__(/*! html2canvas */ \"./node_modules/_html2canvas@1.4.1@html2canvas/dist/html2canvas.js\"));\nvar _index = __webpack_require__(/*! @lib/socket/fileManager/obs/index */ \"./src/lib/socket/fileManager/obs/index.js\");\nvar _index2 = _interopRequireDefault(__webpack_require__(/*! @lib/socket/utils/index */ \"./src/lib/socket/utils/index.js\"));\nvar _cookie = __webpack_require__(/*! @lib/utils/cookie.js */ \"./src/lib/utils/cookie.js\");\nvar _apiObs = _interopRequireDefault(__webpack_require__(/*! @lib/api/apiObs */ \"./src/lib/api/apiObs.js\"));\nconst md = new _markdownIt.default({\n breaks: true,\n html: false,\n linkify: true,\n typographer: true\n});\nmd.enable('table');\nvar _default = exports.default = {\n name: 'ChatMain',\n props: {\n Ak: {\n type: String,\n default: ''\n },\n Sk: {\n type: String,\n default: ''\n },\n imAccount: {\n type: String,\n default: ''\n },\n companyNo: {\n type: String,\n default: ''\n },\n isIntelShow: {\n default: false,\n type: Boolean\n },\n chatImToken: {\n default: '',\n type: String\n }\n },\n data() {\n return {\n agentList: [],\n currentAgent: '',\n currentAgentDesc: '',\n sessionsLoaded: false,\n searchKeyword: '',\n agentSuggestions: [],\n showAgentSuggestions: false,\n sessionList: [],\n activeSessionId: '',\n messages: [],\n loadingMore: false,\n sending: false,\n waitTimer: null,\n waitSeconds: 0,\n canceling: false,\n msgPage: 1,\n msgMaxPage: 1,\n msgTotal: 0,\n inputText: '',\n eventSource: null,\n showToolInfo: false,\n showDownBtn: false,\n // 控制向下箭头显隐\n lastScrollTop: 0,\n scrollTimer: null,\n // 滚动防抖(新增)\n showAgentSelect: true,\n isMobile: false,\n showSidebar: false,\n showH5List: false,\n // H5列表模式(展示会话列表而非聊天详情)\n _scrollTimer: null,\n agentInfo: {},\n contentCache: {},\n // 流式分行缓存 key=msg._key\n loadingSessionMsg: false,\n // 会话消息加载中标记\n greeting: '',\n longPressTimer: null,\n longPressed: false,\n // H5 语音输入\n voiceMode: false,\n // true=语音模式,false=文字模式\n isRecording: false,\n // 是否正在录音\n recordDuration: 0,\n // 录音时长(秒)\n recordingTimer: null,\n // 时长计时器\n audioContext: null,\n // AudioContext 实例\n audioStream: null,\n // MediaStream(用于清理)\n audioProcessor: null,\n // ScriptProcessorNode\n audioChunks: [],\n // Float32Array 数据块\n isCancelSwipe: false,\n // 是否上滑取消\n recordStartY: 0 // 触摸起始Y坐标\n };\n },\n created() {\n if (this.Ak || this.Sk) {\n (0, _apichat.setApiAuth)(this.Ak, this.Sk, this.imAccount, this.companyNo, this.chatImToken);\n }\n this.loadAgents();\n this.loadSessions();\n },\n mounted() {\n this.updateViewportState();\n window.addEventListener('resize', this.updateViewportState, {\n passive: true\n });\n },\n computed: {\n waitClass() {\n if (this.waitSeconds > 15) return 'wait-15';\n if (this.waitSeconds > 10) return 'wait-10';\n if (this.waitSeconds > 5) return 'wait-5';\n return '';\n },\n filteredSessions() {\n if (!this.searchKeyword) return this.sessionList;\n const kw = this.searchKeyword.toLowerCase();\n return this.sessionList.filter(s => {\n const name = (s.agentName || s.agentCode || '').toLowerCase();\n return name.includes(kw);\n });\n },\n currentAgentName() {\n if (!this.currentAgent) return '';\n const a = this.agentList.find(x => x.agentCode === this.currentAgent);\n return a ? a.agentName || a.agentCode : this.currentAgent;\n }\n },\n watch: {\n searchKeyword(val) {\n if (this.searchTimer) clearTimeout(this.searchTimer);\n if (!val.trim()) {\n this.agentSuggestions = [];\n this.showAgentSuggestions = false;\n this.closeSidebar();\n return;\n }\n this.searchTimer = setTimeout(() => {\n (0, _apichat.getChatAgents)(val.trim()).then(list => {\n this.agentSuggestions = list || [];\n this.showAgentSuggestions = this.agentSuggestions.length > 0;\n }).catch(() => {\n this.agentSuggestions = [];\n });\n }, 300);\n }\n // ak: {\n // handler(newVal) {\n // setApiAuth(newVal, this.sk)\n // },\n // immediate: true\n // },\n // sk: {\n // handler(newVal) {\n // setApiAuth(this.ak, newVal)\n // },\n // immediate: true\n // }\n },\n methods: {\n updateViewportState() {\n if (typeof window === 'undefined') return;\n const nextIsMobile = window.innerWidth <= 768;\n const wasMobile = this.isMobile;\n this.isMobile = nextIsMobile;\n if (!nextIsMobile) {\n this.showSidebar = false;\n this.showH5List = false;\n } else if (!wasMobile && nextIsMobile) {\n // 从桌面端切换到H5:如果加载了会话列表且无活跃会话,展示列表页\n if (this.sessionList.length > 0 && !this.activeSessionId) {\n this.showH5List = true;\n this.showAgentSelect = false;\n }\n }\n },\n toggleSidebar() {\n if (!this.isMobile) return;\n this.showSidebar = !this.showSidebar;\n },\n closeSidebar() {\n this.showSidebar = false;\n },\n // H5:调用原生返回上一级\n handleNativeBack() {\n if (this.$hybrid && typeof this.$hybrid.closePage === 'function') {\n this.$hybrid.closePage();\n } else if (window.history.length > 1) {\n window.history.back();\n }\n },\n // H5侧边栏返回按钮\n handleSidebarBack() {\n this.handleNativeBack();\n },\n agentjumpclick() {\n if (this.sending) {\n this.$message.warning('AI正在生成内容,暂时请不要切换对话');\n return;\n }\n this.currentAgent = '';\n this.currentAgentDesc = '';\n this.searchKeyword = '';\n this.activeSessionId = '';\n this.agentSuggestions = [];\n this.messages = [];\n this.showAgentSuggestions = false;\n this.showAgentSelect = true;\n this.showH5List = false;\n this.closeSidebar();\n },\n // H5:从详情页返回列表页\n goBackToList() {\n if (this.sending) {\n this.$message.warning('AI正在生成内容,暂时请不要切换对话');\n return;\n }\n // 关闭流连接\n if (this.eventSource) {\n this.eventSource.close();\n this.eventSource = null;\n }\n this.sending = false;\n this.clearWaitTimer();\n this.activeSessionId = '';\n this.messages = [];\n this.currentAgent = '';\n this.currentAgentDesc = '';\n this.agentInfo = {};\n this.contentCache = {};\n\n // 始终返回列表页\n this.showH5List = true;\n this.showAgentSelect = false;\n this.closeSidebar();\n },\n sendQuickMsg(message) {\n if (message) {\n this.inputText = message;\n this.sendMessage();\n }\n },\n formatMixText(str) {\n if (!str) return '';\n // 1. 中文 <=> 英文/数字 之间加空格\n let res = str.replace(/([a-zA-Z0-9])([\\u4e00-\\u9fff])/g, '$1 $2').replace(/([\\u4e00-\\u9fff])([a-zA-Z0-9])/g, '$1 $2');\n // 2. 连续英文单词分片粘连修复:字母紧跟字母中间加空格\n // 匹配 小写+大写 驼峰、连续分片拼接成一坨的英文\n res = res.replace(/([a-z])([A-Z])/g, '$1 $2');\n return res;\n },\n // 获取右侧头像样式(根据当前智能体在左侧列表中的位置决定颜色)\n getChatAvatarStyle(agent, avatar) {\n if (avatar) {\n return {\n backgroundImage: `url(${avatar})`,\n backgroundSize: 'cover',\n backgroundPosition: 'center',\n backgroundRepeat: 'no-repeat'\n };\n }\n const _agent = this.agentList.find(x => x.agentCode === agent);\n // 如果有网络图片,返回背景图样式\n if (agent.avatar) {\n return {\n backgroundImage: `url(${agent.avatar})`,\n backgroundSize: 'cover',\n backgroundPosition: 'center',\n backgroundRepeat: 'no-repeat'\n };\n }\n\n // 没有网络图片时,根据智能体在 agentList 中的索引位置决定颜色\n if (this.sessionList) {\n // 找到当前智能体在列表中的索引\n const index = this.sessionList.findIndex(item => item.agentCode === agent);\n if (index !== -1) {\n // 根据索引计算颜色类(4色循环)\n const colorIndex = index % 4 + 1;\n return {\n background: this.getGradientByColorIndex(colorIndex)\n };\n }\n }\n\n // 默认返回蓝色渐变\n return {\n background: 'linear-gradient(135deg, #1677ff, #4096ff)'\n };\n },\n // 根据颜色索引获取对应的渐变色\n getGradientByColorIndex(index) {\n const gradients = {\n 1: 'linear-gradient(135deg, #1677ff, #4096ff)',\n 2: 'linear-gradient(135deg, #52c41a, #73d13d)',\n 3: 'linear-gradient(135deg, #fa8c16, #ffa940)',\n 4: 'linear-gradient(135deg, #722ed1, #b37feb)'\n };\n return gradients[index] || gradients[1];\n },\n selectAgent(agentItem) {\n this.showAgentSelect = false;\n this.currentAgent = agentItem.agentCode;\n this.currentAgentName = agentItem.agentName;\n // 查找历史会话\n const existSession = this.sessionList.find(s => s.agentCode === agentItem.agentCode);\n if (existSession) {\n this.activeSessionId = existSession.id;\n this.switchSession(existSession);\n } else {\n this.createNewSession(agentItem.agentCode);\n }\n },\n createNewSession(agentCode) {\n // 你原有新建会话逻辑\n },\n // 检测是否滚动到底部,控制向下箭头显示隐藏\n checkScrollBottom(forceShowWhenNotBottom = false) {\n const el = this.$refs.messagesRef;\n if (!el) {\n this.showDownBtn = false;\n return;\n }\n const {\n scrollHeight,\n scrollTop,\n clientHeight\n } = el;\n const remain = scrollHeight - scrollTop - clientHeight;\n const atBottom = remain <= 80;\n if (atBottom) {\n this.showDownBtn = false;\n } else if (this.sending && scrollTop >= this.lastScrollTop && !forceShowWhenNotBottom) {\n // 发送AI回答时,如果用户没有主动向上滚动,就不要显示下箭头闪烁\n this.showDownBtn = false;\n } else {\n this.showDownBtn = true;\n }\n this.lastScrollTop = scrollTop;\n },\n // 固定最小高度:单行不撑开,超出才增高\n // H5 输入框获取焦点 - 滚动到可见区域(避免键盘遮挡)\n onInputFocus() {\n if (!this.isMobile) return;\n // 等待键盘弹出后再滚动\n setTimeout(() => {\n const footer = this.$el.querySelector('.chat-footer');\n if (footer) footer.scrollIntoView({\n behavior: 'smooth',\n block: 'end'\n });\n }, 350);\n },\n autoResizeTextarea() {\n const ta = this.$refs.taRef;\n if (!ta) return;\n // 根据端适配基准高度和最大高度\n const isMobile = this.isMobile;\n const baseH = isMobile ? 36 : 100;\n const maxH = isMobile ? 100 : 180;\n ta.style.height = `${baseH}px`;\n // 内容真实高度\n const realH = ta.scrollHeight;\n // 只有内容高度>基准才撑开,否则保持初始高度\n if (realH > baseH) {\n ta.style.height = `${Math.min(realH, maxH)}px`;\n }\n this.$nextTick(() => {\n this.checkScrollBottom(true);\n });\n },\n // Shift+Enter换行\n newLine(e) {\n // 取消浏览器默认行为\n e.preventDefault();\n // 拿到光标位置\n const ta = this.$refs.taRef;\n const start = ta.selectionStart;\n const end = ta.selectionEnd;\n // 在光标处插入换行符\n this.inputText = this.inputText.slice(0, start) + '\\n' + this.inputText.slice(end);\n // 光标定位到换行后\n this.$nextTick(() => {\n ta.selectionStart = ta.selectionEnd = start + 1;\n // 自动调整输入框高度\n this.autoResizeTextarea();\n });\n },\n toggleVoiceMode() {\n this.voiceMode = !this.voiceMode;\n if (!this.voiceMode) {\n // 切回文字模式时释放音频设备\n this.releaseAudio();\n }\n },\n // 确保音频设备已就绪(只请求一次权限,缓存 stream / AudioContext)\n async ensureAudioReady() {\n if (this.audioContext && this.audioStream) return true;\n if (!navigator.mediaDevices || !navigator.mediaDevices.getUserMedia) {\n alert('当前环境不支持麦克风访问');\n return false;\n }\n try {\n const stream = await navigator.mediaDevices.getUserMedia({\n audio: true\n });\n this.audioStream = stream;\n const audioContext = new (window.AudioContext || window.webkitAudioContext)({\n sampleRate: 16000\n });\n this.audioContext = audioContext;\n const source = audioContext.createMediaStreamSource(stream);\n const processor = audioContext.createScriptProcessor(4096, 1, 1);\n this.audioProcessor = processor;\n processor.onaudioprocess = e => {\n if (!this.isRecording) return;\n const inputData = e.inputBuffer.getChannelData(0);\n this.audioChunks.push(new Float32Array(inputData));\n };\n source.connect(processor);\n processor.connect(audioContext.destination);\n return true;\n } catch (err) {\n console.error('麦克风访问失败:', err);\n alert('麦克风权限被拒绝');\n return false;\n }\n },\n // H5语音录制 - 触摸开始\n async onRecordTouchStart(e) {\n if (this.sending) return;\n\n // 先确保音频已就绪(首次会请求权限并建立音频管线,后续复用)\n const ready = await this.ensureAudioReady();\n if (!ready) return;\n\n // 重置录音状态\n this.isCancelSwipe = false;\n this.recordStartY = e.touches[0].clientY;\n this.recordDuration = 0;\n this.audioChunks = [];\n\n // 音频就绪后才标记录制中并启动计时\n this.isRecording = true;\n this.recordingTimer = setInterval(() => {\n this.recordDuration++;\n if (this.recordDuration >= 60) {\n this.onRecordTouchEnd();\n }\n }, 1000);\n },\n // H5语音录制 - 触摸移动(检测上滑取消)\n onRecordTouchMove(e) {\n if (!this.isRecording) return;\n const touch = e.touches[0];\n const moveY = touch.clientY;\n const cancelThreshold = 60; // 上滑60px进入取消区域\n this.isCancelSwipe = this.recordStartY - moveY > cancelThreshold;\n },\n // H5语音录制 - 触摸结束\n onRecordTouchEnd() {\n if (!this.isRecording) return;\n this.isRecording = false;\n if (this.recordingTimer) {\n clearInterval(this.recordingTimer);\n this.recordingTimer = null;\n }\n this.stopAudioCapture(!this.isCancelSwipe);\n },\n // 停止音频采集并输出 WAV(保留音频设备,下次复用)\n stopAudioCapture(shouldSend) {\n this.isRecording = false;\n if (shouldSend && this.audioChunks.length > 0) {\n const wavBlob = this.encodePCMToWav(this.audioChunks, 16000);\n this.sendAudioBlob(wavBlob);\n }\n this.audioChunks = [];\n },\n // 取消录音(保留音频设备,下次复用)\n cancelRecording() {\n this.isRecording = false;\n if (this.recordingTimer) {\n clearInterval(this.recordingTimer);\n this.recordingTimer = null;\n }\n this.recordDuration = 0;\n this.isCancelSwipe = false;\n this.audioChunks = [];\n },\n // 释放音频资源(切换回文字模式或组件销毁时调用)\n releaseAudio() {\n this.cancelRecording();\n if (this.audioProcessor) {\n this.audioProcessor.disconnect();\n this.audioProcessor = null;\n }\n if (this.audioContext) {\n this.audioContext.close().catch(() => {});\n this.audioContext = null;\n }\n if (this.audioStream) {\n this.audioStream.getTracks().forEach(t => t.stop());\n this.audioStream = null;\n }\n },\n // 将 Float32 PCM 数据编码为 WAV Blob\n encodePCMToWav(chunks, sampleRate) {\n // 计算总采样数\n let totalLength = 0;\n for (const chunk of chunks) {\n totalLength += chunk.length;\n }\n\n // 转换为 Int16 PCM\n const pcmData = new Int16Array(totalLength);\n let offset = 0;\n for (const chunk of chunks) {\n for (let i = 0; i < chunk.length; i++) {\n const s = Math.max(-1, Math.min(1, chunk[i]));\n pcmData[offset++] = s < 0 ? s * 0x8000 : s * 0x7FFF;\n }\n }\n const numChannels = 1;\n const bitsPerSample = 16;\n const byteRate = sampleRate * numChannels * bitsPerSample / 8;\n const blockAlign = numChannels * bitsPerSample / 8;\n const dataSize = pcmData.length * (bitsPerSample / 8);\n const headerSize = 44;\n const totalSize = headerSize + dataSize;\n const buffer = new ArrayBuffer(totalSize);\n const view = new DataView(buffer);\n\n // RIFF header\n this._wavWriteString(view, 0, 'RIFF');\n view.setUint32(4, totalSize - 8, true);\n this._wavWriteString(view, 8, 'WAVE');\n\n // fmt chunk\n this._wavWriteString(view, 12, 'fmt ');\n view.setUint32(16, 16, true); // chunk size\n view.setUint16(20, 1, true); // PCM format\n view.setUint16(22, numChannels, true); // 单声道\n view.setUint32(24, sampleRate, true); // 采样率\n view.setUint32(28, byteRate, true);\n view.setUint16(32, blockAlign, true);\n view.setUint16(34, bitsPerSample, true);\n\n // data chunk\n this._wavWriteString(view, 36, 'data');\n view.setUint32(40, dataSize, true);\n\n // 写入 PCM 数据\n const pcmView = new Int16Array(buffer, headerSize, pcmData.length);\n pcmView.set(pcmData);\n return new Blob([buffer], {\n type: 'audio/wav'\n });\n },\n _wavWriteString(view, offset, str) {\n for (let i = 0; i < str.length; i++) {\n view.setUint8(offset + i, str.charCodeAt(i));\n }\n },\n // 发送音频\n sendAudioBlob(blob) {\n let appSeqId = _index2.default.getAppSeqId();\n let name = appSeqId + '.wav';\n const file = new File([blob], name, {\n type: 'audio/wav'\n });\n // TODO: 上传音频文件并调用 STT 接口\n this.sendAudioMessage(file);\n },\n sendAudioMessage(file) {\n // 插入本地 pending 消息\n const sttKey = 'stt_' + Date.now();\n const sttMsg = {\n role: 'user',\n content: '转化中...',\n _sttStatus: 'pending',\n _sttKey: sttKey,\n createTime: new Date().toISOString(),\n _key: sttKey\n };\n this.messages.push(sttMsg);\n this.scrollToBottom(true);\n (0, _index.fileUploadToObs)({\n _file: file,\n appSeqId: file.name\n }).then(resp => {\n if (resp.CommonMsg.Status === 200) {\n // 调用语音转文字接口\n return _apiObs.default.aliAudioToText({\n url: resp.obs_upload_data.obsUrl\n }).then(result => {\n if (result.code === '200' && result.data) {\n // 成功:删除 pending 消息,发送给后端\n const idx = this.messages.findIndex(m => m._sttKey === sttKey);\n if (idx !== -1) {\n this.messages.splice(idx, 1);\n }\n this.sendQuickMsg(result.data);\n } else {\n throw new Error(result.msg || '语音转文字失败');\n }\n });\n } else {\n throw new Error(resp.CommonMsg.Message || '文件上传失败');\n }\n }).catch(err => {\n console.error('语音转文字失败:', err);\n // 失败:更新为错误状态\n const idx = this.messages.findIndex(m => m._sttKey === sttKey);\n if (idx !== -1) {\n this.$set(this.messages, idx, {\n ...this.messages[idx],\n _sttStatus: 'error',\n content: '语音转文字失败'\n });\n }\n this.$message.error('语音转文字失败');\n });\n this.$message.success(`录音完成 (${this.recordDuration}s)`);\n },\n clearWaitTimer() {\n if (this.waitTimer) {\n clearInterval(this.waitTimer);\n this.waitTimer = null;\n }\n },\n loadAgents() {\n (0, _apichat.getChatAgents)().then(list => {\n this.agentList = list || [];\n // if (this.agentList.length > 0 && !this.currentAgent) {\n // const first = this.agentList[0]\n // this.currentAgent = first.agentCode\n // this.currentAgentDesc = first.description || ''\n // }\n }).catch(() => {});\n },\n loadSessions() {\n (0, _apichat.getSessionList)().then(list => {\n if (!this.activeSessionId) {\n this.sessionList = list || [];\n if (this.sessionList.length > 0) {\n if (this.isMobile) {\n // H5模式:不自动选中会话,展示列表页\n this.showAgentSelect = false;\n this.showH5List = true;\n this.showSidebar = false;\n } else {\n this.switchSession(this.sessionList[0]);\n }\n }\n if (this.sessionList.length === 0) {\n this.showAgentSelect = true;\n this.showH5List = false;\n }\n } else {\n this.sessionList = list || [];\n let _item = list.find(res => res.sessionId == this.activeSessionId);\n try {\n if (_item.suggestedQuestions) {\n _item.suggestedQuestions = JSON.parse(_item.suggestedQuestions);\n } else {\n _item.suggestedQuestions = [];\n }\n _item && (this.agentInfo = _item);\n } catch (err) {\n // JSON格式错误兜底空数组,防止页面报错\n this.agentInfo.questionArr = [];\n console.warn('快捷提问解析失败', err);\n }\n }\n }).catch(() => {});\n },\n onSearchClear() {\n this.agentSuggestions = [];\n this.showAgentSuggestions = false;\n },\n startChatWithAgent(agent) {\n console.log('选择了助手', agent.agentCode, this.currentAgent);\n if (agent.agentCode == this.currentAgent) {\n this.searchKeyword = '';\n this.agentSuggestions = [];\n this.showAgentSuggestions = false;\n return;\n }\n this.currentAgent = agent.agentCode;\n this.currentAgentDesc = agent.description || '';\n this.searchKeyword = '';\n this.agentInfo = {};\n this.agentSuggestions = [];\n this.messages = [];\n this.showAgentSuggestions = false;\n this.showAgentSelect = false;\n this.closeSidebar();\n if (this.isMobile) {\n this.showH5List = false; // H5:进入详情页,隐藏列表\n }\n const existing = this.sessionList.find(s => s.agentCode === agent.agentCode);\n if (existing) {\n this.switchSession(existing);\n } else {\n this.handleNewSession();\n }\n },\n handleNewSession() {\n if (!this.currentAgent) return;\n if (this.activeSessionId) this.closeOldSession();\n (0, _apichat.startSession)(this.currentAgent).then(res => {\n console.log(res, 'startChatWithAgentstartChatWithAgentstartChatWithAgent', this.agentInfo);\n this.activeSessionId = res.sessionId || '';\n this.loadSessions();\n const agent = this.agentList.find(a => a.agentCode === this.currentAgent);\n if (agent) this.addWelcomeMessage(agent);\n }).catch(() => {});\n },\n // H5长按删除 - 触摸开始\n onSessionTouchStart(s, e) {\n if (!this.isMobile) return;\n this.longPressed = false;\n this.longPressTimer = setTimeout(() => {\n this.longPressed = true;\n this.handleDeleteSession(s);\n }, 600);\n },\n // H5长按删除 - 触摸结束/移动(取消长按)\n onSessionTouchEnd() {\n if (this.longPressTimer) {\n clearTimeout(this.longPressTimer);\n this.longPressTimer = null;\n }\n },\n onSessionTouchMove() {\n if (this.longPressTimer) {\n clearTimeout(this.longPressTimer);\n this.longPressTimer = null;\n }\n },\n async switchSession(s) {\n if (this.longPressed) {\n this.longPressed = false;\n return;\n }\n if (this.sending) {\n this.$message.warning('AI正在生成内容,暂时请不要切换对话');\n return;\n }\n this.showAgentSelect = false;\n this.closeSidebar();\n if (this.isMobile) {\n this.showH5List = false; // H5:进入详情页,隐藏列表\n }\n if (this.activeSessionId === s.sessionId) return;\n this.contentCache = {};\n this.activeSessionId = s.sessionId;\n this.currentAgent = s.agentCode;\n console.log('进入');\n this.agentInfo = s;\n console.log('进入', this.agentInfo);\n try {\n if (s.suggestedQuestions) {\n this.agentInfo.suggestedQuestions = JSON.parse(s.suggestedQuestions);\n } else {\n this.agentInfo.suggestedQuestions = [];\n }\n } catch (err) {\n // JSON格式错误兜底空数组,防止页面报错\n this.agentInfo.questionArr = [];\n console.warn('快捷提问解析失败', err);\n }\n const agent = this.agentList.find(a => a.agentCode === s.agentCode);\n this.currentAgentDesc = agent ? agent.description || '' : '';\n this.msgPage = 1;\n this.msgTotal = 0;\n this.messages = []; // 先清空,但开启加载锁屏蔽空白页\n this.loadingSessionMsg = true; // 开启加载标记\n (0, _apichat.syncToken)((0, _cookie.getToken)(), s.sessionId);\n try {\n const res = await (0, _apichat.getSessionMessages)(s.sessionId, 1, 10);\n const list = Array.isArray(res) ? res : res.list || [];\n this.msgTotal = res.total || list.length;\n this.msgPage = 1;\n const asAsc = (list || []).slice().reverse();\n this.messages = asAsc.map(m => ({\n role: m.role,\n content: m.content || '',\n thinking: m.thinking || '',\n toolCalls: [],\n agentName: m.role === 'assistant' ? s.agentName || '' : '',\n createTime: m.createTime || null,\n _key: m.createTime ? 'msg_' + m.createTime : 'msg_' + Date.now() + '_' + Math.random()\n }));\n if (this.messages.length === 0 && agent) this.addWelcomeMessage(agent);\n await this.$nextTick();\n this.$nextTick(() => {\n this.scrollToBottomOnce();\n this.checkScrollBottom();\n });\n } catch (e) {\n this.messages = [];\n } finally {\n // 无论成功失败,结束后关闭加载锁\n this.loadingSessionMsg = false;\n }\n },\n loadMoreMessages() {\n const nextPage = this.msgPage + 1;\n const maxPage = Math.ceil(this.msgTotal / 10);\n if (nextPage > maxPage) {\n this.loadingMore = false;\n return;\n }\n (0, _apichat.getSessionMessages)(this.activeSessionId, nextPage, 10).then(res => {\n const list = Array.isArray(res) ? res : res.list || [];\n this.msgPage = nextPage;\n const asAsc = (list || []).slice().reverse();\n const prepend = asAsc.map(m => ({\n role: m.role,\n content: m.content || '',\n thinking: m.thinking || '',\n toolCalls: [],\n agentName: '',\n createTime: m.createTime || null,\n _key: m.createTime ? 'msg_' + m.createTime : 'msg_' + Date.now() + '_' + Math.random()\n }));\n const container = this.$refs.messagesRef;\n const oldScrollHeight = container ? container.scrollHeight : 0;\n const oldScrollTop = container ? container.scrollTop : 0;\n this.messages = [...prepend, ...this.messages];\n this.$nextTick(() => {\n if (container) {\n container.scrollTop = oldScrollTop + (container.scrollHeight - oldScrollHeight);\n }\n this.loadingMore = false;\n });\n }).catch(() => {\n this.loadingMore = false;\n });\n },\n onScrollMessages() {\n const container = this.$refs.messagesRef;\n if (!container || this.loadingMore) return;\n const isAtBottom = container.scrollTop + container.clientHeight >= container.scrollHeight - 100;\n this.checkScrollBottom();\n if (isAtBottom) return;\n if (container.scrollTop < 50 && this.msgPage < Math.ceil(this.msgTotal / 10)) {\n this.loadingMore = true;\n this.loadMoreMessages();\n }\n },\n handleDeleteSession(s) {\n this.$confirm(`确认删除「${s.agentName || s.agentCode}」的会话?`, '提示', {\n type: 'warning'\n }).then(() => {\n (0, _apichat.deleteSession)(s.sessionId).then(() => {\n if (this.activeSessionId === s.sessionId) {\n this.activeSessionId = '';\n this.messages = [];\n this.currentAgent = '';\n this.currentAgentDesc = '';\n if (this.isMobile) {\n this.showH5List = false;\n this.showAgentSelect = true;\n } else {\n this.showAgentSelect = true;\n }\n }\n this.loadSessions();\n });\n }).catch(() => {});\n },\n closeOldSession() {},\n onAgentChange(code) {\n const agent = this.agentList.find(a => a.agentCode === code);\n this.currentAgentDesc = agent ? agent.description || '' : '';\n this.handleNewSession();\n },\n addWelcomeMessage(agent) {\n this.greeting = '';\n // if (!agent) return\n // const name = agent.agentName || '助手';\n const _agent = this.agentList.find(x => x.agentCode === this.currentAgent);\n this.greeting = _agent.greeting || `很高兴为您服务,请问有什么可以帮到您?`;\n // this.messages.push({\n // role: 'assistant',\n // content: _content,\n // thinking: '',\n // agentName: name,\n // _key: 'welcome_' + Date.now()\n // })\n },\n async sendMessage() {\n const text = this.inputText.trim();\n if (!text || this.sending) return;\n if (!this.activeSessionId) {\n await (0, _apichat.startSession)(this.currentAgent).then(res => {\n this.activeSessionId = res.sessionId || '';\n this.loadSessions();\n });\n if (!this.activeSessionId) return;\n }\n this.inputText = '';\n const ta = this.$refs.taRef;\n const isMobile = this.isMobile;\n const baseH = isMobile ? 36 : 100;\n if (ta) {\n ta.style.height = baseH + 'px'; // 强制恢复初始高度\n }\n this.showDownBtn = false;\n this.messages.push({\n role: 'user',\n content: text,\n createTime: new Date().toISOString(),\n _key: 'user_' + Date.now() + '_' + Math.random()\n });\n const agentName = this.currentAgentName;\n const msgIdx = this.messages.push({\n role: \"assistant\",\n content: \"\",\n thinking: \"\",\n loading: true,\n toolCalls: [],\n agentName,\n createTime: new Date().toISOString(),\n _key: 'asst_' + Date.now() + '_' + Math.random()\n }) - 1;\n this.scrollToBottom(true);\n this.sending = true;\n this.waitSeconds = 0;\n if (this.waitTimer) clearInterval(this.waitTimer);\n this.waitTimer = setInterval(() => {\n this.waitSeconds++;\n }, 1000);\n let thinkingBuffer = '';\n let finalContent = '';\n let answerBuffer = '';\n let thinkDisplayed = 0;\n let typeTimer = null;\n typeTimer = setInterval(() => {\n if (!this.messages[msgIdx]) return;\n if (thinkDisplayed < thinkingBuffer.length) {\n thinkDisplayed += 50;\n if (thinkDisplayed > thinkingBuffer.length) thinkDisplayed = thinkingBuffer.length;\n this.messages[msgIdx].thinking = thinkingBuffer.substring(0, thinkDisplayed);\n this.scrollToBottom();\n } else if (finalContent && !this.messages[msgIdx].content) {\n clearInterval(typeTimer);\n const key = this.messages[msgIdx]._key;\n if (key) {\n this.$delete(this.contentCache, key);\n this.$delete(this.contentCache, key + '_t');\n }\n typeTimer = null;\n this.messages[msgIdx].content = finalContent;\n this.messages[msgIdx].thinking = thinkingBuffer;\n this.messages[msgIdx].loading = false;\n this.sending = false;\n this.clearWaitTimer();\n this.scrollToBottom();\n this.loadSessions();\n }\n }, 30);\n const url = (0, _apichat.createStreamUrl)(this.activeSessionId, text);\n if (this.eventSource) {\n this.eventSource.close();\n }\n this.eventSource = new EventSource(url);\n const es = this.eventSource;\n es.addEventListener('reasoning', e => {\n if (e.data) {\n const chunk = e.data;\n // 1. 先处理当前分片内部的中英文、数字、标点空格\n let cleanChunk = chunk.replace(/([a-z])([A-Z])/g, '$1 $2').replace(/([A-Z]+)([A-Z][a-z])/g, '$1 $2').replace(/([a-zA-Z])([\\u4e00-\\u9fff])/g, '$1 $2').replace(/([\\u4e00-\\u9fff])([a-zA-Z])/g, '$1 $2').replace(/([a-zA-Z])(\\d)/g, '$1 $2').replace(/(\\d)([a-zA-Z])/g, '$1 $2').replace(/\\s+([:,.!?])/g, '$1').replace(/([:,.!?])\\s+/g, '$1 ');\n cleanChunk = cleanChunk.replace(/\\s+/g, ' ');\n\n // 2. 关键:判断前一段末尾 + 当前段开头都是英文,补空格分隔\n const lastChar = thinkingBuffer.slice(-1);\n const firstChar = cleanChunk.slice(0, 1);\n const isLetter = c => /[a-zA-Z]/.test(c);\n if (isLetter(lastChar) && isLetter(firstChar)) {\n // 两段都是英文衔接,中间加空格\n thinkingBuffer += ' ' + cleanChunk;\n } else {\n thinkingBuffer += cleanChunk;\n }\n }\n });\n es.addEventListener('reasoning_result', e => {\n if (e.data) {\n thinkingBuffer = e.data;\n }\n });\n es.addEventListener('answer', e => {\n if (e.data) {\n answerBuffer += e.data;\n if (this.messages[msgIdx]) {\n this.messages[msgIdx].content += e.data.replace(/([a-zA-Z]+)([\\u4e00-\\u9fff])/g, '$1 $2').replace(/([\\u4e00-\\u9fff])([a-zA-Z]+)/g, '$1 $2').replace(/([a-z])([A-Z])/g, '$1 $2').replace(/([A-Z]+)([A-Z][a-z])/g, '$1 $2').replace(/([a-zA-Z])(\\d)/g, '$1 $2').replace(/(\\d)([a-zA-Z])/g, '$1 $2');\n this.scrollToBottom();\n }\n }\n });\n es.addEventListener('tool_result', e => {\n if (e.data && this.messages[msgIdx]) {\n if (!this.messages[msgIdx].toolCalls) this.messages[msgIdx].toolCalls = [];\n this.messages[msgIdx].toolCalls.push(e.data);\n this.scrollToBottom();\n }\n });\n es.addEventListener('agent_result', e => {\n finalContent = e.data || '';\n es.close();\n this.eventSource = null;\n if (this.messages[msgIdx]) {\n const key = this.messages[msgIdx]._key;\n if (key) this.$delete(this.contentCache, key);\n this.messages[msgIdx].content = finalContent;\n this.messages[msgIdx].thinking = thinkingBuffer;\n this.messages[msgIdx].loading = false;\n }\n this.sending = false;\n this.clearWaitTimer();\n if (typeTimer) {\n clearInterval(typeTimer);\n typeTimer = null;\n }\n this.scrollToBottom();\n this.loadSessions();\n });\n es.onerror = err => {\n console.log('[SSE] onerror', err);\n if (thinkingBuffer.length > 0 && !finalContent) finalContent = thinkingBuffer;\n if (!finalContent) finalContent = '❌ 连接中断';\n es.close();\n this.eventSource = null;\n if (this.messages[msgIdx]) {\n const key = this.messages[msgIdx]._key;\n if (key) this.$delete(this.contentCache, key);\n this.messages[msgIdx].content = finalContent;\n this.messages[msgIdx].thinking = thinkingBuffer;\n this.messages[msgIdx].loading = false;\n }\n this.sending = false;\n this.clearWaitTimer();\n if (typeTimer) {\n clearInterval(typeTimer);\n typeTimer = null;\n }\n this.scrollToBottom();\n };\n },\n stopAgent() {\n if (this.eventSource) {\n this.eventSource.close();\n this.eventSource = null;\n }\n if (this.activeSessionId) {\n (0, _apichat.stopStream)(this.activeSessionId).catch(() => {});\n }\n if (this.messages.length > 0) {\n const last = this.messages[this.messages.length - 1];\n if (last && last.loading) {\n last.content = last.content || last.thinking || '⏹ 已停止';\n last.loading = false;\n this.$delete(this.contentCache, last._key);\n }\n }\n this.sending = false;\n this.clearWaitTimer();\n },\n copyText(content) {\n if (!content) return;\n navigator.clipboard.writeText(content.replace(/<[^>]+>/g, '')).then(() => {\n this.$message({\n message: '已复制到剪贴板',\n type: 'success',\n duration: 1500\n });\n }).catch(() => {\n this.$message({\n message: '复制失败',\n type: 'error',\n duration: 2000\n });\n });\n },\n copyAsImage(content) {\n if (!content) return;\n // 创建临时容器渲染 Markdown\n const div = document.createElement('div');\n div.className = 'copy-image-render';\n div.style.cssText = 'position:fixed;left:-9999px;top:0;width:600px;padding:20px;background:#fff;font-size:14px;line-height:1.6;color:#333;border-radius:8px;font-family:-apple-system,BlinkMacSystemFont,sans-serif;';\n div.innerHTML = this.renderMarkdown(content);\n document.body.appendChild(div);\n this.$message({\n message: '正在生成图片...',\n type: 'info',\n duration: 2000\n });\n (0, _html2canvas.default)(div, {\n scale: 2,\n useCORS: true,\n backgroundColor: '#ffffff'\n }).then(canvas => {\n canvas.toBlob(blob => {\n if (blob) {\n navigator.clipboard.write([new ClipboardItem({\n 'image/png': blob\n })]).then(() => {\n this.$message({\n message: '图片已复制到剪贴板',\n type: 'success',\n duration: 1500\n });\n }).catch(() => {\n this.$message({\n message: '复制图片失败',\n type: 'error',\n duration: 2000\n });\n });\n }\n }, 'image/png');\n }).catch(() => {\n this.$message({\n message: '生成图片失败',\n type: 'error',\n duration: 2000\n });\n }).finally(() => {\n document.body.removeChild(div);\n });\n },\n formatTime(t) {\n if (!t) return '';\n const d = new Date(t.replace(' ', 'T'));\n const now = new Date();\n const diff = (now - d) / 1000;\n if (diff < 60) return '刚刚';\n if (diff < 3600) return Math.floor(diff / 60) + '分钟前';\n if (diff < 86400) return Math.floor(diff / 3600) + '小时前';\n return d.getMonth() + 1 + '/' + d.getDate();\n },\n getInitial(name) {\n if (!name) return '?';\n return name.charAt(0);\n },\n renderMarkdown(text) {\n if (!text) return '';\n try {\n return md.render(text);\n } catch (err) {\n return this.escapeHtml(text);\n }\n },\n renderStreaming(text, msgKey) {\n if (!text) return '';\n console.log('进入');\n const cache = this.contentCache[msgKey];\n const lines = text.split('\\n');\n const lastLineIdx = lines.length - 1;\n if (!cache) {\n try {\n const html = md.render(text);\n this.$set(this.contentCache, msgKey, {\n renderedLines: lastLineIdx,\n html,\n fullText: text\n });\n return html;\n } catch {\n return this.escapeHtml(text);\n }\n }\n if (text === cache.fullText) return cache.html;\n cache.fullText = text;\n\n // 行数没变,仅末尾追加字符,直接拼接尾行(原有逻辑不变)\n if (lastLineIdx === cache.renderedLines) {\n return cache.html + this.escapeHtml(lines[lastLineIdx]);\n }\n\n // 场景1:行数变少/文本回退截断,全量重渲染(原有分支保留,内部修复)\n if (lastLineIdx < cache.renderedLines) {\n try {\n // 重新截取所有完整行生成全新基础html,清空旧叠加内容\n const fullLines = lines.slice(0, lastLineIdx);\n let newBaseHtml = '';\n if (fullLines.length > 0) {\n newBaseHtml = md.render(fullLines.join('\\n'));\n }\n cache.html = newBaseHtml;\n cache.renderedLines = lastLineIdx;\n // 拼接尾行\n const lastLine = this.escapeHtml(lines[lastLineIdx]);\n return cache.html + (lastLine || '');\n } catch {\n return this.escapeHtml(text);\n }\n }\n\n // 场景2:新增完整行,修复:不再累加旧html,重新从0生成完整行基础\n if (cache.renderedLines < lastLineIdx) {\n // 关键修复:重新切片所有完整行,抛弃之前叠加的旧html,杜绝重复\n const allFullLines = lines.slice(0, lastLineIdx);\n let newBaseHtml = '';\n if (allFullLines.length > 0) {\n newBaseHtml = md.render(allFullLines.join('\\n'));\n }\n cache.html = newBaseHtml;\n cache.renderedLines = lastLineIdx;\n }\n const lastLine = this.escapeHtml(lines[lastLineIdx]);\n cache.renderedLines = lastLineIdx;\n return cache.html + (lastLine || '');\n },\n escapeHtml(text) {\n if (!text) return '';\n return text.replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>');\n },\n scrollToTop() {\n const el = this.$refs.messagesRef;\n if (el) el.scrollTop = 0;\n },\n scrollToBottom(force = false) {\n if (this.showDownBtn && !force) return;\n this.$nextTick(() => {\n const el = this.$refs.messagesRef;\n if (el) {\n el.scrollTop = el.scrollHeight;\n this.lastScrollTop = el.scrollTop;\n this.showDownBtn = false; // 滚动到底部后立刻隐藏箭头\n }\n });\n },\n scrollToBottomOnce() {\n // 清理旧定时器,防止任何泄漏\n clearTimeout(this._scrollTimer);\n this.$nextTick(() => {\n let retry = 0;\n const maxRetry = 6; // 重试6次,足够覆盖所有渲染延迟\n\n const tryScroll = () => {\n var _this$$refs;\n const el = (_this$$refs = this.$refs) === null || _this$$refs === void 0 ? void 0 : _this$$refs.messagesRef;\n if (!el) {\n this._scrollTimer = setTimeout(tryScroll, 50);\n return;\n }\n\n // 临时禁用平滑滚动,立即跳到底部\n const originalScrollBehavior = el.style.scrollBehavior;\n el.style.scrollBehavior = 'auto';\n el.scrollTop = el.scrollHeight - el.clientHeight;\n el.style.scrollBehavior = originalScrollBehavior;\n this.showDownBtn = false;\n };\n tryScroll();\n });\n }\n },\n beforeDestroy() {\n window.removeEventListener('resize', this.updateViewportState);\n this.releaseAudio();\n this.contentCache = {};\n clearTimeout(this._scrollTimer);\n if (this.eventSource) {\n this.eventSource.onerror = null;\n this.eventSource.close();\n this.eventSource = null;\n }\n if (this.waitTimer) {\n clearInterval(this.waitTimer);\n this.waitTimer = null;\n }\n if (this._typeTimer) {\n clearInterval(this._typeTimer);\n this._typeTimer = null;\n }\n }\n};\n\n//# sourceURL=webpack://ZjPluginIntelligent/./src/lib/components/chatMain/index.vue?./node_modules/_cache-loader@4.1.0@cache-loader/dist/cjs.js??ref--13-0!./node_modules/_babel-loader@8.4.1@babel-loader/lib!./node_modules/_cache-loader@4.1.0@cache-loader/dist/cjs.js??ref--1-0!./node_modules/_vue-loader@15.11.1@vue-loader/lib??vue-loader-options");
|
|
951
|
+
eval("\n\nvar _interopRequireDefault = __webpack_require__(/*! ./node_modules/_@babel_runtime@7.28.4@@babel/runtime/helpers/interopRequireDefault.js */ \"./node_modules/_@babel_runtime@7.28.4@@babel/runtime/helpers/interopRequireDefault.js\").default;\nObject.defineProperty(exports, \"__esModule\", {\n value: true\n});\nexports.default = void 0;\n__webpack_require__(/*! core-js/modules/es.error.cause.js */ \"./node_modules/_core-js@3.45.1@core-js/modules/es.error.cause.js\");\n__webpack_require__(/*! core-js/modules/es.array.push.js */ \"./node_modules/_core-js@3.45.1@core-js/modules/es.array.push.js\");\n__webpack_require__(/*! core-js/modules/es.array-buffer.detached.js */ \"./node_modules/_core-js@3.45.1@core-js/modules/es.array-buffer.detached.js\");\n__webpack_require__(/*! core-js/modules/es.array-buffer.transfer.js */ \"./node_modules/_core-js@3.45.1@core-js/modules/es.array-buffer.transfer.js\");\n__webpack_require__(/*! core-js/modules/es.array-buffer.transfer-to-fixed-length.js */ \"./node_modules/_core-js@3.45.1@core-js/modules/es.array-buffer.transfer-to-fixed-length.js\");\n__webpack_require__(/*! core-js/modules/es.iterator.constructor.js */ \"./node_modules/_core-js@3.45.1@core-js/modules/es.iterator.constructor.js\");\n__webpack_require__(/*! core-js/modules/es.iterator.filter.js */ \"./node_modules/_core-js@3.45.1@core-js/modules/es.iterator.filter.js\");\n__webpack_require__(/*! core-js/modules/es.iterator.find.js */ \"./node_modules/_core-js@3.45.1@core-js/modules/es.iterator.find.js\");\n__webpack_require__(/*! core-js/modules/es.iterator.for-each.js */ \"./node_modules/_core-js@3.45.1@core-js/modules/es.iterator.for-each.js\");\n__webpack_require__(/*! core-js/modules/es.iterator.map.js */ \"./node_modules/_core-js@3.45.1@core-js/modules/es.iterator.map.js\");\n__webpack_require__(/*! core-js/modules/es.typed-array.at.js */ \"./node_modules/_core-js@3.45.1@core-js/modules/es.typed-array.at.js\");\n__webpack_require__(/*! core-js/modules/es.typed-array.find-last.js */ \"./node_modules/_core-js@3.45.1@core-js/modules/es.typed-array.find-last.js\");\n__webpack_require__(/*! core-js/modules/es.typed-array.find-last-index.js */ \"./node_modules/_core-js@3.45.1@core-js/modules/es.typed-array.find-last-index.js\");\n__webpack_require__(/*! core-js/modules/es.typed-array.set.js */ \"./node_modules/_core-js@3.45.1@core-js/modules/es.typed-array.set.js\");\n__webpack_require__(/*! core-js/modules/es.typed-array.to-reversed.js */ \"./node_modules/_core-js@3.45.1@core-js/modules/es.typed-array.to-reversed.js\");\n__webpack_require__(/*! core-js/modules/es.typed-array.to-sorted.js */ \"./node_modules/_core-js@3.45.1@core-js/modules/es.typed-array.to-sorted.js\");\n__webpack_require__(/*! core-js/modules/es.typed-array.with.js */ \"./node_modules/_core-js@3.45.1@core-js/modules/es.typed-array.with.js\");\nvar _apichat = __webpack_require__(/*! @lib/api/apichat */ \"./src/lib/api/apichat.js\");\nvar _markdownIt = _interopRequireDefault(__webpack_require__(/*! markdown-it */ \"./node_modules/_markdown-it@14.1.0@markdown-it/index.mjs\"));\nvar _html2canvas = _interopRequireDefault(__webpack_require__(/*! html2canvas */ \"./node_modules/_html2canvas@1.4.1@html2canvas/dist/html2canvas.js\"));\nvar _index = __webpack_require__(/*! @lib/socket/fileManager/obs/index */ \"./src/lib/socket/fileManager/obs/index.js\");\nvar _index2 = _interopRequireDefault(__webpack_require__(/*! @lib/socket/utils/index */ \"./src/lib/socket/utils/index.js\"));\nvar _cookie = __webpack_require__(/*! @lib/utils/cookie.js */ \"./src/lib/utils/cookie.js\");\nvar _apiObs = _interopRequireDefault(__webpack_require__(/*! @lib/api/apiObs */ \"./src/lib/api/apiObs.js\"));\nconst md = new _markdownIt.default({\n breaks: true,\n html: false,\n linkify: true,\n typographer: true\n});\nmd.enable('table');\nvar _default = exports.default = {\n name: 'ChatMain',\n props: {\n Ak: {\n type: String,\n default: ''\n },\n Sk: {\n type: String,\n default: ''\n },\n imAccount: {\n type: String,\n default: ''\n },\n companyNo: {\n type: String,\n default: ''\n },\n isIntelShow: {\n default: false,\n type: Boolean\n },\n chatImToken: {\n default: '',\n type: String\n }\n },\n data() {\n return {\n agentList: [],\n currentAgent: '',\n currentAgentDesc: '',\n sessionsLoaded: false,\n searchKeyword: '',\n agentSuggestions: [],\n showAgentSuggestions: false,\n sessionList: [],\n activeSessionId: '',\n messages: [],\n loadingMore: false,\n sending: false,\n waitTimer: null,\n waitSeconds: 0,\n canceling: false,\n msgPage: 1,\n msgMaxPage: 1,\n msgTotal: 0,\n inputText: '',\n eventSource: null,\n showToolInfo: false,\n showDownBtn: false,\n // 控制向下箭头显隐\n lastScrollTop: 0,\n scrollTimer: null,\n // 滚动防抖(新增)\n showAgentSelect: true,\n isMobile: false,\n showSidebar: false,\n showH5List: false,\n // H5列表模式(展示会话列表而非聊天详情)\n _scrollTimer: null,\n agentInfo: {},\n contentCache: {},\n // 流式分行缓存 key=msg._key\n loadingSessionMsg: false,\n // 会话消息加载中标记\n greeting: '',\n longPressTimer: null,\n longPressed: false,\n // H5 语音输入\n voiceMode: false,\n // true=语音模式,false=文字模式\n isRecording: false,\n // 是否正在录音\n recordDuration: 0,\n // 录音时长(秒)\n recordingTimer: null,\n // 时长计时器\n audioContext: null,\n // AudioContext 实例\n audioStream: null,\n // MediaStream(用于清理)\n audioProcessor: null,\n // ScriptProcessorNode\n audioChunks: [],\n // Float32Array 数据块\n isCancelSwipe: false,\n // 是否上滑取消\n recordStartY: 0 // 触摸起始Y坐标\n };\n },\n created() {\n if (this.Ak || this.Sk) {\n (0, _apichat.setApiAuth)(this.Ak, this.Sk, this.imAccount, this.companyNo, this.chatImToken);\n }\n this.loadAgents();\n this.loadSessions();\n },\n mounted() {\n this.updateViewportState();\n window.addEventListener('resize', this.updateViewportState, {\n passive: true\n });\n // 监听 visualViewport 变化(键盘弹出/收起)\n if (window.visualViewport) {\n window.visualViewport.addEventListener('resize', this.onViewportResize, {\n passive: true\n });\n }\n },\n computed: {\n waitClass() {\n if (this.waitSeconds > 15) return 'wait-15';\n if (this.waitSeconds > 10) return 'wait-10';\n if (this.waitSeconds > 5) return 'wait-5';\n return '';\n },\n filteredSessions() {\n if (!this.searchKeyword) return this.sessionList;\n const kw = this.searchKeyword.toLowerCase();\n return this.sessionList.filter(s => {\n const name = (s.agentName || s.agentCode || '').toLowerCase();\n return name.includes(kw);\n });\n },\n currentAgentName() {\n if (!this.currentAgent) return '';\n const a = this.agentList.find(x => x.agentCode === this.currentAgent);\n return a ? a.agentName || a.agentCode : this.currentAgent;\n }\n },\n watch: {\n searchKeyword(val) {\n if (this.searchTimer) clearTimeout(this.searchTimer);\n if (!val.trim()) {\n this.agentSuggestions = [];\n this.showAgentSuggestions = false;\n this.closeSidebar();\n return;\n }\n this.searchTimer = setTimeout(() => {\n (0, _apichat.getChatAgents)(val.trim()).then(list => {\n this.agentSuggestions = list || [];\n this.showAgentSuggestions = this.agentSuggestions.length > 0;\n }).catch(() => {\n this.agentSuggestions = [];\n });\n }, 300);\n }\n // ak: {\n // handler(newVal) {\n // setApiAuth(newVal, this.sk)\n // },\n // immediate: true\n // },\n // sk: {\n // handler(newVal) {\n // setApiAuth(this.ak, newVal)\n // },\n // immediate: true\n // }\n },\n methods: {\n updateViewportState() {\n if (typeof window === 'undefined') return;\n const nextIsMobile = window.innerWidth <= 768;\n const wasMobile = this.isMobile;\n this.isMobile = nextIsMobile;\n if (!nextIsMobile) {\n this.showSidebar = false;\n this.showH5List = false;\n } else if (!wasMobile && nextIsMobile) {\n // 从桌面端切换到H5:如果加载了会话列表且无活跃会话,展示列表页\n if (this.sessionList.length > 0 && !this.activeSessionId) {\n this.showH5List = true;\n this.showAgentSelect = false;\n }\n }\n },\n toggleSidebar() {\n if (!this.isMobile) return;\n this.showSidebar = !this.showSidebar;\n },\n closeSidebar() {\n this.showSidebar = false;\n },\n // H5:调用原生返回上一级\n handleNativeBack() {\n if (this.$hybrid && typeof this.$hybrid.closePage === 'function') {\n this.$hybrid.closePage();\n } else if (window.history.length > 1) {\n window.history.back();\n }\n },\n // H5侧边栏返回按钮\n handleSidebarBack() {\n this.handleNativeBack();\n },\n agentjumpclick() {\n if (this.sending) {\n this.$message.warning('AI正在生成内容,暂时请不要切换对话');\n return;\n }\n this.currentAgent = '';\n this.currentAgentDesc = '';\n this.searchKeyword = '';\n this.activeSessionId = '';\n this.agentSuggestions = [];\n this.messages = [];\n this.showAgentSuggestions = false;\n this.showAgentSelect = true;\n this.showH5List = false;\n this.closeSidebar();\n },\n // H5:从详情页返回列表页\n goBackToList() {\n if (this.sending) {\n this.$message.warning('AI正在生成内容,暂时请不要切换对话');\n return;\n }\n // 关闭流连接\n if (this.eventSource) {\n this.eventSource.close();\n this.eventSource = null;\n }\n this.sending = false;\n this.clearWaitTimer();\n this.activeSessionId = '';\n this.messages = [];\n this.currentAgent = '';\n this.currentAgentDesc = '';\n this.agentInfo = {};\n this.contentCache = {};\n\n // 始终返回列表页\n this.showH5List = true;\n this.showAgentSelect = false;\n this.closeSidebar();\n },\n sendQuickMsg(message) {\n if (message) {\n this.inputText = message;\n this.sendMessage();\n }\n },\n formatMixText(str) {\n if (!str) return '';\n // 1. 中文 <=> 英文/数字 之间加空格\n let res = str.replace(/([a-zA-Z0-9])([\\u4e00-\\u9fff])/g, '$1 $2').replace(/([\\u4e00-\\u9fff])([a-zA-Z0-9])/g, '$1 $2');\n // 2. 连续英文单词分片粘连修复:字母紧跟字母中间加空格\n // 匹配 小写+大写 驼峰、连续分片拼接成一坨的英文\n res = res.replace(/([a-z])([A-Z])/g, '$1 $2');\n return res;\n },\n // 获取右侧头像样式(根据当前智能体在左侧列表中的位置决定颜色)\n getChatAvatarStyle(agent, avatar) {\n if (avatar) {\n return {\n backgroundImage: `url(${avatar})`,\n backgroundSize: 'cover',\n backgroundPosition: 'center',\n backgroundRepeat: 'no-repeat'\n };\n }\n const _agent = this.agentList.find(x => x.agentCode === agent);\n // 如果有网络图片,返回背景图样式\n if (agent.avatar) {\n return {\n backgroundImage: `url(${agent.avatar})`,\n backgroundSize: 'cover',\n backgroundPosition: 'center',\n backgroundRepeat: 'no-repeat'\n };\n }\n\n // 没有网络图片时,根据智能体在 agentList 中的索引位置决定颜色\n if (this.sessionList) {\n // 找到当前智能体在列表中的索引\n const index = this.sessionList.findIndex(item => item.agentCode === agent);\n if (index !== -1) {\n // 根据索引计算颜色类(4色循环)\n const colorIndex = index % 4 + 1;\n return {\n background: this.getGradientByColorIndex(colorIndex)\n };\n }\n }\n\n // 默认返回蓝色渐变\n return {\n background: 'linear-gradient(135deg, #1677ff, #4096ff)'\n };\n },\n // 根据颜色索引获取对应的渐变色\n getGradientByColorIndex(index) {\n const gradients = {\n 1: 'linear-gradient(135deg, #1677ff, #4096ff)',\n 2: 'linear-gradient(135deg, #52c41a, #73d13d)',\n 3: 'linear-gradient(135deg, #fa8c16, #ffa940)',\n 4: 'linear-gradient(135deg, #722ed1, #b37feb)'\n };\n return gradients[index] || gradients[1];\n },\n selectAgent(agentItem) {\n this.showAgentSelect = false;\n this.currentAgent = agentItem.agentCode;\n this.currentAgentName = agentItem.agentName;\n // 查找历史会话\n const existSession = this.sessionList.find(s => s.agentCode === agentItem.agentCode);\n if (existSession) {\n this.activeSessionId = existSession.id;\n this.switchSession(existSession);\n } else {\n this.createNewSession(agentItem.agentCode);\n }\n },\n createNewSession(agentCode) {\n // 你原有新建会话逻辑\n },\n // 检测是否滚动到底部,控制向下箭头显示隐藏\n checkScrollBottom(forceShowWhenNotBottom = false) {\n const el = this.$refs.messagesRef;\n if (!el) {\n this.showDownBtn = false;\n return;\n }\n const {\n scrollHeight,\n scrollTop,\n clientHeight\n } = el;\n const remain = scrollHeight - scrollTop - clientHeight;\n const atBottom = remain <= 80;\n if (atBottom) {\n this.showDownBtn = false;\n } else if (this.sending && scrollTop >= this.lastScrollTop && !forceShowWhenNotBottom) {\n // 发送AI回答时,如果用户没有主动向上滚动,就不要显示下箭头闪烁\n this.showDownBtn = false;\n } else {\n this.showDownBtn = true;\n }\n this.lastScrollTop = scrollTop;\n },\n // 固定最小高度:单行不撑开,超出才增高\n // H5 输入框获取焦点 - 滚动到底部让键盘不遮挡\n onInputFocus() {\n if (!this.isMobile) return;\n // 直接滚动窗口到底部,确保输入框可见\n setTimeout(() => {\n window.scrollTo(0, document.body.scrollHeight);\n }, 300);\n },\n // visualViewport 变化时(如键盘弹出)调整滚动位置\n onViewportResize() {\n if (!this.isMobile) return;\n const activeEl = document.activeElement;\n if (activeEl && (activeEl.tagName === 'TEXTAREA' || activeEl.tagName === 'INPUT')) {\n window.scrollTo(0, document.body.scrollHeight);\n }\n },\n autoResizeTextarea() {\n const ta = this.$refs.taRef;\n if (!ta) return;\n // 根据端适配基准高度和最大高度\n const isMobile = this.isMobile;\n const baseH = isMobile ? 36 : 100;\n const maxH = isMobile ? 100 : 180;\n ta.style.height = `${baseH}px`;\n // 内容真实高度\n const realH = ta.scrollHeight;\n // 只有内容高度>基准才撑开,否则保持初始高度\n if (realH > baseH) {\n ta.style.height = `${Math.min(realH, maxH)}px`;\n }\n this.$nextTick(() => {\n this.checkScrollBottom(true);\n });\n },\n // Shift+Enter换行\n newLine(e) {\n // 取消浏览器默认行为\n e.preventDefault();\n // 拿到光标位置\n const ta = this.$refs.taRef;\n const start = ta.selectionStart;\n const end = ta.selectionEnd;\n // 在光标处插入换行符\n this.inputText = this.inputText.slice(0, start) + '\\n' + this.inputText.slice(end);\n // 光标定位到换行后\n this.$nextTick(() => {\n ta.selectionStart = ta.selectionEnd = start + 1;\n // 自动调整输入框高度\n this.autoResizeTextarea();\n });\n },\n toggleVoiceMode() {\n this.voiceMode = !this.voiceMode;\n if (!this.voiceMode) {\n // 切回文字模式时释放音频设备\n this.releaseAudio();\n }\n },\n // 确保音频设备已就绪(只请求一次权限,缓存 stream / AudioContext)\n async ensureAudioReady() {\n if (this.audioContext && this.audioStream) return true;\n if (!navigator.mediaDevices || !navigator.mediaDevices.getUserMedia) {\n alert('当前环境不支持麦克风访问');\n return false;\n }\n try {\n const stream = await navigator.mediaDevices.getUserMedia({\n audio: true\n });\n this.audioStream = stream;\n const audioContext = new (window.AudioContext || window.webkitAudioContext)({\n sampleRate: 16000\n });\n this.audioContext = audioContext;\n const source = audioContext.createMediaStreamSource(stream);\n const processor = audioContext.createScriptProcessor(4096, 1, 1);\n this.audioProcessor = processor;\n processor.onaudioprocess = e => {\n if (!this.isRecording) return;\n const inputData = e.inputBuffer.getChannelData(0);\n this.audioChunks.push(new Float32Array(inputData));\n };\n source.connect(processor);\n processor.connect(audioContext.destination);\n return true;\n } catch (err) {\n console.error('麦克风访问失败:', err);\n alert('麦克风权限被拒绝');\n return false;\n }\n },\n // H5语音录制 - 触摸开始\n async onRecordTouchStart(e) {\n if (this.sending) return;\n\n // 先确保音频已就绪(首次会请求权限并建立音频管线,后续复用)\n const ready = await this.ensureAudioReady();\n if (!ready) return;\n\n // 重置录音状态\n this.isCancelSwipe = false;\n this.recordStartY = e.touches[0].clientY;\n this.recordDuration = 0;\n this.audioChunks = [];\n\n // 音频就绪后才标记录制中并启动计时\n this.isRecording = true;\n this.recordingTimer = setInterval(() => {\n this.recordDuration++;\n if (this.recordDuration >= 60) {\n this.onRecordTouchEnd();\n }\n }, 1000);\n },\n // H5语音录制 - 触摸移动(检测上滑取消)\n onRecordTouchMove(e) {\n if (!this.isRecording) return;\n const touch = e.touches[0];\n const moveY = touch.clientY;\n const cancelThreshold = 60; // 上滑60px进入取消区域\n this.isCancelSwipe = this.recordStartY - moveY > cancelThreshold;\n },\n // H5语音录制 - 触摸结束\n onRecordTouchEnd() {\n if (!this.isRecording) return;\n this.isRecording = false;\n if (this.recordingTimer) {\n clearInterval(this.recordingTimer);\n this.recordingTimer = null;\n }\n this.stopAudioCapture(!this.isCancelSwipe);\n },\n // 停止音频采集并输出 WAV(保留音频设备,下次复用)\n stopAudioCapture(shouldSend) {\n this.isRecording = false;\n if (shouldSend && this.audioChunks.length > 0) {\n const wavBlob = this.encodePCMToWav(this.audioChunks, 16000);\n this.sendAudioBlob(wavBlob);\n }\n this.audioChunks = [];\n },\n // 取消录音(保留音频设备,下次复用)\n cancelRecording() {\n this.isRecording = false;\n if (this.recordingTimer) {\n clearInterval(this.recordingTimer);\n this.recordingTimer = null;\n }\n this.recordDuration = 0;\n this.isCancelSwipe = false;\n this.audioChunks = [];\n },\n // 释放音频资源(切换回文字模式或组件销毁时调用)\n releaseAudio() {\n this.cancelRecording();\n if (this.audioProcessor) {\n this.audioProcessor.disconnect();\n this.audioProcessor = null;\n }\n if (this.audioContext) {\n this.audioContext.close().catch(() => {});\n this.audioContext = null;\n }\n if (this.audioStream) {\n this.audioStream.getTracks().forEach(t => t.stop());\n this.audioStream = null;\n }\n },\n // 将 Float32 PCM 数据编码为 WAV Blob\n encodePCMToWav(chunks, sampleRate) {\n // 计算总采样数\n let totalLength = 0;\n for (const chunk of chunks) {\n totalLength += chunk.length;\n }\n\n // 转换为 Int16 PCM\n const pcmData = new Int16Array(totalLength);\n let offset = 0;\n for (const chunk of chunks) {\n for (let i = 0; i < chunk.length; i++) {\n const s = Math.max(-1, Math.min(1, chunk[i]));\n pcmData[offset++] = s < 0 ? s * 0x8000 : s * 0x7FFF;\n }\n }\n const numChannels = 1;\n const bitsPerSample = 16;\n const byteRate = sampleRate * numChannels * bitsPerSample / 8;\n const blockAlign = numChannels * bitsPerSample / 8;\n const dataSize = pcmData.length * (bitsPerSample / 8);\n const headerSize = 44;\n const totalSize = headerSize + dataSize;\n const buffer = new ArrayBuffer(totalSize);\n const view = new DataView(buffer);\n\n // RIFF header\n this._wavWriteString(view, 0, 'RIFF');\n view.setUint32(4, totalSize - 8, true);\n this._wavWriteString(view, 8, 'WAVE');\n\n // fmt chunk\n this._wavWriteString(view, 12, 'fmt ');\n view.setUint32(16, 16, true); // chunk size\n view.setUint16(20, 1, true); // PCM format\n view.setUint16(22, numChannels, true); // 单声道\n view.setUint32(24, sampleRate, true); // 采样率\n view.setUint32(28, byteRate, true);\n view.setUint16(32, blockAlign, true);\n view.setUint16(34, bitsPerSample, true);\n\n // data chunk\n this._wavWriteString(view, 36, 'data');\n view.setUint32(40, dataSize, true);\n\n // 写入 PCM 数据\n const pcmView = new Int16Array(buffer, headerSize, pcmData.length);\n pcmView.set(pcmData);\n return new Blob([buffer], {\n type: 'audio/wav'\n });\n },\n _wavWriteString(view, offset, str) {\n for (let i = 0; i < str.length; i++) {\n view.setUint8(offset + i, str.charCodeAt(i));\n }\n },\n // 发送音频\n sendAudioBlob(blob) {\n let appSeqId = _index2.default.getAppSeqId();\n let name = appSeqId + '.wav';\n const file = new File([blob], name, {\n type: 'audio/wav'\n });\n // TODO: 上传音频文件并调用 STT 接口\n this.sendAudioMessage(file);\n },\n sendAudioMessage(file) {\n // 插入本地 pending 消息\n const sttKey = 'stt_' + Date.now();\n const sttMsg = {\n role: 'user',\n content: '转化中...',\n _sttStatus: 'pending',\n _sttKey: sttKey,\n createTime: new Date().toISOString(),\n _key: sttKey\n };\n this.messages.push(sttMsg);\n this.scrollToBottom(true);\n (0, _index.fileUploadToObs)({\n _file: file,\n appSeqId: file.name\n }).then(resp => {\n if (resp.CommonMsg.Status === 200) {\n // 调用语音转文字接口\n return _apiObs.default.aliAudioToText({\n url: resp.obs_upload_data.obsUrl\n }).then(result => {\n if (result.code === '200' && result.data) {\n // 成功:删除 pending 消息,发送给后端\n const idx = this.messages.findIndex(m => m._sttKey === sttKey);\n if (idx !== -1) {\n this.messages.splice(idx, 1);\n }\n this.sendQuickMsg(result.data);\n } else {\n throw new Error(result.msg || '语音转文字失败');\n }\n });\n } else {\n throw new Error(resp.CommonMsg.Message || '文件上传失败');\n }\n }).catch(err => {\n console.error('语音转文字失败:', err);\n // 失败:更新为错误状态\n const idx = this.messages.findIndex(m => m._sttKey === sttKey);\n if (idx !== -1) {\n this.$set(this.messages, idx, {\n ...this.messages[idx],\n _sttStatus: 'error',\n content: '语音转文字失败'\n });\n }\n this.$message.error('语音转文字失败');\n });\n this.$message.success(`录音完成 (${this.recordDuration}s)`);\n },\n clearWaitTimer() {\n if (this.waitTimer) {\n clearInterval(this.waitTimer);\n this.waitTimer = null;\n }\n },\n loadAgents() {\n (0, _apichat.getChatAgents)().then(list => {\n this.agentList = list || [];\n // if (this.agentList.length > 0 && !this.currentAgent) {\n // const first = this.agentList[0]\n // this.currentAgent = first.agentCode\n // this.currentAgentDesc = first.description || ''\n // }\n }).catch(() => {});\n },\n loadSessions() {\n (0, _apichat.getSessionList)().then(list => {\n if (!this.activeSessionId) {\n this.sessionList = list || [];\n if (this.sessionList.length > 0) {\n if (this.isMobile) {\n // H5模式:不自动选中会话,展示列表页\n this.showAgentSelect = false;\n this.showH5List = true;\n this.showSidebar = false;\n } else {\n this.switchSession(this.sessionList[0]);\n }\n }\n if (this.sessionList.length === 0) {\n this.showAgentSelect = true;\n this.showH5List = false;\n }\n } else {\n this.sessionList = list || [];\n let _item = list.find(res => res.sessionId == this.activeSessionId);\n try {\n if (_item.suggestedQuestions) {\n _item.suggestedQuestions = JSON.parse(_item.suggestedQuestions);\n } else {\n _item.suggestedQuestions = [];\n }\n _item && (this.agentInfo = _item);\n } catch (err) {\n // JSON格式错误兜底空数组,防止页面报错\n this.agentInfo.questionArr = [];\n console.warn('快捷提问解析失败', err);\n }\n }\n }).catch(() => {});\n },\n onSearchClear() {\n this.agentSuggestions = [];\n this.showAgentSuggestions = false;\n },\n startChatWithAgent(agent) {\n console.log('选择了助手', agent.agentCode, this.currentAgent);\n if (agent.agentCode == this.currentAgent) {\n this.searchKeyword = '';\n this.agentSuggestions = [];\n this.showAgentSuggestions = false;\n return;\n }\n this.currentAgent = agent.agentCode;\n this.currentAgentDesc = agent.description || '';\n this.searchKeyword = '';\n this.agentInfo = {};\n this.agentSuggestions = [];\n this.messages = [];\n this.showAgentSuggestions = false;\n this.showAgentSelect = false;\n this.closeSidebar();\n if (this.isMobile) {\n this.showH5List = false; // H5:进入详情页,隐藏列表\n }\n const existing = this.sessionList.find(s => s.agentCode === agent.agentCode);\n if (existing) {\n this.switchSession(existing);\n } else {\n this.handleNewSession();\n }\n },\n handleNewSession() {\n if (!this.currentAgent) return;\n if (this.activeSessionId) this.closeOldSession();\n (0, _apichat.startSession)(this.currentAgent).then(res => {\n console.log(res, 'startChatWithAgentstartChatWithAgentstartChatWithAgent', this.agentInfo);\n this.activeSessionId = res.sessionId || '';\n this.loadSessions();\n const agent = this.agentList.find(a => a.agentCode === this.currentAgent);\n if (agent) this.addWelcomeMessage(agent);\n }).catch(() => {});\n },\n // H5长按删除 - 触摸开始\n onSessionTouchStart(s, e) {\n if (!this.isMobile) return;\n this.longPressed = false;\n this.longPressTimer = setTimeout(() => {\n this.longPressed = true;\n this.handleDeleteSession(s);\n }, 600);\n },\n // H5长按删除 - 触摸结束/移动(取消长按)\n onSessionTouchEnd() {\n if (this.longPressTimer) {\n clearTimeout(this.longPressTimer);\n this.longPressTimer = null;\n }\n },\n onSessionTouchMove() {\n if (this.longPressTimer) {\n clearTimeout(this.longPressTimer);\n this.longPressTimer = null;\n }\n },\n async switchSession(s) {\n if (this.longPressed) {\n this.longPressed = false;\n return;\n }\n if (this.sending) {\n this.$message.warning('AI正在生成内容,暂时请不要切换对话');\n return;\n }\n this.showAgentSelect = false;\n this.closeSidebar();\n if (this.isMobile) {\n this.showH5List = false; // H5:进入详情页,隐藏列表\n }\n if (this.activeSessionId === s.sessionId) return;\n this.contentCache = {};\n this.activeSessionId = s.sessionId;\n this.currentAgent = s.agentCode;\n console.log('进入');\n this.agentInfo = s;\n console.log('进入', this.agentInfo);\n try {\n if (s.suggestedQuestions) {\n this.agentInfo.suggestedQuestions = JSON.parse(s.suggestedQuestions);\n } else {\n this.agentInfo.suggestedQuestions = [];\n }\n } catch (err) {\n // JSON格式错误兜底空数组,防止页面报错\n this.agentInfo.questionArr = [];\n console.warn('快捷提问解析失败', err);\n }\n const agent = this.agentList.find(a => a.agentCode === s.agentCode);\n this.currentAgentDesc = agent ? agent.description || '' : '';\n this.msgPage = 1;\n this.msgTotal = 0;\n this.messages = []; // 先清空,但开启加载锁屏蔽空白页\n this.loadingSessionMsg = true; // 开启加载标记\n (0, _apichat.syncToken)((0, _cookie.getToken)(), s.sessionId);\n try {\n const res = await (0, _apichat.getSessionMessages)(s.sessionId, 1, 10);\n const list = Array.isArray(res) ? res : res.list || [];\n this.msgTotal = res.total || list.length;\n this.msgPage = 1;\n const asAsc = (list || []).slice().reverse();\n this.messages = asAsc.map(m => ({\n role: m.role,\n content: m.content || '',\n thinking: m.thinking || '',\n toolCalls: [],\n agentName: m.role === 'assistant' ? s.agentName || '' : '',\n createTime: m.createTime || null,\n _key: m.createTime ? 'msg_' + m.createTime : 'msg_' + Date.now() + '_' + Math.random()\n }));\n if (this.messages.length === 0 && agent) this.addWelcomeMessage(agent);\n await this.$nextTick();\n this.$nextTick(() => {\n this.scrollToBottomOnce();\n this.checkScrollBottom();\n });\n } catch (e) {\n this.messages = [];\n } finally {\n // 无论成功失败,结束后关闭加载锁\n this.loadingSessionMsg = false;\n }\n },\n loadMoreMessages() {\n const nextPage = this.msgPage + 1;\n const maxPage = Math.ceil(this.msgTotal / 10);\n if (nextPage > maxPage) {\n this.loadingMore = false;\n return;\n }\n (0, _apichat.getSessionMessages)(this.activeSessionId, nextPage, 10).then(res => {\n const list = Array.isArray(res) ? res : res.list || [];\n this.msgPage = nextPage;\n const asAsc = (list || []).slice().reverse();\n const prepend = asAsc.map(m => ({\n role: m.role,\n content: m.content || '',\n thinking: m.thinking || '',\n toolCalls: [],\n agentName: '',\n createTime: m.createTime || null,\n _key: m.createTime ? 'msg_' + m.createTime : 'msg_' + Date.now() + '_' + Math.random()\n }));\n const container = this.$refs.messagesRef;\n const oldScrollHeight = container ? container.scrollHeight : 0;\n const oldScrollTop = container ? container.scrollTop : 0;\n this.messages = [...prepend, ...this.messages];\n this.$nextTick(() => {\n if (container) {\n container.scrollTop = oldScrollTop + (container.scrollHeight - oldScrollHeight);\n }\n this.loadingMore = false;\n });\n }).catch(() => {\n this.loadingMore = false;\n });\n },\n onScrollMessages() {\n const container = this.$refs.messagesRef;\n if (!container || this.loadingMore) return;\n const isAtBottom = container.scrollTop + container.clientHeight >= container.scrollHeight - 100;\n this.checkScrollBottom();\n if (isAtBottom) return;\n if (container.scrollTop < 50 && this.msgPage < Math.ceil(this.msgTotal / 10)) {\n this.loadingMore = true;\n this.loadMoreMessages();\n }\n },\n handleDeleteSession(s) {\n this.$confirm(`确认删除「${s.agentName || s.agentCode}」的会话?`, '提示', {\n type: 'warning'\n }).then(() => {\n (0, _apichat.deleteSession)(s.sessionId).then(() => {\n if (this.activeSessionId === s.sessionId) {\n this.activeSessionId = '';\n this.messages = [];\n this.currentAgent = '';\n this.currentAgentDesc = '';\n if (this.isMobile) {\n this.showH5List = false;\n this.showAgentSelect = true;\n } else {\n this.showAgentSelect = true;\n }\n }\n this.loadSessions();\n });\n }).catch(() => {});\n },\n closeOldSession() {},\n onAgentChange(code) {\n const agent = this.agentList.find(a => a.agentCode === code);\n this.currentAgentDesc = agent ? agent.description || '' : '';\n this.handleNewSession();\n },\n addWelcomeMessage(agent) {\n this.greeting = '';\n // if (!agent) return\n // const name = agent.agentName || '助手';\n const _agent = this.agentList.find(x => x.agentCode === this.currentAgent);\n this.greeting = _agent.greeting || `很高兴为您服务,请问有什么可以帮到您?`;\n // this.messages.push({\n // role: 'assistant',\n // content: _content,\n // thinking: '',\n // agentName: name,\n // _key: 'welcome_' + Date.now()\n // })\n },\n async sendMessage() {\n const text = this.inputText.trim();\n if (!text || this.sending) return;\n if (!this.activeSessionId) {\n await (0, _apichat.startSession)(this.currentAgent).then(res => {\n this.activeSessionId = res.sessionId || '';\n this.loadSessions();\n });\n if (!this.activeSessionId) return;\n }\n this.inputText = '';\n const ta = this.$refs.taRef;\n const isMobile = this.isMobile;\n const baseH = isMobile ? 36 : 100;\n if (ta) {\n ta.style.height = baseH + 'px'; // 强制恢复初始高度\n }\n this.showDownBtn = false;\n this.messages.push({\n role: 'user',\n content: text,\n createTime: new Date().toISOString(),\n _key: 'user_' + Date.now() + '_' + Math.random()\n });\n const agentName = this.currentAgentName;\n const msgIdx = this.messages.push({\n role: \"assistant\",\n content: \"\",\n thinking: \"\",\n loading: true,\n toolCalls: [],\n agentName,\n createTime: new Date().toISOString(),\n _key: 'asst_' + Date.now() + '_' + Math.random()\n }) - 1;\n this.scrollToBottom(true);\n this.sending = true;\n this.waitSeconds = 0;\n if (this.waitTimer) clearInterval(this.waitTimer);\n this.waitTimer = setInterval(() => {\n this.waitSeconds++;\n }, 1000);\n let thinkingBuffer = '';\n let finalContent = '';\n let answerBuffer = '';\n let thinkDisplayed = 0;\n let typeTimer = null;\n typeTimer = setInterval(() => {\n if (!this.messages[msgIdx]) return;\n if (thinkDisplayed < thinkingBuffer.length) {\n thinkDisplayed += 50;\n if (thinkDisplayed > thinkingBuffer.length) thinkDisplayed = thinkingBuffer.length;\n this.messages[msgIdx].thinking = thinkingBuffer.substring(0, thinkDisplayed);\n this.scrollToBottom();\n } else if (finalContent && !this.messages[msgIdx].content) {\n clearInterval(typeTimer);\n const key = this.messages[msgIdx]._key;\n if (key) {\n this.$delete(this.contentCache, key);\n this.$delete(this.contentCache, key + '_t');\n }\n typeTimer = null;\n this.messages[msgIdx].content = finalContent;\n this.messages[msgIdx].thinking = thinkingBuffer;\n this.messages[msgIdx].loading = false;\n this.sending = false;\n this.clearWaitTimer();\n this.scrollToBottom();\n this.loadSessions();\n }\n }, 30);\n const url = (0, _apichat.createStreamUrl)(this.activeSessionId, text);\n if (this.eventSource) {\n this.eventSource.close();\n }\n this.eventSource = new EventSource(url);\n const es = this.eventSource;\n es.addEventListener('reasoning', e => {\n if (e.data) {\n const chunk = e.data;\n // 1. 先处理当前分片内部的中英文、数字、标点空格\n let cleanChunk = chunk.replace(/([a-z])([A-Z])/g, '$1 $2').replace(/([A-Z]+)([A-Z][a-z])/g, '$1 $2').replace(/([a-zA-Z])([\\u4e00-\\u9fff])/g, '$1 $2').replace(/([\\u4e00-\\u9fff])([a-zA-Z])/g, '$1 $2').replace(/([a-zA-Z])(\\d)/g, '$1 $2').replace(/(\\d)([a-zA-Z])/g, '$1 $2').replace(/\\s+([:,.!?])/g, '$1').replace(/([:,.!?])\\s+/g, '$1 ');\n cleanChunk = cleanChunk.replace(/\\s+/g, ' ');\n\n // 2. 关键:判断前一段末尾 + 当前段开头都是英文,补空格分隔\n const lastChar = thinkingBuffer.slice(-1);\n const firstChar = cleanChunk.slice(0, 1);\n const isLetter = c => /[a-zA-Z]/.test(c);\n if (isLetter(lastChar) && isLetter(firstChar)) {\n // 两段都是英文衔接,中间加空格\n thinkingBuffer += ' ' + cleanChunk;\n } else {\n thinkingBuffer += cleanChunk;\n }\n }\n });\n es.addEventListener('reasoning_result', e => {\n if (e.data) {\n thinkingBuffer = e.data;\n }\n });\n es.addEventListener('answer', e => {\n if (e.data) {\n answerBuffer += e.data;\n if (this.messages[msgIdx]) {\n this.messages[msgIdx].content += e.data.replace(/([a-zA-Z]+)([\\u4e00-\\u9fff])/g, '$1 $2').replace(/([\\u4e00-\\u9fff])([a-zA-Z]+)/g, '$1 $2').replace(/([a-z])([A-Z])/g, '$1 $2').replace(/([A-Z]+)([A-Z][a-z])/g, '$1 $2').replace(/([a-zA-Z])(\\d)/g, '$1 $2').replace(/(\\d)([a-zA-Z])/g, '$1 $2');\n this.scrollToBottom();\n }\n }\n });\n es.addEventListener('tool_result', e => {\n if (e.data && this.messages[msgIdx]) {\n if (!this.messages[msgIdx].toolCalls) this.messages[msgIdx].toolCalls = [];\n this.messages[msgIdx].toolCalls.push(e.data);\n this.scrollToBottom();\n }\n });\n es.addEventListener('agent_result', e => {\n finalContent = e.data || '';\n es.close();\n this.eventSource = null;\n if (this.messages[msgIdx]) {\n const key = this.messages[msgIdx]._key;\n if (key) this.$delete(this.contentCache, key);\n this.messages[msgIdx].content = finalContent;\n this.messages[msgIdx].thinking = thinkingBuffer;\n this.messages[msgIdx].loading = false;\n }\n this.sending = false;\n this.clearWaitTimer();\n if (typeTimer) {\n clearInterval(typeTimer);\n typeTimer = null;\n }\n this.scrollToBottom();\n this.loadSessions();\n });\n es.onerror = err => {\n console.log('[SSE] onerror', err);\n if (thinkingBuffer.length > 0 && !finalContent) finalContent = thinkingBuffer;\n if (!finalContent) finalContent = '❌ 连接中断';\n es.close();\n this.eventSource = null;\n if (this.messages[msgIdx]) {\n const key = this.messages[msgIdx]._key;\n if (key) this.$delete(this.contentCache, key);\n this.messages[msgIdx].content = finalContent;\n this.messages[msgIdx].thinking = thinkingBuffer;\n this.messages[msgIdx].loading = false;\n }\n this.sending = false;\n this.clearWaitTimer();\n if (typeTimer) {\n clearInterval(typeTimer);\n typeTimer = null;\n }\n this.scrollToBottom();\n };\n },\n stopAgent() {\n if (this.eventSource) {\n this.eventSource.close();\n this.eventSource = null;\n }\n if (this.activeSessionId) {\n (0, _apichat.stopStream)(this.activeSessionId).catch(() => {});\n }\n if (this.messages.length > 0) {\n const last = this.messages[this.messages.length - 1];\n if (last && last.loading) {\n last.content = last.content || last.thinking || '⏹ 已停止';\n last.loading = false;\n this.$delete(this.contentCache, last._key);\n }\n }\n this.sending = false;\n this.clearWaitTimer();\n },\n copyText(content) {\n if (!content) return;\n navigator.clipboard.writeText(content.replace(/<[^>]+>/g, '')).then(() => {\n this.$message({\n message: '已复制到剪贴板',\n type: 'success',\n duration: 1500\n });\n }).catch(() => {\n this.$message({\n message: '复制失败',\n type: 'error',\n duration: 2000\n });\n });\n },\n copyAsImage(content) {\n if (!content) return;\n // 创建临时容器渲染 Markdown\n const div = document.createElement('div');\n div.className = 'copy-image-render';\n div.style.cssText = 'position:fixed;left:-9999px;top:0;width:600px;padding:20px;background:#fff;font-size:14px;line-height:1.6;color:#333;border-radius:8px;font-family:-apple-system,BlinkMacSystemFont,sans-serif;';\n div.innerHTML = this.renderMarkdown(content);\n document.body.appendChild(div);\n this.$message({\n message: '正在生成图片...',\n type: 'info',\n duration: 2000\n });\n (0, _html2canvas.default)(div, {\n scale: 2,\n useCORS: true,\n backgroundColor: '#ffffff'\n }).then(canvas => {\n canvas.toBlob(blob => {\n if (blob) {\n navigator.clipboard.write([new ClipboardItem({\n 'image/png': blob\n })]).then(() => {\n this.$message({\n message: '图片已复制到剪贴板',\n type: 'success',\n duration: 1500\n });\n }).catch(() => {\n this.$message({\n message: '复制图片失败',\n type: 'error',\n duration: 2000\n });\n });\n }\n }, 'image/png');\n }).catch(() => {\n this.$message({\n message: '生成图片失败',\n type: 'error',\n duration: 2000\n });\n }).finally(() => {\n document.body.removeChild(div);\n });\n },\n formatTime(t) {\n if (!t) return '';\n const d = new Date(t.replace(' ', 'T'));\n const now = new Date();\n const diff = (now - d) / 1000;\n if (diff < 60) return '刚刚';\n if (diff < 3600) return Math.floor(diff / 60) + '分钟前';\n if (diff < 86400) return Math.floor(diff / 3600) + '小时前';\n return d.getMonth() + 1 + '/' + d.getDate();\n },\n getInitial(name) {\n if (!name) return '?';\n return name.charAt(0);\n },\n renderMarkdown(text) {\n if (!text) return '';\n try {\n return md.render(text);\n } catch (err) {\n return this.escapeHtml(text);\n }\n },\n renderStreaming(text, msgKey) {\n if (!text) return '';\n console.log('进入');\n const cache = this.contentCache[msgKey];\n const lines = text.split('\\n');\n const lastLineIdx = lines.length - 1;\n if (!cache) {\n try {\n const html = md.render(text);\n this.$set(this.contentCache, msgKey, {\n renderedLines: lastLineIdx,\n html,\n fullText: text\n });\n return html;\n } catch {\n return this.escapeHtml(text);\n }\n }\n if (text === cache.fullText) return cache.html;\n cache.fullText = text;\n\n // 行数没变,仅末尾追加字符,直接拼接尾行(原有逻辑不变)\n if (lastLineIdx === cache.renderedLines) {\n return cache.html + this.escapeHtml(lines[lastLineIdx]);\n }\n\n // 场景1:行数变少/文本回退截断,全量重渲染(原有分支保留,内部修复)\n if (lastLineIdx < cache.renderedLines) {\n try {\n // 重新截取所有完整行生成全新基础html,清空旧叠加内容\n const fullLines = lines.slice(0, lastLineIdx);\n let newBaseHtml = '';\n if (fullLines.length > 0) {\n newBaseHtml = md.render(fullLines.join('\\n'));\n }\n cache.html = newBaseHtml;\n cache.renderedLines = lastLineIdx;\n // 拼接尾行\n const lastLine = this.escapeHtml(lines[lastLineIdx]);\n return cache.html + (lastLine || '');\n } catch {\n return this.escapeHtml(text);\n }\n }\n\n // 场景2:新增完整行,修复:不再累加旧html,重新从0生成完整行基础\n if (cache.renderedLines < lastLineIdx) {\n // 关键修复:重新切片所有完整行,抛弃之前叠加的旧html,杜绝重复\n const allFullLines = lines.slice(0, lastLineIdx);\n let newBaseHtml = '';\n if (allFullLines.length > 0) {\n newBaseHtml = md.render(allFullLines.join('\\n'));\n }\n cache.html = newBaseHtml;\n cache.renderedLines = lastLineIdx;\n }\n const lastLine = this.escapeHtml(lines[lastLineIdx]);\n cache.renderedLines = lastLineIdx;\n return cache.html + (lastLine || '');\n },\n escapeHtml(text) {\n if (!text) return '';\n return text.replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>');\n },\n scrollToTop() {\n const el = this.$refs.messagesRef;\n if (el) el.scrollTop = 0;\n },\n scrollToBottom(force = false) {\n if (this.showDownBtn && !force) return;\n this.$nextTick(() => {\n const el = this.$refs.messagesRef;\n if (el) {\n el.scrollTop = el.scrollHeight;\n this.lastScrollTop = el.scrollTop;\n this.showDownBtn = false; // 滚动到底部后立刻隐藏箭头\n }\n });\n },\n scrollToBottomOnce() {\n // 清理旧定时器,防止任何泄漏\n clearTimeout(this._scrollTimer);\n this.$nextTick(() => {\n let retry = 0;\n const maxRetry = 6; // 重试6次,足够覆盖所有渲染延迟\n\n const tryScroll = () => {\n var _this$$refs;\n const el = (_this$$refs = this.$refs) === null || _this$$refs === void 0 ? void 0 : _this$$refs.messagesRef;\n if (!el) {\n this._scrollTimer = setTimeout(tryScroll, 50);\n return;\n }\n\n // 临时禁用平滑滚动,立即跳到底部\n const originalScrollBehavior = el.style.scrollBehavior;\n el.style.scrollBehavior = 'auto';\n el.scrollTop = el.scrollHeight - el.clientHeight;\n el.style.scrollBehavior = originalScrollBehavior;\n this.showDownBtn = false;\n };\n tryScroll();\n });\n }\n },\n beforeDestroy() {\n window.removeEventListener('resize', this.updateViewportState);\n if (window.visualViewport) {\n window.visualViewport.removeEventListener('resize', this.onViewportResize);\n }\n this.releaseAudio();\n this.contentCache = {};\n clearTimeout(this._scrollTimer);\n if (this.eventSource) {\n this.eventSource.onerror = null;\n this.eventSource.close();\n this.eventSource = null;\n }\n if (this.waitTimer) {\n clearInterval(this.waitTimer);\n this.waitTimer = null;\n }\n if (this._typeTimer) {\n clearInterval(this._typeTimer);\n this._typeTimer = null;\n }\n }\n};\n\n//# sourceURL=webpack://ZjPluginIntelligent/./src/lib/components/chatMain/index.vue?./node_modules/_cache-loader@4.1.0@cache-loader/dist/cjs.js??ref--13-0!./node_modules/_babel-loader@8.4.1@babel-loader/lib!./node_modules/_cache-loader@4.1.0@cache-loader/dist/cjs.js??ref--1-0!./node_modules/_vue-loader@15.11.1@vue-loader/lib??vue-loader-options");
|
|
952
952
|
|
|
953
953
|
/***/ }),
|
|
954
954
|
|
|
@@ -12457,7 +12457,7 @@ eval("module.exports = function(originalModule) {\n\tif (!originalModule.webpack
|
|
|
12457
12457
|
/*! exports provided: name, version, main, private, scripts, dependencies, devDependencies, browserslist, directories, keywords, license, default */
|
|
12458
12458
|
/***/ (function(module) {
|
|
12459
12459
|
|
|
12460
|
-
eval("module.exports = JSON.parse(\"{\\\"name\\\":\\\"zj-plugin-intelligent\\\",\\\"version\\\":\\\"1.2.5-beta.
|
|
12460
|
+
eval("module.exports = JSON.parse(\"{\\\"name\\\":\\\"zj-plugin-intelligent\\\",\\\"version\\\":\\\"1.2.5-beta.8\\\",\\\"main\\\":\\\"lib/ZjPluginIntelligent.umd.min.js\\\",\\\"private\\\":false,\\\"scripts\\\":{\\\"serve\\\":\\\"vue-cli-service serve\\\",\\\"build\\\":\\\"vue-cli-service build\\\",\\\"lib\\\":\\\"vue-cli-service build --target lib --name ZjPluginIntelligent --dest lib src/lib/index.js\\\",\\\"lib:test\\\":\\\"vue-cli-service build --mode test --target lib --name ZjPluginIntelligent --dest lib src/lib/index.js\\\"},\\\"dependencies\\\":{\\\"html2canvas\\\":\\\"^1.4.1\\\",\\\"markdown-it\\\":\\\"^14.1.0\\\"},\\\"devDependencies\\\":{\\\"@babel/preset-env\\\":\\\"^7.14.9\\\",\\\"@vue/cli-plugin-babel\\\":\\\"~4.5.0\\\",\\\"@vue/cli-plugin-eslint\\\":\\\"^4.5.13\\\",\\\"@vue/cli-plugin-vuex\\\":\\\"~4.5.0\\\",\\\"@vue/cli-service\\\":\\\"~4.5.0\\\",\\\"axios\\\":\\\"^0.27.2\\\",\\\"babel-eslint\\\":\\\"^10.1.0\\\",\\\"babel-plugin-component\\\":\\\"^1.1.1\\\",\\\"compression-webpack-plugin\\\":\\\"^6.0.3\\\",\\\"core-js\\\":\\\"^3.6.5\\\",\\\"element-ui\\\":\\\"^2.15.4\\\",\\\"eslint\\\":\\\"^7.30.0\\\",\\\"eslint-plugin-vue\\\":\\\"^7.13.0\\\",\\\"js-cookie\\\":\\\"^2.2.1\\\",\\\"node-sass\\\":\\\"^4.12.0\\\",\\\"obs-upload\\\":\\\"^1.0.4-alpha.0\\\",\\\"reconnecting-websocket\\\":\\\"^4.4.0\\\",\\\"sass-loader\\\":\\\"^8.0.2\\\",\\\"snowflake-id\\\":\\\"^1.1.0\\\",\\\"vue\\\":\\\"^2.6.11\\\",\\\"vue-template-compiler\\\":\\\"^2.6.11\\\",\\\"vuex\\\":\\\"^3.4.0\\\",\\\"pako\\\":\\\"^2.1.0\\\",\\\"webpack-bundle-analyzer\\\":\\\"^4.4.2\\\"},\\\"browserslist\\\":[\\\"> 1%\\\",\\\"last 2 versions\\\",\\\"not dead\\\"],\\\"directories\\\":{\\\"lib\\\":\\\"lib\\\"},\\\"keywords\\\":[],\\\"license\\\":\\\"ISC\\\"}\");\n\n//# sourceURL=webpack://ZjPluginIntelligent/./package.json?");
|
|
12461
12461
|
|
|
12462
12462
|
/***/ }),
|
|
12463
12463
|
|
|
@@ -948,7 +948,7 @@ eval("\n\nvar _interopRequireWildcard = __webpack_require__(/*! ./node_modules/_
|
|
|
948
948
|
/***/ (function(module, exports, __webpack_require__) {
|
|
949
949
|
|
|
950
950
|
"use strict";
|
|
951
|
-
eval("\n\nvar _interopRequireDefault = __webpack_require__(/*! ./node_modules/_@babel_runtime@7.28.4@@babel/runtime/helpers/interopRequireDefault.js */ \"./node_modules/_@babel_runtime@7.28.4@@babel/runtime/helpers/interopRequireDefault.js\").default;\nObject.defineProperty(exports, \"__esModule\", {\n value: true\n});\nexports.default = void 0;\n__webpack_require__(/*! core-js/modules/es.error.cause.js */ \"./node_modules/_core-js@3.45.1@core-js/modules/es.error.cause.js\");\n__webpack_require__(/*! core-js/modules/es.array.push.js */ \"./node_modules/_core-js@3.45.1@core-js/modules/es.array.push.js\");\n__webpack_require__(/*! core-js/modules/es.array-buffer.detached.js */ \"./node_modules/_core-js@3.45.1@core-js/modules/es.array-buffer.detached.js\");\n__webpack_require__(/*! core-js/modules/es.array-buffer.transfer.js */ \"./node_modules/_core-js@3.45.1@core-js/modules/es.array-buffer.transfer.js\");\n__webpack_require__(/*! core-js/modules/es.array-buffer.transfer-to-fixed-length.js */ \"./node_modules/_core-js@3.45.1@core-js/modules/es.array-buffer.transfer-to-fixed-length.js\");\n__webpack_require__(/*! core-js/modules/es.iterator.constructor.js */ \"./node_modules/_core-js@3.45.1@core-js/modules/es.iterator.constructor.js\");\n__webpack_require__(/*! core-js/modules/es.iterator.filter.js */ \"./node_modules/_core-js@3.45.1@core-js/modules/es.iterator.filter.js\");\n__webpack_require__(/*! core-js/modules/es.iterator.find.js */ \"./node_modules/_core-js@3.45.1@core-js/modules/es.iterator.find.js\");\n__webpack_require__(/*! core-js/modules/es.iterator.for-each.js */ \"./node_modules/_core-js@3.45.1@core-js/modules/es.iterator.for-each.js\");\n__webpack_require__(/*! core-js/modules/es.iterator.map.js */ \"./node_modules/_core-js@3.45.1@core-js/modules/es.iterator.map.js\");\n__webpack_require__(/*! core-js/modules/es.typed-array.at.js */ \"./node_modules/_core-js@3.45.1@core-js/modules/es.typed-array.at.js\");\n__webpack_require__(/*! core-js/modules/es.typed-array.find-last.js */ \"./node_modules/_core-js@3.45.1@core-js/modules/es.typed-array.find-last.js\");\n__webpack_require__(/*! core-js/modules/es.typed-array.find-last-index.js */ \"./node_modules/_core-js@3.45.1@core-js/modules/es.typed-array.find-last-index.js\");\n__webpack_require__(/*! core-js/modules/es.typed-array.set.js */ \"./node_modules/_core-js@3.45.1@core-js/modules/es.typed-array.set.js\");\n__webpack_require__(/*! core-js/modules/es.typed-array.to-reversed.js */ \"./node_modules/_core-js@3.45.1@core-js/modules/es.typed-array.to-reversed.js\");\n__webpack_require__(/*! core-js/modules/es.typed-array.to-sorted.js */ \"./node_modules/_core-js@3.45.1@core-js/modules/es.typed-array.to-sorted.js\");\n__webpack_require__(/*! core-js/modules/es.typed-array.with.js */ \"./node_modules/_core-js@3.45.1@core-js/modules/es.typed-array.with.js\");\nvar _apichat = __webpack_require__(/*! @lib/api/apichat */ \"./src/lib/api/apichat.js\");\nvar _markdownIt = _interopRequireDefault(__webpack_require__(/*! markdown-it */ \"./node_modules/_markdown-it@14.1.0@markdown-it/index.mjs\"));\nvar _html2canvas = _interopRequireDefault(__webpack_require__(/*! html2canvas */ \"./node_modules/_html2canvas@1.4.1@html2canvas/dist/html2canvas.js\"));\nvar _index = __webpack_require__(/*! @lib/socket/fileManager/obs/index */ \"./src/lib/socket/fileManager/obs/index.js\");\nvar _index2 = _interopRequireDefault(__webpack_require__(/*! @lib/socket/utils/index */ \"./src/lib/socket/utils/index.js\"));\nvar _cookie = __webpack_require__(/*! @lib/utils/cookie.js */ \"./src/lib/utils/cookie.js\");\nvar _apiObs = _interopRequireDefault(__webpack_require__(/*! @lib/api/apiObs */ \"./src/lib/api/apiObs.js\"));\nconst md = new _markdownIt.default({\n breaks: true,\n html: false,\n linkify: true,\n typographer: true\n});\nmd.enable('table');\nvar _default = exports.default = {\n name: 'ChatMain',\n props: {\n Ak: {\n type: String,\n default: ''\n },\n Sk: {\n type: String,\n default: ''\n },\n imAccount: {\n type: String,\n default: ''\n },\n companyNo: {\n type: String,\n default: ''\n },\n isIntelShow: {\n default: false,\n type: Boolean\n },\n chatImToken: {\n default: '',\n type: String\n }\n },\n data() {\n return {\n agentList: [],\n currentAgent: '',\n currentAgentDesc: '',\n sessionsLoaded: false,\n searchKeyword: '',\n agentSuggestions: [],\n showAgentSuggestions: false,\n sessionList: [],\n activeSessionId: '',\n messages: [],\n loadingMore: false,\n sending: false,\n waitTimer: null,\n waitSeconds: 0,\n canceling: false,\n msgPage: 1,\n msgMaxPage: 1,\n msgTotal: 0,\n inputText: '',\n eventSource: null,\n showToolInfo: false,\n showDownBtn: false,\n // 控制向下箭头显隐\n lastScrollTop: 0,\n scrollTimer: null,\n // 滚动防抖(新增)\n showAgentSelect: true,\n isMobile: false,\n showSidebar: false,\n showH5List: false,\n // H5列表模式(展示会话列表而非聊天详情)\n _scrollTimer: null,\n agentInfo: {},\n contentCache: {},\n // 流式分行缓存 key=msg._key\n loadingSessionMsg: false,\n // 会话消息加载中标记\n greeting: '',\n longPressTimer: null,\n longPressed: false,\n // H5 语音输入\n voiceMode: false,\n // true=语音模式,false=文字模式\n isRecording: false,\n // 是否正在录音\n recordDuration: 0,\n // 录音时长(秒)\n recordingTimer: null,\n // 时长计时器\n audioContext: null,\n // AudioContext 实例\n audioStream: null,\n // MediaStream(用于清理)\n audioProcessor: null,\n // ScriptProcessorNode\n audioChunks: [],\n // Float32Array 数据块\n isCancelSwipe: false,\n // 是否上滑取消\n recordStartY: 0 // 触摸起始Y坐标\n };\n },\n created() {\n if (this.Ak || this.Sk) {\n (0, _apichat.setApiAuth)(this.Ak, this.Sk, this.imAccount, this.companyNo, this.chatImToken);\n }\n this.loadAgents();\n this.loadSessions();\n },\n mounted() {\n this.updateViewportState();\n window.addEventListener('resize', this.updateViewportState, {\n passive: true\n });\n },\n computed: {\n waitClass() {\n if (this.waitSeconds > 15) return 'wait-15';\n if (this.waitSeconds > 10) return 'wait-10';\n if (this.waitSeconds > 5) return 'wait-5';\n return '';\n },\n filteredSessions() {\n if (!this.searchKeyword) return this.sessionList;\n const kw = this.searchKeyword.toLowerCase();\n return this.sessionList.filter(s => {\n const name = (s.agentName || s.agentCode || '').toLowerCase();\n return name.includes(kw);\n });\n },\n currentAgentName() {\n if (!this.currentAgent) return '';\n const a = this.agentList.find(x => x.agentCode === this.currentAgent);\n return a ? a.agentName || a.agentCode : this.currentAgent;\n }\n },\n watch: {\n searchKeyword(val) {\n if (this.searchTimer) clearTimeout(this.searchTimer);\n if (!val.trim()) {\n this.agentSuggestions = [];\n this.showAgentSuggestions = false;\n this.closeSidebar();\n return;\n }\n this.searchTimer = setTimeout(() => {\n (0, _apichat.getChatAgents)(val.trim()).then(list => {\n this.agentSuggestions = list || [];\n this.showAgentSuggestions = this.agentSuggestions.length > 0;\n }).catch(() => {\n this.agentSuggestions = [];\n });\n }, 300);\n }\n // ak: {\n // handler(newVal) {\n // setApiAuth(newVal, this.sk)\n // },\n // immediate: true\n // },\n // sk: {\n // handler(newVal) {\n // setApiAuth(this.ak, newVal)\n // },\n // immediate: true\n // }\n },\n methods: {\n updateViewportState() {\n if (typeof window === 'undefined') return;\n const nextIsMobile = window.innerWidth <= 768;\n const wasMobile = this.isMobile;\n this.isMobile = nextIsMobile;\n if (!nextIsMobile) {\n this.showSidebar = false;\n this.showH5List = false;\n } else if (!wasMobile && nextIsMobile) {\n // 从桌面端切换到H5:如果加载了会话列表且无活跃会话,展示列表页\n if (this.sessionList.length > 0 && !this.activeSessionId) {\n this.showH5List = true;\n this.showAgentSelect = false;\n }\n }\n },\n toggleSidebar() {\n if (!this.isMobile) return;\n this.showSidebar = !this.showSidebar;\n },\n closeSidebar() {\n this.showSidebar = false;\n },\n // H5:调用原生返回上一级\n handleNativeBack() {\n if (this.$hybrid && typeof this.$hybrid.closePage === 'function') {\n this.$hybrid.closePage();\n } else if (window.history.length > 1) {\n window.history.back();\n }\n },\n // H5侧边栏返回按钮\n handleSidebarBack() {\n this.handleNativeBack();\n },\n agentjumpclick() {\n if (this.sending) {\n this.$message.warning('AI正在生成内容,暂时请不要切换对话');\n return;\n }\n this.currentAgent = '';\n this.currentAgentDesc = '';\n this.searchKeyword = '';\n this.activeSessionId = '';\n this.agentSuggestions = [];\n this.messages = [];\n this.showAgentSuggestions = false;\n this.showAgentSelect = true;\n this.showH5List = false;\n this.closeSidebar();\n },\n // H5:从详情页返回列表页\n goBackToList() {\n if (this.sending) {\n this.$message.warning('AI正在生成内容,暂时请不要切换对话');\n return;\n }\n // 关闭流连接\n if (this.eventSource) {\n this.eventSource.close();\n this.eventSource = null;\n }\n this.sending = false;\n this.clearWaitTimer();\n this.activeSessionId = '';\n this.messages = [];\n this.currentAgent = '';\n this.currentAgentDesc = '';\n this.agentInfo = {};\n this.contentCache = {};\n\n // 始终返回列表页\n this.showH5List = true;\n this.showAgentSelect = false;\n this.closeSidebar();\n },\n sendQuickMsg(message) {\n if (message) {\n this.inputText = message;\n this.sendMessage();\n }\n },\n formatMixText(str) {\n if (!str) return '';\n // 1. 中文 <=> 英文/数字 之间加空格\n let res = str.replace(/([a-zA-Z0-9])([\\u4e00-\\u9fff])/g, '$1 $2').replace(/([\\u4e00-\\u9fff])([a-zA-Z0-9])/g, '$1 $2');\n // 2. 连续英文单词分片粘连修复:字母紧跟字母中间加空格\n // 匹配 小写+大写 驼峰、连续分片拼接成一坨的英文\n res = res.replace(/([a-z])([A-Z])/g, '$1 $2');\n return res;\n },\n // 获取右侧头像样式(根据当前智能体在左侧列表中的位置决定颜色)\n getChatAvatarStyle(agent, avatar) {\n if (avatar) {\n return {\n backgroundImage: `url(${avatar})`,\n backgroundSize: 'cover',\n backgroundPosition: 'center',\n backgroundRepeat: 'no-repeat'\n };\n }\n const _agent = this.agentList.find(x => x.agentCode === agent);\n // 如果有网络图片,返回背景图样式\n if (agent.avatar) {\n return {\n backgroundImage: `url(${agent.avatar})`,\n backgroundSize: 'cover',\n backgroundPosition: 'center',\n backgroundRepeat: 'no-repeat'\n };\n }\n\n // 没有网络图片时,根据智能体在 agentList 中的索引位置决定颜色\n if (this.sessionList) {\n // 找到当前智能体在列表中的索引\n const index = this.sessionList.findIndex(item => item.agentCode === agent);\n if (index !== -1) {\n // 根据索引计算颜色类(4色循环)\n const colorIndex = index % 4 + 1;\n return {\n background: this.getGradientByColorIndex(colorIndex)\n };\n }\n }\n\n // 默认返回蓝色渐变\n return {\n background: 'linear-gradient(135deg, #1677ff, #4096ff)'\n };\n },\n // 根据颜色索引获取对应的渐变色\n getGradientByColorIndex(index) {\n const gradients = {\n 1: 'linear-gradient(135deg, #1677ff, #4096ff)',\n 2: 'linear-gradient(135deg, #52c41a, #73d13d)',\n 3: 'linear-gradient(135deg, #fa8c16, #ffa940)',\n 4: 'linear-gradient(135deg, #722ed1, #b37feb)'\n };\n return gradients[index] || gradients[1];\n },\n selectAgent(agentItem) {\n this.showAgentSelect = false;\n this.currentAgent = agentItem.agentCode;\n this.currentAgentName = agentItem.agentName;\n // 查找历史会话\n const existSession = this.sessionList.find(s => s.agentCode === agentItem.agentCode);\n if (existSession) {\n this.activeSessionId = existSession.id;\n this.switchSession(existSession);\n } else {\n this.createNewSession(agentItem.agentCode);\n }\n },\n createNewSession(agentCode) {\n // 你原有新建会话逻辑\n },\n // 检测是否滚动到底部,控制向下箭头显示隐藏\n checkScrollBottom(forceShowWhenNotBottom = false) {\n const el = this.$refs.messagesRef;\n if (!el) {\n this.showDownBtn = false;\n return;\n }\n const {\n scrollHeight,\n scrollTop,\n clientHeight\n } = el;\n const remain = scrollHeight - scrollTop - clientHeight;\n const atBottom = remain <= 80;\n if (atBottom) {\n this.showDownBtn = false;\n } else if (this.sending && scrollTop >= this.lastScrollTop && !forceShowWhenNotBottom) {\n // 发送AI回答时,如果用户没有主动向上滚动,就不要显示下箭头闪烁\n this.showDownBtn = false;\n } else {\n this.showDownBtn = true;\n }\n this.lastScrollTop = scrollTop;\n },\n // 固定最小高度:单行不撑开,超出才增高\n // H5 输入框获取焦点 - 滚动到可见区域(避免键盘遮挡)\n onInputFocus() {\n if (!this.isMobile) return;\n // 等待键盘弹出后再滚动\n setTimeout(() => {\n const footer = this.$el.querySelector('.chat-footer');\n if (footer) footer.scrollIntoView({\n behavior: 'smooth',\n block: 'end'\n });\n }, 350);\n },\n autoResizeTextarea() {\n const ta = this.$refs.taRef;\n if (!ta) return;\n // 根据端适配基准高度和最大高度\n const isMobile = this.isMobile;\n const baseH = isMobile ? 36 : 100;\n const maxH = isMobile ? 100 : 180;\n ta.style.height = `${baseH}px`;\n // 内容真实高度\n const realH = ta.scrollHeight;\n // 只有内容高度>基准才撑开,否则保持初始高度\n if (realH > baseH) {\n ta.style.height = `${Math.min(realH, maxH)}px`;\n }\n this.$nextTick(() => {\n this.checkScrollBottom(true);\n });\n },\n // Shift+Enter换行\n newLine(e) {\n // 取消浏览器默认行为\n e.preventDefault();\n // 拿到光标位置\n const ta = this.$refs.taRef;\n const start = ta.selectionStart;\n const end = ta.selectionEnd;\n // 在光标处插入换行符\n this.inputText = this.inputText.slice(0, start) + '\\n' + this.inputText.slice(end);\n // 光标定位到换行后\n this.$nextTick(() => {\n ta.selectionStart = ta.selectionEnd = start + 1;\n // 自动调整输入框高度\n this.autoResizeTextarea();\n });\n },\n toggleVoiceMode() {\n this.voiceMode = !this.voiceMode;\n if (!this.voiceMode) {\n // 切回文字模式时释放音频设备\n this.releaseAudio();\n }\n },\n // 确保音频设备已就绪(只请求一次权限,缓存 stream / AudioContext)\n async ensureAudioReady() {\n if (this.audioContext && this.audioStream) return true;\n if (!navigator.mediaDevices || !navigator.mediaDevices.getUserMedia) {\n alert('当前环境不支持麦克风访问');\n return false;\n }\n try {\n const stream = await navigator.mediaDevices.getUserMedia({\n audio: true\n });\n this.audioStream = stream;\n const audioContext = new (window.AudioContext || window.webkitAudioContext)({\n sampleRate: 16000\n });\n this.audioContext = audioContext;\n const source = audioContext.createMediaStreamSource(stream);\n const processor = audioContext.createScriptProcessor(4096, 1, 1);\n this.audioProcessor = processor;\n processor.onaudioprocess = e => {\n if (!this.isRecording) return;\n const inputData = e.inputBuffer.getChannelData(0);\n this.audioChunks.push(new Float32Array(inputData));\n };\n source.connect(processor);\n processor.connect(audioContext.destination);\n return true;\n } catch (err) {\n console.error('麦克风访问失败:', err);\n alert('麦克风权限被拒绝');\n return false;\n }\n },\n // H5语音录制 - 触摸开始\n async onRecordTouchStart(e) {\n if (this.sending) return;\n\n // 先确保音频已就绪(首次会请求权限并建立音频管线,后续复用)\n const ready = await this.ensureAudioReady();\n if (!ready) return;\n\n // 重置录音状态\n this.isCancelSwipe = false;\n this.recordStartY = e.touches[0].clientY;\n this.recordDuration = 0;\n this.audioChunks = [];\n\n // 音频就绪后才标记录制中并启动计时\n this.isRecording = true;\n this.recordingTimer = setInterval(() => {\n this.recordDuration++;\n if (this.recordDuration >= 60) {\n this.onRecordTouchEnd();\n }\n }, 1000);\n },\n // H5语音录制 - 触摸移动(检测上滑取消)\n onRecordTouchMove(e) {\n if (!this.isRecording) return;\n const touch = e.touches[0];\n const moveY = touch.clientY;\n const cancelThreshold = 60; // 上滑60px进入取消区域\n this.isCancelSwipe = this.recordStartY - moveY > cancelThreshold;\n },\n // H5语音录制 - 触摸结束\n onRecordTouchEnd() {\n if (!this.isRecording) return;\n this.isRecording = false;\n if (this.recordingTimer) {\n clearInterval(this.recordingTimer);\n this.recordingTimer = null;\n }\n this.stopAudioCapture(!this.isCancelSwipe);\n },\n // 停止音频采集并输出 WAV(保留音频设备,下次复用)\n stopAudioCapture(shouldSend) {\n this.isRecording = false;\n if (shouldSend && this.audioChunks.length > 0) {\n const wavBlob = this.encodePCMToWav(this.audioChunks, 16000);\n this.sendAudioBlob(wavBlob);\n }\n this.audioChunks = [];\n },\n // 取消录音(保留音频设备,下次复用)\n cancelRecording() {\n this.isRecording = false;\n if (this.recordingTimer) {\n clearInterval(this.recordingTimer);\n this.recordingTimer = null;\n }\n this.recordDuration = 0;\n this.isCancelSwipe = false;\n this.audioChunks = [];\n },\n // 释放音频资源(切换回文字模式或组件销毁时调用)\n releaseAudio() {\n this.cancelRecording();\n if (this.audioProcessor) {\n this.audioProcessor.disconnect();\n this.audioProcessor = null;\n }\n if (this.audioContext) {\n this.audioContext.close().catch(() => {});\n this.audioContext = null;\n }\n if (this.audioStream) {\n this.audioStream.getTracks().forEach(t => t.stop());\n this.audioStream = null;\n }\n },\n // 将 Float32 PCM 数据编码为 WAV Blob\n encodePCMToWav(chunks, sampleRate) {\n // 计算总采样数\n let totalLength = 0;\n for (const chunk of chunks) {\n totalLength += chunk.length;\n }\n\n // 转换为 Int16 PCM\n const pcmData = new Int16Array(totalLength);\n let offset = 0;\n for (const chunk of chunks) {\n for (let i = 0; i < chunk.length; i++) {\n const s = Math.max(-1, Math.min(1, chunk[i]));\n pcmData[offset++] = s < 0 ? s * 0x8000 : s * 0x7FFF;\n }\n }\n const numChannels = 1;\n const bitsPerSample = 16;\n const byteRate = sampleRate * numChannels * bitsPerSample / 8;\n const blockAlign = numChannels * bitsPerSample / 8;\n const dataSize = pcmData.length * (bitsPerSample / 8);\n const headerSize = 44;\n const totalSize = headerSize + dataSize;\n const buffer = new ArrayBuffer(totalSize);\n const view = new DataView(buffer);\n\n // RIFF header\n this._wavWriteString(view, 0, 'RIFF');\n view.setUint32(4, totalSize - 8, true);\n this._wavWriteString(view, 8, 'WAVE');\n\n // fmt chunk\n this._wavWriteString(view, 12, 'fmt ');\n view.setUint32(16, 16, true); // chunk size\n view.setUint16(20, 1, true); // PCM format\n view.setUint16(22, numChannels, true); // 单声道\n view.setUint32(24, sampleRate, true); // 采样率\n view.setUint32(28, byteRate, true);\n view.setUint16(32, blockAlign, true);\n view.setUint16(34, bitsPerSample, true);\n\n // data chunk\n this._wavWriteString(view, 36, 'data');\n view.setUint32(40, dataSize, true);\n\n // 写入 PCM 数据\n const pcmView = new Int16Array(buffer, headerSize, pcmData.length);\n pcmView.set(pcmData);\n return new Blob([buffer], {\n type: 'audio/wav'\n });\n },\n _wavWriteString(view, offset, str) {\n for (let i = 0; i < str.length; i++) {\n view.setUint8(offset + i, str.charCodeAt(i));\n }\n },\n // 发送音频\n sendAudioBlob(blob) {\n let appSeqId = _index2.default.getAppSeqId();\n let name = appSeqId + '.wav';\n const file = new File([blob], name, {\n type: 'audio/wav'\n });\n // TODO: 上传音频文件并调用 STT 接口\n this.sendAudioMessage(file);\n },\n sendAudioMessage(file) {\n // 插入本地 pending 消息\n const sttKey = 'stt_' + Date.now();\n const sttMsg = {\n role: 'user',\n content: '转化中...',\n _sttStatus: 'pending',\n _sttKey: sttKey,\n createTime: new Date().toISOString(),\n _key: sttKey\n };\n this.messages.push(sttMsg);\n this.scrollToBottom(true);\n (0, _index.fileUploadToObs)({\n _file: file,\n appSeqId: file.name\n }).then(resp => {\n if (resp.CommonMsg.Status === 200) {\n // 调用语音转文字接口\n return _apiObs.default.aliAudioToText({\n url: resp.obs_upload_data.obsUrl\n }).then(result => {\n if (result.code === '200' && result.data) {\n // 成功:删除 pending 消息,发送给后端\n const idx = this.messages.findIndex(m => m._sttKey === sttKey);\n if (idx !== -1) {\n this.messages.splice(idx, 1);\n }\n this.sendQuickMsg(result.data);\n } else {\n throw new Error(result.msg || '语音转文字失败');\n }\n });\n } else {\n throw new Error(resp.CommonMsg.Message || '文件上传失败');\n }\n }).catch(err => {\n console.error('语音转文字失败:', err);\n // 失败:更新为错误状态\n const idx = this.messages.findIndex(m => m._sttKey === sttKey);\n if (idx !== -1) {\n this.$set(this.messages, idx, {\n ...this.messages[idx],\n _sttStatus: 'error',\n content: '语音转文字失败'\n });\n }\n this.$message.error('语音转文字失败');\n });\n this.$message.success(`录音完成 (${this.recordDuration}s)`);\n },\n clearWaitTimer() {\n if (this.waitTimer) {\n clearInterval(this.waitTimer);\n this.waitTimer = null;\n }\n },\n loadAgents() {\n (0, _apichat.getChatAgents)().then(list => {\n this.agentList = list || [];\n // if (this.agentList.length > 0 && !this.currentAgent) {\n // const first = this.agentList[0]\n // this.currentAgent = first.agentCode\n // this.currentAgentDesc = first.description || ''\n // }\n }).catch(() => {});\n },\n loadSessions() {\n (0, _apichat.getSessionList)().then(list => {\n if (!this.activeSessionId) {\n this.sessionList = list || [];\n if (this.sessionList.length > 0) {\n if (this.isMobile) {\n // H5模式:不自动选中会话,展示列表页\n this.showAgentSelect = false;\n this.showH5List = true;\n this.showSidebar = false;\n } else {\n this.switchSession(this.sessionList[0]);\n }\n }\n if (this.sessionList.length === 0) {\n this.showAgentSelect = true;\n this.showH5List = false;\n }\n } else {\n this.sessionList = list || [];\n let _item = list.find(res => res.sessionId == this.activeSessionId);\n try {\n if (_item.suggestedQuestions) {\n _item.suggestedQuestions = JSON.parse(_item.suggestedQuestions);\n } else {\n _item.suggestedQuestions = [];\n }\n _item && (this.agentInfo = _item);\n } catch (err) {\n // JSON格式错误兜底空数组,防止页面报错\n this.agentInfo.questionArr = [];\n console.warn('快捷提问解析失败', err);\n }\n }\n }).catch(() => {});\n },\n onSearchClear() {\n this.agentSuggestions = [];\n this.showAgentSuggestions = false;\n },\n startChatWithAgent(agent) {\n console.log('选择了助手', agent.agentCode, this.currentAgent);\n if (agent.agentCode == this.currentAgent) {\n this.searchKeyword = '';\n this.agentSuggestions = [];\n this.showAgentSuggestions = false;\n return;\n }\n this.currentAgent = agent.agentCode;\n this.currentAgentDesc = agent.description || '';\n this.searchKeyword = '';\n this.agentInfo = {};\n this.agentSuggestions = [];\n this.messages = [];\n this.showAgentSuggestions = false;\n this.showAgentSelect = false;\n this.closeSidebar();\n if (this.isMobile) {\n this.showH5List = false; // H5:进入详情页,隐藏列表\n }\n const existing = this.sessionList.find(s => s.agentCode === agent.agentCode);\n if (existing) {\n this.switchSession(existing);\n } else {\n this.handleNewSession();\n }\n },\n handleNewSession() {\n if (!this.currentAgent) return;\n if (this.activeSessionId) this.closeOldSession();\n (0, _apichat.startSession)(this.currentAgent).then(res => {\n console.log(res, 'startChatWithAgentstartChatWithAgentstartChatWithAgent', this.agentInfo);\n this.activeSessionId = res.sessionId || '';\n this.loadSessions();\n const agent = this.agentList.find(a => a.agentCode === this.currentAgent);\n if (agent) this.addWelcomeMessage(agent);\n }).catch(() => {});\n },\n // H5长按删除 - 触摸开始\n onSessionTouchStart(s, e) {\n if (!this.isMobile) return;\n this.longPressed = false;\n this.longPressTimer = setTimeout(() => {\n this.longPressed = true;\n this.handleDeleteSession(s);\n }, 600);\n },\n // H5长按删除 - 触摸结束/移动(取消长按)\n onSessionTouchEnd() {\n if (this.longPressTimer) {\n clearTimeout(this.longPressTimer);\n this.longPressTimer = null;\n }\n },\n onSessionTouchMove() {\n if (this.longPressTimer) {\n clearTimeout(this.longPressTimer);\n this.longPressTimer = null;\n }\n },\n async switchSession(s) {\n if (this.longPressed) {\n this.longPressed = false;\n return;\n }\n if (this.sending) {\n this.$message.warning('AI正在生成内容,暂时请不要切换对话');\n return;\n }\n this.showAgentSelect = false;\n this.closeSidebar();\n if (this.isMobile) {\n this.showH5List = false; // H5:进入详情页,隐藏列表\n }\n if (this.activeSessionId === s.sessionId) return;\n this.contentCache = {};\n this.activeSessionId = s.sessionId;\n this.currentAgent = s.agentCode;\n console.log('进入');\n this.agentInfo = s;\n console.log('进入', this.agentInfo);\n try {\n if (s.suggestedQuestions) {\n this.agentInfo.suggestedQuestions = JSON.parse(s.suggestedQuestions);\n } else {\n this.agentInfo.suggestedQuestions = [];\n }\n } catch (err) {\n // JSON格式错误兜底空数组,防止页面报错\n this.agentInfo.questionArr = [];\n console.warn('快捷提问解析失败', err);\n }\n const agent = this.agentList.find(a => a.agentCode === s.agentCode);\n this.currentAgentDesc = agent ? agent.description || '' : '';\n this.msgPage = 1;\n this.msgTotal = 0;\n this.messages = []; // 先清空,但开启加载锁屏蔽空白页\n this.loadingSessionMsg = true; // 开启加载标记\n (0, _apichat.syncToken)((0, _cookie.getToken)(), s.sessionId);\n try {\n const res = await (0, _apichat.getSessionMessages)(s.sessionId, 1, 10);\n const list = Array.isArray(res) ? res : res.list || [];\n this.msgTotal = res.total || list.length;\n this.msgPage = 1;\n const asAsc = (list || []).slice().reverse();\n this.messages = asAsc.map(m => ({\n role: m.role,\n content: m.content || '',\n thinking: m.thinking || '',\n toolCalls: [],\n agentName: m.role === 'assistant' ? s.agentName || '' : '',\n createTime: m.createTime || null,\n _key: m.createTime ? 'msg_' + m.createTime : 'msg_' + Date.now() + '_' + Math.random()\n }));\n if (this.messages.length === 0 && agent) this.addWelcomeMessage(agent);\n await this.$nextTick();\n this.$nextTick(() => {\n this.scrollToBottomOnce();\n this.checkScrollBottom();\n });\n } catch (e) {\n this.messages = [];\n } finally {\n // 无论成功失败,结束后关闭加载锁\n this.loadingSessionMsg = false;\n }\n },\n loadMoreMessages() {\n const nextPage = this.msgPage + 1;\n const maxPage = Math.ceil(this.msgTotal / 10);\n if (nextPage > maxPage) {\n this.loadingMore = false;\n return;\n }\n (0, _apichat.getSessionMessages)(this.activeSessionId, nextPage, 10).then(res => {\n const list = Array.isArray(res) ? res : res.list || [];\n this.msgPage = nextPage;\n const asAsc = (list || []).slice().reverse();\n const prepend = asAsc.map(m => ({\n role: m.role,\n content: m.content || '',\n thinking: m.thinking || '',\n toolCalls: [],\n agentName: '',\n createTime: m.createTime || null,\n _key: m.createTime ? 'msg_' + m.createTime : 'msg_' + Date.now() + '_' + Math.random()\n }));\n const container = this.$refs.messagesRef;\n const oldScrollHeight = container ? container.scrollHeight : 0;\n const oldScrollTop = container ? container.scrollTop : 0;\n this.messages = [...prepend, ...this.messages];\n this.$nextTick(() => {\n if (container) {\n container.scrollTop = oldScrollTop + (container.scrollHeight - oldScrollHeight);\n }\n this.loadingMore = false;\n });\n }).catch(() => {\n this.loadingMore = false;\n });\n },\n onScrollMessages() {\n const container = this.$refs.messagesRef;\n if (!container || this.loadingMore) return;\n const isAtBottom = container.scrollTop + container.clientHeight >= container.scrollHeight - 100;\n this.checkScrollBottom();\n if (isAtBottom) return;\n if (container.scrollTop < 50 && this.msgPage < Math.ceil(this.msgTotal / 10)) {\n this.loadingMore = true;\n this.loadMoreMessages();\n }\n },\n handleDeleteSession(s) {\n this.$confirm(`确认删除「${s.agentName || s.agentCode}」的会话?`, '提示', {\n type: 'warning'\n }).then(() => {\n (0, _apichat.deleteSession)(s.sessionId).then(() => {\n if (this.activeSessionId === s.sessionId) {\n this.activeSessionId = '';\n this.messages = [];\n this.currentAgent = '';\n this.currentAgentDesc = '';\n if (this.isMobile) {\n this.showH5List = false;\n this.showAgentSelect = true;\n } else {\n this.showAgentSelect = true;\n }\n }\n this.loadSessions();\n });\n }).catch(() => {});\n },\n closeOldSession() {},\n onAgentChange(code) {\n const agent = this.agentList.find(a => a.agentCode === code);\n this.currentAgentDesc = agent ? agent.description || '' : '';\n this.handleNewSession();\n },\n addWelcomeMessage(agent) {\n this.greeting = '';\n // if (!agent) return\n // const name = agent.agentName || '助手';\n const _agent = this.agentList.find(x => x.agentCode === this.currentAgent);\n this.greeting = _agent.greeting || `很高兴为您服务,请问有什么可以帮到您?`;\n // this.messages.push({\n // role: 'assistant',\n // content: _content,\n // thinking: '',\n // agentName: name,\n // _key: 'welcome_' + Date.now()\n // })\n },\n async sendMessage() {\n const text = this.inputText.trim();\n if (!text || this.sending) return;\n if (!this.activeSessionId) {\n await (0, _apichat.startSession)(this.currentAgent).then(res => {\n this.activeSessionId = res.sessionId || '';\n this.loadSessions();\n });\n if (!this.activeSessionId) return;\n }\n this.inputText = '';\n const ta = this.$refs.taRef;\n const isMobile = this.isMobile;\n const baseH = isMobile ? 36 : 100;\n if (ta) {\n ta.style.height = baseH + 'px'; // 强制恢复初始高度\n }\n this.showDownBtn = false;\n this.messages.push({\n role: 'user',\n content: text,\n createTime: new Date().toISOString(),\n _key: 'user_' + Date.now() + '_' + Math.random()\n });\n const agentName = this.currentAgentName;\n const msgIdx = this.messages.push({\n role: \"assistant\",\n content: \"\",\n thinking: \"\",\n loading: true,\n toolCalls: [],\n agentName,\n createTime: new Date().toISOString(),\n _key: 'asst_' + Date.now() + '_' + Math.random()\n }) - 1;\n this.scrollToBottom(true);\n this.sending = true;\n this.waitSeconds = 0;\n if (this.waitTimer) clearInterval(this.waitTimer);\n this.waitTimer = setInterval(() => {\n this.waitSeconds++;\n }, 1000);\n let thinkingBuffer = '';\n let finalContent = '';\n let answerBuffer = '';\n let thinkDisplayed = 0;\n let typeTimer = null;\n typeTimer = setInterval(() => {\n if (!this.messages[msgIdx]) return;\n if (thinkDisplayed < thinkingBuffer.length) {\n thinkDisplayed += 50;\n if (thinkDisplayed > thinkingBuffer.length) thinkDisplayed = thinkingBuffer.length;\n this.messages[msgIdx].thinking = thinkingBuffer.substring(0, thinkDisplayed);\n this.scrollToBottom();\n } else if (finalContent && !this.messages[msgIdx].content) {\n clearInterval(typeTimer);\n const key = this.messages[msgIdx]._key;\n if (key) {\n this.$delete(this.contentCache, key);\n this.$delete(this.contentCache, key + '_t');\n }\n typeTimer = null;\n this.messages[msgIdx].content = finalContent;\n this.messages[msgIdx].thinking = thinkingBuffer;\n this.messages[msgIdx].loading = false;\n this.sending = false;\n this.clearWaitTimer();\n this.scrollToBottom();\n this.loadSessions();\n }\n }, 30);\n const url = (0, _apichat.createStreamUrl)(this.activeSessionId, text);\n if (this.eventSource) {\n this.eventSource.close();\n }\n this.eventSource = new EventSource(url);\n const es = this.eventSource;\n es.addEventListener('reasoning', e => {\n if (e.data) {\n const chunk = e.data;\n // 1. 先处理当前分片内部的中英文、数字、标点空格\n let cleanChunk = chunk.replace(/([a-z])([A-Z])/g, '$1 $2').replace(/([A-Z]+)([A-Z][a-z])/g, '$1 $2').replace(/([a-zA-Z])([\\u4e00-\\u9fff])/g, '$1 $2').replace(/([\\u4e00-\\u9fff])([a-zA-Z])/g, '$1 $2').replace(/([a-zA-Z])(\\d)/g, '$1 $2').replace(/(\\d)([a-zA-Z])/g, '$1 $2').replace(/\\s+([:,.!?])/g, '$1').replace(/([:,.!?])\\s+/g, '$1 ');\n cleanChunk = cleanChunk.replace(/\\s+/g, ' ');\n\n // 2. 关键:判断前一段末尾 + 当前段开头都是英文,补空格分隔\n const lastChar = thinkingBuffer.slice(-1);\n const firstChar = cleanChunk.slice(0, 1);\n const isLetter = c => /[a-zA-Z]/.test(c);\n if (isLetter(lastChar) && isLetter(firstChar)) {\n // 两段都是英文衔接,中间加空格\n thinkingBuffer += ' ' + cleanChunk;\n } else {\n thinkingBuffer += cleanChunk;\n }\n }\n });\n es.addEventListener('reasoning_result', e => {\n if (e.data) {\n thinkingBuffer = e.data;\n }\n });\n es.addEventListener('answer', e => {\n if (e.data) {\n answerBuffer += e.data;\n if (this.messages[msgIdx]) {\n this.messages[msgIdx].content += e.data.replace(/([a-zA-Z]+)([\\u4e00-\\u9fff])/g, '$1 $2').replace(/([\\u4e00-\\u9fff])([a-zA-Z]+)/g, '$1 $2').replace(/([a-z])([A-Z])/g, '$1 $2').replace(/([A-Z]+)([A-Z][a-z])/g, '$1 $2').replace(/([a-zA-Z])(\\d)/g, '$1 $2').replace(/(\\d)([a-zA-Z])/g, '$1 $2');\n this.scrollToBottom();\n }\n }\n });\n es.addEventListener('tool_result', e => {\n if (e.data && this.messages[msgIdx]) {\n if (!this.messages[msgIdx].toolCalls) this.messages[msgIdx].toolCalls = [];\n this.messages[msgIdx].toolCalls.push(e.data);\n this.scrollToBottom();\n }\n });\n es.addEventListener('agent_result', e => {\n finalContent = e.data || '';\n es.close();\n this.eventSource = null;\n if (this.messages[msgIdx]) {\n const key = this.messages[msgIdx]._key;\n if (key) this.$delete(this.contentCache, key);\n this.messages[msgIdx].content = finalContent;\n this.messages[msgIdx].thinking = thinkingBuffer;\n this.messages[msgIdx].loading = false;\n }\n this.sending = false;\n this.clearWaitTimer();\n if (typeTimer) {\n clearInterval(typeTimer);\n typeTimer = null;\n }\n this.scrollToBottom();\n this.loadSessions();\n });\n es.onerror = err => {\n console.log('[SSE] onerror', err);\n if (thinkingBuffer.length > 0 && !finalContent) finalContent = thinkingBuffer;\n if (!finalContent) finalContent = '❌ 连接中断';\n es.close();\n this.eventSource = null;\n if (this.messages[msgIdx]) {\n const key = this.messages[msgIdx]._key;\n if (key) this.$delete(this.contentCache, key);\n this.messages[msgIdx].content = finalContent;\n this.messages[msgIdx].thinking = thinkingBuffer;\n this.messages[msgIdx].loading = false;\n }\n this.sending = false;\n this.clearWaitTimer();\n if (typeTimer) {\n clearInterval(typeTimer);\n typeTimer = null;\n }\n this.scrollToBottom();\n };\n },\n stopAgent() {\n if (this.eventSource) {\n this.eventSource.close();\n this.eventSource = null;\n }\n if (this.activeSessionId) {\n (0, _apichat.stopStream)(this.activeSessionId).catch(() => {});\n }\n if (this.messages.length > 0) {\n const last = this.messages[this.messages.length - 1];\n if (last && last.loading) {\n last.content = last.content || last.thinking || '⏹ 已停止';\n last.loading = false;\n this.$delete(this.contentCache, last._key);\n }\n }\n this.sending = false;\n this.clearWaitTimer();\n },\n copyText(content) {\n if (!content) return;\n navigator.clipboard.writeText(content.replace(/<[^>]+>/g, '')).then(() => {\n this.$message({\n message: '已复制到剪贴板',\n type: 'success',\n duration: 1500\n });\n }).catch(() => {\n this.$message({\n message: '复制失败',\n type: 'error',\n duration: 2000\n });\n });\n },\n copyAsImage(content) {\n if (!content) return;\n // 创建临时容器渲染 Markdown\n const div = document.createElement('div');\n div.className = 'copy-image-render';\n div.style.cssText = 'position:fixed;left:-9999px;top:0;width:600px;padding:20px;background:#fff;font-size:14px;line-height:1.6;color:#333;border-radius:8px;font-family:-apple-system,BlinkMacSystemFont,sans-serif;';\n div.innerHTML = this.renderMarkdown(content);\n document.body.appendChild(div);\n this.$message({\n message: '正在生成图片...',\n type: 'info',\n duration: 2000\n });\n (0, _html2canvas.default)(div, {\n scale: 2,\n useCORS: true,\n backgroundColor: '#ffffff'\n }).then(canvas => {\n canvas.toBlob(blob => {\n if (blob) {\n navigator.clipboard.write([new ClipboardItem({\n 'image/png': blob\n })]).then(() => {\n this.$message({\n message: '图片已复制到剪贴板',\n type: 'success',\n duration: 1500\n });\n }).catch(() => {\n this.$message({\n message: '复制图片失败',\n type: 'error',\n duration: 2000\n });\n });\n }\n }, 'image/png');\n }).catch(() => {\n this.$message({\n message: '生成图片失败',\n type: 'error',\n duration: 2000\n });\n }).finally(() => {\n document.body.removeChild(div);\n });\n },\n formatTime(t) {\n if (!t) return '';\n const d = new Date(t.replace(' ', 'T'));\n const now = new Date();\n const diff = (now - d) / 1000;\n if (diff < 60) return '刚刚';\n if (diff < 3600) return Math.floor(diff / 60) + '分钟前';\n if (diff < 86400) return Math.floor(diff / 3600) + '小时前';\n return d.getMonth() + 1 + '/' + d.getDate();\n },\n getInitial(name) {\n if (!name) return '?';\n return name.charAt(0);\n },\n renderMarkdown(text) {\n if (!text) return '';\n try {\n return md.render(text);\n } catch (err) {\n return this.escapeHtml(text);\n }\n },\n renderStreaming(text, msgKey) {\n if (!text) return '';\n console.log('进入');\n const cache = this.contentCache[msgKey];\n const lines = text.split('\\n');\n const lastLineIdx = lines.length - 1;\n if (!cache) {\n try {\n const html = md.render(text);\n this.$set(this.contentCache, msgKey, {\n renderedLines: lastLineIdx,\n html,\n fullText: text\n });\n return html;\n } catch {\n return this.escapeHtml(text);\n }\n }\n if (text === cache.fullText) return cache.html;\n cache.fullText = text;\n\n // 行数没变,仅末尾追加字符,直接拼接尾行(原有逻辑不变)\n if (lastLineIdx === cache.renderedLines) {\n return cache.html + this.escapeHtml(lines[lastLineIdx]);\n }\n\n // 场景1:行数变少/文本回退截断,全量重渲染(原有分支保留,内部修复)\n if (lastLineIdx < cache.renderedLines) {\n try {\n // 重新截取所有完整行生成全新基础html,清空旧叠加内容\n const fullLines = lines.slice(0, lastLineIdx);\n let newBaseHtml = '';\n if (fullLines.length > 0) {\n newBaseHtml = md.render(fullLines.join('\\n'));\n }\n cache.html = newBaseHtml;\n cache.renderedLines = lastLineIdx;\n // 拼接尾行\n const lastLine = this.escapeHtml(lines[lastLineIdx]);\n return cache.html + (lastLine || '');\n } catch {\n return this.escapeHtml(text);\n }\n }\n\n // 场景2:新增完整行,修复:不再累加旧html,重新从0生成完整行基础\n if (cache.renderedLines < lastLineIdx) {\n // 关键修复:重新切片所有完整行,抛弃之前叠加的旧html,杜绝重复\n const allFullLines = lines.slice(0, lastLineIdx);\n let newBaseHtml = '';\n if (allFullLines.length > 0) {\n newBaseHtml = md.render(allFullLines.join('\\n'));\n }\n cache.html = newBaseHtml;\n cache.renderedLines = lastLineIdx;\n }\n const lastLine = this.escapeHtml(lines[lastLineIdx]);\n cache.renderedLines = lastLineIdx;\n return cache.html + (lastLine || '');\n },\n escapeHtml(text) {\n if (!text) return '';\n return text.replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>');\n },\n scrollToTop() {\n const el = this.$refs.messagesRef;\n if (el) el.scrollTop = 0;\n },\n scrollToBottom(force = false) {\n if (this.showDownBtn && !force) return;\n this.$nextTick(() => {\n const el = this.$refs.messagesRef;\n if (el) {\n el.scrollTop = el.scrollHeight;\n this.lastScrollTop = el.scrollTop;\n this.showDownBtn = false; // 滚动到底部后立刻隐藏箭头\n }\n });\n },\n scrollToBottomOnce() {\n // 清理旧定时器,防止任何泄漏\n clearTimeout(this._scrollTimer);\n this.$nextTick(() => {\n let retry = 0;\n const maxRetry = 6; // 重试6次,足够覆盖所有渲染延迟\n\n const tryScroll = () => {\n var _this$$refs;\n const el = (_this$$refs = this.$refs) === null || _this$$refs === void 0 ? void 0 : _this$$refs.messagesRef;\n if (!el) {\n this._scrollTimer = setTimeout(tryScroll, 50);\n return;\n }\n\n // 临时禁用平滑滚动,立即跳到底部\n const originalScrollBehavior = el.style.scrollBehavior;\n el.style.scrollBehavior = 'auto';\n el.scrollTop = el.scrollHeight - el.clientHeight;\n el.style.scrollBehavior = originalScrollBehavior;\n this.showDownBtn = false;\n };\n tryScroll();\n });\n }\n },\n beforeDestroy() {\n window.removeEventListener('resize', this.updateViewportState);\n this.releaseAudio();\n this.contentCache = {};\n clearTimeout(this._scrollTimer);\n if (this.eventSource) {\n this.eventSource.onerror = null;\n this.eventSource.close();\n this.eventSource = null;\n }\n if (this.waitTimer) {\n clearInterval(this.waitTimer);\n this.waitTimer = null;\n }\n if (this._typeTimer) {\n clearInterval(this._typeTimer);\n this._typeTimer = null;\n }\n }\n};\n\n//# sourceURL=webpack://ZjPluginIntelligent/./src/lib/components/chatMain/index.vue?./node_modules/_cache-loader@4.1.0@cache-loader/dist/cjs.js??ref--13-0!./node_modules/_babel-loader@8.4.1@babel-loader/lib!./node_modules/_cache-loader@4.1.0@cache-loader/dist/cjs.js??ref--1-0!./node_modules/_vue-loader@15.11.1@vue-loader/lib??vue-loader-options");
|
|
951
|
+
eval("\n\nvar _interopRequireDefault = __webpack_require__(/*! ./node_modules/_@babel_runtime@7.28.4@@babel/runtime/helpers/interopRequireDefault.js */ \"./node_modules/_@babel_runtime@7.28.4@@babel/runtime/helpers/interopRequireDefault.js\").default;\nObject.defineProperty(exports, \"__esModule\", {\n value: true\n});\nexports.default = void 0;\n__webpack_require__(/*! core-js/modules/es.error.cause.js */ \"./node_modules/_core-js@3.45.1@core-js/modules/es.error.cause.js\");\n__webpack_require__(/*! core-js/modules/es.array.push.js */ \"./node_modules/_core-js@3.45.1@core-js/modules/es.array.push.js\");\n__webpack_require__(/*! core-js/modules/es.array-buffer.detached.js */ \"./node_modules/_core-js@3.45.1@core-js/modules/es.array-buffer.detached.js\");\n__webpack_require__(/*! core-js/modules/es.array-buffer.transfer.js */ \"./node_modules/_core-js@3.45.1@core-js/modules/es.array-buffer.transfer.js\");\n__webpack_require__(/*! core-js/modules/es.array-buffer.transfer-to-fixed-length.js */ \"./node_modules/_core-js@3.45.1@core-js/modules/es.array-buffer.transfer-to-fixed-length.js\");\n__webpack_require__(/*! core-js/modules/es.iterator.constructor.js */ \"./node_modules/_core-js@3.45.1@core-js/modules/es.iterator.constructor.js\");\n__webpack_require__(/*! core-js/modules/es.iterator.filter.js */ \"./node_modules/_core-js@3.45.1@core-js/modules/es.iterator.filter.js\");\n__webpack_require__(/*! core-js/modules/es.iterator.find.js */ \"./node_modules/_core-js@3.45.1@core-js/modules/es.iterator.find.js\");\n__webpack_require__(/*! core-js/modules/es.iterator.for-each.js */ \"./node_modules/_core-js@3.45.1@core-js/modules/es.iterator.for-each.js\");\n__webpack_require__(/*! core-js/modules/es.iterator.map.js */ \"./node_modules/_core-js@3.45.1@core-js/modules/es.iterator.map.js\");\n__webpack_require__(/*! core-js/modules/es.typed-array.at.js */ \"./node_modules/_core-js@3.45.1@core-js/modules/es.typed-array.at.js\");\n__webpack_require__(/*! core-js/modules/es.typed-array.find-last.js */ \"./node_modules/_core-js@3.45.1@core-js/modules/es.typed-array.find-last.js\");\n__webpack_require__(/*! core-js/modules/es.typed-array.find-last-index.js */ \"./node_modules/_core-js@3.45.1@core-js/modules/es.typed-array.find-last-index.js\");\n__webpack_require__(/*! core-js/modules/es.typed-array.set.js */ \"./node_modules/_core-js@3.45.1@core-js/modules/es.typed-array.set.js\");\n__webpack_require__(/*! core-js/modules/es.typed-array.to-reversed.js */ \"./node_modules/_core-js@3.45.1@core-js/modules/es.typed-array.to-reversed.js\");\n__webpack_require__(/*! core-js/modules/es.typed-array.to-sorted.js */ \"./node_modules/_core-js@3.45.1@core-js/modules/es.typed-array.to-sorted.js\");\n__webpack_require__(/*! core-js/modules/es.typed-array.with.js */ \"./node_modules/_core-js@3.45.1@core-js/modules/es.typed-array.with.js\");\nvar _apichat = __webpack_require__(/*! @lib/api/apichat */ \"./src/lib/api/apichat.js\");\nvar _markdownIt = _interopRequireDefault(__webpack_require__(/*! markdown-it */ \"./node_modules/_markdown-it@14.1.0@markdown-it/index.mjs\"));\nvar _html2canvas = _interopRequireDefault(__webpack_require__(/*! html2canvas */ \"./node_modules/_html2canvas@1.4.1@html2canvas/dist/html2canvas.js\"));\nvar _index = __webpack_require__(/*! @lib/socket/fileManager/obs/index */ \"./src/lib/socket/fileManager/obs/index.js\");\nvar _index2 = _interopRequireDefault(__webpack_require__(/*! @lib/socket/utils/index */ \"./src/lib/socket/utils/index.js\"));\nvar _cookie = __webpack_require__(/*! @lib/utils/cookie.js */ \"./src/lib/utils/cookie.js\");\nvar _apiObs = _interopRequireDefault(__webpack_require__(/*! @lib/api/apiObs */ \"./src/lib/api/apiObs.js\"));\nconst md = new _markdownIt.default({\n breaks: true,\n html: false,\n linkify: true,\n typographer: true\n});\nmd.enable('table');\nvar _default = exports.default = {\n name: 'ChatMain',\n props: {\n Ak: {\n type: String,\n default: ''\n },\n Sk: {\n type: String,\n default: ''\n },\n imAccount: {\n type: String,\n default: ''\n },\n companyNo: {\n type: String,\n default: ''\n },\n isIntelShow: {\n default: false,\n type: Boolean\n },\n chatImToken: {\n default: '',\n type: String\n }\n },\n data() {\n return {\n agentList: [],\n currentAgent: '',\n currentAgentDesc: '',\n sessionsLoaded: false,\n searchKeyword: '',\n agentSuggestions: [],\n showAgentSuggestions: false,\n sessionList: [],\n activeSessionId: '',\n messages: [],\n loadingMore: false,\n sending: false,\n waitTimer: null,\n waitSeconds: 0,\n canceling: false,\n msgPage: 1,\n msgMaxPage: 1,\n msgTotal: 0,\n inputText: '',\n eventSource: null,\n showToolInfo: false,\n showDownBtn: false,\n // 控制向下箭头显隐\n lastScrollTop: 0,\n scrollTimer: null,\n // 滚动防抖(新增)\n showAgentSelect: true,\n isMobile: false,\n showSidebar: false,\n showH5List: false,\n // H5列表模式(展示会话列表而非聊天详情)\n _scrollTimer: null,\n agentInfo: {},\n contentCache: {},\n // 流式分行缓存 key=msg._key\n loadingSessionMsg: false,\n // 会话消息加载中标记\n greeting: '',\n longPressTimer: null,\n longPressed: false,\n // H5 语音输入\n voiceMode: false,\n // true=语音模式,false=文字模式\n isRecording: false,\n // 是否正在录音\n recordDuration: 0,\n // 录音时长(秒)\n recordingTimer: null,\n // 时长计时器\n audioContext: null,\n // AudioContext 实例\n audioStream: null,\n // MediaStream(用于清理)\n audioProcessor: null,\n // ScriptProcessorNode\n audioChunks: [],\n // Float32Array 数据块\n isCancelSwipe: false,\n // 是否上滑取消\n recordStartY: 0 // 触摸起始Y坐标\n };\n },\n created() {\n if (this.Ak || this.Sk) {\n (0, _apichat.setApiAuth)(this.Ak, this.Sk, this.imAccount, this.companyNo, this.chatImToken);\n }\n this.loadAgents();\n this.loadSessions();\n },\n mounted() {\n this.updateViewportState();\n window.addEventListener('resize', this.updateViewportState, {\n passive: true\n });\n // 监听 visualViewport 变化(键盘弹出/收起)\n if (window.visualViewport) {\n window.visualViewport.addEventListener('resize', this.onViewportResize, {\n passive: true\n });\n }\n },\n computed: {\n waitClass() {\n if (this.waitSeconds > 15) return 'wait-15';\n if (this.waitSeconds > 10) return 'wait-10';\n if (this.waitSeconds > 5) return 'wait-5';\n return '';\n },\n filteredSessions() {\n if (!this.searchKeyword) return this.sessionList;\n const kw = this.searchKeyword.toLowerCase();\n return this.sessionList.filter(s => {\n const name = (s.agentName || s.agentCode || '').toLowerCase();\n return name.includes(kw);\n });\n },\n currentAgentName() {\n if (!this.currentAgent) return '';\n const a = this.agentList.find(x => x.agentCode === this.currentAgent);\n return a ? a.agentName || a.agentCode : this.currentAgent;\n }\n },\n watch: {\n searchKeyword(val) {\n if (this.searchTimer) clearTimeout(this.searchTimer);\n if (!val.trim()) {\n this.agentSuggestions = [];\n this.showAgentSuggestions = false;\n this.closeSidebar();\n return;\n }\n this.searchTimer = setTimeout(() => {\n (0, _apichat.getChatAgents)(val.trim()).then(list => {\n this.agentSuggestions = list || [];\n this.showAgentSuggestions = this.agentSuggestions.length > 0;\n }).catch(() => {\n this.agentSuggestions = [];\n });\n }, 300);\n }\n // ak: {\n // handler(newVal) {\n // setApiAuth(newVal, this.sk)\n // },\n // immediate: true\n // },\n // sk: {\n // handler(newVal) {\n // setApiAuth(this.ak, newVal)\n // },\n // immediate: true\n // }\n },\n methods: {\n updateViewportState() {\n if (typeof window === 'undefined') return;\n const nextIsMobile = window.innerWidth <= 768;\n const wasMobile = this.isMobile;\n this.isMobile = nextIsMobile;\n if (!nextIsMobile) {\n this.showSidebar = false;\n this.showH5List = false;\n } else if (!wasMobile && nextIsMobile) {\n // 从桌面端切换到H5:如果加载了会话列表且无活跃会话,展示列表页\n if (this.sessionList.length > 0 && !this.activeSessionId) {\n this.showH5List = true;\n this.showAgentSelect = false;\n }\n }\n },\n toggleSidebar() {\n if (!this.isMobile) return;\n this.showSidebar = !this.showSidebar;\n },\n closeSidebar() {\n this.showSidebar = false;\n },\n // H5:调用原生返回上一级\n handleNativeBack() {\n if (this.$hybrid && typeof this.$hybrid.closePage === 'function') {\n this.$hybrid.closePage();\n } else if (window.history.length > 1) {\n window.history.back();\n }\n },\n // H5侧边栏返回按钮\n handleSidebarBack() {\n this.handleNativeBack();\n },\n agentjumpclick() {\n if (this.sending) {\n this.$message.warning('AI正在生成内容,暂时请不要切换对话');\n return;\n }\n this.currentAgent = '';\n this.currentAgentDesc = '';\n this.searchKeyword = '';\n this.activeSessionId = '';\n this.agentSuggestions = [];\n this.messages = [];\n this.showAgentSuggestions = false;\n this.showAgentSelect = true;\n this.showH5List = false;\n this.closeSidebar();\n },\n // H5:从详情页返回列表页\n goBackToList() {\n if (this.sending) {\n this.$message.warning('AI正在生成内容,暂时请不要切换对话');\n return;\n }\n // 关闭流连接\n if (this.eventSource) {\n this.eventSource.close();\n this.eventSource = null;\n }\n this.sending = false;\n this.clearWaitTimer();\n this.activeSessionId = '';\n this.messages = [];\n this.currentAgent = '';\n this.currentAgentDesc = '';\n this.agentInfo = {};\n this.contentCache = {};\n\n // 始终返回列表页\n this.showH5List = true;\n this.showAgentSelect = false;\n this.closeSidebar();\n },\n sendQuickMsg(message) {\n if (message) {\n this.inputText = message;\n this.sendMessage();\n }\n },\n formatMixText(str) {\n if (!str) return '';\n // 1. 中文 <=> 英文/数字 之间加空格\n let res = str.replace(/([a-zA-Z0-9])([\\u4e00-\\u9fff])/g, '$1 $2').replace(/([\\u4e00-\\u9fff])([a-zA-Z0-9])/g, '$1 $2');\n // 2. 连续英文单词分片粘连修复:字母紧跟字母中间加空格\n // 匹配 小写+大写 驼峰、连续分片拼接成一坨的英文\n res = res.replace(/([a-z])([A-Z])/g, '$1 $2');\n return res;\n },\n // 获取右侧头像样式(根据当前智能体在左侧列表中的位置决定颜色)\n getChatAvatarStyle(agent, avatar) {\n if (avatar) {\n return {\n backgroundImage: `url(${avatar})`,\n backgroundSize: 'cover',\n backgroundPosition: 'center',\n backgroundRepeat: 'no-repeat'\n };\n }\n const _agent = this.agentList.find(x => x.agentCode === agent);\n // 如果有网络图片,返回背景图样式\n if (agent.avatar) {\n return {\n backgroundImage: `url(${agent.avatar})`,\n backgroundSize: 'cover',\n backgroundPosition: 'center',\n backgroundRepeat: 'no-repeat'\n };\n }\n\n // 没有网络图片时,根据智能体在 agentList 中的索引位置决定颜色\n if (this.sessionList) {\n // 找到当前智能体在列表中的索引\n const index = this.sessionList.findIndex(item => item.agentCode === agent);\n if (index !== -1) {\n // 根据索引计算颜色类(4色循环)\n const colorIndex = index % 4 + 1;\n return {\n background: this.getGradientByColorIndex(colorIndex)\n };\n }\n }\n\n // 默认返回蓝色渐变\n return {\n background: 'linear-gradient(135deg, #1677ff, #4096ff)'\n };\n },\n // 根据颜色索引获取对应的渐变色\n getGradientByColorIndex(index) {\n const gradients = {\n 1: 'linear-gradient(135deg, #1677ff, #4096ff)',\n 2: 'linear-gradient(135deg, #52c41a, #73d13d)',\n 3: 'linear-gradient(135deg, #fa8c16, #ffa940)',\n 4: 'linear-gradient(135deg, #722ed1, #b37feb)'\n };\n return gradients[index] || gradients[1];\n },\n selectAgent(agentItem) {\n this.showAgentSelect = false;\n this.currentAgent = agentItem.agentCode;\n this.currentAgentName = agentItem.agentName;\n // 查找历史会话\n const existSession = this.sessionList.find(s => s.agentCode === agentItem.agentCode);\n if (existSession) {\n this.activeSessionId = existSession.id;\n this.switchSession(existSession);\n } else {\n this.createNewSession(agentItem.agentCode);\n }\n },\n createNewSession(agentCode) {\n // 你原有新建会话逻辑\n },\n // 检测是否滚动到底部,控制向下箭头显示隐藏\n checkScrollBottom(forceShowWhenNotBottom = false) {\n const el = this.$refs.messagesRef;\n if (!el) {\n this.showDownBtn = false;\n return;\n }\n const {\n scrollHeight,\n scrollTop,\n clientHeight\n } = el;\n const remain = scrollHeight - scrollTop - clientHeight;\n const atBottom = remain <= 80;\n if (atBottom) {\n this.showDownBtn = false;\n } else if (this.sending && scrollTop >= this.lastScrollTop && !forceShowWhenNotBottom) {\n // 发送AI回答时,如果用户没有主动向上滚动,就不要显示下箭头闪烁\n this.showDownBtn = false;\n } else {\n this.showDownBtn = true;\n }\n this.lastScrollTop = scrollTop;\n },\n // 固定最小高度:单行不撑开,超出才增高\n // H5 输入框获取焦点 - 滚动到底部让键盘不遮挡\n onInputFocus() {\n if (!this.isMobile) return;\n // 直接滚动窗口到底部,确保输入框可见\n setTimeout(() => {\n window.scrollTo(0, document.body.scrollHeight);\n }, 300);\n },\n // visualViewport 变化时(如键盘弹出)调整滚动位置\n onViewportResize() {\n if (!this.isMobile) return;\n const activeEl = document.activeElement;\n if (activeEl && (activeEl.tagName === 'TEXTAREA' || activeEl.tagName === 'INPUT')) {\n window.scrollTo(0, document.body.scrollHeight);\n }\n },\n autoResizeTextarea() {\n const ta = this.$refs.taRef;\n if (!ta) return;\n // 根据端适配基准高度和最大高度\n const isMobile = this.isMobile;\n const baseH = isMobile ? 36 : 100;\n const maxH = isMobile ? 100 : 180;\n ta.style.height = `${baseH}px`;\n // 内容真实高度\n const realH = ta.scrollHeight;\n // 只有内容高度>基准才撑开,否则保持初始高度\n if (realH > baseH) {\n ta.style.height = `${Math.min(realH, maxH)}px`;\n }\n this.$nextTick(() => {\n this.checkScrollBottom(true);\n });\n },\n // Shift+Enter换行\n newLine(e) {\n // 取消浏览器默认行为\n e.preventDefault();\n // 拿到光标位置\n const ta = this.$refs.taRef;\n const start = ta.selectionStart;\n const end = ta.selectionEnd;\n // 在光标处插入换行符\n this.inputText = this.inputText.slice(0, start) + '\\n' + this.inputText.slice(end);\n // 光标定位到换行后\n this.$nextTick(() => {\n ta.selectionStart = ta.selectionEnd = start + 1;\n // 自动调整输入框高度\n this.autoResizeTextarea();\n });\n },\n toggleVoiceMode() {\n this.voiceMode = !this.voiceMode;\n if (!this.voiceMode) {\n // 切回文字模式时释放音频设备\n this.releaseAudio();\n }\n },\n // 确保音频设备已就绪(只请求一次权限,缓存 stream / AudioContext)\n async ensureAudioReady() {\n if (this.audioContext && this.audioStream) return true;\n if (!navigator.mediaDevices || !navigator.mediaDevices.getUserMedia) {\n alert('当前环境不支持麦克风访问');\n return false;\n }\n try {\n const stream = await navigator.mediaDevices.getUserMedia({\n audio: true\n });\n this.audioStream = stream;\n const audioContext = new (window.AudioContext || window.webkitAudioContext)({\n sampleRate: 16000\n });\n this.audioContext = audioContext;\n const source = audioContext.createMediaStreamSource(stream);\n const processor = audioContext.createScriptProcessor(4096, 1, 1);\n this.audioProcessor = processor;\n processor.onaudioprocess = e => {\n if (!this.isRecording) return;\n const inputData = e.inputBuffer.getChannelData(0);\n this.audioChunks.push(new Float32Array(inputData));\n };\n source.connect(processor);\n processor.connect(audioContext.destination);\n return true;\n } catch (err) {\n console.error('麦克风访问失败:', err);\n alert('麦克风权限被拒绝');\n return false;\n }\n },\n // H5语音录制 - 触摸开始\n async onRecordTouchStart(e) {\n if (this.sending) return;\n\n // 先确保音频已就绪(首次会请求权限并建立音频管线,后续复用)\n const ready = await this.ensureAudioReady();\n if (!ready) return;\n\n // 重置录音状态\n this.isCancelSwipe = false;\n this.recordStartY = e.touches[0].clientY;\n this.recordDuration = 0;\n this.audioChunks = [];\n\n // 音频就绪后才标记录制中并启动计时\n this.isRecording = true;\n this.recordingTimer = setInterval(() => {\n this.recordDuration++;\n if (this.recordDuration >= 60) {\n this.onRecordTouchEnd();\n }\n }, 1000);\n },\n // H5语音录制 - 触摸移动(检测上滑取消)\n onRecordTouchMove(e) {\n if (!this.isRecording) return;\n const touch = e.touches[0];\n const moveY = touch.clientY;\n const cancelThreshold = 60; // 上滑60px进入取消区域\n this.isCancelSwipe = this.recordStartY - moveY > cancelThreshold;\n },\n // H5语音录制 - 触摸结束\n onRecordTouchEnd() {\n if (!this.isRecording) return;\n this.isRecording = false;\n if (this.recordingTimer) {\n clearInterval(this.recordingTimer);\n this.recordingTimer = null;\n }\n this.stopAudioCapture(!this.isCancelSwipe);\n },\n // 停止音频采集并输出 WAV(保留音频设备,下次复用)\n stopAudioCapture(shouldSend) {\n this.isRecording = false;\n if (shouldSend && this.audioChunks.length > 0) {\n const wavBlob = this.encodePCMToWav(this.audioChunks, 16000);\n this.sendAudioBlob(wavBlob);\n }\n this.audioChunks = [];\n },\n // 取消录音(保留音频设备,下次复用)\n cancelRecording() {\n this.isRecording = false;\n if (this.recordingTimer) {\n clearInterval(this.recordingTimer);\n this.recordingTimer = null;\n }\n this.recordDuration = 0;\n this.isCancelSwipe = false;\n this.audioChunks = [];\n },\n // 释放音频资源(切换回文字模式或组件销毁时调用)\n releaseAudio() {\n this.cancelRecording();\n if (this.audioProcessor) {\n this.audioProcessor.disconnect();\n this.audioProcessor = null;\n }\n if (this.audioContext) {\n this.audioContext.close().catch(() => {});\n this.audioContext = null;\n }\n if (this.audioStream) {\n this.audioStream.getTracks().forEach(t => t.stop());\n this.audioStream = null;\n }\n },\n // 将 Float32 PCM 数据编码为 WAV Blob\n encodePCMToWav(chunks, sampleRate) {\n // 计算总采样数\n let totalLength = 0;\n for (const chunk of chunks) {\n totalLength += chunk.length;\n }\n\n // 转换为 Int16 PCM\n const pcmData = new Int16Array(totalLength);\n let offset = 0;\n for (const chunk of chunks) {\n for (let i = 0; i < chunk.length; i++) {\n const s = Math.max(-1, Math.min(1, chunk[i]));\n pcmData[offset++] = s < 0 ? s * 0x8000 : s * 0x7FFF;\n }\n }\n const numChannels = 1;\n const bitsPerSample = 16;\n const byteRate = sampleRate * numChannels * bitsPerSample / 8;\n const blockAlign = numChannels * bitsPerSample / 8;\n const dataSize = pcmData.length * (bitsPerSample / 8);\n const headerSize = 44;\n const totalSize = headerSize + dataSize;\n const buffer = new ArrayBuffer(totalSize);\n const view = new DataView(buffer);\n\n // RIFF header\n this._wavWriteString(view, 0, 'RIFF');\n view.setUint32(4, totalSize - 8, true);\n this._wavWriteString(view, 8, 'WAVE');\n\n // fmt chunk\n this._wavWriteString(view, 12, 'fmt ');\n view.setUint32(16, 16, true); // chunk size\n view.setUint16(20, 1, true); // PCM format\n view.setUint16(22, numChannels, true); // 单声道\n view.setUint32(24, sampleRate, true); // 采样率\n view.setUint32(28, byteRate, true);\n view.setUint16(32, blockAlign, true);\n view.setUint16(34, bitsPerSample, true);\n\n // data chunk\n this._wavWriteString(view, 36, 'data');\n view.setUint32(40, dataSize, true);\n\n // 写入 PCM 数据\n const pcmView = new Int16Array(buffer, headerSize, pcmData.length);\n pcmView.set(pcmData);\n return new Blob([buffer], {\n type: 'audio/wav'\n });\n },\n _wavWriteString(view, offset, str) {\n for (let i = 0; i < str.length; i++) {\n view.setUint8(offset + i, str.charCodeAt(i));\n }\n },\n // 发送音频\n sendAudioBlob(blob) {\n let appSeqId = _index2.default.getAppSeqId();\n let name = appSeqId + '.wav';\n const file = new File([blob], name, {\n type: 'audio/wav'\n });\n // TODO: 上传音频文件并调用 STT 接口\n this.sendAudioMessage(file);\n },\n sendAudioMessage(file) {\n // 插入本地 pending 消息\n const sttKey = 'stt_' + Date.now();\n const sttMsg = {\n role: 'user',\n content: '转化中...',\n _sttStatus: 'pending',\n _sttKey: sttKey,\n createTime: new Date().toISOString(),\n _key: sttKey\n };\n this.messages.push(sttMsg);\n this.scrollToBottom(true);\n (0, _index.fileUploadToObs)({\n _file: file,\n appSeqId: file.name\n }).then(resp => {\n if (resp.CommonMsg.Status === 200) {\n // 调用语音转文字接口\n return _apiObs.default.aliAudioToText({\n url: resp.obs_upload_data.obsUrl\n }).then(result => {\n if (result.code === '200' && result.data) {\n // 成功:删除 pending 消息,发送给后端\n const idx = this.messages.findIndex(m => m._sttKey === sttKey);\n if (idx !== -1) {\n this.messages.splice(idx, 1);\n }\n this.sendQuickMsg(result.data);\n } else {\n throw new Error(result.msg || '语音转文字失败');\n }\n });\n } else {\n throw new Error(resp.CommonMsg.Message || '文件上传失败');\n }\n }).catch(err => {\n console.error('语音转文字失败:', err);\n // 失败:更新为错误状态\n const idx = this.messages.findIndex(m => m._sttKey === sttKey);\n if (idx !== -1) {\n this.$set(this.messages, idx, {\n ...this.messages[idx],\n _sttStatus: 'error',\n content: '语音转文字失败'\n });\n }\n this.$message.error('语音转文字失败');\n });\n this.$message.success(`录音完成 (${this.recordDuration}s)`);\n },\n clearWaitTimer() {\n if (this.waitTimer) {\n clearInterval(this.waitTimer);\n this.waitTimer = null;\n }\n },\n loadAgents() {\n (0, _apichat.getChatAgents)().then(list => {\n this.agentList = list || [];\n // if (this.agentList.length > 0 && !this.currentAgent) {\n // const first = this.agentList[0]\n // this.currentAgent = first.agentCode\n // this.currentAgentDesc = first.description || ''\n // }\n }).catch(() => {});\n },\n loadSessions() {\n (0, _apichat.getSessionList)().then(list => {\n if (!this.activeSessionId) {\n this.sessionList = list || [];\n if (this.sessionList.length > 0) {\n if (this.isMobile) {\n // H5模式:不自动选中会话,展示列表页\n this.showAgentSelect = false;\n this.showH5List = true;\n this.showSidebar = false;\n } else {\n this.switchSession(this.sessionList[0]);\n }\n }\n if (this.sessionList.length === 0) {\n this.showAgentSelect = true;\n this.showH5List = false;\n }\n } else {\n this.sessionList = list || [];\n let _item = list.find(res => res.sessionId == this.activeSessionId);\n try {\n if (_item.suggestedQuestions) {\n _item.suggestedQuestions = JSON.parse(_item.suggestedQuestions);\n } else {\n _item.suggestedQuestions = [];\n }\n _item && (this.agentInfo = _item);\n } catch (err) {\n // JSON格式错误兜底空数组,防止页面报错\n this.agentInfo.questionArr = [];\n console.warn('快捷提问解析失败', err);\n }\n }\n }).catch(() => {});\n },\n onSearchClear() {\n this.agentSuggestions = [];\n this.showAgentSuggestions = false;\n },\n startChatWithAgent(agent) {\n console.log('选择了助手', agent.agentCode, this.currentAgent);\n if (agent.agentCode == this.currentAgent) {\n this.searchKeyword = '';\n this.agentSuggestions = [];\n this.showAgentSuggestions = false;\n return;\n }\n this.currentAgent = agent.agentCode;\n this.currentAgentDesc = agent.description || '';\n this.searchKeyword = '';\n this.agentInfo = {};\n this.agentSuggestions = [];\n this.messages = [];\n this.showAgentSuggestions = false;\n this.showAgentSelect = false;\n this.closeSidebar();\n if (this.isMobile) {\n this.showH5List = false; // H5:进入详情页,隐藏列表\n }\n const existing = this.sessionList.find(s => s.agentCode === agent.agentCode);\n if (existing) {\n this.switchSession(existing);\n } else {\n this.handleNewSession();\n }\n },\n handleNewSession() {\n if (!this.currentAgent) return;\n if (this.activeSessionId) this.closeOldSession();\n (0, _apichat.startSession)(this.currentAgent).then(res => {\n console.log(res, 'startChatWithAgentstartChatWithAgentstartChatWithAgent', this.agentInfo);\n this.activeSessionId = res.sessionId || '';\n this.loadSessions();\n const agent = this.agentList.find(a => a.agentCode === this.currentAgent);\n if (agent) this.addWelcomeMessage(agent);\n }).catch(() => {});\n },\n // H5长按删除 - 触摸开始\n onSessionTouchStart(s, e) {\n if (!this.isMobile) return;\n this.longPressed = false;\n this.longPressTimer = setTimeout(() => {\n this.longPressed = true;\n this.handleDeleteSession(s);\n }, 600);\n },\n // H5长按删除 - 触摸结束/移动(取消长按)\n onSessionTouchEnd() {\n if (this.longPressTimer) {\n clearTimeout(this.longPressTimer);\n this.longPressTimer = null;\n }\n },\n onSessionTouchMove() {\n if (this.longPressTimer) {\n clearTimeout(this.longPressTimer);\n this.longPressTimer = null;\n }\n },\n async switchSession(s) {\n if (this.longPressed) {\n this.longPressed = false;\n return;\n }\n if (this.sending) {\n this.$message.warning('AI正在生成内容,暂时请不要切换对话');\n return;\n }\n this.showAgentSelect = false;\n this.closeSidebar();\n if (this.isMobile) {\n this.showH5List = false; // H5:进入详情页,隐藏列表\n }\n if (this.activeSessionId === s.sessionId) return;\n this.contentCache = {};\n this.activeSessionId = s.sessionId;\n this.currentAgent = s.agentCode;\n console.log('进入');\n this.agentInfo = s;\n console.log('进入', this.agentInfo);\n try {\n if (s.suggestedQuestions) {\n this.agentInfo.suggestedQuestions = JSON.parse(s.suggestedQuestions);\n } else {\n this.agentInfo.suggestedQuestions = [];\n }\n } catch (err) {\n // JSON格式错误兜底空数组,防止页面报错\n this.agentInfo.questionArr = [];\n console.warn('快捷提问解析失败', err);\n }\n const agent = this.agentList.find(a => a.agentCode === s.agentCode);\n this.currentAgentDesc = agent ? agent.description || '' : '';\n this.msgPage = 1;\n this.msgTotal = 0;\n this.messages = []; // 先清空,但开启加载锁屏蔽空白页\n this.loadingSessionMsg = true; // 开启加载标记\n (0, _apichat.syncToken)((0, _cookie.getToken)(), s.sessionId);\n try {\n const res = await (0, _apichat.getSessionMessages)(s.sessionId, 1, 10);\n const list = Array.isArray(res) ? res : res.list || [];\n this.msgTotal = res.total || list.length;\n this.msgPage = 1;\n const asAsc = (list || []).slice().reverse();\n this.messages = asAsc.map(m => ({\n role: m.role,\n content: m.content || '',\n thinking: m.thinking || '',\n toolCalls: [],\n agentName: m.role === 'assistant' ? s.agentName || '' : '',\n createTime: m.createTime || null,\n _key: m.createTime ? 'msg_' + m.createTime : 'msg_' + Date.now() + '_' + Math.random()\n }));\n if (this.messages.length === 0 && agent) this.addWelcomeMessage(agent);\n await this.$nextTick();\n this.$nextTick(() => {\n this.scrollToBottomOnce();\n this.checkScrollBottom();\n });\n } catch (e) {\n this.messages = [];\n } finally {\n // 无论成功失败,结束后关闭加载锁\n this.loadingSessionMsg = false;\n }\n },\n loadMoreMessages() {\n const nextPage = this.msgPage + 1;\n const maxPage = Math.ceil(this.msgTotal / 10);\n if (nextPage > maxPage) {\n this.loadingMore = false;\n return;\n }\n (0, _apichat.getSessionMessages)(this.activeSessionId, nextPage, 10).then(res => {\n const list = Array.isArray(res) ? res : res.list || [];\n this.msgPage = nextPage;\n const asAsc = (list || []).slice().reverse();\n const prepend = asAsc.map(m => ({\n role: m.role,\n content: m.content || '',\n thinking: m.thinking || '',\n toolCalls: [],\n agentName: '',\n createTime: m.createTime || null,\n _key: m.createTime ? 'msg_' + m.createTime : 'msg_' + Date.now() + '_' + Math.random()\n }));\n const container = this.$refs.messagesRef;\n const oldScrollHeight = container ? container.scrollHeight : 0;\n const oldScrollTop = container ? container.scrollTop : 0;\n this.messages = [...prepend, ...this.messages];\n this.$nextTick(() => {\n if (container) {\n container.scrollTop = oldScrollTop + (container.scrollHeight - oldScrollHeight);\n }\n this.loadingMore = false;\n });\n }).catch(() => {\n this.loadingMore = false;\n });\n },\n onScrollMessages() {\n const container = this.$refs.messagesRef;\n if (!container || this.loadingMore) return;\n const isAtBottom = container.scrollTop + container.clientHeight >= container.scrollHeight - 100;\n this.checkScrollBottom();\n if (isAtBottom) return;\n if (container.scrollTop < 50 && this.msgPage < Math.ceil(this.msgTotal / 10)) {\n this.loadingMore = true;\n this.loadMoreMessages();\n }\n },\n handleDeleteSession(s) {\n this.$confirm(`确认删除「${s.agentName || s.agentCode}」的会话?`, '提示', {\n type: 'warning'\n }).then(() => {\n (0, _apichat.deleteSession)(s.sessionId).then(() => {\n if (this.activeSessionId === s.sessionId) {\n this.activeSessionId = '';\n this.messages = [];\n this.currentAgent = '';\n this.currentAgentDesc = '';\n if (this.isMobile) {\n this.showH5List = false;\n this.showAgentSelect = true;\n } else {\n this.showAgentSelect = true;\n }\n }\n this.loadSessions();\n });\n }).catch(() => {});\n },\n closeOldSession() {},\n onAgentChange(code) {\n const agent = this.agentList.find(a => a.agentCode === code);\n this.currentAgentDesc = agent ? agent.description || '' : '';\n this.handleNewSession();\n },\n addWelcomeMessage(agent) {\n this.greeting = '';\n // if (!agent) return\n // const name = agent.agentName || '助手';\n const _agent = this.agentList.find(x => x.agentCode === this.currentAgent);\n this.greeting = _agent.greeting || `很高兴为您服务,请问有什么可以帮到您?`;\n // this.messages.push({\n // role: 'assistant',\n // content: _content,\n // thinking: '',\n // agentName: name,\n // _key: 'welcome_' + Date.now()\n // })\n },\n async sendMessage() {\n const text = this.inputText.trim();\n if (!text || this.sending) return;\n if (!this.activeSessionId) {\n await (0, _apichat.startSession)(this.currentAgent).then(res => {\n this.activeSessionId = res.sessionId || '';\n this.loadSessions();\n });\n if (!this.activeSessionId) return;\n }\n this.inputText = '';\n const ta = this.$refs.taRef;\n const isMobile = this.isMobile;\n const baseH = isMobile ? 36 : 100;\n if (ta) {\n ta.style.height = baseH + 'px'; // 强制恢复初始高度\n }\n this.showDownBtn = false;\n this.messages.push({\n role: 'user',\n content: text,\n createTime: new Date().toISOString(),\n _key: 'user_' + Date.now() + '_' + Math.random()\n });\n const agentName = this.currentAgentName;\n const msgIdx = this.messages.push({\n role: \"assistant\",\n content: \"\",\n thinking: \"\",\n loading: true,\n toolCalls: [],\n agentName,\n createTime: new Date().toISOString(),\n _key: 'asst_' + Date.now() + '_' + Math.random()\n }) - 1;\n this.scrollToBottom(true);\n this.sending = true;\n this.waitSeconds = 0;\n if (this.waitTimer) clearInterval(this.waitTimer);\n this.waitTimer = setInterval(() => {\n this.waitSeconds++;\n }, 1000);\n let thinkingBuffer = '';\n let finalContent = '';\n let answerBuffer = '';\n let thinkDisplayed = 0;\n let typeTimer = null;\n typeTimer = setInterval(() => {\n if (!this.messages[msgIdx]) return;\n if (thinkDisplayed < thinkingBuffer.length) {\n thinkDisplayed += 50;\n if (thinkDisplayed > thinkingBuffer.length) thinkDisplayed = thinkingBuffer.length;\n this.messages[msgIdx].thinking = thinkingBuffer.substring(0, thinkDisplayed);\n this.scrollToBottom();\n } else if (finalContent && !this.messages[msgIdx].content) {\n clearInterval(typeTimer);\n const key = this.messages[msgIdx]._key;\n if (key) {\n this.$delete(this.contentCache, key);\n this.$delete(this.contentCache, key + '_t');\n }\n typeTimer = null;\n this.messages[msgIdx].content = finalContent;\n this.messages[msgIdx].thinking = thinkingBuffer;\n this.messages[msgIdx].loading = false;\n this.sending = false;\n this.clearWaitTimer();\n this.scrollToBottom();\n this.loadSessions();\n }\n }, 30);\n const url = (0, _apichat.createStreamUrl)(this.activeSessionId, text);\n if (this.eventSource) {\n this.eventSource.close();\n }\n this.eventSource = new EventSource(url);\n const es = this.eventSource;\n es.addEventListener('reasoning', e => {\n if (e.data) {\n const chunk = e.data;\n // 1. 先处理当前分片内部的中英文、数字、标点空格\n let cleanChunk = chunk.replace(/([a-z])([A-Z])/g, '$1 $2').replace(/([A-Z]+)([A-Z][a-z])/g, '$1 $2').replace(/([a-zA-Z])([\\u4e00-\\u9fff])/g, '$1 $2').replace(/([\\u4e00-\\u9fff])([a-zA-Z])/g, '$1 $2').replace(/([a-zA-Z])(\\d)/g, '$1 $2').replace(/(\\d)([a-zA-Z])/g, '$1 $2').replace(/\\s+([:,.!?])/g, '$1').replace(/([:,.!?])\\s+/g, '$1 ');\n cleanChunk = cleanChunk.replace(/\\s+/g, ' ');\n\n // 2. 关键:判断前一段末尾 + 当前段开头都是英文,补空格分隔\n const lastChar = thinkingBuffer.slice(-1);\n const firstChar = cleanChunk.slice(0, 1);\n const isLetter = c => /[a-zA-Z]/.test(c);\n if (isLetter(lastChar) && isLetter(firstChar)) {\n // 两段都是英文衔接,中间加空格\n thinkingBuffer += ' ' + cleanChunk;\n } else {\n thinkingBuffer += cleanChunk;\n }\n }\n });\n es.addEventListener('reasoning_result', e => {\n if (e.data) {\n thinkingBuffer = e.data;\n }\n });\n es.addEventListener('answer', e => {\n if (e.data) {\n answerBuffer += e.data;\n if (this.messages[msgIdx]) {\n this.messages[msgIdx].content += e.data.replace(/([a-zA-Z]+)([\\u4e00-\\u9fff])/g, '$1 $2').replace(/([\\u4e00-\\u9fff])([a-zA-Z]+)/g, '$1 $2').replace(/([a-z])([A-Z])/g, '$1 $2').replace(/([A-Z]+)([A-Z][a-z])/g, '$1 $2').replace(/([a-zA-Z])(\\d)/g, '$1 $2').replace(/(\\d)([a-zA-Z])/g, '$1 $2');\n this.scrollToBottom();\n }\n }\n });\n es.addEventListener('tool_result', e => {\n if (e.data && this.messages[msgIdx]) {\n if (!this.messages[msgIdx].toolCalls) this.messages[msgIdx].toolCalls = [];\n this.messages[msgIdx].toolCalls.push(e.data);\n this.scrollToBottom();\n }\n });\n es.addEventListener('agent_result', e => {\n finalContent = e.data || '';\n es.close();\n this.eventSource = null;\n if (this.messages[msgIdx]) {\n const key = this.messages[msgIdx]._key;\n if (key) this.$delete(this.contentCache, key);\n this.messages[msgIdx].content = finalContent;\n this.messages[msgIdx].thinking = thinkingBuffer;\n this.messages[msgIdx].loading = false;\n }\n this.sending = false;\n this.clearWaitTimer();\n if (typeTimer) {\n clearInterval(typeTimer);\n typeTimer = null;\n }\n this.scrollToBottom();\n this.loadSessions();\n });\n es.onerror = err => {\n console.log('[SSE] onerror', err);\n if (thinkingBuffer.length > 0 && !finalContent) finalContent = thinkingBuffer;\n if (!finalContent) finalContent = '❌ 连接中断';\n es.close();\n this.eventSource = null;\n if (this.messages[msgIdx]) {\n const key = this.messages[msgIdx]._key;\n if (key) this.$delete(this.contentCache, key);\n this.messages[msgIdx].content = finalContent;\n this.messages[msgIdx].thinking = thinkingBuffer;\n this.messages[msgIdx].loading = false;\n }\n this.sending = false;\n this.clearWaitTimer();\n if (typeTimer) {\n clearInterval(typeTimer);\n typeTimer = null;\n }\n this.scrollToBottom();\n };\n },\n stopAgent() {\n if (this.eventSource) {\n this.eventSource.close();\n this.eventSource = null;\n }\n if (this.activeSessionId) {\n (0, _apichat.stopStream)(this.activeSessionId).catch(() => {});\n }\n if (this.messages.length > 0) {\n const last = this.messages[this.messages.length - 1];\n if (last && last.loading) {\n last.content = last.content || last.thinking || '⏹ 已停止';\n last.loading = false;\n this.$delete(this.contentCache, last._key);\n }\n }\n this.sending = false;\n this.clearWaitTimer();\n },\n copyText(content) {\n if (!content) return;\n navigator.clipboard.writeText(content.replace(/<[^>]+>/g, '')).then(() => {\n this.$message({\n message: '已复制到剪贴板',\n type: 'success',\n duration: 1500\n });\n }).catch(() => {\n this.$message({\n message: '复制失败',\n type: 'error',\n duration: 2000\n });\n });\n },\n copyAsImage(content) {\n if (!content) return;\n // 创建临时容器渲染 Markdown\n const div = document.createElement('div');\n div.className = 'copy-image-render';\n div.style.cssText = 'position:fixed;left:-9999px;top:0;width:600px;padding:20px;background:#fff;font-size:14px;line-height:1.6;color:#333;border-radius:8px;font-family:-apple-system,BlinkMacSystemFont,sans-serif;';\n div.innerHTML = this.renderMarkdown(content);\n document.body.appendChild(div);\n this.$message({\n message: '正在生成图片...',\n type: 'info',\n duration: 2000\n });\n (0, _html2canvas.default)(div, {\n scale: 2,\n useCORS: true,\n backgroundColor: '#ffffff'\n }).then(canvas => {\n canvas.toBlob(blob => {\n if (blob) {\n navigator.clipboard.write([new ClipboardItem({\n 'image/png': blob\n })]).then(() => {\n this.$message({\n message: '图片已复制到剪贴板',\n type: 'success',\n duration: 1500\n });\n }).catch(() => {\n this.$message({\n message: '复制图片失败',\n type: 'error',\n duration: 2000\n });\n });\n }\n }, 'image/png');\n }).catch(() => {\n this.$message({\n message: '生成图片失败',\n type: 'error',\n duration: 2000\n });\n }).finally(() => {\n document.body.removeChild(div);\n });\n },\n formatTime(t) {\n if (!t) return '';\n const d = new Date(t.replace(' ', 'T'));\n const now = new Date();\n const diff = (now - d) / 1000;\n if (diff < 60) return '刚刚';\n if (diff < 3600) return Math.floor(diff / 60) + '分钟前';\n if (diff < 86400) return Math.floor(diff / 3600) + '小时前';\n return d.getMonth() + 1 + '/' + d.getDate();\n },\n getInitial(name) {\n if (!name) return '?';\n return name.charAt(0);\n },\n renderMarkdown(text) {\n if (!text) return '';\n try {\n return md.render(text);\n } catch (err) {\n return this.escapeHtml(text);\n }\n },\n renderStreaming(text, msgKey) {\n if (!text) return '';\n console.log('进入');\n const cache = this.contentCache[msgKey];\n const lines = text.split('\\n');\n const lastLineIdx = lines.length - 1;\n if (!cache) {\n try {\n const html = md.render(text);\n this.$set(this.contentCache, msgKey, {\n renderedLines: lastLineIdx,\n html,\n fullText: text\n });\n return html;\n } catch {\n return this.escapeHtml(text);\n }\n }\n if (text === cache.fullText) return cache.html;\n cache.fullText = text;\n\n // 行数没变,仅末尾追加字符,直接拼接尾行(原有逻辑不变)\n if (lastLineIdx === cache.renderedLines) {\n return cache.html + this.escapeHtml(lines[lastLineIdx]);\n }\n\n // 场景1:行数变少/文本回退截断,全量重渲染(原有分支保留,内部修复)\n if (lastLineIdx < cache.renderedLines) {\n try {\n // 重新截取所有完整行生成全新基础html,清空旧叠加内容\n const fullLines = lines.slice(0, lastLineIdx);\n let newBaseHtml = '';\n if (fullLines.length > 0) {\n newBaseHtml = md.render(fullLines.join('\\n'));\n }\n cache.html = newBaseHtml;\n cache.renderedLines = lastLineIdx;\n // 拼接尾行\n const lastLine = this.escapeHtml(lines[lastLineIdx]);\n return cache.html + (lastLine || '');\n } catch {\n return this.escapeHtml(text);\n }\n }\n\n // 场景2:新增完整行,修复:不再累加旧html,重新从0生成完整行基础\n if (cache.renderedLines < lastLineIdx) {\n // 关键修复:重新切片所有完整行,抛弃之前叠加的旧html,杜绝重复\n const allFullLines = lines.slice(0, lastLineIdx);\n let newBaseHtml = '';\n if (allFullLines.length > 0) {\n newBaseHtml = md.render(allFullLines.join('\\n'));\n }\n cache.html = newBaseHtml;\n cache.renderedLines = lastLineIdx;\n }\n const lastLine = this.escapeHtml(lines[lastLineIdx]);\n cache.renderedLines = lastLineIdx;\n return cache.html + (lastLine || '');\n },\n escapeHtml(text) {\n if (!text) return '';\n return text.replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>');\n },\n scrollToTop() {\n const el = this.$refs.messagesRef;\n if (el) el.scrollTop = 0;\n },\n scrollToBottom(force = false) {\n if (this.showDownBtn && !force) return;\n this.$nextTick(() => {\n const el = this.$refs.messagesRef;\n if (el) {\n el.scrollTop = el.scrollHeight;\n this.lastScrollTop = el.scrollTop;\n this.showDownBtn = false; // 滚动到底部后立刻隐藏箭头\n }\n });\n },\n scrollToBottomOnce() {\n // 清理旧定时器,防止任何泄漏\n clearTimeout(this._scrollTimer);\n this.$nextTick(() => {\n let retry = 0;\n const maxRetry = 6; // 重试6次,足够覆盖所有渲染延迟\n\n const tryScroll = () => {\n var _this$$refs;\n const el = (_this$$refs = this.$refs) === null || _this$$refs === void 0 ? void 0 : _this$$refs.messagesRef;\n if (!el) {\n this._scrollTimer = setTimeout(tryScroll, 50);\n return;\n }\n\n // 临时禁用平滑滚动,立即跳到底部\n const originalScrollBehavior = el.style.scrollBehavior;\n el.style.scrollBehavior = 'auto';\n el.scrollTop = el.scrollHeight - el.clientHeight;\n el.style.scrollBehavior = originalScrollBehavior;\n this.showDownBtn = false;\n };\n tryScroll();\n });\n }\n },\n beforeDestroy() {\n window.removeEventListener('resize', this.updateViewportState);\n if (window.visualViewport) {\n window.visualViewport.removeEventListener('resize', this.onViewportResize);\n }\n this.releaseAudio();\n this.contentCache = {};\n clearTimeout(this._scrollTimer);\n if (this.eventSource) {\n this.eventSource.onerror = null;\n this.eventSource.close();\n this.eventSource = null;\n }\n if (this.waitTimer) {\n clearInterval(this.waitTimer);\n this.waitTimer = null;\n }\n if (this._typeTimer) {\n clearInterval(this._typeTimer);\n this._typeTimer = null;\n }\n }\n};\n\n//# sourceURL=webpack://ZjPluginIntelligent/./src/lib/components/chatMain/index.vue?./node_modules/_cache-loader@4.1.0@cache-loader/dist/cjs.js??ref--13-0!./node_modules/_babel-loader@8.4.1@babel-loader/lib!./node_modules/_cache-loader@4.1.0@cache-loader/dist/cjs.js??ref--1-0!./node_modules/_vue-loader@15.11.1@vue-loader/lib??vue-loader-options");
|
|
952
952
|
|
|
953
953
|
/***/ }),
|
|
954
954
|
|
|
@@ -12457,7 +12457,7 @@ eval("module.exports = function(originalModule) {\n\tif (!originalModule.webpack
|
|
|
12457
12457
|
/*! exports provided: name, version, main, private, scripts, dependencies, devDependencies, browserslist, directories, keywords, license, default */
|
|
12458
12458
|
/***/ (function(module) {
|
|
12459
12459
|
|
|
12460
|
-
eval("module.exports = JSON.parse(\"{\\\"name\\\":\\\"zj-plugin-intelligent\\\",\\\"version\\\":\\\"1.2.5-beta.
|
|
12460
|
+
eval("module.exports = JSON.parse(\"{\\\"name\\\":\\\"zj-plugin-intelligent\\\",\\\"version\\\":\\\"1.2.5-beta.8\\\",\\\"main\\\":\\\"lib/ZjPluginIntelligent.umd.min.js\\\",\\\"private\\\":false,\\\"scripts\\\":{\\\"serve\\\":\\\"vue-cli-service serve\\\",\\\"build\\\":\\\"vue-cli-service build\\\",\\\"lib\\\":\\\"vue-cli-service build --target lib --name ZjPluginIntelligent --dest lib src/lib/index.js\\\",\\\"lib:test\\\":\\\"vue-cli-service build --mode test --target lib --name ZjPluginIntelligent --dest lib src/lib/index.js\\\"},\\\"dependencies\\\":{\\\"html2canvas\\\":\\\"^1.4.1\\\",\\\"markdown-it\\\":\\\"^14.1.0\\\"},\\\"devDependencies\\\":{\\\"@babel/preset-env\\\":\\\"^7.14.9\\\",\\\"@vue/cli-plugin-babel\\\":\\\"~4.5.0\\\",\\\"@vue/cli-plugin-eslint\\\":\\\"^4.5.13\\\",\\\"@vue/cli-plugin-vuex\\\":\\\"~4.5.0\\\",\\\"@vue/cli-service\\\":\\\"~4.5.0\\\",\\\"axios\\\":\\\"^0.27.2\\\",\\\"babel-eslint\\\":\\\"^10.1.0\\\",\\\"babel-plugin-component\\\":\\\"^1.1.1\\\",\\\"compression-webpack-plugin\\\":\\\"^6.0.3\\\",\\\"core-js\\\":\\\"^3.6.5\\\",\\\"element-ui\\\":\\\"^2.15.4\\\",\\\"eslint\\\":\\\"^7.30.0\\\",\\\"eslint-plugin-vue\\\":\\\"^7.13.0\\\",\\\"js-cookie\\\":\\\"^2.2.1\\\",\\\"node-sass\\\":\\\"^4.12.0\\\",\\\"obs-upload\\\":\\\"^1.0.4-alpha.0\\\",\\\"reconnecting-websocket\\\":\\\"^4.4.0\\\",\\\"sass-loader\\\":\\\"^8.0.2\\\",\\\"snowflake-id\\\":\\\"^1.1.0\\\",\\\"vue\\\":\\\"^2.6.11\\\",\\\"vue-template-compiler\\\":\\\"^2.6.11\\\",\\\"vuex\\\":\\\"^3.4.0\\\",\\\"pako\\\":\\\"^2.1.0\\\",\\\"webpack-bundle-analyzer\\\":\\\"^4.4.2\\\"},\\\"browserslist\\\":[\\\"> 1%\\\",\\\"last 2 versions\\\",\\\"not dead\\\"],\\\"directories\\\":{\\\"lib\\\":\\\"lib\\\"},\\\"keywords\\\":[],\\\"license\\\":\\\"ISC\\\"}\");\n\n//# sourceURL=webpack://ZjPluginIntelligent/./package.json?");
|
|
12461
12461
|
|
|
12462
12462
|
/***/ }),
|
|
12463
12463
|
|