diff --git a/.env.development b/.env.development index 26bf791..aedcfae 100644 --- a/.env.development +++ b/.env.development @@ -3,11 +3,5 @@ NODE_ENV = development # 测试 VITE_BASE_URL = https://onefeel.brother7.cn/ingress -# 生产 -# VITE_BASE_URL = https://biz.nianxx.cn - # 测试 VITE_WSS_URL = wss://onefeel.brother7.cn/ingress/agent/ws/chat - -# 生产 -# VITE_WSS_URL = wss://biz.nianxx.cn/agent/ws/chat diff --git a/.env.production b/.env.production index 5d07a8b..e2be08e 100644 --- a/.env.production +++ b/.env.production @@ -1,13 +1,7 @@ NODE_ENV = production -# 测试 -VITE_BASE_URL = https://onefeel.brother7.cn/ingress +# 生产 +VITE_BASE_URL = https://biz.nianxx.cn # 生产 -# VITE_BASE_URL = https://biz.nianxx.cn - -# 测试 -VITE_WSS_URL = wss://onefeel.brother7.cn/ingress/agent/ws/chat - -# 生产 -# VITE_WSS_URL = wss://biz.nianxx.cn/agent/ws/chat \ No newline at end of file +VITE_WSS_URL = wss://biz.nianxx.cn/agent/ws/chat \ No newline at end of file diff --git a/.env.staging b/.env.staging index da39e91..84749b3 100644 --- a/.env.staging +++ b/.env.staging @@ -1,13 +1,7 @@ NODE_ENV = staging -# 测试 -VITE_BASE_URL = https://onefeel.brother7.cn/ingress +# 生产 +VITE_BASE_URL = https://biz.nianxx.cn # 生产 -# VITE_BASE_URL = https://biz.nianxx.cn - -# 测试 -VITE_WSS_URL = wss://onefeel.brother7.cn/ingress/agent/ws/chat - -# 生产 -# VITE_WSS_URL = wss://biz.nianxx.cn/agent/ws/chat \ No newline at end of file +VITE_WSS_URL = wss://biz.nianxx.cn/agent/ws/chat \ No newline at end of file diff --git a/constant/base.js b/constant/base.js index a6b185a..e69de29 100644 --- a/constant/base.js +++ b/constant/base.js @@ -1,8 +0,0 @@ -const isProd = true; - -console.log(import.meta.env); - -export const BASE_URL = import.meta.env.VITE_BASE_URL; - -// socket地址 -export const WSS_URL = import.meta.env.VITE_WSS_URL; diff --git a/manifest.json b/manifest.json index e5f85a7..424edf2 100644 --- a/manifest.json +++ b/manifest.json @@ -55,7 +55,10 @@ }, /* 快应用特有相关 */ "quickapp": {}, - /* 小程序特有相关 朵花用:wx23f86d809ae80259 测试用:wx5e79df5996572539 */ + /* 小程序特有相关 同时更改 project.config.json文件 + 智念:wx5e79df5996572539 + 朵花:wx23f86d809ae80259 + */ "mp-weixin": { "appid": "wx5e79df5996572539", "setting": { diff --git a/pages/chat/ChatMainList.vue b/pages/chat/ChatMainList.vue index 3984de9..fab47cf 100644 --- a/pages/chat/ChatMainList.vue +++ b/pages/chat/ChatMainList.vue @@ -143,7 +143,7 @@ import { RECOMMEND_POSTS_TITLE, SEND_COMMAND_TEXT, } from "@/constant/constant"; -import { WSS_URL } from "@/constant/base"; +import { WSS_URL } from "@/request/base/baseUrl"; import { MessageRole, MessageType, CompName } from "../../model/ChatModel"; import ChatTopWelcome from "./ChatTopWelcome.vue"; import ChatTopBgImg from "./ChatTopBgImg.vue"; diff --git a/request/api/AgentChatStream.js b/request/api/AgentChatStream.js index 2057e7d..39758c8 100644 --- a/request/api/AgentChatStream.js +++ b/request/api/AgentChatStream.js @@ -1,8 +1,8 @@ -import { BASE_URL } from "../../constant/base"; +import { BASE_URL } from "@/request/base/baseUrl"; import { goLogin } from "@/hooks/useGoLogin"; /// 请求流式数据的API -const API = '/agent/assistant/chat'; +const API = "/agent/assistant/chat"; /** * 获取AI聊天流式信息(仅微信小程序支持) @@ -15,8 +15,8 @@ const API = '/agent/assistant/chat'; let requestTask = null; let isAborted = false; let currentPromiseReject = null; -let lastRequestId = null; // 记录上一次请求ID -let activeRequestId = null; // 记录当前活动请求ID +let lastRequestId = null; // 记录上一次请求ID +let activeRequestId = null; // 记录当前活动请求ID /** * 终止的请求 @@ -24,14 +24,14 @@ let activeRequestId = null; // 记录当前活动请求ID const stopAbortTask = () => { console.log("🛑 开始强制终止请求... "); isAborted = true; - + // 将当前活动请求ID保存为上一次请求ID lastRequestId = activeRequestId; // 清除当前活动请求ID activeRequestId = null; if (currentPromiseReject) { - currentPromiseReject(new Error('请求已被用户终止')); + currentPromiseReject(new Error("请求已被用户终止")); currentPromiseReject = null; } @@ -39,16 +39,16 @@ const stopAbortTask = () => { // 先移除监听器,再终止请求 const cleanupListeners = () => { try { - if(requestTask.offChunkReceived) { - console.log("======>offChunkReceived") + if (requestTask.offChunkReceived) { + console.log("======>offChunkReceived"); requestTask.offChunkReceived(); } - if(requestTask.offHeadersReceived) { - console.log("======>offHeadersReceived") + if (requestTask.offHeadersReceived) { + console.log("======>offHeadersReceived"); requestTask.offHeadersReceived(); } } catch (e) { - console.error('清理事件监听器失败:', e); + console.error("清理事件监听器失败:", e); } }; @@ -57,51 +57,53 @@ const stopAbortTask = () => { // 终止请求 try { if (requestTask.abort) { - console.log("======>abort") + console.log("======>abort"); requestTask.abort(); } } catch (e) { - console.log('🛑 终止网络请求失败:', e); + console.log("🛑 终止网络请求失败:", e); } requestTask = null; } - console.log('🛑 请求强制终止完成'); -} + console.log("🛑 请求强制终止完成"); +}; const agentChatStream = (params, onChunk) => { return new Promise((resolve, reject) => { - const token = uni.getStorageSync('token'); + const token = uni.getStorageSync("token"); const requestId = Date.now().toString(); // 生成唯一请求ID - + // 重置状态 isAborted = false; currentPromiseReject = reject; - + // 更新请求ID追踪 - lastRequestId = activeRequestId; // 保存上一次请求ID - activeRequestId = requestId; // 设置新的活动请求ID + lastRequestId = activeRequestId; // 保存上一次请求ID + activeRequestId = requestId; // 设置新的活动请求ID console.log(`🚀 发送请求 [${requestId}], 上一次请求ID [${lastRequestId}]`); // 检查数据块是否来自已终止的请求 const isStaleData = (dataRequestId) => { - return dataRequestId === lastRequestId || dataRequestId !== activeRequestId; + return ( + dataRequestId === lastRequestId || dataRequestId !== activeRequestId + ); }; // #ifdef MP-WEIXIN requestTask = uni.request({ url: BASE_URL + API, // 替换为你的接口地址 - method: 'POST', + method: "POST", data: params, enableChunked: true, header: { - Accept: 'text/event-stream', - 'Content-Type': 'application/json', + Accept: "text/event-stream", + "Content-Type": "application/json", Authorization: `Bearer ${token}`, // 如需token可加 }, - responseType: 'arraybuffer', + responseType: "arraybuffer", success(res) { if (!isAborted && !isStaleData(requestId)) { console.log(`✅ 请求 [${requestId}] 成功`); @@ -122,43 +124,52 @@ const agentChatStream = (params, onChunk) => { // 使用 requestId 来验证请求有效性 if (!isAborted && activeRequestId === requestId) { if (res.statusCode !== 200) { - console.log(`❌ 请求 [${requestId}] 完成但状态错误,状态:`, res.statusCode); - if(res.statusCode === 424) { - uni.setStorageSync('token', ''); + console.log( + `❌ 请求 [${requestId}] 完成但状态错误,状态:`, + res.statusCode + ); + if (res.statusCode === 424) { + uni.setStorageSync("token", ""); goLogin(); } if (onChunk) { - onChunk({ - error: true, - message: '服务器错误', - detail: res + onChunk({ + error: true, + message: "服务器错误", + detail: res, }); } reject(res); } } else { - console.log(`❌ 请求 [${requestId}] ${isAborted ? '已终止' : '已过期'},忽略complete回调`); + console.log( + `❌ 请求 [${requestId}] ${ + isAborted ? "已终止" : "已过期" + },忽略complete回调` + ); } - } + }, }); - requestTask.onHeadersReceived(res => { + requestTask.onHeadersReceived((res) => { // 使用 requestId 验证请求有效性 if (isAborted || activeRequestId !== requestId) { - console.log(`🚫 Headers [${requestId}] ${isAborted ? '已终止' : '已过期'},忽略`); + console.log( + `🚫 Headers [${requestId}] ${isAborted ? "已终止" : "已过期"},忽略` + ); return; } console.log(`📡 请求 [${requestId}] Headers接收:`, res); const status = res.statusCode || (res.header && res.header.statusCode); - + if (status && status !== 200) { console.log(`❌ 请求 [${requestId}] 服务器返回错误状态:`, status); if (onChunk && !isAborted && activeRequestId === requestId) { - onChunk({ - error: true, - message: `服务器错误(${status})`, - detail: res + onChunk({ + error: true, + message: `服务器错误(${status})`, + detail: res, }); } // 终止异常请求 @@ -168,7 +179,7 @@ const agentChatStream = (params, onChunk) => { } }); - requestTask.onChunkReceived(res => { + requestTask.onChunkReceived((res) => { // 立即验证请求有效性 if (isAborted || isStaleData(requestId)) { console.log(`🚫 数据块 [${requestId}] 已终止或过期,忽略`); @@ -176,15 +187,15 @@ const agentChatStream = (params, onChunk) => { } const base64 = uni.arrayBufferToBase64(res.data); - let data = ''; + let data = ""; try { data = decodeURIComponent(escape(weAtob(base64))); } catch (e) { - console.error('Base64解码失败:', e); + console.error("Base64解码失败:", e); return; } - console.log("📦 onChunkReceived,res:", data) + console.log("📦 onChunkReceived,res:", data); // 再次验证请求有效性 if (isAborted || activeRequestId !== requestId) { @@ -193,7 +204,7 @@ const agentChatStream = (params, onChunk) => { } const messages = parseSSEChunk(data); - messages.forEach(msg => { + messages.forEach((msg) => { if (!isAborted && !isStaleData(requestId) && onChunk) { onChunk(msg); } @@ -201,14 +212,16 @@ const agentChatStream = (params, onChunk) => { }); // #endif }); -} +}; // window.atob兼容性处理 const weAtob = (string) => { - const b64re = /^(?:[A-Za-z\d+/]{4})*?(?:[A-Za-z\d+/]{2}(?:==)?|[A-Za-z\d+/]{3}=?)?$/; - const b64 = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/='; + const b64re = + /^(?:[A-Za-z\d+/]{4})*?(?:[A-Za-z\d+/]{2}(?:==)?|[A-Za-z\d+/]{3}=?)?$/; + const b64 = + "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/="; // 去除空白字符 - string = String(string).replace(/[\t\n\f\r ]+/g, ''); + string = String(string).replace(/[\t\n\f\r ]+/g, ""); // 验证 Base64 编码 if (!b64re.test(string)) { throw new TypeError( @@ -218,15 +231,15 @@ const weAtob = (string) => { } // 填充字符 - string += '=='.slice(2 - (string.length & 3)); + string += "==".slice(2 - (string.length & 3)); let bitmap, - result = '', + result = "", r1, r2, i = 0; - for (; i < string.length;) { + for (; i < string.length; ) { bitmap = (b64.indexOf(string.charAt(i++)) << 18) | (b64.indexOf(string.charAt(i++)) << 12) | @@ -236,10 +249,7 @@ const weAtob = (string) => { if (r1 === 64) { result += String.fromCharCode((bitmap >> 16) & 255); } else if (r2 === 64) { - result += String.fromCharCode( - (bitmap >> 16) & 255, - (bitmap >> 8) & 255 - ); + result += String.fromCharCode((bitmap >> 16) & 255, (bitmap >> 8) & 255); } else { result += String.fromCharCode( (bitmap >> 16) & 255, @@ -251,7 +261,6 @@ const weAtob = (string) => { return result; }; - // 解析SSE分段数据 const parseSSEChunk = (raw) => { const results = []; @@ -264,7 +273,7 @@ const parseSSEChunk = (raw) => { let dataLines = []; for (const line of lines) { - if (line.startsWith('data:')) { + if (line.startsWith("data:")) { // 提取data:后面的内容并去除首尾空格 dataLines.push(line.slice(5).trim()); } @@ -272,18 +281,18 @@ const parseSSEChunk = (raw) => { if (dataLines.length > 0) { // 拼接多行数据 - const fullData = dataLines.join('\n'); + const fullData = dataLines.join("\n"); try { const obj = JSON.parse(fullData); results.push(obj); } catch (e) { - console.warn('⚠️ SSE数据解析失败:', e, '原始数据:', fullData); + console.warn("⚠️ SSE数据解析失败:", e, "原始数据:", fullData); // 解析失败忽略 } } } return results; -} +}; -export { agentChatStream, stopAbortTask } +export { agentChatStream, stopAbortTask }; diff --git a/request/base/baseUrl.js b/request/base/baseUrl.js new file mode 100644 index 0000000..7ee442d --- /dev/null +++ b/request/base/baseUrl.js @@ -0,0 +1,19 @@ +const isProd = false; + +// 测试 +const VITE_BASE_URL_TEST = "https://onefeel.brother7.cn/ingress"; +const VITE_WSS_URL_TEST = "wss://onefeel.brother7.cn/ingress/agent/ws/chat"; + +// 生产 +const VITE_BASE_URL_PRO = "https://biz.nianxx.cn"; +const VITE_WSS_URL_PRO = "wss://biz.nianxx.cn/agent/ws/chat"; + +// 环境配置 +export const BASE_URL = isProd ? VITE_BASE_URL_PRO : VITE_BASE_URL_TEST; +export const WSS_URL = isProd ? VITE_WSS_URL_PRO : VITE_WSS_URL_TEST; + +// ===================================== +// 环境配置文件使用方法 +// console.log("当前环境:", import.meta.env); +// export const BASE_URL = import.meta.env.VITE_BASE_URL; +// export const WSS_URL = import.meta.env.VITE_WSS_URL; diff --git a/request/base/request.js b/request/base/request.js index 133e4ad..7a73bce 100644 --- a/request/base/request.js +++ b/request/base/request.js @@ -1,4 +1,4 @@ -import { BASE_URL } from "../../constant/base"; +import { BASE_URL } from "./baseUrl"; import { goLogin } from "@/hooks/useGoLogin"; const defaultConfig = {