| 776 | } |
| 777 | |
| 778 | insertMessageAfter( |
| 779 | aiChatId: string, |
| 780 | afterMessageId: string, |
| 781 | role: AIMessageRole, |
| 782 | content: string, |
| 783 | contentBlocks?: ContentBlock[], |
| 784 | tokenUsage?: TokenUsageData |
| 785 | ): AIMessage { |
| 786 | const db = this.getDb() |
| 787 | const now = Math.floor(Date.now() / 1000) |
| 788 | const id = this.generateId('msg') |
| 789 | |
| 790 | const pendingDebug = role === 'assistant' ? this.pendingDebugContextMap.get(aiChatId) : undefined |
| 791 | if (pendingDebug) { |
| 792 | this.pendingDebugContextMap.delete(aiChatId) |
| 793 | } |
| 794 | |
| 795 | const childRow = db |
| 796 | .prepare('SELECT id FROM ai_message WHERE parent_id = ? AND ai_chat_id = ? LIMIT 1') |
| 797 | .get(afterMessageId, aiChatId) as { id: string } | undefined |
| 798 | |
| 799 | db.prepare( |
| 800 | `INSERT INTO ai_message ( |
| 801 | id, ai_chat_id, role, content, timestamp, data_keywords, data_message_count, |
| 802 | content_blocks, token_usage, debug_context, parent_id, sibling_group_id, branch_index |
| 803 | ) |
| 804 | VALUES (?, ?, ?, ?, ?, NULL, NULL, ?, ?, ?, ?, ?, 0)` |
| 805 | ).run( |
| 806 | id, |
| 807 | aiChatId, |
| 808 | role, |
| 809 | content, |
| 810 | now, |
| 811 | contentBlocks ? JSON.stringify(contentBlocks) : null, |
| 812 | tokenUsage ? JSON.stringify(tokenUsage) : null, |
| 813 | pendingDebug ?? null, |
| 814 | afterMessageId, |
| 815 | id |
| 816 | ) |
| 817 | |
| 818 | if (childRow) { |
| 819 | db.prepare('UPDATE ai_message SET parent_id = ? WHERE id = ?').run(id, childRow.id) |
| 820 | db.prepare('UPDATE ai_chat SET updated_at = ? WHERE id = ?').run(now, aiChatId) |
| 821 | } else { |
| 822 | db.prepare('UPDATE ai_chat SET active_message_id = ?, updated_at = ? WHERE id = ?').run(id, now, aiChatId) |
| 823 | } |
| 824 | |
| 825 | return { |
| 826 | id, |
| 827 | aiChatId, |
| 828 | role, |
| 829 | content, |
| 830 | timestamp: now, |
| 831 | parentId: afterMessageId, |
| 832 | contentBlocks, |
| 833 | tokenUsage, |
| 834 | } |
| 835 | } |