小程序聊天修正

This commit is contained in:
2026-01-12 10:47:44 +08:00
parent 0972d504ab
commit 6921ac7e66
2 changed files with 146 additions and 101 deletions

View File

@@ -22,6 +22,51 @@ declare const uni: {
request: (options: any) => any
}
/**
* ArrayBuffer 转字符串(兼容微信小程序真机环境)
* 微信小程序真机不支持 TextDecoder需要手动解码 UTF-8
*/
function arrayBufferToString(buffer: ArrayBuffer): string {
// 优先使用 TextDecoder开发者工具和支持的环境
if (typeof TextDecoder !== 'undefined') {
return new TextDecoder('utf-8').decode(new Uint8Array(buffer))
}
// 微信小程序真机兼容方案:手动解码 UTF-8
const bytes = new Uint8Array(buffer)
let result = ''
let i = 0
while (i < bytes.length) {
const byte1 = bytes[i++]
if (byte1 < 0x80) {
// 单字节字符 (0xxxxxxx)
result += String.fromCharCode(byte1)
} else if ((byte1 & 0xE0) === 0xC0) {
// 双字节字符 (110xxxxx 10xxxxxx)
const byte2 = bytes[i++] & 0x3F
result += String.fromCharCode(((byte1 & 0x1F) << 6) | byte2)
} else if ((byte1 & 0xF0) === 0xE0) {
// 三字节字符 (1110xxxx 10xxxxxx 10xxxxxx) - 中文常用
const byte2 = bytes[i++] & 0x3F
const byte3 = bytes[i++] & 0x3F
result += String.fromCharCode(((byte1 & 0x0F) << 12) | (byte2 << 6) | byte3)
} else if ((byte1 & 0xF8) === 0xF0) {
// 四字节字符 (11110xxx 10xxxxxx 10xxxxxx 10xxxxxx) - emoji等
const byte2 = bytes[i++] & 0x3F
const byte3 = bytes[i++] & 0x3F
const byte4 = bytes[i++] & 0x3F
const codePoint = ((byte1 & 0x07) << 18) | (byte2 << 12) | (byte3 << 6) | byte4
// 转换为 UTF-16 代理对
const surrogate = codePoint - 0x10000
result += String.fromCharCode(0xD800 + (surrogate >> 10), 0xDC00 + (surrogate & 0x3FF))
}
}
return result
}
/**
* @description AI对话相关接口直接调用ai模块
* @filename aiChat.ts
@@ -128,8 +173,8 @@ export const aiChatAPI = {
// 监听分块数据
requestTask.onChunkReceived((res: any) => {
try {
const decoder = new TextDecoder('utf-8')
const text = decoder.decode(new Uint8Array(res.data))
// 兼容微信小程序真机环境(不支持 TextDecoder
const text = arrayBufferToString(res.data)
const lines = text.split('\n')
for (const line of lines) {