fix: topic branch incomplete copy - split ID mapping into two passes (#10900)

Fix the bug where topic branching would not copy all message relationships completely.The issue was that askId mapping lookup happened in the same loop as ID generation, causing later messages' askIds to fail mapping when they referenced messages that hadn't been processed yet.

Solution: Split into two passes:
 1. First pass: Generate new IDs for all messages and build complete mapping
 2. Second pass: Clone messages and blocks using the complete ID mapping

This ensures all message relationships (especially assistant message askId references)are properly maintained in the new topic.

(cherry picked from commit 35c15cd02c)
This commit is contained in:
Zhaokun 2025-10-23 16:18:23 +08:00 committed by dev
parent b8c435138b
commit a2004082af

View File

@ -1046,10 +1046,15 @@ export const cloneMessagesToNewTopicThunk =
const filesToUpdateCount: FileMetadata[] = []
const originalToNewMsgIdMap = new Map<string, string>() // Map original message ID -> new message ID
// 3. Clone Messages and Blocks with New IDs
// 3. First pass: Create ID mappings for all messages
for (const oldMessage of messagesToClone) {
const newMsgId = uuid()
originalToNewMsgIdMap.set(oldMessage.id, newMsgId) // Store mapping for all cloned messages
}
// 4. Second pass: Clone Messages and Blocks with New IDs using complete mapping
for (const oldMessage of messagesToClone) {
const newMsgId = originalToNewMsgIdMap.get(oldMessage.id)!
let newAskId: string | undefined = undefined // Initialize newAskId
if (oldMessage.role === 'assistant' && oldMessage.askId) {
@ -1110,7 +1115,7 @@ export const cloneMessagesToNewTopicThunk =
clonedMessages.push(newMessage)
}
// 4. Update Database (Atomic Transaction)
// 5. Update Database (Atomic Transaction)
await db.transaction('rw', db.topics, db.message_blocks, db.files, async () => {
// Update the NEW topic with the cloned messages
// Assumes topic entry was added by caller, so we UPDATE.