Skip to content

Commit 7406f4c

Browse files
committed
feat(conversation): enhance conversation loading logic and merging strategy
- Improved the loading mechanism in `useConversation` to handle empty conversation lists gracefully. - Implemented a merging strategy that prioritizes in-memory conversations over stored ones, ensuring that newly created conversations are not overwritten. - Added checks to maintain the integrity of the active conversation after merging, preventing accidental loss of context.
1 parent 08bce08 commit 7406f4c

File tree

1 file changed

+24
-1
lines changed

1 file changed

+24
-1
lines changed

packages/kit/src/vue/conversation/useConversation.ts

Lines changed: 24 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -116,7 +116,30 @@ export const useConversation = (options: UseConversationOptions): UseConversatio
116116
if (storage?.loadConversations) {
117117
Promise.resolve(storage.loadConversations())
118118
.then((list) => {
119-
conversations.value = list
119+
// 如果加载的列表为空,直接返回
120+
if (!list?.length) return
121+
122+
// 如果当前内存中的会话列表为空,直接使用加载的列表
123+
if (conversations.value.length === 0) {
124+
conversations.value = list
125+
return
126+
}
127+
128+
// 合并策略:内存数据优先于存储数据
129+
// 1. 保留内存中已存在的会话(不会被存储数据覆盖)
130+
// 2. 添加存储中存在但内存中不存在的会话
131+
// 这样可以避免覆盖在 loadConversations 完成之前通过 createConversation 创建的会话
132+
const merged = new Map(conversations.value.map((c) => [c.id, c]))
133+
list.forEach((c) => {
134+
if (!merged.has(c.id)) {
135+
merged.set(c.id, c)
136+
}
137+
})
138+
conversations.value = Array.from(merged.values())
139+
140+
// 确保 activeConversation 对应的会话在合并后的列表中
141+
// 如果 activeConversationId 存在但对应的会话不在列表中,说明可能被意外删除
142+
// 这种情况下,activeConversation 会自动变为 null(通过 computed 属性)
120143
})
121144
.catch((error) => {
122145
console.error('[useConversation] loadConversations failed:', error)

0 commit comments

Comments
 (0)