Andrew commited on
Commit
8bba2e0
·
1 Parent(s): 6bd5f9f

feat(utils): add message merging utility for persona responses

Browse files
Files changed (1) hide show
  1. src/lib/utils/mergeMessages.ts +43 -0
src/lib/utils/mergeMessages.ts ADDED
@@ -0,0 +1,43 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import type { Message } from "$lib/types/Message";
2
+
3
+ /**
4
+ * Merges server messages with local optimistic messages to preserve streaming content
5
+ * while updating structure/IDs from the server.
6
+ */
7
+ export function mergeMessages(serverMessages: Message[], localMessages: Message[]): Message[] {
8
+ if (serverMessages.length === 0) return localMessages;
9
+ if (localMessages.length === 0) return serverMessages;
10
+
11
+ const lastServerMsg = serverMessages[serverMessages.length - 1];
12
+ const lastLocalMsg = localMessages[localMessages.length - 1];
13
+
14
+ // Check if they look like the same message (same role)
15
+ if (lastServerMsg.from === lastLocalMsg.from) {
16
+ // If server content is empty/short but local is long, keep local content
17
+ if ((lastServerMsg.content?.length || 0) < (lastLocalMsg.content?.length || 0)) {
18
+ const newLastServerMsg = { ...lastServerMsg };
19
+
20
+ // Adopt server ID but keep local content
21
+ newLastServerMsg.content = lastLocalMsg.content;
22
+ newLastServerMsg.reasoning = lastLocalMsg.reasoning;
23
+
24
+ // Merge persona responses
25
+ if (lastLocalMsg.personaResponses?.length && !lastServerMsg.personaResponses?.length) {
26
+ newLastServerMsg.personaResponses = lastLocalMsg.personaResponses;
27
+ } else if (lastLocalMsg.personaResponses && lastServerMsg.personaResponses) {
28
+ newLastServerMsg.personaResponses = lastServerMsg.personaResponses.map((sPR) => {
29
+ const lPR = lastLocalMsg.personaResponses?.find((l) => l.personaId === sPR.personaId);
30
+ if (lPR && lPR.content.length > sPR.content.length) {
31
+ return { ...sPR, content: lPR.content };
32
+ }
33
+ return sPR;
34
+ });
35
+ }
36
+
37
+ // Return new array with replaced last message
38
+ return [...serverMessages.slice(0, -1), newLastServerMsg];
39
+ }
40
+ }
41
+
42
+ return serverMessages;
43
+ }