| 62 | }, |
| 63 | |
| 64 | async save({ conversationId, items }) { |
| 65 | const owner = chatRunContext.getStore(); |
| 66 | if (!owner) { |
| 67 | throw new Error( |
| 68 | 'chatRunContext missing during save — the Fastify wrapper must run first', |
| 69 | ); |
| 70 | } |
| 71 | |
| 72 | await db.$transaction(async (tx) => { |
| 73 | await tx.conversation.upsert({ |
| 74 | where: { id: conversationId }, |
| 75 | create: { |
| 76 | id: conversationId, |
| 77 | projectId: owner.projectId, |
| 78 | organizationId: owner.organizationId, |
| 79 | userId: owner.userId, |
| 80 | }, |
| 81 | update: { updatedAt: new Date() }, |
| 82 | }); |
| 83 | |
| 84 | const existingCount = await tx.chatMessage.count({ |
| 85 | where: { conversationId }, |
| 86 | }); |
| 87 | |
| 88 | if (items.length >= existingCount) { |
| 89 | // Append-only fast path: Better Agent guarantees prior items |
| 90 | // are immutable, so we can safely insert only the tail. |
| 91 | const newItems = items.slice(existingCount); |
| 92 | if (newItems.length > 0) { |
| 93 | await tx.chatMessage.createMany({ |
| 94 | data: newItems.map((item) => itemToRow(conversationId, item)), |
| 95 | }); |
| 96 | } |
| 97 | } else { |
| 98 | // Incoming list is shorter than what's stored — an edit, |
| 99 | // retry, or deletion. Rewrite. |
| 100 | await tx.chatMessage.deleteMany({ where: { conversationId } }); |
| 101 | if (items.length > 0) { |
| 102 | await tx.chatMessage.createMany({ |
| 103 | data: items.map((item) => itemToRow(conversationId, item)), |
| 104 | }); |
| 105 | } |
| 106 | } |
| 107 | }); |
| 108 | |
| 109 | const updated = await db.conversation.findUnique({ |
| 110 | where: { id: conversationId }, |
| 111 | select: { updatedAt: true }, |
| 112 | }); |
| 113 | return { cursor: updated?.updatedAt.getTime() ?? Date.now() }; |
| 114 | }, |
| 115 | }; |