chore:目前为止加了历史会话,正常运行没有出错

This commit is contained in:
2025-12-12 16:23:00 +08:00
parent aa03abf651
commit b4aed459c5

View File

@@ -837,35 +837,56 @@ export default {
}, },
// 加载更多历史消息 // 加载更多历史消息
loadMoreHistory() { async loadMoreHistory() {
if (!this.showLoadMore) return if (!this.showLoadMore || !this.currentConversationId) {
this.hasMoreHistory = false
return
}
this.hasMoreHistory = true this.hasMoreHistory = true
this.loadingText = '加载历史消息中...' this.loadingText = '加载历史消息中...'
// 模拟加载历史消息 try {
setTimeout(() => { const res = await aiService.getConversationHistory({
const historyMessages = [ conversation_id: this.currentConversationId,
{ limit: 20,
id: --this.messageId, offset: this.messages.length // 简单分页:已加载多少条,就跳过多少
role: 'ai', })
type: 'text',
content: '这是历史消息1',
timestamp: Date.now() - 86400000
},
{
id: --this.messageId,
role: 'user',
type: 'text',
content: '这是历史消息2',
timestamp: Date.now() - 86400000
}
]
this.messages = [...historyMessages, ...this.messages] if (res.success && Array.isArray(res.messages)) {
// 转换后端消息格式 → 前端组件格式
const historyMessages = res.messages.map(msg => ({
id: msg.id, // 直接用后端的字符串 ID比自增数字更可靠
role: msg.role === 'user' ? 'user' : 'ai', // 关键:'assistant' → 'ai'
type: 'text',
content: msg.content,
timestamp: msg.create_time * 1000 // 秒 → 毫秒
})).reverse() // 后端按时间正序(旧→新),但我们要插到顶部,所以 reverse 成 新→旧?不!
// ⚠️ 注意getHistory 返回的是从旧到新offset=0 是最早的消息)
// 而 this.messages 是 [旧, ..., 新]
// 所以新加载的历史应该放在现有消息的前面,且保持“旧→新”顺序
// 因此 **不要 reverse**!直接拼接即可(但确保 offset 正确)
// 更安全的做法:按时间排序(可选)
// historyMessages.sort((a, b) => a.timestamp - b.timestamp)
// 插入到顶部(历史在上,最新在下)
this.messages = [...historyMessages, ...this.messages]
// 判断是否还有更多历史
this.hasMoreHistory = res.total > this.messages.length
this.showLoadMore = res.total > this.messages.length
} else {
this.hasMoreHistory = false
this.showLoadMore = false
}
} catch (error) {
console.error('加载历史失败:', error)
uni.showToast({ title: '加载历史失败', icon: 'none' })
this.hasMoreHistory = false this.hasMoreHistory = false
this.$emit('history-loaded', historyMessages) this.showLoadMore = false
}, 1000) }
}, },
// 显示更多工具 // 显示更多工具